lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
Vendored
+31
@@ -0,0 +1,31 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrCacheMiss = errors.New("cache miss")
|
||||
|
||||
type Cache interface {
|
||||
Get(ctx context.Context, key string) ([]byte, error)
|
||||
Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
|
||||
Delete(ctx context.Context, keys ...string) error
|
||||
Ping(ctx context.Context) error
|
||||
Close() error
|
||||
}
|
||||
|
||||
type NoOpCache struct{}
|
||||
|
||||
func (NoOpCache) Get(context.Context, string) ([]byte, error) { return nil, ErrCacheMiss }
|
||||
func (NoOpCache) Set(context.Context, string, []byte, time.Duration) error { return nil }
|
||||
func (NoOpCache) Delete(context.Context, ...string) error { return nil }
|
||||
func (NoOpCache) AcquireLock(context.Context, string, string, time.Duration) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (NoOpCache) ReleaseLock(context.Context, string, string) (bool, error) { return true, nil }
|
||||
func (NoOpCache) LockHeld(context.Context, string) (bool, error) { return false, nil }
|
||||
func (NoOpCache) Ping(context.Context) error { return nil }
|
||||
func (NoOpCache) Close() error { return nil }
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package cache_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
)
|
||||
|
||||
func TestNoOpCache(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := t.Context()
|
||||
store := cache.NoOpCache{}
|
||||
require.NoError(t, store.Set(ctx, "key", []byte("value"), time.Minute))
|
||||
_, err := store.Get(ctx, "key")
|
||||
require.ErrorIs(t, err, cache.ErrCacheMiss)
|
||||
require.NoError(t, store.Delete(ctx, "key"))
|
||||
acquired, err := store.AcquireLock(ctx, "lock", "token", time.Second)
|
||||
require.NoError(t, err)
|
||||
require.True(t, acquired)
|
||||
held, err := store.LockHeld(ctx, "lock")
|
||||
require.NoError(t, err)
|
||||
require.False(t, held)
|
||||
released, err := store.ReleaseLock(ctx, "lock", "token")
|
||||
require.NoError(t, err)
|
||||
require.True(t, released)
|
||||
require.NoError(t, store.Ping(ctx))
|
||||
require.NoError(t, store.Close())
|
||||
}
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
mathrand "math/rand/v2"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sync/singleflight"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultLockTTL = 10 * time.Second
|
||||
DefaultWaitTimeout = 2 * time.Second
|
||||
minLockTTL = time.Second
|
||||
redisOpTimeout = 200 * time.Millisecond
|
||||
releaseTimeout = 300 * time.Millisecond
|
||||
)
|
||||
|
||||
type DistributedConfig struct {
|
||||
LockTTL time.Duration
|
||||
WaitTimeout time.Duration
|
||||
}
|
||||
|
||||
type LockStore interface {
|
||||
Cache
|
||||
AcquireLock(ctx context.Context, key, token string, ttl time.Duration) (bool, error)
|
||||
ReleaseLock(ctx context.Context, key, token string) (bool, error)
|
||||
LockHeld(ctx context.Context, key string) (bool, error)
|
||||
}
|
||||
|
||||
type DistributedCache struct {
|
||||
store LockStore
|
||||
lockTTL time.Duration
|
||||
waitTimeout time.Duration
|
||||
log *slog.Logger
|
||||
group singleflight.Group
|
||||
}
|
||||
|
||||
var fallbackTokenCounter atomic.Uint64
|
||||
|
||||
func NewDistributed(store LockStore, cfg DistributedConfig, log *slog.Logger) (*DistributedCache, error) {
|
||||
if cfg.LockTTL <= 0 {
|
||||
cfg.LockTTL = DefaultLockTTL
|
||||
}
|
||||
|
||||
if cfg.WaitTimeout <= 0 {
|
||||
cfg.WaitTimeout = DefaultWaitTimeout
|
||||
}
|
||||
|
||||
if cfg.LockTTL <= minLockTTL {
|
||||
return nil, fmt.Errorf("cache: lock ttl %s must be greater than %s", cfg.LockTTL, minLockTTL)
|
||||
}
|
||||
|
||||
if cfg.WaitTimeout > cfg.LockTTL {
|
||||
return nil, fmt.Errorf("cache: wait timeout %s must not exceed lock ttl %s", cfg.WaitTimeout, cfg.LockTTL)
|
||||
}
|
||||
|
||||
return &DistributedCache{
|
||||
store: store,
|
||||
lockTTL: cfg.LockTTL,
|
||||
waitTimeout: cfg.WaitTimeout,
|
||||
log: log,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *DistributedCache) GetOrLoad(
|
||||
ctx context.Context,
|
||||
key string,
|
||||
ttl time.Duration,
|
||||
loader func(ctx context.Context) ([]byte, error),
|
||||
) ([]byte, error) {
|
||||
ch := d.group.DoChan(key, func() (any, error) {
|
||||
lctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), d.lockTTL+d.waitTimeout)
|
||||
defer cancel()
|
||||
|
||||
return d.getOrLoad(lctx, key, ttl, loader)
|
||||
})
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case result := <-ch:
|
||||
if result.Err != nil {
|
||||
return nil, result.Err
|
||||
}
|
||||
|
||||
value, ok := result.Val.([]byte)
|
||||
if !ok {
|
||||
return nil, errors.New("cache: unexpected singleflight result")
|
||||
}
|
||||
|
||||
return bytes.Clone(value), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (d *DistributedCache) getOrLoad(
|
||||
ctx context.Context,
|
||||
key string,
|
||||
ttl time.Duration,
|
||||
loader func(ctx context.Context) ([]byte, error),
|
||||
) ([]byte, error) {
|
||||
lockKey := "lock:" + key
|
||||
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if value, err := d.store.Get(ctx, key); err == nil {
|
||||
return value, nil
|
||||
} else if !errors.Is(err, ErrCacheMiss) {
|
||||
return loader(ctx)
|
||||
}
|
||||
|
||||
token := randomToken()
|
||||
|
||||
acquired, err := d.store.AcquireLock(ctx, lockKey, token, d.lockTTL)
|
||||
if err != nil {
|
||||
return loader(ctx)
|
||||
}
|
||||
|
||||
if acquired {
|
||||
return d.fill(ctx, key, lockKey, token, ttl, loader)
|
||||
}
|
||||
|
||||
value, outcome, err := d.await(ctx, key, lockKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch outcome {
|
||||
case waitHit:
|
||||
return value, nil
|
||||
case waitDegraded:
|
||||
return loader(ctx)
|
||||
case waitTimeout:
|
||||
return loader(ctx)
|
||||
case waitRetry:
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
case waitNone:
|
||||
return nil, errors.New("cache: unexpected wait outcome")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *DistributedCache) fill(
|
||||
ctx context.Context,
|
||||
key, lockKey, token string,
|
||||
ttl time.Duration,
|
||||
loader func(ctx context.Context) ([]byte, error),
|
||||
) ([]byte, error) {
|
||||
base := context.WithoutCancel(ctx)
|
||||
|
||||
defer func() {
|
||||
rctx, cancel := context.WithTimeout(base, releaseTimeout)
|
||||
defer cancel()
|
||||
|
||||
held, err := d.store.ReleaseLock(rctx, lockKey, token)
|
||||
switch {
|
||||
case err != nil:
|
||||
d.warn(base, "lock release failed", key, err)
|
||||
case !held:
|
||||
d.warn(base, "lock expired before release: loader slower than lock ttl", key, nil)
|
||||
}
|
||||
}()
|
||||
|
||||
getCtx, cancelGet := context.WithTimeout(base, redisOpTimeout)
|
||||
value, err := d.store.Get(getCtx, key)
|
||||
cancelGet()
|
||||
|
||||
if err == nil {
|
||||
return value, nil
|
||||
}
|
||||
|
||||
loadCtx, cancel := context.WithTimeout(base, d.lockTTL-minLockTTL)
|
||||
defer cancel()
|
||||
|
||||
value, err = loader(loadCtx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
setCtx, cancelSet := context.WithTimeout(base, redisOpTimeout)
|
||||
setErr := d.store.Set(setCtx, key, value, ttl)
|
||||
cancelSet()
|
||||
|
||||
if setErr != nil {
|
||||
d.warn(base, "distributed cache write failed", key, setErr)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
type waitOutcome int
|
||||
|
||||
const (
|
||||
waitNone waitOutcome = iota
|
||||
waitHit
|
||||
waitRetry
|
||||
waitTimeout
|
||||
waitDegraded
|
||||
)
|
||||
|
||||
func (d *DistributedCache) await(ctx context.Context, key, lockKey string) ([]byte, waitOutcome, error) {
|
||||
wctx, cancel := context.WithTimeout(ctx, d.waitTimeout)
|
||||
defer cancel()
|
||||
|
||||
for attempt := 1; ; attempt++ {
|
||||
value, err := d.store.Get(wctx, key)
|
||||
switch {
|
||||
case err == nil:
|
||||
return value, waitHit, nil
|
||||
case ctx.Err() != nil:
|
||||
return nil, waitNone, ctx.Err()
|
||||
case wctx.Err() != nil:
|
||||
return nil, waitTimeout, nil
|
||||
case !errors.Is(err, ErrCacheMiss):
|
||||
return nil, waitDegraded, nil
|
||||
}
|
||||
|
||||
if held, err := d.store.LockHeld(wctx, lockKey); err == nil && !held {
|
||||
return nil, waitRetry, nil
|
||||
}
|
||||
|
||||
select {
|
||||
case <-wctx.Done():
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, waitNone, err
|
||||
}
|
||||
|
||||
return nil, waitTimeout, nil
|
||||
case <-time.After(jittered(waitBackoff(attempt))):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *DistributedCache) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
return d.store.Get(ctx, key)
|
||||
}
|
||||
|
||||
func (d *DistributedCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
|
||||
return d.store.Set(ctx, key, value, ttl)
|
||||
}
|
||||
|
||||
func (d *DistributedCache) Delete(ctx context.Context, keys ...string) error {
|
||||
return d.store.Delete(ctx, keys...)
|
||||
}
|
||||
|
||||
func (d *DistributedCache) Ping(ctx context.Context) error {
|
||||
return d.store.Ping(ctx)
|
||||
}
|
||||
|
||||
func (d *DistributedCache) Close() error {
|
||||
return d.store.Close()
|
||||
}
|
||||
|
||||
func (d *DistributedCache) warn(ctx context.Context, msg, key string, err error) {
|
||||
if d.log == nil {
|
||||
return
|
||||
}
|
||||
|
||||
attrs := []slog.Attr{slog.String("key", key)}
|
||||
if err != nil {
|
||||
attrs = append(attrs, slog.Any("error", err))
|
||||
}
|
||||
|
||||
d.log.LogAttrs(ctx, slog.LevelWarn, msg, attrs...)
|
||||
}
|
||||
|
||||
func waitBackoff(attempt int) time.Duration {
|
||||
const base, maxWait = 50 * time.Millisecond, 500 * time.Millisecond
|
||||
if attempt > 4 {
|
||||
return maxWait
|
||||
}
|
||||
|
||||
return base << (attempt - 1)
|
||||
}
|
||||
|
||||
func jittered(d time.Duration) time.Duration {
|
||||
half := d / 2
|
||||
if half <= 0 {
|
||||
return d
|
||||
}
|
||||
|
||||
return half + mathrand.N(half)
|
||||
}
|
||||
|
||||
func randomToken() string {
|
||||
raw := make([]byte, 16)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
counter := fallbackTokenCounter.Add(1)
|
||||
|
||||
return strconv.FormatInt(time.Now().UnixNano(), 10) + ":" + strconv.FormatUint(counter, 10)
|
||||
}
|
||||
|
||||
return hex.EncodeToString(raw)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/platform/cache/mocks"
|
||||
)
|
||||
|
||||
func TestAwaitChecksCacheBeforePolling(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
store.EXPECT().Get(mock.Anything, "key").Return([]byte("ready"), nil).Once()
|
||||
|
||||
d, err := NewDistributed(store, DistributedConfig{WaitTimeout: time.Second}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
started := time.Now()
|
||||
value, outcome, err := d.await(t.Context(), "key", "lock:key")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, waitHit, outcome)
|
||||
require.Equal(t, "ready", string(value))
|
||||
require.Less(t, time.Since(started), 25*time.Millisecond, "cache must be checked before the first sleep")
|
||||
}
|
||||
|
||||
func TestAwaitReturnsTimeoutWhileLockHeld(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
store.EXPECT().Get(mock.Anything, "key").Return(nil, ErrCacheMiss).Maybe()
|
||||
store.EXPECT().LockHeld(mock.Anything, "lock:key").Return(true, nil).Maybe()
|
||||
|
||||
d, err := NewDistributed(store, DistributedConfig{WaitTimeout: 60 * time.Millisecond}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, outcome, err := d.await(t.Context(), "key", "lock:key")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, waitTimeout, outcome)
|
||||
}
|
||||
+374
@@ -0,0 +1,374 @@
|
||||
package cache_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
"mtusi-messenger/internal/platform/cache/mocks"
|
||||
)
|
||||
|
||||
func newDistributed(t *testing.T, store cache.LockStore, cfg cache.DistributedConfig) *cache.DistributedCache {
|
||||
t.Helper()
|
||||
|
||||
dc, err := cache.NewDistributed(store, cfg, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
return dc
|
||||
}
|
||||
|
||||
func expectFill(store *mocks.MockLockStore, key string) {
|
||||
store.EXPECT().Get(mock.Anything, key).Return(nil, cache.ErrCacheMiss).Once()
|
||||
store.EXPECT().AcquireLock(mock.Anything, "lock:"+key, mock.AnythingOfType("string"), mock.Anything).Return(true, nil).Once()
|
||||
store.EXPECT().Get(mock.Anything, key).Return(nil, cache.ErrCacheMiss).Once()
|
||||
store.EXPECT().Set(mock.Anything, key, mock.Anything, mock.Anything).Return(nil).Once()
|
||||
store.EXPECT().ReleaseLock(mock.Anything, "lock:"+key, mock.AnythingOfType("string")).Return(true, nil).Once()
|
||||
}
|
||||
|
||||
// sharedWaitTimeout bounds every wait in these tests: a stuck helper must fail
|
||||
// the test instead of hanging the whole package until -timeout fires.
|
||||
const sharedWaitTimeout = 5 * time.Second
|
||||
|
||||
func awaitSignal(t *testing.T, ch <-chan struct{}, message string) {
|
||||
t.Helper()
|
||||
|
||||
select {
|
||||
case <-ch:
|
||||
case <-time.After(sharedWaitTimeout):
|
||||
t.Fatal("timed out: " + message)
|
||||
}
|
||||
}
|
||||
|
||||
func awaitValue[T any](t *testing.T, ch <-chan T) T {
|
||||
t.Helper()
|
||||
|
||||
select {
|
||||
case value := <-ch:
|
||||
return value
|
||||
case <-time.After(sharedWaitTimeout):
|
||||
var zero T
|
||||
|
||||
t.Fatal("timed out waiting for the shared load to report its result")
|
||||
|
||||
return zero
|
||||
}
|
||||
}
|
||||
|
||||
func awaitWaitGroup(t *testing.T, wg *sync.WaitGroup) {
|
||||
t.Helper()
|
||||
|
||||
done := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(done)
|
||||
}()
|
||||
|
||||
awaitSignal(t, done, "goroutines did not finish")
|
||||
}
|
||||
|
||||
func TestDistributedCachesResult(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
dc := newDistributed(t, store, cache.DistributedConfig{})
|
||||
ctx := context.Background()
|
||||
|
||||
var calls atomic.Int32
|
||||
|
||||
loader := func(context.Context) ([]byte, error) {
|
||||
calls.Add(1)
|
||||
|
||||
return []byte("payload"), nil
|
||||
}
|
||||
|
||||
expectFill(store, "key")
|
||||
store.EXPECT().Get(mock.Anything, "key").Return([]byte("payload"), nil).Once()
|
||||
|
||||
first, err := dc.GetOrLoad(ctx, "key", time.Minute, loader)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte("payload"), first)
|
||||
|
||||
second, err := dc.GetOrLoad(ctx, "key", time.Minute, loader)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte("payload"), second)
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
}
|
||||
|
||||
func TestDistributedDeduplicatesConcurrentMisses(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
dc := newDistributed(t, store, cache.DistributedConfig{})
|
||||
ctx := context.Background()
|
||||
|
||||
var calls atomic.Int32
|
||||
|
||||
loader := func(context.Context) ([]byte, error) {
|
||||
calls.Add(1)
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
|
||||
return []byte("payload"), nil
|
||||
}
|
||||
|
||||
store.EXPECT().Get(mock.Anything, "shared").Return(nil, cache.ErrCacheMiss).Twice()
|
||||
store.EXPECT().AcquireLock(mock.Anything, "lock:shared", mock.AnythingOfType("string"), mock.Anything).Return(true, nil).Once()
|
||||
store.EXPECT().Set(mock.Anything, "shared", mock.Anything, mock.Anything).Return(nil).Once()
|
||||
store.EXPECT().ReleaseLock(mock.Anything, "lock:shared", mock.AnythingOfType("string")).Return(true, nil).Once()
|
||||
|
||||
const workers = 50
|
||||
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
failures atomic.Int32
|
||||
)
|
||||
|
||||
wg.Add(workers)
|
||||
|
||||
for range workers {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
value, err := dc.GetOrLoad(ctx, "shared", time.Minute, loader)
|
||||
if err != nil || string(value) != "payload" {
|
||||
failures.Add(1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
awaitWaitGroup(t, &wg)
|
||||
|
||||
require.Zero(t, failures.Load())
|
||||
require.Equal(t, int32(1), calls.Load(), "one instance must load once for concurrent misses")
|
||||
}
|
||||
|
||||
func TestDistributedFallsBackOnWaitTimeout(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
dc := newDistributed(t, store, cache.DistributedConfig{WaitTimeout: 100 * time.Millisecond})
|
||||
ctx := context.Background()
|
||||
|
||||
store.EXPECT().Get(mock.Anything, "key").Return(nil, cache.ErrCacheMiss).Maybe()
|
||||
store.EXPECT().AcquireLock(mock.Anything, "lock:key", mock.AnythingOfType("string"), mock.Anything).Return(false, nil).Once()
|
||||
store.EXPECT().LockHeld(mock.Anything, "lock:key").Return(true, nil).Maybe()
|
||||
|
||||
var calls atomic.Int32
|
||||
|
||||
value, err := dc.GetOrLoad(ctx, "key", time.Minute, func(context.Context) ([]byte, error) {
|
||||
calls.Add(1)
|
||||
|
||||
return []byte("fallback"), nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte("fallback"), value)
|
||||
require.Equal(t, int32(1), calls.Load(), "a wait timeout must fall back to a direct load")
|
||||
}
|
||||
|
||||
func TestDistributedSharedLoadSurvivesCallerCancellation(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
dc := newDistributed(t, store, cache.DistributedConfig{})
|
||||
leaderCtx, cancelLeader := context.WithCancel(context.Background())
|
||||
defer cancelLeader()
|
||||
|
||||
var calls atomic.Int32
|
||||
|
||||
started := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
|
||||
loader := func(loadCtx context.Context) ([]byte, error) {
|
||||
calls.Add(1)
|
||||
close(started)
|
||||
<-release
|
||||
|
||||
if err := loadCtx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return []byte("value"), nil
|
||||
}
|
||||
|
||||
store.EXPECT().Get(mock.Anything, "key").Return(nil, cache.ErrCacheMiss).Twice()
|
||||
store.EXPECT().AcquireLock(mock.Anything, "lock:key", mock.AnythingOfType("string"), mock.Anything).Return(true, nil).Once()
|
||||
store.EXPECT().Set(mock.Anything, "key", mock.Anything, mock.Anything).Return(nil).Once()
|
||||
store.EXPECT().ReleaseLock(mock.Anything, "lock:key", mock.AnythingOfType("string")).Return(true, nil).Once()
|
||||
|
||||
leaderErr := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
_, err := dc.GetOrLoad(leaderCtx, "key", time.Minute, loader)
|
||||
leaderErr <- err
|
||||
}()
|
||||
|
||||
awaitSignal(t, started, "leader must reach the loader")
|
||||
|
||||
// The follower starts while the leader's loader is still blocked, so the
|
||||
// singleflight call cannot complete: the signal below means DoChan was
|
||||
// already called, i.e. the follower joined the leader's in-flight call
|
||||
// instead of starting its own load.
|
||||
followerJoined := make(chan struct{})
|
||||
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
followerV []byte
|
||||
followerE error
|
||||
)
|
||||
|
||||
wg.Add(1)
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
ctx := newJoiningContext(followerJoined)
|
||||
followerV, followerE = dc.GetOrLoad(ctx, "key", time.Minute, loader)
|
||||
}()
|
||||
|
||||
awaitSignal(t, followerJoined, "follower must join the in-flight load")
|
||||
|
||||
cancelLeader()
|
||||
close(release)
|
||||
|
||||
require.ErrorIs(t, awaitValue(t, leaderErr), context.Canceled)
|
||||
awaitWaitGroup(t, &wg)
|
||||
|
||||
require.NoError(t, followerE)
|
||||
require.Equal(t, []byte("value"), followerV)
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
}
|
||||
|
||||
// joiningContext reports when GetOrLoad reaches the shared-result wait path. The
|
||||
// delegate is kept as function fields so no struct holds a context.Context.
|
||||
type joiningContext struct {
|
||||
deadline func() (time.Time, bool)
|
||||
done func() <-chan struct{}
|
||||
err func() error
|
||||
value func(any) any
|
||||
|
||||
once *sync.Once
|
||||
joined chan struct{}
|
||||
}
|
||||
|
||||
func newJoiningContext(joined chan struct{}) joiningContext {
|
||||
base := context.Background()
|
||||
|
||||
return joiningContext{
|
||||
deadline: base.Deadline,
|
||||
done: base.Done,
|
||||
err: base.Err,
|
||||
value: base.Value,
|
||||
once: new(sync.Once),
|
||||
joined: joined,
|
||||
}
|
||||
}
|
||||
|
||||
func (c joiningContext) Deadline() (time.Time, bool) { return c.deadline() }
|
||||
|
||||
func (c joiningContext) Done() <-chan struct{} {
|
||||
c.once.Do(func() { close(c.joined) })
|
||||
|
||||
return c.done()
|
||||
}
|
||||
|
||||
func (c joiningContext) Err() error { return c.err() }
|
||||
|
||||
func (c joiningContext) Value(key any) any { return c.value(key) }
|
||||
|
||||
func TestDistributedRetriesWhenLockVanishes(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
dc := newDistributed(t, store, cache.DistributedConfig{})
|
||||
ctx := context.Background()
|
||||
|
||||
var released atomic.Bool
|
||||
|
||||
time.AfterFunc(120*time.Millisecond, func() { released.Store(true) })
|
||||
|
||||
store.EXPECT().Get(mock.Anything, "key").Return(nil, cache.ErrCacheMiss).Maybe()
|
||||
store.EXPECT().AcquireLock(mock.Anything, "lock:key", mock.AnythingOfType("string"), mock.Anything).Return(false, nil).Once()
|
||||
store.EXPECT().AcquireLock(mock.Anything, "lock:key", mock.AnythingOfType("string"), mock.Anything).Return(true, nil).Once()
|
||||
store.EXPECT().LockHeld(mock.Anything, "lock:key").RunAndReturn(func(context.Context, string) (bool, error) {
|
||||
return !released.Load(), nil
|
||||
}).Maybe()
|
||||
store.EXPECT().Set(mock.Anything, "key", mock.Anything, mock.Anything).Return(nil).Once()
|
||||
store.EXPECT().ReleaseLock(mock.Anything, "lock:key", mock.AnythingOfType("string")).Return(true, nil).Once()
|
||||
|
||||
var calls atomic.Int32
|
||||
|
||||
value, err := dc.GetOrLoad(ctx, "key", time.Minute, func(context.Context) ([]byte, error) {
|
||||
calls.Add(1)
|
||||
|
||||
return []byte("recovered"), nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte("recovered"), value)
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
}
|
||||
|
||||
func TestFillStoreCallsAreBoundedByDeadline(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
dc := newDistributed(t, store, cache.DistributedConfig{})
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
getBudgets []time.Duration
|
||||
setBudget time.Duration
|
||||
setHasDead bool
|
||||
)
|
||||
|
||||
store.EXPECT().Get(mock.Anything, "key").RunAndReturn(func(ctx context.Context, _ string) ([]byte, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
if deadline, ok := ctx.Deadline(); ok {
|
||||
getBudgets = append(getBudgets, time.Until(deadline))
|
||||
}
|
||||
|
||||
return nil, cache.ErrCacheMiss
|
||||
}).Twice()
|
||||
store.EXPECT().AcquireLock(mock.Anything, "lock:key", mock.AnythingOfType("string"), mock.Anything).Return(true, nil).Once()
|
||||
store.EXPECT().Set(mock.Anything, "key", mock.Anything, mock.Anything).
|
||||
RunAndReturn(func(ctx context.Context, _ string, _ []byte, _ time.Duration) error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
deadline, ok := ctx.Deadline()
|
||||
setHasDead = ok
|
||||
if ok {
|
||||
setBudget = time.Until(deadline)
|
||||
}
|
||||
|
||||
return nil
|
||||
}).Once()
|
||||
store.EXPECT().ReleaseLock(mock.Anything, "lock:key", mock.AnythingOfType("string")).Return(true, nil).Once()
|
||||
|
||||
_, err := dc.GetOrLoad(context.Background(), "key", time.Minute, func(context.Context) ([]byte, error) {
|
||||
return []byte("value"), nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
require.True(t, setHasDead, "Set must receive a bounded context")
|
||||
require.LessOrEqual(t, setBudget, 300*time.Millisecond)
|
||||
|
||||
minGetBudget := time.Hour
|
||||
for _, budget := range getBudgets {
|
||||
if budget < minGetBudget {
|
||||
minGetBudget = budget
|
||||
}
|
||||
}
|
||||
|
||||
require.LessOrEqual(t, minGetBudget, 300*time.Millisecond, "fill's Get must receive a bounded context")
|
||||
}
|
||||
+346
@@ -0,0 +1,346 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockCache creates a new instance of MockCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockCache(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockCache {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockCache{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockCache is an autogenerated mock type for the Cache type
|
||||
type MockCache struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockCache_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockCache) EXPECT() *MockCache_Expecter {
|
||||
return &MockCache_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Close provides a mock function for the type MockCache
|
||||
func (_mock *MockCache) Close() error {
|
||||
ret := _mock.Called()
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Close")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func() error); ok {
|
||||
r0 = returnFunc()
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockCache_Close_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Close'
|
||||
type MockCache_Close_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Close is a helper method to define mock.On call
|
||||
func (_e *MockCache_Expecter) Close() *MockCache_Close_Call {
|
||||
return &MockCache_Close_Call{Call: _e.mock.On("Close")}
|
||||
}
|
||||
|
||||
func (_c *MockCache_Close_Call) Run(run func()) *MockCache_Close_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run()
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Close_Call) Return(err error) *MockCache_Close_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Close_Call) RunAndReturn(run func() error) *MockCache_Close_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Delete provides a mock function for the type MockCache
|
||||
func (_mock *MockCache) Delete(ctx context.Context, keys ...string) error {
|
||||
var tmpRet mock.Arguments
|
||||
if len(keys) > 0 {
|
||||
tmpRet = _mock.Called(ctx, keys)
|
||||
} else {
|
||||
tmpRet = _mock.Called(ctx)
|
||||
}
|
||||
ret := tmpRet
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Delete")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, ...string) error); ok {
|
||||
r0 = returnFunc(ctx, keys...)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockCache_Delete_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Delete'
|
||||
type MockCache_Delete_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Delete is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - keys ...string
|
||||
func (_e *MockCache_Expecter) Delete(ctx any, keys ...any) *MockCache_Delete_Call {
|
||||
return &MockCache_Delete_Call{Call: _e.mock.On("Delete",
|
||||
append([]any{ctx}, keys...)...)}
|
||||
}
|
||||
|
||||
func (_c *MockCache_Delete_Call) Run(run func(ctx context.Context, keys ...string)) *MockCache_Delete_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 []string
|
||||
var variadicArgs []string
|
||||
if len(args) > 1 {
|
||||
variadicArgs = args[1].([]string)
|
||||
}
|
||||
arg1 = variadicArgs
|
||||
run(
|
||||
arg0,
|
||||
arg1...,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Delete_Call) Return(err error) *MockCache_Delete_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Delete_Call) RunAndReturn(run func(ctx context.Context, keys ...string) error) *MockCache_Delete_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Get provides a mock function for the type MockCache
|
||||
func (_mock *MockCache) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
ret := _mock.Called(ctx, key)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Get")
|
||||
}
|
||||
|
||||
var r0 []byte
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) ([]byte, error)); ok {
|
||||
return returnFunc(ctx, key)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) []byte); ok {
|
||||
r0 = returnFunc(ctx, key)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]byte)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
|
||||
r1 = returnFunc(ctx, key)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockCache_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get'
|
||||
type MockCache_Get_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Get is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - key string
|
||||
func (_e *MockCache_Expecter) Get(ctx any, key any) *MockCache_Get_Call {
|
||||
return &MockCache_Get_Call{Call: _e.mock.On("Get", ctx, key)}
|
||||
}
|
||||
|
||||
func (_c *MockCache_Get_Call) Run(run func(ctx context.Context, key string)) *MockCache_Get_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Get_Call) Return(bytes []byte, err error) *MockCache_Get_Call {
|
||||
_c.Call.Return(bytes, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Get_Call) RunAndReturn(run func(ctx context.Context, key string) ([]byte, error)) *MockCache_Get_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Ping provides a mock function for the type MockCache
|
||||
func (_mock *MockCache) Ping(ctx context.Context) error {
|
||||
ret := _mock.Called(ctx)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Ping")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context) error); ok {
|
||||
r0 = returnFunc(ctx)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockCache_Ping_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ping'
|
||||
type MockCache_Ping_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Ping is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
func (_e *MockCache_Expecter) Ping(ctx any) *MockCache_Ping_Call {
|
||||
return &MockCache_Ping_Call{Call: _e.mock.On("Ping", ctx)}
|
||||
}
|
||||
|
||||
func (_c *MockCache_Ping_Call) Run(run func(ctx context.Context)) *MockCache_Ping_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Ping_Call) Return(err error) *MockCache_Ping_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Ping_Call) RunAndReturn(run func(ctx context.Context) error) *MockCache_Ping_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Set provides a mock function for the type MockCache
|
||||
func (_mock *MockCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
|
||||
ret := _mock.Called(ctx, key, value, ttl)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Set")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, []byte, time.Duration) error); ok {
|
||||
r0 = returnFunc(ctx, key, value, ttl)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockCache_Set_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Set'
|
||||
type MockCache_Set_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Set is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - key string
|
||||
// - value []byte
|
||||
// - ttl time.Duration
|
||||
func (_e *MockCache_Expecter) Set(ctx any, key any, value any, ttl any) *MockCache_Set_Call {
|
||||
return &MockCache_Set_Call{Call: _e.mock.On("Set", ctx, key, value, ttl)}
|
||||
}
|
||||
|
||||
func (_c *MockCache_Set_Call) Run(run func(ctx context.Context, key string, value []byte, ttl time.Duration)) *MockCache_Set_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
var arg2 []byte
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].([]byte)
|
||||
}
|
||||
var arg3 time.Duration
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(time.Duration)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Set_Call) Return(err error) *MockCache_Set_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Set_Call) RunAndReturn(run func(ctx context.Context, key string, value []byte, ttl time.Duration) error) *MockCache_Set_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
+562
@@ -0,0 +1,562 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockLockStore creates a new instance of MockLockStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockLockStore(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockLockStore {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockLockStore{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockLockStore is an autogenerated mock type for the LockStore type
|
||||
type MockLockStore struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockLockStore_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockLockStore) EXPECT() *MockLockStore_Expecter {
|
||||
return &MockLockStore_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// AcquireLock provides a mock function for the type MockLockStore
|
||||
func (_mock *MockLockStore) AcquireLock(ctx context.Context, key string, token string, ttl time.Duration) (bool, error) {
|
||||
ret := _mock.Called(ctx, key, token, ttl)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for AcquireLock")
|
||||
}
|
||||
|
||||
var r0 bool
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, string, time.Duration) (bool, error)); ok {
|
||||
return returnFunc(ctx, key, token, ttl)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, string, time.Duration) bool); ok {
|
||||
r0 = returnFunc(ctx, key, token, ttl)
|
||||
} else {
|
||||
r0 = ret.Get(0).(bool)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string, string, time.Duration) error); ok {
|
||||
r1 = returnFunc(ctx, key, token, ttl)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockLockStore_AcquireLock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AcquireLock'
|
||||
type MockLockStore_AcquireLock_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// AcquireLock is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - key string
|
||||
// - token string
|
||||
// - ttl time.Duration
|
||||
func (_e *MockLockStore_Expecter) AcquireLock(ctx any, key any, token any, ttl any) *MockLockStore_AcquireLock_Call {
|
||||
return &MockLockStore_AcquireLock_Call{Call: _e.mock.On("AcquireLock", ctx, key, token, ttl)}
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_AcquireLock_Call) Run(run func(ctx context.Context, key string, token string, ttl time.Duration)) *MockLockStore_AcquireLock_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
var arg2 string
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(string)
|
||||
}
|
||||
var arg3 time.Duration
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(time.Duration)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_AcquireLock_Call) Return(b bool, err error) *MockLockStore_AcquireLock_Call {
|
||||
_c.Call.Return(b, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_AcquireLock_Call) RunAndReturn(run func(ctx context.Context, key string, token string, ttl time.Duration) (bool, error)) *MockLockStore_AcquireLock_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Close provides a mock function for the type MockLockStore
|
||||
func (_mock *MockLockStore) Close() error {
|
||||
ret := _mock.Called()
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Close")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func() error); ok {
|
||||
r0 = returnFunc()
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockLockStore_Close_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Close'
|
||||
type MockLockStore_Close_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Close is a helper method to define mock.On call
|
||||
func (_e *MockLockStore_Expecter) Close() *MockLockStore_Close_Call {
|
||||
return &MockLockStore_Close_Call{Call: _e.mock.On("Close")}
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Close_Call) Run(run func()) *MockLockStore_Close_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run()
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Close_Call) Return(err error) *MockLockStore_Close_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Close_Call) RunAndReturn(run func() error) *MockLockStore_Close_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Delete provides a mock function for the type MockLockStore
|
||||
func (_mock *MockLockStore) Delete(ctx context.Context, keys ...string) error {
|
||||
var tmpRet mock.Arguments
|
||||
if len(keys) > 0 {
|
||||
tmpRet = _mock.Called(ctx, keys)
|
||||
} else {
|
||||
tmpRet = _mock.Called(ctx)
|
||||
}
|
||||
ret := tmpRet
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Delete")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, ...string) error); ok {
|
||||
r0 = returnFunc(ctx, keys...)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockLockStore_Delete_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Delete'
|
||||
type MockLockStore_Delete_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Delete is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - keys ...string
|
||||
func (_e *MockLockStore_Expecter) Delete(ctx any, keys ...any) *MockLockStore_Delete_Call {
|
||||
return &MockLockStore_Delete_Call{Call: _e.mock.On("Delete",
|
||||
append([]any{ctx}, keys...)...)}
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Delete_Call) Run(run func(ctx context.Context, keys ...string)) *MockLockStore_Delete_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 []string
|
||||
var variadicArgs []string
|
||||
if len(args) > 1 {
|
||||
variadicArgs = args[1].([]string)
|
||||
}
|
||||
arg1 = variadicArgs
|
||||
run(
|
||||
arg0,
|
||||
arg1...,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Delete_Call) Return(err error) *MockLockStore_Delete_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Delete_Call) RunAndReturn(run func(ctx context.Context, keys ...string) error) *MockLockStore_Delete_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Get provides a mock function for the type MockLockStore
|
||||
func (_mock *MockLockStore) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
ret := _mock.Called(ctx, key)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Get")
|
||||
}
|
||||
|
||||
var r0 []byte
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) ([]byte, error)); ok {
|
||||
return returnFunc(ctx, key)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) []byte); ok {
|
||||
r0 = returnFunc(ctx, key)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]byte)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
|
||||
r1 = returnFunc(ctx, key)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockLockStore_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get'
|
||||
type MockLockStore_Get_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Get is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - key string
|
||||
func (_e *MockLockStore_Expecter) Get(ctx any, key any) *MockLockStore_Get_Call {
|
||||
return &MockLockStore_Get_Call{Call: _e.mock.On("Get", ctx, key)}
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Get_Call) Run(run func(ctx context.Context, key string)) *MockLockStore_Get_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Get_Call) Return(bytes []byte, err error) *MockLockStore_Get_Call {
|
||||
_c.Call.Return(bytes, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Get_Call) RunAndReturn(run func(ctx context.Context, key string) ([]byte, error)) *MockLockStore_Get_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// LockHeld provides a mock function for the type MockLockStore
|
||||
func (_mock *MockLockStore) LockHeld(ctx context.Context, key string) (bool, error) {
|
||||
ret := _mock.Called(ctx, key)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for LockHeld")
|
||||
}
|
||||
|
||||
var r0 bool
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) (bool, error)); ok {
|
||||
return returnFunc(ctx, key)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) bool); ok {
|
||||
r0 = returnFunc(ctx, key)
|
||||
} else {
|
||||
r0 = ret.Get(0).(bool)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
|
||||
r1 = returnFunc(ctx, key)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockLockStore_LockHeld_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LockHeld'
|
||||
type MockLockStore_LockHeld_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// LockHeld is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - key string
|
||||
func (_e *MockLockStore_Expecter) LockHeld(ctx any, key any) *MockLockStore_LockHeld_Call {
|
||||
return &MockLockStore_LockHeld_Call{Call: _e.mock.On("LockHeld", ctx, key)}
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_LockHeld_Call) Run(run func(ctx context.Context, key string)) *MockLockStore_LockHeld_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_LockHeld_Call) Return(b bool, err error) *MockLockStore_LockHeld_Call {
|
||||
_c.Call.Return(b, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_LockHeld_Call) RunAndReturn(run func(ctx context.Context, key string) (bool, error)) *MockLockStore_LockHeld_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Ping provides a mock function for the type MockLockStore
|
||||
func (_mock *MockLockStore) Ping(ctx context.Context) error {
|
||||
ret := _mock.Called(ctx)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Ping")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context) error); ok {
|
||||
r0 = returnFunc(ctx)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockLockStore_Ping_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ping'
|
||||
type MockLockStore_Ping_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Ping is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
func (_e *MockLockStore_Expecter) Ping(ctx any) *MockLockStore_Ping_Call {
|
||||
return &MockLockStore_Ping_Call{Call: _e.mock.On("Ping", ctx)}
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Ping_Call) Run(run func(ctx context.Context)) *MockLockStore_Ping_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Ping_Call) Return(err error) *MockLockStore_Ping_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Ping_Call) RunAndReturn(run func(ctx context.Context) error) *MockLockStore_Ping_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ReleaseLock provides a mock function for the type MockLockStore
|
||||
func (_mock *MockLockStore) ReleaseLock(ctx context.Context, key string, token string) (bool, error) {
|
||||
ret := _mock.Called(ctx, key, token)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ReleaseLock")
|
||||
}
|
||||
|
||||
var r0 bool
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, string) (bool, error)); ok {
|
||||
return returnFunc(ctx, key, token)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, string) bool); ok {
|
||||
r0 = returnFunc(ctx, key, token)
|
||||
} else {
|
||||
r0 = ret.Get(0).(bool)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string, string) error); ok {
|
||||
r1 = returnFunc(ctx, key, token)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockLockStore_ReleaseLock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReleaseLock'
|
||||
type MockLockStore_ReleaseLock_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ReleaseLock is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - key string
|
||||
// - token string
|
||||
func (_e *MockLockStore_Expecter) ReleaseLock(ctx any, key any, token any) *MockLockStore_ReleaseLock_Call {
|
||||
return &MockLockStore_ReleaseLock_Call{Call: _e.mock.On("ReleaseLock", ctx, key, token)}
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_ReleaseLock_Call) Run(run func(ctx context.Context, key string, token string)) *MockLockStore_ReleaseLock_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
var arg2 string
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_ReleaseLock_Call) Return(b bool, err error) *MockLockStore_ReleaseLock_Call {
|
||||
_c.Call.Return(b, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_ReleaseLock_Call) RunAndReturn(run func(ctx context.Context, key string, token string) (bool, error)) *MockLockStore_ReleaseLock_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Set provides a mock function for the type MockLockStore
|
||||
func (_mock *MockLockStore) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
|
||||
ret := _mock.Called(ctx, key, value, ttl)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Set")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, []byte, time.Duration) error); ok {
|
||||
r0 = returnFunc(ctx, key, value, ttl)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockLockStore_Set_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Set'
|
||||
type MockLockStore_Set_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Set is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - key string
|
||||
// - value []byte
|
||||
// - ttl time.Duration
|
||||
func (_e *MockLockStore_Expecter) Set(ctx any, key any, value any, ttl any) *MockLockStore_Set_Call {
|
||||
return &MockLockStore_Set_Call{Call: _e.mock.On("Set", ctx, key, value, ttl)}
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Set_Call) Run(run func(ctx context.Context, key string, value []byte, ttl time.Duration)) *MockLockStore_Set_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
var arg2 []byte
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].([]byte)
|
||||
}
|
||||
var arg3 time.Duration
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(time.Duration)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Set_Call) Return(err error) *MockLockStore_Set_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Set_Call) RunAndReturn(run func(ctx context.Context, key string, value []byte, ttl time.Duration) error) *MockLockStore_Set_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
Vendored
+152
@@ -0,0 +1,152 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi-messenger/internal/platform/tlsconfig"
|
||||
)
|
||||
|
||||
type RedisConfig struct {
|
||||
Host string
|
||||
Port int
|
||||
Username string
|
||||
Password string
|
||||
DB int
|
||||
MaxRetries int
|
||||
DialTimeout time.Duration
|
||||
ReadTimeout time.Duration
|
||||
WriteTimeout time.Duration
|
||||
PoolSize int
|
||||
}
|
||||
|
||||
type RedisCache struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewRedis(ctx context.Context, cfg RedisConfig) (*RedisCache, error) {
|
||||
if cfg.Username == "" || cfg.Password == "" {
|
||||
return nil, errors.New("redis: username and password are required")
|
||||
}
|
||||
clientTLS, err := tlsconfig.NewClientFromEnv(cfg.Host)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("configure redis tls: %w", err)
|
||||
}
|
||||
opts := newClientOptions(cfg)
|
||||
opts.TLSConfig = clientTLS
|
||||
client := redis.NewClient(opts)
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(ctx, cfg.DialTimeout)
|
||||
defer cancel()
|
||||
|
||||
if err := client.Ping(pingCtx).Err(); err != nil {
|
||||
_ = client.Close()
|
||||
|
||||
return nil, fmt.Errorf("ping redis: %w", err)
|
||||
}
|
||||
|
||||
return &RedisCache{client: client}, nil
|
||||
}
|
||||
|
||||
func newClientOptions(cfg RedisConfig) *redis.Options {
|
||||
return &redis.Options{
|
||||
Addr: net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port)),
|
||||
Username: cfg.Username,
|
||||
Password: cfg.Password,
|
||||
DB: cfg.DB,
|
||||
MaxRetries: cfg.MaxRetries,
|
||||
DialTimeout: cfg.DialTimeout,
|
||||
ReadTimeout: cfg.ReadTimeout,
|
||||
WriteTimeout: cfg.WriteTimeout,
|
||||
PoolSize: cfg.PoolSize,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RedisCache) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
value, err := r.client.Get(ctx, key).Bytes()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return nil, ErrCacheMiss
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("redis get %q: %w", key, err)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (r *RedisCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
|
||||
if err := r.client.Set(ctx, key, value, ttl).Err(); err != nil {
|
||||
return fmt.Errorf("redis set %q: %w", key, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RedisCache) Delete(ctx context.Context, keys ...string) error {
|
||||
if len(keys) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := r.client.Del(ctx, keys...).Err(); err != nil {
|
||||
return fmt.Errorf("redis delete: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var releaseLockScript = redis.NewScript(`
|
||||
if redis.call("GET", KEYS[1]) == ARGV[1] then
|
||||
return redis.call("DEL", KEYS[1])
|
||||
end
|
||||
return 0
|
||||
`)
|
||||
|
||||
func (r *RedisCache) AcquireLock(ctx context.Context, key, token string, ttl time.Duration) (bool, error) {
|
||||
acquired, err := r.client.SetNX(ctx, key, token, ttl).Result()
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("redis acquire lock %q: %w", key, err)
|
||||
}
|
||||
|
||||
return acquired, nil
|
||||
}
|
||||
|
||||
func (r *RedisCache) ReleaseLock(ctx context.Context, key, token string) (bool, error) {
|
||||
deleted, err := releaseLockScript.Run(ctx, r.client, []string{key}, token).Int64()
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("redis release lock %q: %w", key, err)
|
||||
}
|
||||
|
||||
return deleted > 0, nil
|
||||
}
|
||||
|
||||
func (r *RedisCache) LockHeld(ctx context.Context, key string) (bool, error) {
|
||||
exists, err := r.client.Exists(ctx, key).Result()
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("redis check lock %q: %w", key, err)
|
||||
}
|
||||
|
||||
return exists > 0, nil
|
||||
}
|
||||
|
||||
func (r *RedisCache) Ping(ctx context.Context) error {
|
||||
if err := r.client.Ping(ctx).Err(); err != nil {
|
||||
return fmt.Errorf("redis ping: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RedisCache) Close() error {
|
||||
if err := r.client.Close(); err != nil {
|
||||
return fmt.Errorf("redis close: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNewClientOptionsAppliesTimeoutsAndRetries(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := redis.NewClient(newClientOptions(RedisConfig{
|
||||
Host: "localhost",
|
||||
Port: 6379,
|
||||
MaxRetries: -1,
|
||||
DialTimeout: 300 * time.Millisecond,
|
||||
ReadTimeout: 200 * time.Millisecond,
|
||||
WriteTimeout: 200 * time.Millisecond,
|
||||
PoolSize: 5,
|
||||
}))
|
||||
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
opts := client.Options()
|
||||
require.Equal(t, 0, opts.MaxRetries, "go-redis: -1 disables retries, 0 would restore the default of 3")
|
||||
require.Equal(t, 300*time.Millisecond, opts.DialTimeout)
|
||||
require.Equal(t, 200*time.Millisecond, opts.ReadTimeout)
|
||||
require.Equal(t, 200*time.Millisecond, opts.WriteTimeout)
|
||||
require.Equal(t, 5, opts.PoolSize)
|
||||
}
|
||||
Reference in New Issue
Block a user