2021-08-18 13:48:58 +00:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/bluele/gcache"
|
2021-09-10 06:56:56 +00:00
|
|
|
"github.com/nspcc-dev/neofs-s3-gw/api/data"
|
2021-08-18 13:48:58 +00:00
|
|
|
)
|
|
|
|
|
2021-09-10 06:56:56 +00:00
|
|
|
// BucketCache contains cache with objects and lifetime of cache entries.
|
|
|
|
type BucketCache struct {
|
|
|
|
cache gcache.Cache
|
|
|
|
}
|
2021-08-18 13:48:58 +00:00
|
|
|
|
2021-09-10 06:56:56 +00:00
|
|
|
const (
|
|
|
|
// DefaultBucketCacheSize is a default maximum number of entries in cache.
|
|
|
|
DefaultBucketCacheSize = 1e3
|
|
|
|
// DefaultBucketCacheLifetime is a default lifetime of entries in cache.
|
|
|
|
DefaultBucketCacheLifetime = time.Minute
|
2021-08-18 13:48:58 +00:00
|
|
|
)
|
|
|
|
|
2021-09-10 06:56:56 +00:00
|
|
|
// DefaultBucketConfig return new default cache expiration values.
|
|
|
|
func DefaultBucketConfig() *Config {
|
|
|
|
return &Config{Size: DefaultBucketCacheSize, Lifetime: DefaultBucketCacheLifetime}
|
|
|
|
}
|
2021-08-18 13:48:58 +00:00
|
|
|
|
2021-09-10 06:56:56 +00:00
|
|
|
// NewBucketCache creates an object of BucketCache.
|
|
|
|
func NewBucketCache(config *Config) *BucketCache {
|
|
|
|
gc := gcache.New(config.Size).LRU().Expiration(config.Lifetime).Build()
|
|
|
|
return &BucketCache{cache: gc}
|
2021-08-18 13:48:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Get returns cached object.
|
2021-09-10 06:56:56 +00:00
|
|
|
func (o *BucketCache) Get(key string) *data.BucketInfo {
|
2021-08-18 13:48:58 +00:00
|
|
|
entry, err := o.cache.Get(key)
|
|
|
|
if err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-09-10 06:56:56 +00:00
|
|
|
result, ok := entry.(*data.BucketInfo)
|
2021-08-18 13:48:58 +00:00
|
|
|
if !ok {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
|
|
|
// Put puts an object to cache.
|
2021-09-10 06:56:56 +00:00
|
|
|
func (o *BucketCache) Put(bkt *data.BucketInfo) error {
|
|
|
|
return o.cache.Set(bkt.Name, bkt)
|
2021-08-18 13:48:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Delete deletes an object from cache.
|
2021-09-10 06:56:56 +00:00
|
|
|
func (o *BucketCache) Delete(key string) bool {
|
2021-08-18 13:48:58 +00:00
|
|
|
return o.cache.Remove(key)
|
|
|
|
}
|