lab2 fix
Application / Lint (pull_request) Canceled after 0s
Application / Unit tests (pull_request) Canceled after 0s
Application / Docker build (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Vladislav Kunetskiy
2026-10-10 00:50:24 +03:00
parent 1e38dbdf35
commit da9fcf346a
36 changed files with 995 additions and 1038 deletions
+16 -27
View File
@@ -20,22 +20,13 @@ 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
redisOpTimeout = 200 * time.Millisecond
releaseTimeout = 300 * time.Millisecond
)
type DistributedConfig struct {
LockTTL time.Duration
WaitTimeout time.Duration
TimeoutPolicy TimeoutPolicy
LockTTL time.Duration
WaitTimeout time.Duration
}
type LockStore interface {
@@ -49,7 +40,6 @@ type DistributedCache struct {
store LockStore
lockTTL time.Duration
waitTimeout time.Duration
policy TimeoutPolicy
log *slog.Logger
group singleflight.Group
}
@@ -73,15 +63,10 @@ func NewDistributed(store LockStore, cfg DistributedConfig, log *slog.Logger) (*
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
}
@@ -157,11 +142,7 @@ func (d *DistributedCache) getOrLoad(
case waitDegraded:
return loader(ctx)
case waitTimeout:
if d.policy == TimeoutLoad {
return loader(ctx)
}
return nil, ErrLoadInProgress
return loader(ctx)
case waitRetry:
if ctx.Err() != nil {
return nil, ctx.Err()
@@ -193,19 +174,27 @@ func (d *DistributedCache) fill(
}
}()
if value, err := d.store.Get(base, key); err == 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)
value, err = loader(loadCtx)
if err != nil {
return nil, err
}
if setErr := d.store.Set(base, key, value, ttl); setErr != nil {
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)
}
+63 -31
View File
@@ -106,39 +106,11 @@ func TestDistributedDeduplicatesConcurrentMisses(t *testing.T) {
require.Equal(t, int32(1), calls.Load(), "one instance must load once for concurrent misses")
}
func TestDistributedTimeoutPolicyError(t *testing.T) {
func TestDistributedFallsBackOnWaitTimeout(t *testing.T) {
t.Parallel()
store := mocks.NewMockLockStore(t)
dc := newDistributed(t, store, cache.DistributedConfig{
WaitTimeout: 100 * time.Millisecond,
TimeoutPolicy: cache.TimeoutError,
})
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
_, 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 := mocks.NewMockLockStore(t)
dc := newDistributed(t, store, cache.DistributedConfig{
WaitTimeout: 100 * time.Millisecond,
TimeoutPolicy: cache.TimeoutLoad,
})
dc := newDistributed(t, store, cache.DistributedConfig{WaitTimeout: 100 * time.Millisecond})
ctx := context.Background()
store.EXPECT().Get(mock.Anything, "key").Return(nil, cache.ErrCacheMiss).Maybe()
@@ -154,7 +126,7 @@ func TestDistributedTimeoutPolicyLoad(t *testing.T) {
})
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")
require.Equal(t, int32(1), calls.Load(), "a wait timeout must fall back to a direct load")
}
func TestDistributedSharedLoadSurvivesCallerCancellation(t *testing.T) {
@@ -252,3 +224,63 @@ func TestDistributedRetriesWhenLockVanishes(t *testing.T) {
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")
}
+14 -10
View File
@@ -28,16 +28,7 @@ type RedisCache struct {
}
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,
})
client := redis.NewClient(newClientOptions(cfg))
ctx, cancel := context.WithTimeout(context.Background(), cfg.DialTimeout)
defer cancel()
@@ -51,6 +42,19 @@ func NewRedis(cfg RedisConfig) (*RedisCache, error) {
return &RedisCache{client: client}, nil
}
func newClientOptions(cfg RedisConfig) *redis.Options {
return &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,
}
}
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) {
+32
View File
@@ -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)
}