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"
|
|
|
|
)
|
|
|
|
|
2021-09-10 06:56:56 +00:00
|
|
|
// ObjectsCache provides lru cache for objects.
|
|
|
|
type ObjectsCache struct {
|
|
|
|
cache gcache.Cache
|
2021-08-10 11:19:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
)
|
|
|
|
|
2021-09-10 06:56:56 +00:00
|
|
|
// DefaultObjectsConfig return new default cache expiration values.
|
|
|
|
func DefaultObjectsConfig() *Config {
|
|
|
|
return &Config{Size: DefaultObjectsCacheSize, Lifetime: DefaultObjectsCacheLifetime}
|
|
|
|
}
|
2021-08-10 11:19:26 +00:00
|
|
|
|
|
|
|
// New creates an object of ObjectHeadersCache.
|
2021-09-10 06:56:56 +00:00
|
|
|
func New(config *Config) *ObjectsCache {
|
|
|
|
gc := gcache.New(config.Size).LRU().Expiration(config.Lifetime).Build()
|
|
|
|
return &ObjectsCache{cache: gc}
|
2021-08-10 11:19:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Get returns cached object.
|
2021-09-10 06:56:56 +00:00
|
|
|
func (o *ObjectsCache) Get(address *object.Address) *object.Object {
|
2021-08-10 11:19:26 +00:00
|
|
|
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-09-10 06:56:56 +00:00
|
|
|
func (o *ObjectsCache) Put(obj object.Object) error {
|
|
|
|
return o.cache.Set(obj.ContainerID().String()+"/"+obj.ID().String(), obj)
|
2021-08-10 11:19:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Delete deletes an object from cache.
|
2021-09-10 06:56:56 +00:00
|
|
|
func (o *ObjectsCache) Delete(address *object.Address) bool {
|
2021-08-10 11:19:26 +00:00
|
|
|
return o.cache.Remove(address.String())
|
|
|
|
}
|