forked from mtusi2026/mtusi2026lab2
lab2
This commit is contained in:
+306
@@ -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())
|
||||
}
|
||||
Reference in New Issue
Block a user