forked from TrueCloudLab/frostfs-http-gw
62 lines
1.6 KiB
Go
62 lines
1.6 KiB
Go
package cache
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/data"
|
|
"git.frostfs.info/TrueCloudLab/frostfs-http-gw/internal/logs"
|
|
cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
|
|
"github.com/bluele/gcache"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
// CORSCache contains cache with CORS objects.
|
|
type CORSCache struct {
|
|
cache gcache.Cache
|
|
logger *zap.Logger
|
|
}
|
|
|
|
const (
|
|
// DefaultCORSCacheSize is a default maximum number of entries in cache.
|
|
DefaultCORSCacheSize = 1e3
|
|
// DefaultCORSCacheLifetime is a default lifetime of entries in cache.
|
|
DefaultCORSCacheLifetime = 5 * time.Minute
|
|
)
|
|
|
|
// DefaultCORSConfig returns new default cache expiration values.
|
|
func DefaultCORSConfig(logger *zap.Logger) *Config {
|
|
return &Config{
|
|
Size: DefaultCORSCacheSize,
|
|
Lifetime: DefaultCORSCacheLifetime,
|
|
Logger: logger,
|
|
}
|
|
}
|
|
|
|
// NewCORSCache creates an object of CORSCache.
|
|
func NewCORSCache(config *Config) *CORSCache {
|
|
gc := gcache.New(config.Size).LRU().Expiration(config.Lifetime).Build()
|
|
return &CORSCache{cache: gc, logger: config.Logger}
|
|
}
|
|
|
|
// Get returns a cached object.
|
|
func (o *CORSCache) Get(cnrID cid.ID) *data.CORSConfiguration {
|
|
entry, err := o.cache.Get(cnrID)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
|
|
result, ok := entry.(*data.CORSConfiguration)
|
|
if !ok {
|
|
o.logger.Warn(logs.InvalidCacheEntryType, zap.String("actual", fmt.Sprintf("%T", entry)),
|
|
zap.String("expected", fmt.Sprintf("%T", result)), logs.TagField(logs.TagDatapath))
|
|
return nil
|
|
}
|
|
|
|
return result
|
|
}
|
|
|
|
// Put puts an object to cache.
|
|
func (o *CORSCache) Put(cnrID cid.ID, cors *data.CORSConfiguration) error {
|
|
return o.cache.Set(cnrID, cors)
|
|
}
|