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 ( // NetworkCache provides cache for network-related values. NetworkCache struct { cache gcache.Cache logger *zap.Logger } // NetworkCacheConfig stores expiration params for cache. NetworkCacheConfig struct { Lifetime time.Duration Logger *zap.Logger } ) const ( DefaultNetworkCacheLifetime = 1 * time.Minute networkCacheSize = 2 networkInfoKey = "network_info" netmapKey = "netmap" ) // DefaultNetworkConfig returns new default cache expiration values. func DefaultNetworkConfig(logger *zap.Logger) *NetworkCacheConfig { return &NetworkCacheConfig{ Lifetime: DefaultNetworkCacheLifetime, Logger: logger, } } // NewNetworkCache creates an object of NetworkCache. func NewNetworkCache(config *NetworkCacheConfig) *NetworkCache { gc := gcache.New(networkCacheSize).LRU().Expiration(config.Lifetime).Build() return &NetworkCache{cache: gc, logger: config.Logger} } func (c *NetworkCache) GetNetworkInfo() *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 *NetworkCache) PutNetworkInfo(info netmap.NetworkInfo) error { return c.cache.Set(networkInfoKey, info) } func (c *NetworkCache) GetNetmap() *netmap.NetMap { entry, err := c.cache.Get(netmapKey) if err != nil { return nil } result, ok := entry.(netmap.NetMap) 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 *NetworkCache) PutNetmap(nm netmap.NetMap) error { return c.cache.Set(netmapKey, nm) }