Marina Biryukova
95d847d611
All checks were successful
/ DCO (pull_request) Successful in 4m12s
/ Vulncheck (pull_request) Successful in 4m31s
/ Builds (pull_request) Successful in 2m28s
/ Lint (pull_request) Successful in 2m52s
/ Tests (pull_request) Successful in 2m34s
/ Vulncheck (push) Successful in 1m41s
/ Builds (push) Successful in 2m4s
/ Lint (push) Successful in 6m4s
/ Tests (push) Successful in 5m20s
Signed-off-by: Marina Biryukova <m.biryukova@yadro.com>
86 lines
2 KiB
Go
86 lines
2 KiB
Go
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)
|
|
}
|