github.com/telepresenceio/telepresence/v2@v2.20.0-pro.6.0.20240517030216-236ea954e789/pkg/client/userd/trafficmgr/session_info_cache.go (about) 1 package trafficmgr 2 3 import ( 4 "context" 5 "os" 6 "path/filepath" 7 8 "github.com/telepresenceio/telepresence/rpc/v2/manager" 9 "github.com/telepresenceio/telepresence/v2/pkg/client/cache" 10 "github.com/telepresenceio/telepresence/v2/pkg/client/cli/daemon" 11 ) 12 13 func sessionInfoFile(daemonID *daemon.Identifier) string { 14 return filepath.Join("sessions", daemonID.InfoFileName()) 15 } 16 17 type SavedSession struct { 18 KubeContext string `json:"kubeContext"` 19 Namespace string `json:"namespace"` 20 Session *manager.SessionInfo `json:"session"` 21 } 22 23 // SaveSessionInfoToUserCache saves the provided SessionInfo to user cache and returns an error if 24 // something goes wrong while marshalling or persisting. 25 func SaveSessionInfoToUserCache(ctx context.Context, daemonID *daemon.Identifier, session *manager.SessionInfo) error { 26 return cache.SaveToUserCache(ctx, &SavedSession{ 27 KubeContext: daemonID.KubeContext, 28 Namespace: daemonID.Namespace, 29 Session: session, 30 }, sessionInfoFile(daemonID), cache.Public) 31 } 32 33 // LoadSessionInfoFromUserCache gets the SessionInfo from cache or returns an error if something goes 34 // wrong while loading or unmarshalling. 35 func LoadSessionInfoFromUserCache(ctx context.Context, daemonID *daemon.Identifier) (*manager.SessionInfo, error) { 36 var ss *SavedSession 37 err := cache.LoadFromUserCache(ctx, &ss, sessionInfoFile(daemonID)) 38 if err == nil && ss.KubeContext == daemonID.KubeContext && ss.Namespace == daemonID.Namespace { 39 return ss.Session, nil 40 } 41 if err != nil && os.IsNotExist(err) { 42 err = nil 43 } 44 return nil, err 45 } 46 47 // DeleteSessionInfoFromUserCache removes SessionInfo cache if existing or returns an error. An attempt 48 // to remove a non-existing cache is a no-op and the function returns nil. 49 func DeleteSessionInfoFromUserCache(ctx context.Context, daemonID *daemon.Identifier) error { 50 return cache.DeleteFromUserCache(ctx, sessionInfoFile(daemonID)) 51 }