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
|
|
|
)
|
|
|
|
|
2022-03-11 11:57:35 +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
|
|
|
|
}
|
|
|
|
|
2022-03-11 11:57:35 +00:00
|
|
|
func newCache() (*sessionCache, error) {
|
2021-11-08 13:28:28 +00:00
|
|
|
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
|
|
|
|
2022-03-11 11:57:35 +00:00
|
|
|
return &sessionCache{cache: cache}, nil
|
2021-10-25 12:57:55 +00:00
|
|
|
}
|
|
|
|
|
2022-04-06 08:05:08 +00:00
|
|
|
// Get returns a copy of the session token from the cache without signature
|
|
|
|
// and context related fields. Returns nil if token is missing in the cache.
|
|
|
|
// It is safe to modify and re-sign returned session token.
|
2022-03-11 11:57:35 +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()
|
|
|
|
|
2022-04-06 08:05:08 +00:00
|
|
|
if value.token == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
res := copySessionTokenWithoutSignatureAndContext(*value.token)
|
|
|
|
|
|
|
|
return &res
|
2022-02-02 11:18:05 +00:00
|
|
|
}
|
|
|
|
|
2022-03-11 11:57:35 +00:00
|
|
|
func (c *sessionCache) GetAccessTime(key string) (time.Time, bool) {
|
2022-02-02 11:18:05 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2022-03-11 11:57:35 +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
|
|
|
}
|
|
|
|
|
2022-03-11 11:57:35 +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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|