package cache import ( "fmt" "time" "git.frostfs.info/TrueCloudLab/frostfs-s3-gw/internal/logs" "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/netmap" "github.com/bluele/gcache" "go.uber.org/zap" ) type ( // NetworkInfoCache provides cache for network info. NetworkInfoCache struct { cache gcache.Cache logger *zap.Logger } // NetworkInfoCacheConfig stores expiration params for cache. NetworkInfoCacheConfig struct { Lifetime time.Duration Logger *zap.Logger } ) const ( DefaultNetworkInfoCacheLifetime = 1 * time.Minute networkInfoCacheSize = 1 networkInfoKey = "network_info" ) // DefaultNetworkInfoConfig returns new default cache expiration values. func DefaultNetworkInfoConfig(logger *zap.Logger) *NetworkInfoCacheConfig { return &NetworkInfoCacheConfig{ Lifetime: DefaultNetworkInfoCacheLifetime, Logger: logger, } } // NewNetworkInfoCache creates an object of NetworkInfoCache. func NewNetworkInfoCache(config *NetworkInfoCacheConfig) *NetworkInfoCache { gc := gcache.New(networkInfoCacheSize).LRU().Expiration(config.Lifetime).Build() return &NetworkInfoCache{cache: gc, logger: config.Logger} } func (c *NetworkInfoCache) Get() *netmap.NetworkInfo { entry, err := c.cache.Get(networkInfoKey) if err != nil { return nil } result, ok := entry.(netmap.NetworkInfo) if !ok { c.logger.Warn(logs.InvalidCacheEntryType, zap.String("actual", fmt.Sprintf("%T", entry)), zap.String("expected", fmt.Sprintf("%T", result))) return nil } return &result } func (c *NetworkInfoCache) Put(info netmap.NetworkInfo) error { return c.cache.Set(networkInfoKey, info) }