This commit is contained in:
Vladislav Kunetskiy
2026-10-06 18:01:00 +03:00
parent 51b236a69f
commit dc743548c8
122 changed files with 10682 additions and 2139 deletions
+31
View File
@@ -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
View File
@@ -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())
}
+318
View File
@@ -0,0 +1,318 @@
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
releaseTimeout = time.Second
)
var ErrLoadInProgress = errors.New("distributed cache: load already in progress")
type TimeoutPolicy int
const (
TimeoutError TimeoutPolicy = iota
TimeoutLoad
)
type DistributedConfig struct {
LockTTL time.Duration
WaitTimeout time.Duration
TimeoutPolicy TimeoutPolicy
}
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
policy TimeoutPolicy
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)
}
if cfg.TimeoutPolicy != TimeoutError && cfg.TimeoutPolicy != TimeoutLoad {
return nil, fmt.Errorf("cache: unknown wait-timeout policy %d", cfg.TimeoutPolicy)
}
return &DistributedCache{
store: store,
lockTTL: cfg.LockTTL,
waitTimeout: cfg.WaitTimeout,
policy: cfg.TimeoutPolicy,
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:
if d.policy == TimeoutLoad {
return loader(ctx)
}
return nil, ErrLoadInProgress
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)
}
}()
if value, err := d.store.Get(base, key); 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
}
if setErr := d.store.Set(base, key, value, ttl); 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)
}
+60
View File
@@ -0,0 +1,60 @@
package cache
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
)
type awaitStore struct {
value []byte
held bool
lockErr error
}
func (s awaitStore) Get(context.Context, string) ([]byte, error) {
if s.value != nil {
return s.value, nil
}
return nil, ErrCacheMiss
}
func (awaitStore) Set(context.Context, string, []byte, time.Duration) error { return nil }
func (awaitStore) Delete(context.Context, ...string) error { return nil }
func (awaitStore) AcquireLock(context.Context, string, string, time.Duration) (bool, error) {
return false, nil
}
func (awaitStore) ReleaseLock(context.Context, string, string) (bool, error) { return false, nil }
func (s awaitStore) LockHeld(context.Context, string) (bool, error) { return s.held, s.lockErr }
func (awaitStore) Ping(context.Context) error { return nil }
func (awaitStore) Close() error { return nil }
func TestAwaitChecksCacheBeforePolling(t *testing.T) {
t.Parallel()
d, err := NewDistributed(awaitStore{value: []byte("ready")}, 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()
d, err := NewDistributed(awaitStore{held: true}, 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)
}
+306
View File
@@ -0,0 +1,306 @@
package cache_test
import (
"context"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/platform/cache"
)
type memoryLockStore struct {
mu sync.Mutex
data map[string][]byte
locks map[string]string
}
func newMemoryLockStore() *memoryLockStore {
return &memoryLockStore{
data: make(map[string][]byte),
locks: make(map[string]string),
}
}
func (m *memoryLockStore) Get(_ context.Context, key string) ([]byte, error) {
m.mu.Lock()
defer m.mu.Unlock()
value, ok := m.data[key]
if !ok {
return nil, cache.ErrCacheMiss
}
return value, nil
}
func (m *memoryLockStore) Set(_ context.Context, key string, value []byte, _ time.Duration) error {
m.mu.Lock()
defer m.mu.Unlock()
m.data[key] = value
return nil
}
func (m *memoryLockStore) Delete(_ context.Context, keys ...string) error {
m.mu.Lock()
defer m.mu.Unlock()
for _, key := range keys {
delete(m.data, key)
}
return nil
}
func (m *memoryLockStore) AcquireLock(_ context.Context, key, token string, _ time.Duration) (bool, error) {
m.mu.Lock()
defer m.mu.Unlock()
if _, held := m.locks[key]; held {
return false, nil
}
m.locks[key] = token
return true, nil
}
func (m *memoryLockStore) ReleaseLock(_ context.Context, key, token string) (bool, error) {
m.mu.Lock()
defer m.mu.Unlock()
if m.locks[key] == token {
delete(m.locks, key)
return true, nil
}
return false, nil
}
func (m *memoryLockStore) LockHeld(_ context.Context, key string) (bool, error) {
m.mu.Lock()
defer m.mu.Unlock()
_, held := m.locks[key]
return held, nil
}
func (m *memoryLockStore) Ping(context.Context) error { return nil }
func (m *memoryLockStore) Close() error { return nil }
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 TestDistributedCachesResult(t *testing.T) {
t.Parallel()
dc := newDistributed(t, newMemoryLockStore(), cache.DistributedConfig{})
ctx := context.Background()
var calls atomic.Int32
loader := func(context.Context) ([]byte, error) {
calls.Add(1)
return []byte("payload"), nil
}
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()
dc := newDistributed(t, newMemoryLockStore(), 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
}
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)
}
}()
}
wg.Wait()
require.Zero(t, failures.Load())
require.Equal(t, int32(1), calls.Load(), "one instance must load once for concurrent misses")
}
func TestDistributedTimeoutPolicyError(t *testing.T) {
t.Parallel()
store := newMemoryLockStore()
dc := newDistributed(t, store, cache.DistributedConfig{
WaitTimeout: 100 * time.Millisecond,
TimeoutPolicy: cache.TimeoutError,
})
ctx := context.Background()
acquired, err := store.AcquireLock(ctx, "lock:key", "other-instance", time.Minute)
require.NoError(t, err)
require.True(t, acquired)
var calls atomic.Int32
_, err = dc.GetOrLoad(ctx, "key", time.Minute, func(context.Context) ([]byte, error) {
calls.Add(1)
return []byte("value"), nil
})
require.ErrorIs(t, err, cache.ErrLoadInProgress)
require.Zero(t, calls.Load(), "the error policy must not fall back to a direct load")
}
func TestDistributedTimeoutPolicyLoad(t *testing.T) {
t.Parallel()
store := newMemoryLockStore()
dc := newDistributed(t, store, cache.DistributedConfig{
WaitTimeout: 100 * time.Millisecond,
TimeoutPolicy: cache.TimeoutLoad,
})
ctx := context.Background()
acquired, err := store.AcquireLock(ctx, "lock:key", "other-instance", time.Minute)
require.NoError(t, err)
require.True(t, acquired)
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(), "the load policy must fall back to a direct load")
}
func TestDistributedSharedLoadSurvivesCallerCancellation(t *testing.T) {
t.Parallel()
dc := newDistributed(t, newMemoryLockStore(), 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
}
leaderErr := make(chan error, 1)
go func() {
_, err := dc.GetOrLoad(leaderCtx, "key", time.Minute, loader)
leaderErr <- err
}()
<-started
var (
wg sync.WaitGroup
followerV []byte
followerE error
)
wg.Add(1)
go func() {
defer wg.Done()
followerV, followerE = dc.GetOrLoad(context.Background(), "key", time.Minute, loader)
}()
cancelLeader()
close(release)
require.ErrorIs(t, <-leaderErr, context.Canceled)
wg.Wait()
require.NoError(t, followerE)
require.Equal(t, []byte("value"), followerV)
require.Equal(t, int32(1), calls.Load())
}
func TestDistributedRetriesWhenLockVanishes(t *testing.T) {
t.Parallel()
store := newMemoryLockStore()
dc := newDistributed(t, store, cache.DistributedConfig{})
ctx := context.Background()
acquired, err := store.AcquireLock(ctx, "lock:key", "other-instance", time.Minute)
require.NoError(t, err)
require.True(t, acquired)
time.AfterFunc(120*time.Millisecond, func() {
_, _ = store.ReleaseLock(context.Background(), "lock:key", "other-instance")
})
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())
}
+135
View File
@@ -0,0 +1,135 @@
package cache
import (
"context"
"errors"
"fmt"
"net"
"strconv"
"time"
"github.com/redis/go-redis/v9"
)
type RedisConfig struct {
Host string
Port int
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(cfg RedisConfig) (*RedisCache, error) {
client := redis.NewClient(&redis.Options{
Addr: net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port)),
Password: cfg.Password,
DB: cfg.DB,
MaxRetries: cfg.MaxRetries,
DialTimeout: cfg.DialTimeout,
ReadTimeout: cfg.ReadTimeout,
WriteTimeout: cfg.WriteTimeout,
PoolSize: cfg.PoolSize,
})
ctx, cancel := context.WithTimeout(context.Background(), cfg.DialTimeout)
defer cancel()
if err := client.Ping(ctx).Err(); err != nil {
_ = client.Close()
return nil, fmt.Errorf("ping redis: %w", err)
}
return &RedisCache{client: client}, nil
}
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
}