2021-10-25 12:57:55 +00:00
|
|
|
package pool
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
2022-02-16 06:57:14 +00:00
|
|
|
"sync/atomic"
|
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 {
|
2022-02-16 06:57:14 +00:00
|
|
|
cache *lru.Cache
|
|
|
|
currentEpoch uint64
|
2021-10-25 12:57:55 +00:00
|
|
|
}
|
|
|
|
|
2022-02-02 11:18:05 +00:00
|
|
|
type cacheValue struct {
|
|
|
|
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)
|
2022-02-16 06:57:14 +00:00
|
|
|
if c.expired(value) {
|
|
|
|
c.cache.Remove(key)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
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) Put(key string, token *session.Token) bool {
|
2022-02-02 11:18:05 +00:00
|
|
|
return c.cache.Add(key, &cacheValue{
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-02-16 06:57:14 +00:00
|
|
|
|
2022-04-05 09:15:13 +00:00
|
|
|
func (c *sessionCache) updateEpoch(newEpoch uint64) {
|
2022-02-16 06:57:14 +00:00
|
|
|
epoch := atomic.LoadUint64(&c.currentEpoch)
|
|
|
|
if newEpoch > epoch {
|
|
|
|
atomic.StoreUint64(&c.currentEpoch, newEpoch)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *sessionCache) expired(val *cacheValue) bool {
|
|
|
|
epoch := atomic.LoadUint64(&c.currentEpoch)
|
|
|
|
return val.token.Exp() <= epoch
|
|
|
|
}
|