This commit is contained in:
66
provider/lru/provider.go
Normal file
66
provider/lru/provider.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package lru
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
lru "github.com/hashicorp/golang-lru"
|
||||
"gitoa.ru/go-4devs/cache"
|
||||
)
|
||||
|
||||
// New create new lru cache provider.
|
||||
func New(client *lru.Cache) cache.Provider {
|
||||
return func(ctx context.Context, operation string, item *cache.Item) error {
|
||||
switch operation {
|
||||
case cache.OperationGet:
|
||||
val, ok := client.Get(item.Key)
|
||||
if !ok {
|
||||
return wrapErr(cache.ErrCacheMiss)
|
||||
}
|
||||
|
||||
it, _ := val.(expired)
|
||||
|
||||
if !it.ex.IsZero() {
|
||||
item.TTL = time.Until(it.ex)
|
||||
}
|
||||
|
||||
if item.IsExpired() {
|
||||
return wrapErr(cache.ErrCacheExpired)
|
||||
}
|
||||
|
||||
return wrapErr(cache.TypeAssert(it.value, item.Value))
|
||||
case cache.OperationSet:
|
||||
it := expired{
|
||||
value: item.Value,
|
||||
ex: time.Time{},
|
||||
}
|
||||
if item.TTL > 0 {
|
||||
it.ex = item.Expired()
|
||||
}
|
||||
|
||||
_ = client.Add(item.Key, it)
|
||||
|
||||
return nil
|
||||
case cache.OperationDelete:
|
||||
_ = client.Remove(item.Key)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return wrapErr(cache.ErrOperationNotAllwed)
|
||||
}
|
||||
}
|
||||
|
||||
type expired struct {
|
||||
ex time.Time
|
||||
value interface{}
|
||||
}
|
||||
|
||||
func wrapErr(err error) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: lru", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
18
provider/lru/provider_test.go
Normal file
18
provider/lru/provider_test.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package lru_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
glru "github.com/hashicorp/golang-lru"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gitoa.ru/go-4devs/cache/provider/lru"
|
||||
"gitoa.ru/go-4devs/cache/test"
|
||||
)
|
||||
|
||||
func TestEncoding(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client, err := glru.New(10)
|
||||
require.Nil(t, err)
|
||||
test.RunSute(t, lru.New(client))
|
||||
}
|
||||
Reference in New Issue
Block a user