2021-10-25 12:57:55 +00:00
|
|
|
package pool
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
2022-02-02 11:18:05 +00:00
|
|
|
"time"
|
2021-10-25 12:57:55 +00:00
|
|
|
|
2021-11-08 13:28:28 +00:00
|
|
|
lru "github.com/hashicorp/golang-lru"
|
|
|
|
"github.com/nspcc-dev/neofs-sdk-go/session"
|
2021-10-25 12:57:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type SessionCache struct {
|
2021-11-08 13:28:28 +00:00
|
|
|
cache *lru.Cache
|
2021-10-25 12:57:55 +00:00
|
|
|
}
|
|
|
|
|
2022-02-02 11:18:05 +00:00
|
|
|
type cacheValue struct {
|
|
|
|
atime time.Time
|
|
|
|
token *session.Token
|
|
|
|
}
|
|
|
|
|
2021-11-08 13:28:28 +00:00
|
|
|
func NewCache() (*SessionCache, error) {
|
|
|
|
cache, err := lru.New(100)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2021-10-25 12:57:55 +00:00
|
|
|
}
|
2021-11-08 13:28:28 +00:00
|
|
|
|
|
|
|
return &SessionCache{cache: cache}, nil
|
2021-10-25 12:57:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *SessionCache) Get(key string) *session.Token {
|
2022-02-02 11:18:05 +00:00
|
|
|
valueRaw, ok := c.cache.Get(key)
|
2021-10-25 12:57:55 +00:00
|
|
|
if !ok {
|
|
|
|
return nil
|
|
|
|
}
|
2022-02-02 11:18:05 +00:00
|
|
|
|
|
|
|
value := valueRaw.(*cacheValue)
|
|
|
|
value.atime = time.Now()
|
|
|
|
|
|
|
|
return value.token
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *SessionCache) GetAccessTime(key string) (time.Time, bool) {
|
|
|
|
valueRaw, ok := c.cache.Peek(key)
|
|
|
|
if !ok {
|
|
|
|
return time.Time{}, false
|
|
|
|
}
|
|
|
|
|
|
|
|
return valueRaw.(*cacheValue).atime, true
|
2021-10-25 12:57:55 +00:00
|
|
|
}
|
|
|
|
|
2021-11-08 13:28:28 +00:00
|
|
|
func (c *SessionCache) Put(key string, token *session.Token) bool {
|
2022-02-02 11:18:05 +00:00
|
|
|
return c.cache.Add(key, &cacheValue{
|
|
|
|
atime: time.Now(),
|
|
|
|
token: token,
|
|
|
|
})
|
2021-10-25 12:57:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *SessionCache) DeleteByPrefix(prefix string) {
|
2021-11-08 13:28:28 +00:00
|
|
|
for _, key := range c.cache.Keys() {
|
|
|
|
if strings.HasPrefix(key.(string), prefix) {
|
2021-10-25 12:57:55 +00:00
|
|
|
c.cache.Remove(key)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|