2021-09-10 06:56:56 +00:00
|
|
|
package cache
|
2021-09-08 07:08:56 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/bluele/gcache"
|
|
|
|
"github.com/nspcc-dev/neofs-s3-gw/creds/accessbox"
|
2022-02-08 16:54:04 +00:00
|
|
|
"github.com/nspcc-dev/neofs-sdk-go/object/address"
|
2021-09-08 07:08:56 +00:00
|
|
|
)
|
|
|
|
|
2021-09-10 06:56:56 +00:00
|
|
|
type (
|
|
|
|
// AccessBoxCache stores access box by its address.
|
|
|
|
AccessBoxCache struct {
|
|
|
|
cache gcache.Cache
|
|
|
|
}
|
2021-09-08 07:08:56 +00:00
|
|
|
|
2021-09-10 06:56:56 +00:00
|
|
|
// Config stores expiration params for cache.
|
|
|
|
Config struct {
|
|
|
|
Size int
|
|
|
|
Lifetime time.Duration
|
|
|
|
}
|
|
|
|
)
|
2021-09-08 07:08:56 +00:00
|
|
|
|
2021-09-10 06:56:56 +00:00
|
|
|
const (
|
|
|
|
// DefaultAccessBoxCacheSize is a default maximum number of entries in cache.
|
|
|
|
DefaultAccessBoxCacheSize = 100
|
|
|
|
// DefaultAccessBoxCacheLifetime is a default lifetime of entries in cache.
|
|
|
|
DefaultAccessBoxCacheLifetime = 10 * time.Minute
|
|
|
|
)
|
2021-09-08 07:08:56 +00:00
|
|
|
|
2021-09-10 06:56:56 +00:00
|
|
|
// DefaultAccessBoxConfig return new default cache expiration values.
|
|
|
|
func DefaultAccessBoxConfig() *Config {
|
|
|
|
return &Config{Size: DefaultAccessBoxCacheSize, Lifetime: DefaultAccessBoxCacheLifetime}
|
2021-09-08 07:08:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewAccessBoxCache creates an object of BucketCache.
|
2021-09-10 06:56:56 +00:00
|
|
|
func NewAccessBoxCache(config *Config) *AccessBoxCache {
|
2021-09-08 07:08:56 +00:00
|
|
|
gc := gcache.New(config.Size).LRU().Expiration(config.Lifetime).Build()
|
|
|
|
|
|
|
|
return &AccessBoxCache{cache: gc}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get returns cached object.
|
2022-02-08 16:54:04 +00:00
|
|
|
func (o *AccessBoxCache) Get(address *address.Address) *accessbox.Box {
|
2021-09-08 07:08:56 +00:00
|
|
|
entry, err := o.cache.Get(address.String())
|
|
|
|
if err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
result, ok := entry.(*accessbox.Box)
|
|
|
|
if !ok {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
|
|
|
// Put stores an object to cache.
|
2022-02-08 16:54:04 +00:00
|
|
|
func (o *AccessBoxCache) Put(address *address.Address, box *accessbox.Box) error {
|
2021-09-08 07:08:56 +00:00
|
|
|
return o.cache.Set(address.String(), box)
|
|
|
|
}
|