first commit
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
andrey1s
2021-04-26 17:13:36 +03:00
commit 7da0cd57ce
45 changed files with 3703 additions and 0 deletions

View File

@@ -0,0 +1,69 @@
package ristretto
import (
"context"
"errors"
"fmt"
"github.com/dgraph-io/ristretto"
"gitoa.ru/go-4devs/cache"
)
var ErrSetValue = errors.New("failed set value")
type Option func(*setting)
func WithCost(cost int64) Option {
return func(s *setting) {
s.cost = cost
}
}
type setting struct {
cost int64
}
func New(retto *ristretto.Cache, opts ...Option) cache.Provider {
s := setting{
cost: 1,
}
for _, opt := range opts {
opt(&s)
}
return func(ctx context.Context, operation string, item *cache.Item) error {
var key interface{}
if item.Key.Prefix != "" {
key = item.Key.String()
} else {
key = item.Key.Key
}
switch operation {
case cache.OperationGet:
res, ok := retto.Get(key)
if !ok {
return fmt.Errorf("%w: ristretto", cache.ErrCacheMiss)
}
if err := cache.TypeAssert(res, item.Value); err != nil {
return fmt.Errorf("failed assert type: %w", err)
}
return nil
case cache.OperationDelete:
retto.Del(key)
return nil
case cache.OperationSet:
if ok := retto.SetWithTTL(key, item.Value, s.cost, item.TTL); !ok {
return ErrSetValue
}
return nil
}
return cache.ErrOperationNotAllwed
}
}

View File

@@ -0,0 +1,26 @@
package ristretto_test
import (
"testing"
"time"
"github.com/dgraph-io/ristretto"
"github.com/stretchr/testify/require"
"gitoa.ru/go-4devs/cache"
provider "gitoa.ru/go-4devs/cache/provider/ristretto"
"gitoa.ru/go-4devs/cache/test"
)
func TestRistretto(t *testing.T) {
t.Parallel()
retto, err := ristretto.NewCache(&ristretto.Config{
NumCounters: 1e7, // number of keys to track frequency of (10M).
MaxCost: 1 << 30, // maximum cost of cache (1GB).
BufferItems: 64, // number of keys per Get buffer.
})
require.Nil(t, err)
test.RunSute(t, provider.New(retto), test.WithWaitGet(func() {
time.Sleep(10 * time.Millisecond)
}), test.WithExpire(cache.ErrCacheMiss))
}