2021-08-10 11:19:26 +00:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/bluele/gcache"
|
|
|
|
"github.com/nspcc-dev/neofs-api-go/pkg/object"
|
|
|
|
)
|
|
|
|
|
|
|
|
// ObjectsCache provides interface for lru cache for objects.
|
|
|
|
type ObjectsCache interface {
|
|
|
|
Get(address *object.Address) *object.Object
|
2021-08-18 13:48:58 +00:00
|
|
|
Put(obj object.Object) error
|
2021-08-10 11:19:26 +00:00
|
|
|
Delete(address *object.Address) bool
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
2021-08-16 09:58:09 +00:00
|
|
|
// DefaultObjectsCacheLifetime is a default lifetime of entries in objects' cache.
|
2021-08-10 11:19:26 +00:00
|
|
|
DefaultObjectsCacheLifetime = time.Minute * 5
|
2021-08-16 09:58:09 +00:00
|
|
|
// DefaultObjectsCacheSize is a default maximum number of entries in objects' in cache.
|
2021-08-10 11:19:26 +00:00
|
|
|
DefaultObjectsCacheSize = 1e6
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
// ObjectHeadersCache contains cache with objects and lifetime of cache entries.
|
|
|
|
ObjectHeadersCache struct {
|
|
|
|
cache gcache.Cache
|
|
|
|
lifetime time.Duration
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
// New creates an object of ObjectHeadersCache.
|
|
|
|
func New(cacheSize int, lifetime time.Duration) *ObjectHeadersCache {
|
|
|
|
gc := gcache.New(cacheSize).LRU().Build()
|
|
|
|
|
|
|
|
return &ObjectHeadersCache{cache: gc, lifetime: lifetime}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get returns cached object.
|
|
|
|
func (o *ObjectHeadersCache) Get(address *object.Address) *object.Object {
|
|
|
|
entry, err := o.cache.Get(address.String())
|
|
|
|
if err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
result, ok := entry.(object.Object)
|
|
|
|
if !ok {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return &result
|
|
|
|
}
|
|
|
|
|
|
|
|
// Put puts an object to cache.
|
2021-08-18 13:48:58 +00:00
|
|
|
func (o *ObjectHeadersCache) Put(obj object.Object) error {
|
|
|
|
return o.cache.SetWithExpire(obj.ContainerID().String()+"/"+obj.ID().String(), obj, o.lifetime)
|
2021-08-10 11:19:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Delete deletes an object from cache.
|
|
|
|
func (o *ObjectHeadersCache) Delete(address *object.Address) bool {
|
|
|
|
return o.cache.Remove(address.String())
|
|
|
|
}
|