2021-08-18 13:48:58 +00:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/bluele/gcache"
|
2021-08-27 21:33:50 +00:00
|
|
|
"github.com/nspcc-dev/neofs-s3-gw/api"
|
2021-08-18 13:48:58 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
// BucketCache provides interface for lru cache for objects.
|
|
|
|
BucketCache interface {
|
2021-08-27 21:33:50 +00:00
|
|
|
Get(key string) *api.BucketInfo
|
|
|
|
Put(bkt *api.BucketInfo) error
|
2021-08-18 13:48:58 +00:00
|
|
|
Delete(key string) bool
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetBucketCache contains cache with objects and lifetime of cache entries.
|
|
|
|
GetBucketCache struct {
|
|
|
|
cache gcache.Cache
|
|
|
|
lifetime time.Duration
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
// NewBucketCache creates an object of BucketCache.
|
|
|
|
func NewBucketCache(cacheSize int, lifetime time.Duration) *GetBucketCache {
|
|
|
|
gc := gcache.New(cacheSize).LRU().Build()
|
|
|
|
|
|
|
|
return &GetBucketCache{cache: gc, lifetime: lifetime}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get returns cached object.
|
2021-08-27 21:33:50 +00:00
|
|
|
func (o *GetBucketCache) Get(key string) *api.BucketInfo {
|
2021-08-18 13:48:58 +00:00
|
|
|
entry, err := o.cache.Get(key)
|
|
|
|
if err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-08-27 21:33:50 +00:00
|
|
|
result, ok := entry.(*api.BucketInfo)
|
2021-08-18 13:48:58 +00:00
|
|
|
if !ok {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
|
|
|
// Put puts an object to cache.
|
2021-08-27 21:33:50 +00:00
|
|
|
func (o *GetBucketCache) Put(bkt *api.BucketInfo) error {
|
2021-08-18 13:48:58 +00:00
|
|
|
return o.cache.SetWithExpire(bkt.Name, bkt, o.lifetime)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Delete deletes an object from cache.
|
|
|
|
func (o *GetBucketCache) Delete(key string) bool {
|
|
|
|
return o.cache.Remove(key)
|
|
|
|
}
|