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
+30 -17
View File
@@ -20,8 +20,8 @@ import (
)
const (
envPrefix = "APP"
configEnvKey = "APP_CONFIG"
envKey = "APP_ENV"
configName = "config"
defaultEnv = "dev"
configDir = "./config/"
@@ -47,7 +47,7 @@ type Redis struct {
Port int `mapstructure:"port" validate:"omitempty,min=1,max=65535"`
Password string `mapstructure:"password"`
DB int `mapstructure:"db" validate:"omitempty,gte=0,lte=15"`
MaxRetries int `mapstructure:"max_retries" validate:"omitempty,gte=0"`
MaxRetries int `mapstructure:"max_retries" validate:"omitempty,gte=-1"`
DialTimeout time.Duration `mapstructure:"dial_timeout" validate:"omitempty,gt=0"`
ReadTimeout time.Duration `mapstructure:"read_timeout" validate:"omitempty,gt=0"`
WriteTimeout time.Duration `mapstructure:"write_timeout" validate:"omitempty,gt=0"`
@@ -55,12 +55,10 @@ type Redis struct {
}
type Cache struct {
Enabled bool `mapstructure:"enabled"`
ChatListTTL time.Duration `mapstructure:"chat_list_ttl" validate:"required,gt=0"`
SessionTTL time.Duration `mapstructure:"session_ttl" validate:"required,gt=0"`
LockTTL time.Duration `mapstructure:"lock_ttl" validate:"required,gt=1s"`
LockWaitTimeout time.Duration `mapstructure:"lock_wait_timeout" validate:"required,gt=0"`
LockTimeoutPolicy string `mapstructure:"lock_timeout_policy" validate:"required,oneof=error load"`
Enabled bool `mapstructure:"enabled"`
ChatListTTL time.Duration `mapstructure:"chat_list_ttl" validate:"required,gt=0"`
LockTTL time.Duration `mapstructure:"lock_ttl" validate:"required,gt=1s"`
LockWaitTimeout time.Duration `mapstructure:"lock_wait_timeout" validate:"required,gt=0"`
}
type Server struct {
@@ -123,17 +121,15 @@ var defaults = map[string]any{
"redis.host": "localhost",
"redis.port": 6379,
"redis.db": 0,
"redis.max_retries": 3,
"redis.dial_timeout": "5s",
"redis.read_timeout": "3s",
"redis.write_timeout": "3s",
"redis.max_retries": -1,
"redis.dial_timeout": "300ms",
"redis.read_timeout": "200ms",
"redis.write_timeout": "200ms",
"redis.pool_size": 10,
"cache.enabled": false,
"cache.chat_list_ttl": "5m",
"cache.session_ttl": "5m",
"cache.lock_ttl": "10s",
"cache.lock_wait_timeout": "2s",
"cache.lock_timeout_policy": "error",
}
func Load() (Config, error) {
@@ -143,11 +139,16 @@ func Load() (Config, error) {
return Config{}, err
}
v.SetEnvPrefix(envPrefix)
v.AllowEmptyEnv(true)
v.AutomaticEnv()
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
for key := range defaults {
if err := v.BindEnv(key); err != nil {
return Config{}, fmt.Errorf("bind env %q: %w", key, err)
}
}
var cfg Config
if err := v.Unmarshal(&cfg); err != nil {
return Config{}, fmt.Errorf("unmarshal config: %w", err)
@@ -157,9 +158,21 @@ func Load() (Config, error) {
return Config{}, fmt.Errorf("validate config: %w", err)
}
if err := cfg.validateDependencies(); err != nil {
return Config{}, err
}
return cfg, nil
}
func (c Config) validateDependencies() error {
if c.Cache.Enabled && !c.Redis.Enabled {
return errors.New("validate config: cache.enabled requires redis.enabled")
}
return nil
}
func configureSource(v *viper.Viper) error {
for key, value := range defaults {
v.SetDefault(key, value)
@@ -170,7 +183,7 @@ func configureSource(v *viper.Viper) error {
if path := os.Getenv(configEnvKey); path != "" {
v.SetConfigFile(path)
} else {
env := os.Getenv(envPrefix + "_ENV")
env := os.Getenv(envKey)
if env == "" {
env = defaultEnv
}
@@ -222,5 +235,5 @@ func envName(field reflect.StructField) string {
return field.Name
}
return envPrefix + "_" + strings.ToUpper(key)
return strings.ToUpper(key)
}
+57 -55
View File
@@ -28,12 +28,12 @@ func TestDefaults(t *testing.T) {
}
func TestEnvOverridesDefaults(t *testing.T) {
t.Setenv("APP_SERVER_HOST", "127.0.0.1")
t.Setenv("APP_SERVER_PORT", "9090")
t.Setenv("APP_SERVER_READ_HEADER_TIMEOUT", "3s")
t.Setenv("APP_SERVER_SHUTDOWN_TIMEOUT", "30s")
t.Setenv("APP_LOG_LEVEL", "debug")
t.Setenv("APP_LOG_FORMAT", "console")
t.Setenv("SERVER_HOST", "127.0.0.1")
t.Setenv("SERVER_PORT", "9090")
t.Setenv("SERVER_READ_HEADER_TIMEOUT", "3s")
t.Setenv("SERVER_SHUTDOWN_TIMEOUT", "30s")
t.Setenv("LOG_LEVEL", "debug")
t.Setenv("LOG_FORMAT", "console")
cfg, err := config.Load()
require.NoError(t, err)
@@ -132,27 +132,36 @@ postgres:
`)
t.Setenv("APP_CONFIG", path)
t.Setenv("APP_SERVER_HOST", "127.0.0.1")
t.Setenv("APP_POSTGRES_PASSWORD", "env")
t.Setenv("SERVER_HOST", "127.0.0.1")
t.Setenv("POSTGRES_PASSWORD", "env")
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, "127.0.0.1", cfg.Server.Host, "APP_* переопределяет YAML")
assert.Equal(t, "127.0.0.1", cfg.Server.Host, "env переопределяет YAML")
assert.Equal(t, 9999, cfg.Server.Port)
assert.Equal(t, "env", cfg.Postgres.Password)
}
func TestSessionTTLFromContractEnv(t *testing.T) {
t.Setenv("SESSION_TTL_SECONDS", "2")
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, 2, cfg.Session.TTLSeconds)
}
func TestInvalidValues(t *testing.T) {
tests := map[string]map[string]string{
"пустой server.host": {"APP_SERVER_HOST": ""},
"host не адрес и не имя": {"APP_SERVER_HOST": "не адрес"},
"порт ниже диапазона": {"APP_SERVER_PORT": "0"},
"порт выше диапазона": {"APP_SERVER_PORT": "65536"},
"нулевой read header timeout": {"APP_SERVER_READ_HEADER_TIMEOUT": "0s"},
"отрицательный shutdown": {"APP_SERVER_SHUTDOWN_TIMEOUT": "-1s"},
"неизвестный log level": {"APP_LOG_LEVEL": "trace"},
"неизвестный log format": {"APP_LOG_FORMAT": "xml"},
"пустой server.host": {"SERVER_HOST": ""},
"host не адрес и не имя": {"SERVER_HOST": "не адрес"},
"порт ниже диапазона": {"SERVER_PORT": "0"},
"порт выше диапазона": {"SERVER_PORT": "65536"},
"нулевой read header timeout": {"SERVER_READ_HEADER_TIMEOUT": "0s"},
"отрицательный shutdown": {"SERVER_SHUTDOWN_TIMEOUT": "-1s"},
"неизвестный log level": {"LOG_LEVEL": "trace"},
"неизвестный log format": {"LOG_FORMAT": "xml"},
}
for name, env := range tests {
@@ -184,8 +193,8 @@ postgres:
`)
tests := map[string]map[string]string{
"неизвестный ssl mode": {"APP_POSTGRES_SSL_MODE": "bogus"},
"отрицательный max_conns": {"APP_POSTGRES_MAX_CONNS": "-1"},
"неизвестный ssl mode": {"POSTGRES_SSL_MODE": "bogus"},
"отрицательный max_conns": {"POSTGRES_MAX_CONNS": "-1"},
}
for name, env := range tests {
@@ -207,8 +216,8 @@ postgres:
func TestUnparsableValues(t *testing.T) {
tests := map[string]map[string]string{
"порт не число": {"APP_SERVER_PORT": "не-число"},
"timeout не duration": {"APP_SERVER_READ_HEADER_TIMEOUT": "быстро"},
"порт не число": {"SERVER_PORT": "не-число"},
"timeout не duration": {"SERVER_READ_HEADER_TIMEOUT": "быстро"},
}
for name, env := range tests {
@@ -224,8 +233,8 @@ func TestUnparsableValues(t *testing.T) {
}
func TestLoggerSettings(t *testing.T) {
t.Setenv("APP_LOG_LEVEL", "warn")
t.Setenv("APP_LOG_FORMAT", "console")
t.Setenv("LOG_LEVEL", "warn")
t.Setenv("LOG_FORMAT", "console")
cfg, err := config.Load()
require.NoError(t, err)
@@ -240,8 +249,8 @@ func TestLoggerSettings(t *testing.T) {
}
func TestAddr(t *testing.T) {
t.Setenv("APP_SERVER_HOST", "0.0.0.0")
t.Setenv("APP_SERVER_PORT", "8080")
t.Setenv("SERVER_HOST", "0.0.0.0")
t.Setenv("SERVER_PORT", "8080")
cfg, err := config.Load()
require.NoError(t, err)
@@ -250,7 +259,7 @@ func TestAddr(t *testing.T) {
}
func TestAddrWithIPv6Host(t *testing.T) {
t.Setenv("APP_SERVER_HOST", "::1")
t.Setenv("SERVER_HOST", "::1")
cfg, err := config.Load()
require.NoError(t, err)
@@ -259,7 +268,7 @@ func TestAddrWithIPv6Host(t *testing.T) {
}
func TestLoadIsIndependentOfProcessState(t *testing.T) {
t.Setenv("APP_SERVER_PORT", "7070")
t.Setenv("SERVER_PORT", "7070")
first, err := config.Load()
require.NoError(t, err)
@@ -277,25 +286,24 @@ func TestRedisDefaultsDisabled(t *testing.T) {
assert.False(t, cfg.Redis.Enabled)
assert.Equal(t, "localhost", cfg.Redis.Host)
assert.Equal(t, 6379, cfg.Redis.Port)
assert.Equal(t, 5*time.Second, cfg.Redis.DialTimeout)
assert.Equal(t, -1, cfg.Redis.MaxRetries)
assert.Equal(t, 300*time.Millisecond, cfg.Redis.DialTimeout)
assert.Equal(t, 200*time.Millisecond, cfg.Redis.ReadTimeout)
assert.Equal(t, 200*time.Millisecond, cfg.Redis.WriteTimeout)
assert.False(t, cfg.Cache.Enabled)
assert.Equal(t, 5*time.Minute, cfg.Cache.ChatListTTL)
assert.Equal(t, 5*time.Minute, cfg.Cache.SessionTTL)
assert.Equal(t, 10*time.Second, cfg.Cache.LockTTL)
assert.Equal(t, 2*time.Second, cfg.Cache.LockWaitTimeout)
assert.Equal(t, "error", cfg.Cache.LockTimeoutPolicy)
}
func TestRedisEnvOverrides(t *testing.T) {
t.Setenv("APP_REDIS_ENABLED", "true")
t.Setenv("APP_REDIS_HOST", "cache")
t.Setenv("APP_REDIS_PORT", "6380")
t.Setenv("APP_CACHE_ENABLED", "true")
t.Setenv("APP_CACHE_CHAT_LIST_TTL", "1m")
t.Setenv("APP_CACHE_SESSION_TTL", "30s")
t.Setenv("APP_CACHE_LOCK_TTL", "7s")
t.Setenv("APP_CACHE_LOCK_WAIT_TIMEOUT", "1500ms")
t.Setenv("APP_CACHE_LOCK_TIMEOUT_POLICY", "load")
t.Setenv("REDIS_ENABLED", "true")
t.Setenv("REDIS_HOST", "cache")
t.Setenv("REDIS_PORT", "6380")
t.Setenv("CACHE_ENABLED", "true")
t.Setenv("CACHE_CHAT_LIST_TTL", "1m")
t.Setenv("CACHE_LOCK_TTL", "7s")
t.Setenv("CACHE_LOCK_WAIT_TIMEOUT", "1500ms")
cfg, err := config.Load()
require.NoError(t, err)
@@ -305,28 +313,15 @@ func TestRedisEnvOverrides(t *testing.T) {
assert.Equal(t, 6380, cfg.Redis.Port)
assert.True(t, cfg.Cache.Enabled)
assert.Equal(t, time.Minute, cfg.Cache.ChatListTTL)
assert.Equal(t, 30*time.Second, cfg.Cache.SessionTTL)
assert.Equal(t, 7*time.Second, cfg.Cache.LockTTL)
assert.Equal(t, 1500*time.Millisecond, cfg.Cache.LockWaitTimeout)
assert.Equal(t, "load", cfg.Cache.LockTimeoutPolicy)
}
func TestInvalidLockTimeoutPolicy(t *testing.T) {
t.Setenv("APP_CACHE_LOCK_TIMEOUT_POLICY", "bogus")
_, err := config.Load()
require.Error(t, err)
var validationErrs validator.ValidationErrors
require.ErrorAs(t, err, &validationErrs)
}
func TestInvalidCacheTTL(t *testing.T) {
for _, key := range []string{
"APP_CACHE_CHAT_LIST_TTL",
"APP_CACHE_SESSION_TTL",
"APP_CACHE_LOCK_TTL",
"APP_CACHE_LOCK_WAIT_TIMEOUT",
"CACHE_CHAT_LIST_TTL",
"CACHE_LOCK_TTL",
"CACHE_LOCK_WAIT_TIMEOUT",
} {
for _, value := range []string{"0s", "-1s"} {
t.Run(key+"/"+value, func(t *testing.T) {
@@ -339,3 +334,10 @@ func TestInvalidCacheTTL(t *testing.T) {
}
}
}
func TestCacheRequiresRedis(t *testing.T) {
t.Setenv("CACHE_ENABLED", "true")
_, err := config.Load()
require.ErrorContains(t, err, "cache.enabled requires redis.enabled")
}
+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)
}
@@ -51,6 +51,10 @@ func TestCacheLatencyExperiment(t *testing.T) {
var loads atomic.Int32
source := mocks.NewMockChatSource(t)
source.EXPECT().ListVersion(mock.Anything, mock.Anything).RunAndReturn(
func(ctx context.Context, userID uuid.UUID) (int64, error) {
return realChats.ListVersion(ctx, userID)
}).Maybe()
source.EXPECT().ListVisible(mock.Anything, mock.Anything, mock.Anything, mock.Anything).
RunAndReturn(func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
loads.Add(1)
@@ -67,6 +67,10 @@ func TestCachePerformanceExperiment(t *testing.T) {
var loads atomic.Int32
source := mocks.NewMockChatSource(t)
source.EXPECT().ListVersion(mock.Anything, mock.Anything).RunAndReturn(
func(ctx context.Context, userID uuid.UUID) (int64, error) {
return realChats.ListVersion(ctx, userID)
}).Maybe()
source.EXPECT().ListVisible(mock.Anything, mock.Anything, mock.Anything, mock.Anything).
RunAndReturn(func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
loads.Add(1)
@@ -1,9 +1,11 @@
package postgres
import (
"bytes"
"context"
"errors"
"fmt"
"slices"
"time"
"github.com/google/uuid"
@@ -44,6 +46,10 @@ func (r *ChatRepository) Create(ctx context.Context, draft domain.ChatDraft) (do
return fmt.Errorf("add chat members: %w", mapError(err))
}
if err := queries.BumpChatListVersions(ctx, sortedUnique(draft.MemberIDs)); err != nil {
return fmt.Errorf("bump chat list versions: %w", mapError(err))
}
created = mapChat(row.ID, row.Title, row.CreatedAt, draft.MemberIDs)
return nil
@@ -54,6 +60,27 @@ func (r *ChatRepository) Create(ctx context.Context, draft domain.ChatDraft) (do
return created, nil
}
func (r *ChatRepository) ListVersion(ctx context.Context, userID uuid.UUID) (int64, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
version, err := r.store.queries.GetChatListVersion(ctx, userID)
if err != nil {
return 0, fmt.Errorf("get chat list version: %w", mapError(err))
}
return version, nil
}
func sortedUnique(ids []uuid.UUID) []uuid.UUID {
sorted := slices.Clone(ids)
slices.SortFunc(sorted, func(a, b uuid.UUID) int {
return bytes.Compare(a[:], b[:])
})
return slices.Compact(sorted)
}
func (r *ChatRepository) GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
@@ -3,6 +3,9 @@
package postgres_test
import (
"fmt"
"slices"
"sync"
"testing"
"github.com/google/uuid"
@@ -49,6 +52,85 @@ func (s *ChatRepositorySuite) TestCreateRejectsDuplicateMembers() {
s.Require().ErrorIs(err, domain.ErrConflict)
}
func (s *ChatRepositorySuite) TestCreateBumpsMemberListVersions() {
ctx := s.T().Context()
alice := s.createUser("alice")
bob := s.createUser("bob")
carol := s.createUser("carol")
s.createChat(alice, bob)
aliceVersion, err := s.store.Chats().ListVersion(ctx, alice.ID)
s.Require().NoError(err)
s.Equal(int64(1), aliceVersion, "creator version must be bumped")
bobVersion, err := s.store.Chats().ListVersion(ctx, bob.ID)
s.Require().NoError(err)
s.Equal(int64(1), bobVersion, "member version must be bumped")
carolVersion, err := s.store.Chats().ListVersion(ctx, carol.ID)
s.Require().NoError(err)
s.Zero(carolVersion, "non-member version must stay unchanged")
s.createChat(alice, carol)
aliceVersion, err = s.store.Chats().ListVersion(ctx, alice.ID)
s.Require().NoError(err)
s.Equal(int64(2), aliceVersion, "version must grow monotonically")
carolVersion, err = s.store.Chats().ListVersion(ctx, carol.ID)
s.Require().NoError(err)
s.Equal(int64(1), carolVersion)
}
func (s *ChatRepositorySuite) TestConcurrentCreateNoDeadlock() {
ctx := s.T().Context()
users := make([]domain.User, 0, 8)
for i := range 8 {
users = append(users, s.createUser(fmt.Sprintf("member%d", i)))
}
const workers = 16
var wg sync.WaitGroup
errs := make(chan error, workers)
wg.Add(workers)
for w := range workers {
go func(w int) {
defer wg.Done()
ids := []uuid.UUID{
users[w%len(users)].ID,
users[(w+1)%len(users)].ID,
users[(w+2)%len(users)].ID,
}
if w%2 == 1 {
slices.Reverse(ids)
}
_, err := s.store.Chats().Create(ctx, domain.ChatDraft{
Title: fmt.Sprintf("chat-%d", w),
MemberIDs: ids,
CallerID: ids[0],
})
if err != nil {
errs <- err
}
}(w)
}
wg.Wait()
close(errs)
for err := range errs {
s.Require().NoError(err)
}
}
func (s *ChatRepositorySuite) TestCreateStoresAllMembers() {
alice := s.createUser("alice")
bob := s.createUser("bob")
@@ -28,6 +28,19 @@ func (q *Queries) AddChatMembers(ctx context.Context, arg AddChatMembersParams)
return err
}
const bumpChatListVersions = `-- name: BumpChatListVersions :exec
INSERT INTO user_chat_versions (user_id, version)
SELECT DISTINCT m, 1
FROM unnest($1::uuid[]) AS m
ORDER BY m
ON CONFLICT (user_id) DO UPDATE SET version = user_chat_versions.version + 1
`
func (q *Queries) BumpChatListVersions(ctx context.Context, userIds []uuid.UUID) error {
_, err := q.db.Exec(ctx, bumpChatListVersions, userIds)
return err
}
const createChat = `-- name: CreateChat :one
INSERT INTO chats (title)
VALUES ($1)
@@ -81,6 +94,19 @@ func (q *Queries) GetChatForMember(ctx context.Context, arg GetChatForMemberPara
return i, err
}
const getChatListVersion = `-- name: GetChatListVersion :one
SELECT COALESCE(MAX(version), 0)::bigint AS version
FROM user_chat_versions
WHERE user_id = $1
`
func (q *Queries) GetChatListVersion(ctx context.Context, userID uuid.UUID) (int64, error) {
row := q.db.QueryRow(ctx, getChatListVersion, userID)
var version int64
err := row.Scan(&version)
return version, err
}
const listChatsForMember = `-- name: ListChatsForMember :many
SELECT
c.id,
@@ -44,3 +44,8 @@ type User struct {
DisplayName string
CreatedAt time.Time
}
type UserChatVersion struct {
UserID uuid.UUID
Version int64
}
@@ -54,7 +54,7 @@ func (q *Queries) DeleteSession(ctx context.Context, arg DeleteSessionParams) er
}
const getSessionUser = `-- name: GetSessionUser :one
SELECT u.id, u.username, u.display_name, u.created_at, u.password_hash, s.expires_at
SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
FROM sessions s
JOIN users u ON u.id = s.user_id
WHERE s.token_hash = $1
@@ -62,12 +62,11 @@ WHERE s.token_hash = $1
`
type GetSessionUserRow struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
PasswordHash string
ExpiresAt time.Time
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
ExpiresAt time.Time
}
func (q *Queries) GetSessionUser(ctx context.Context, tokenHash []byte) (GetSessionUserRow, error) {
@@ -78,7 +77,6 @@ func (q *Queries) GetSessionUser(ctx context.Context, tokenHash []byte) (GetSess
&i.Username,
&i.DisplayName,
&i.CreatedAt,
&i.PasswordHash,
&i.ExpiresAt,
)
return i, err
@@ -44,6 +44,10 @@ CREATE TABLE sessions (
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE user_chat_versions (
user_id uuid PRIMARY KEY REFERENCES users (id) ON DELETE CASCADE,
version bigint NOT NULL DEFAULT 0
);
CREATE INDEX messages_chat_id_created_at_id_idx
ON messages (chat_id, created_at, id);
@@ -54,6 +58,9 @@ CREATE INDEX chat_members_user_id_chat_id_idx
CREATE INDEX chats_created_at_id_idx
ON chats (created_at, id);
CREATE INDEX sessions_user_id_idx
ON sessions (user_id);
-- +goose Down
DROP TABLE sessions;
@@ -61,3 +68,4 @@ DROP TABLE messages;
DROP TABLE chat_members;
DROP TABLE chats;
DROP TABLE users;
DROP TABLE user_chat_versions;
@@ -14,6 +14,18 @@ FROM unnest(sqlc.arg(user_ids)::uuid[]) AS input(id)
LEFT JOIN users u ON u.id = input.id
WHERE u.id IS NULL;
-- name: BumpChatListVersions :exec
INSERT INTO user_chat_versions (user_id, version)
SELECT DISTINCT m, 1
FROM unnest(sqlc.arg(user_ids)::uuid[]) AS m
ORDER BY m
ON CONFLICT (user_id) DO UPDATE SET version = user_chat_versions.version + 1;
-- name: GetChatListVersion :one
SELECT COALESCE(MAX(version), 0)::bigint AS version
FROM user_chat_versions
WHERE user_id = sqlc.arg(user_id);
-- name: GetChatForMember :one
SELECT
c.id,
@@ -4,7 +4,7 @@ VALUES (sqlc.arg(token_hash), sqlc.arg(user_id), sqlc.arg(expires_at))
RETURNING token_hash, user_id, expires_at;
-- name: GetSessionUser :one
SELECT u.id, u.username, u.display_name, u.created_at, u.password_hash, s.expires_at
SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
FROM sessions s
JOIN users u ON u.id = s.user_id
WHERE s.token_hash = sqlc.arg(token_hash)
@@ -80,14 +80,13 @@ func (r *SessionRepository) Resolve(ctx context.Context, tokenHash []byte) (doma
}, nil
}
// Revoke is intentionally idempotent: deleting an already absent session is a no-op.
// The HTTP contract for DELETE /auth/sessions/current defines only 204/401, so a
// missing session must not surface as an error.
func (r *SessionRepository) Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
if err := r.store.queries.DeleteSession(ctx, sqlcgen.DeleteSessionParams{TokenHash: tokenHash, UserID: userID}); err != nil {
if err := r.store.queries.DeleteSession(
ctx, sqlcgen.DeleteSessionParams{TokenHash: tokenHash, UserID: userID},
); err != nil {
return fmt.Errorf("revoke session: %w", mapError(err))
}
+43 -45
View File
@@ -17,6 +17,7 @@ import (
type ChatSource interface {
Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)
GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error)
ListVersion(ctx context.Context, userID uuid.UUID) (int64, error)
ListVisible(
ctx context.Context,
callerID uuid.UUID,
@@ -42,20 +43,21 @@ func NewChatRepository(
}
func (r *ChatRepository) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
chat, err := r.source.Create(ctx, draft)
if err != nil {
return domain.Chat{}, err
}
r.invalidate(ctx, draft.MemberIDs)
return chat, nil
return r.source.Create(ctx, draft)
}
func (r *ChatRepository) GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error) {
return r.source.GetVisible(ctx, chatID, callerID)
}
type sourceError struct{ err error }
func (e sourceError) Error() string { return e.err.Error() }
func (e sourceError) Unwrap() error { return e.err }
const cacheOperationTimeout = 500 * time.Millisecond
func (r *ChatRepository) ListVisible(
ctx context.Context,
callerID uuid.UUID,
@@ -66,58 +68,54 @@ func (r *ChatRepository) ListVisible(
return r.source.ListVisible(ctx, callerID, after, limit)
}
key := chatListKey(callerID, r.generation(ctx, callerID), limit)
version, err := r.source.ListVersion(ctx, callerID)
if err != nil {
return domain.Page[domain.Chat]{}, fmt.Errorf("chat list version: %w", err)
}
key := chatListKey(callerID, version, limit)
loader := func(ctx context.Context) ([]byte, error) {
page, err := r.source.ListVisible(ctx, callerID, nil, limit)
if err != nil {
return nil, err
return nil, sourceError{err}
}
return json.Marshal(newChatPageDTO(page))
}
encoded, err := r.cache.GetOrLoad(ctx, key, r.ttl, loader)
cctx, cancel := context.WithTimeout(ctx, cacheOperationTimeout)
defer cancel()
encoded, err := r.cache.GetOrLoad(cctx, key, r.ttl, loader)
if err != nil {
if errors.Is(err, cache.ErrLoadInProgress) {
return domain.Page[domain.Chat]{}, fmt.Errorf("load chat list: %w", domain.ErrUnavailable)
var sourceErr sourceError
switch {
case errors.As(err, &sourceErr):
return domain.Page[domain.Chat]{}, sourceErr.err
case ctx.Err() != nil:
return domain.Page[domain.Chat]{}, ctx.Err()
}
return domain.Page[domain.Chat]{}, fmt.Errorf("load chat list: %w", err)
}
var dto chatPageDTO
if err := json.Unmarshal(encoded, &dto); err != nil {
return domain.Page[domain.Chat]{}, fmt.Errorf("decode cached chat list: %w", err)
}
return dto.toDomain(), nil
}
func (r *ChatRepository) generation(ctx context.Context, userID uuid.UUID) string {
value, err := r.cache.Get(ctx, chatGenKey(userID))
if err != nil {
return ""
}
return string(value)
}
func (r *ChatRepository) invalidate(ctx context.Context, memberIDs []uuid.UUID) {
for _, memberID := range memberIDs {
if err := r.cache.Set(ctx, chatGenKey(memberID), []byte(uuid.NewString()), 0); err != nil && r.log != nil {
r.log.WarnContext(ctx, "chat cache invalidation failed",
slog.String("user_id", memberID.String()), slog.Any("error", err))
} else {
var dto chatPageDTO
unmarshalErr := json.Unmarshal(encoded, &dto)
if unmarshalErr == nil {
return dto.toDomain(), nil
}
err = unmarshalErr
_ = r.cache.Delete(ctx, key)
}
if r.log != nil {
r.log.WarnContext(ctx, "chat list cache unavailable, falling back to source", slog.Any("error", err))
}
return r.source.ListVisible(ctx, callerID, nil, limit)
}
func chatGenKey(userID uuid.UUID) string {
return "chat_gen:" + userID.String()
}
func chatListKey(userID uuid.UUID, generation string, limit int) string {
return fmt.Sprintf("chat_list:%s:%s:%d", userID, generation, limit)
func chatListKey(userID uuid.UUID, version int64, limit int) string {
return fmt.Sprintf("chat_list:%s:%d:%d", userID, version, limit)
}
type chatPageDTO struct {
+142 -8
View File
@@ -4,6 +4,7 @@ package redis_test
import (
"context"
"errors"
"sync"
"sync/atomic"
"testing"
@@ -15,8 +16,9 @@ import (
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/cache"
cachemocks "mtusi-messenger/internal/platform/cache/mocks"
storageredis "mtusi-messenger/internal/storage/redis"
"mtusi-messenger/internal/storage/redis/mocks"
storagemocks "mtusi-messenger/internal/storage/redis/mocks"
)
type ChatRepositorySuite struct {
@@ -65,7 +67,8 @@ func (s *ChatRepositorySuite) TestFirstPageIsCached() {
alice := uuid.New()
page := domain.Page[domain.Chat]{Items: []domain.Chat{}}
source := mocks.NewMockChatSource(s.T())
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Twice()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(page, nil).Once()
repo := s.newRepo(source)
@@ -92,10 +95,14 @@ func (s *ChatRepositorySuite) TestCreateInvalidatesMemberCaches() {
}
page := domain.Page[domain.Chat]{Items: []domain.Chat{chat}}
source := mocks.NewMockChatSource(s.T())
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Once()
source.EXPECT().ListVersion(mock.Anything, bob).Return(int64(0), nil).Once()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(empty, nil).Once()
source.EXPECT().ListVisible(mock.Anything, bob, (*domain.Cursor)(nil), 50).Return(empty, nil).Once()
source.EXPECT().Create(mock.Anything, mock.AnythingOfType("domain.ChatDraft")).Return(chat, nil).Once()
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(1), nil).Once()
source.EXPECT().ListVersion(mock.Anything, bob).Return(int64(1), nil).Once()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(page, nil).Once()
source.EXPECT().ListVisible(mock.Anything, bob, (*domain.Cursor)(nil), 50).Return(page, nil).Once()
@@ -122,13 +129,34 @@ func (s *ChatRepositorySuite) TestCreateInvalidatesMemberCaches() {
s.Len(bobPage.Items, 1, "other member must observe the new chat immediately")
}
func (s *ChatRepositorySuite) TestEvictedCacheEntryReloadsFromSource() {
ctx := s.T().Context()
alice := uuid.New()
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Twice()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(empty, nil).Twice()
repo := s.newRepo(source)
_, err := repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err)
// Simulate a Redis flush/restart by dropping all cache entries.
s.Require().NoError(flushRedisDB(ctx))
_, err = repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err)
}
func (s *ChatRepositorySuite) TestDeeperPagesBypassCache() {
ctx := s.T().Context()
alice := uuid.New()
cursor := &domain.Cursor{Scope: alice, CreatedAt: time.Now().UTC(), ID: uuid.New()}
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
source := mocks.NewMockChatSource(s.T())
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVisible(mock.Anything, alice, cursor, 50).Return(empty, nil).Twice()
repo := s.newRepo(source)
@@ -144,7 +172,8 @@ func (s *ChatRepositorySuite) TestLimitIsPartOfCacheKey() {
alice := uuid.New()
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
source := mocks.NewMockChatSource(s.T())
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Twice()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 10).Return(empty, nil).Once()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(empty, nil).Once()
@@ -161,7 +190,8 @@ func (s *ChatRepositorySuite) TestConcurrentColdReadsAreDeduplicated() {
alice := uuid.New()
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
source := mocks.NewMockChatSource(s.T())
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Maybe()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
RunAndReturn(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error) {
time.Sleep(25 * time.Millisecond)
@@ -193,6 +223,7 @@ func (s *ChatRepositorySuite) TestConcurrentColdReadsAreDeduplicated() {
wg.Wait()
s.Require().Zero(failures.Load())
s.T().Logf("distributed lock: %d concurrent cold reads -> 1 source load", workers)
}
func (s *ChatRepositorySuite) TestMultipleInstancesShareDistributedLock() {
@@ -200,7 +231,8 @@ func (s *ChatRepositorySuite) TestMultipleInstancesShareDistributedLock() {
alice := uuid.New()
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
source := mocks.NewMockChatSource(s.T())
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Maybe()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
RunAndReturn(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error) {
time.Sleep(25 * time.Millisecond)
@@ -241,6 +273,108 @@ func (s *ChatRepositorySuite) TestMultipleInstancesShareDistributedLock() {
wg.Wait()
s.Require().Zero(failures.Load())
s.T().Logf("multi-instance distributed lock: %d instances x %d reads -> 1 source load",
instances, workersPerInstance)
}
func (s *ChatRepositorySuite) TestCacheUnavailableFallsBackToSource() {
ctx := s.T().Context()
alice := uuid.New()
page := domain.Page[domain.Chat]{Items: []domain.Chat{}}
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Once()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(page, nil).Once()
lockStore := cachemocks.NewMockLockStore(s.T())
lockStore.EXPECT().Get(mock.Anything, mock.Anything).Return(nil, errors.New("redis down")).Maybe()
distributed, err := cache.NewDistributed(lockStore, cache.DistributedConfig{}, nil)
s.Require().NoError(err)
repo := storageredis.NewChatRepository(source, distributed, time.Minute, nil)
got, err := repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err, "cache failure must not fail the read")
s.Empty(got.Items)
}
func (s *ChatRepositorySuite) TestBrokenCacheEntryIsDroppedAndRepopulated() {
ctx := s.T().Context()
alice := uuid.New()
page := domain.Page[domain.Chat]{Items: []domain.Chat{}}
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Times(3)
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(page, nil).Twice()
repo := s.newRepo(source)
key := "chat_list:" + alice.String() + ":0:50"
s.Require().NoError(s.cache.Set(ctx, key, []byte("{not json"), time.Minute))
// 1st: garbage -> dropped -> source.
first, err := repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err, "a corrupted cache entry must not fail the read")
// 2nd: miss -> source -> repopulate.
second, err := repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err)
// 3rd: served from cache, no source call.
third, err := repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err)
s.Equal(first, second)
s.Equal(second, third)
}
func (s *ChatRepositorySuite) TestSlowLoaderBeyondCacheBudgetReturnsData() {
ctx := s.T().Context()
alice := uuid.New()
page := domain.Page[domain.Chat]{Items: []domain.Chat{}}
release := make(chan struct{})
var calls atomic.Int32
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Once()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
RunAndReturn(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error) {
if calls.Add(1) == 1 {
<-release // the loader outlives the caller's cache budget
}
return page, nil
}).Maybe()
repo := s.newRepo(source)
started := time.Now()
got, err := repo.ListVisible(ctx, alice, nil, 50)
s.Require().NoError(err, "budget expiry must fall back to the source, not fail")
s.Empty(got.Items)
s.GreaterOrEqual(time.Since(started), 450*time.Millisecond, "the caller must be bounded by the cache budget")
// Let the background loader finish before the test (and its mock) is torn down.
close(release)
time.Sleep(200 * time.Millisecond)
}
func (s *ChatRepositorySuite) TestSourceErrorIsNotRetried() {
ctx := s.T().Context()
alice := uuid.New()
sentinel := errors.New("postgres down")
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Once()
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
Return(domain.Page[domain.Chat]{}, sentinel).Once()
repo := s.newRepo(source)
_, err := repo.ListVisible(ctx, alice, nil, 50)
s.Require().ErrorIs(err, sentinel, "source error must propagate")
}
func (s *ChatRepositorySuite) TestConcurrentColdReadsWithoutProtectionStampede() {
@@ -251,7 +385,7 @@ func (s *ChatRepositorySuite) TestConcurrentColdReadsWithoutProtectionStampede()
var loads atomic.Int32
source := mocks.NewMockChatSource(s.T())
source := storagemocks.NewMockChatSource(s.T())
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
RunAndReturn(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error) {
loads.Add(1)
+66
View File
@@ -0,0 +1,66 @@
//go:build integration
package redis_test
import (
"context"
"os"
"strconv"
"time"
goredis "github.com/redis/go-redis/v9"
"mtusi-messenger/internal/platform/cache"
)
const testRedisDB = 1
func redisEnv(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}
func redisEnvInt(key string, fallback int) int {
value := os.Getenv(key)
if value == "" {
return fallback
}
parsed, err := strconv.Atoi(value)
if err != nil {
return fallback
}
return parsed
}
func testRedisConfig() cache.RedisConfig {
return cache.RedisConfig{
Host: redisEnv("TEST_REDIS_HOST", "localhost"),
Port: redisEnvInt("TEST_REDIS_PORT", 6379),
Password: os.Getenv("TEST_REDIS_PASSWORD"),
DB: redisEnvInt("TEST_REDIS_DB", testRedisDB),
MaxRetries: 3,
DialTimeout: 5 * time.Second,
ReadTimeout: 3 * time.Second,
WriteTimeout: 3 * time.Second,
PoolSize: 5,
}
}
func flushRedisDB(ctx context.Context) error {
cfg := testRedisConfig()
client := goredis.NewClient(&goredis.Options{
Addr: cfg.Host + ":" + strconv.Itoa(cfg.Port),
Password: cfg.Password,
DB: cfg.DB,
})
defer func() { _ = client.Close() }()
return client.FlushDB(ctx).Err()
}
@@ -186,6 +186,72 @@ func (_c *MockChatSource_GetVisible_Call) RunAndReturn(run func(ctx context.Cont
return _c
}
// ListVersion provides a mock function for the type MockChatSource
func (_mock *MockChatSource) ListVersion(ctx context.Context, userID uuid.UUID) (int64, error) {
ret := _mock.Called(ctx, userID)
if len(ret) == 0 {
panic("no return value specified for ListVersion")
}
var r0 int64
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) (int64, error)); ok {
return returnFunc(ctx, userID)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) int64); ok {
r0 = returnFunc(ctx, userID)
} else {
r0 = ret.Get(0).(int64)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID) error); ok {
r1 = returnFunc(ctx, userID)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockChatSource_ListVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListVersion'
type MockChatSource_ListVersion_Call struct {
*mock.Call
}
// ListVersion is a helper method to define mock.On call
// - ctx context.Context
// - userID uuid.UUID
func (_e *MockChatSource_Expecter) ListVersion(ctx any, userID any) *MockChatSource_ListVersion_Call {
return &MockChatSource_ListVersion_Call{Call: _e.mock.On("ListVersion", ctx, userID)}
}
func (_c *MockChatSource_ListVersion_Call) Run(run func(ctx context.Context, userID uuid.UUID)) *MockChatSource_ListVersion_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 uuid.UUID
if args[1] != nil {
arg1 = args[1].(uuid.UUID)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockChatSource_ListVersion_Call) Return(n int64, err error) *MockChatSource_ListVersion_Call {
_c.Call.Return(n, err)
return _c
}
func (_c *MockChatSource_ListVersion_Call) RunAndReturn(run func(ctx context.Context, userID uuid.UUID) (int64, error)) *MockChatSource_ListVersion_Call {
_c.Call.Return(run)
return _c
}
// ListVisible provides a mock function for the type MockChatSource
func (_mock *MockChatSource) ListVisible(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
ret := _mock.Called(ctx, callerID, after, limit)
@@ -1,310 +0,0 @@
// Code generated by mockery; DO NOT EDIT.
// github.com/vektra/mockery
// template: testify
package mocks
import (
"context"
"mtusi-messenger/internal/domain"
"github.com/google/uuid"
mock "github.com/stretchr/testify/mock"
)
// NewMockSessionSource creates a new instance of MockSessionSource. 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 NewMockSessionSource(t interface {
mock.TestingT
Cleanup(func())
}) *MockSessionSource {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock := &MockSessionSource{}
mock.Mock.Test(t)
t.Cleanup(func() {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock.AssertExpectations(t)
})
return mock
}
// MockSessionSource is an autogenerated mock type for the SessionSource type
type MockSessionSource struct {
mock.Mock
}
type MockSessionSource_Expecter struct {
mock *mock.Mock
}
func (_m *MockSessionSource) EXPECT() *MockSessionSource_Expecter {
return &MockSessionSource_Expecter{mock: &_m.Mock}
}
// Create provides a mock function for the type MockSessionSource
func (_mock *MockSessionSource) Create(ctx context.Context, session domain.NewSession) (domain.Session, error) {
ret := _mock.Called(ctx, session)
if len(ret) == 0 {
panic("no return value specified for Create")
}
var r0 domain.Session
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewSession) (domain.Session, error)); ok {
return returnFunc(ctx, session)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewSession) domain.Session); ok {
r0 = returnFunc(ctx, session)
} else {
r0 = ret.Get(0).(domain.Session)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.NewSession) error); ok {
r1 = returnFunc(ctx, session)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockSessionSource_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
type MockSessionSource_Create_Call struct {
*mock.Call
}
// Create is a helper method to define mock.On call
// - ctx context.Context
// - session domain.NewSession
func (_e *MockSessionSource_Expecter) Create(ctx any, session any) *MockSessionSource_Create_Call {
return &MockSessionSource_Create_Call{Call: _e.mock.On("Create", ctx, session)}
}
func (_c *MockSessionSource_Create_Call) Run(run func(ctx context.Context, session domain.NewSession)) *MockSessionSource_Create_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 domain.NewSession
if args[1] != nil {
arg1 = args[1].(domain.NewSession)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockSessionSource_Create_Call) Return(session1 domain.Session, err error) *MockSessionSource_Create_Call {
_c.Call.Return(session1, err)
return _c
}
func (_c *MockSessionSource_Create_Call) RunAndReturn(run func(ctx context.Context, session domain.NewSession) (domain.Session, error)) *MockSessionSource_Create_Call {
_c.Call.Return(run)
return _c
}
// Credentials provides a mock function for the type MockSessionSource
func (_mock *MockSessionSource) Credentials(ctx context.Context, username string) (domain.UserCredentials, error) {
ret := _mock.Called(ctx, username)
if len(ret) == 0 {
panic("no return value specified for Credentials")
}
var r0 domain.UserCredentials
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, string) (domain.UserCredentials, error)); ok {
return returnFunc(ctx, username)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, string) domain.UserCredentials); ok {
r0 = returnFunc(ctx, username)
} else {
r0 = ret.Get(0).(domain.UserCredentials)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
r1 = returnFunc(ctx, username)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockSessionSource_Credentials_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Credentials'
type MockSessionSource_Credentials_Call struct {
*mock.Call
}
// Credentials is a helper method to define mock.On call
// - ctx context.Context
// - username string
func (_e *MockSessionSource_Expecter) Credentials(ctx any, username any) *MockSessionSource_Credentials_Call {
return &MockSessionSource_Credentials_Call{Call: _e.mock.On("Credentials", ctx, username)}
}
func (_c *MockSessionSource_Credentials_Call) Run(run func(ctx context.Context, username string)) *MockSessionSource_Credentials_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 *MockSessionSource_Credentials_Call) Return(userCredentials domain.UserCredentials, err error) *MockSessionSource_Credentials_Call {
_c.Call.Return(userCredentials, err)
return _c
}
func (_c *MockSessionSource_Credentials_Call) RunAndReturn(run func(ctx context.Context, username string) (domain.UserCredentials, error)) *MockSessionSource_Credentials_Call {
_c.Call.Return(run)
return _c
}
// Resolve provides a mock function for the type MockSessionSource
func (_mock *MockSessionSource) Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error) {
ret := _mock.Called(ctx, tokenHash)
if len(ret) == 0 {
panic("no return value specified for Resolve")
}
var r0 domain.Session
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) (domain.Session, error)); ok {
return returnFunc(ctx, tokenHash)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) domain.Session); ok {
r0 = returnFunc(ctx, tokenHash)
} else {
r0 = ret.Get(0).(domain.Session)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, []byte) error); ok {
r1 = returnFunc(ctx, tokenHash)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockSessionSource_Resolve_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Resolve'
type MockSessionSource_Resolve_Call struct {
*mock.Call
}
// Resolve is a helper method to define mock.On call
// - ctx context.Context
// - tokenHash []byte
func (_e *MockSessionSource_Expecter) Resolve(ctx any, tokenHash any) *MockSessionSource_Resolve_Call {
return &MockSessionSource_Resolve_Call{Call: _e.mock.On("Resolve", ctx, tokenHash)}
}
func (_c *MockSessionSource_Resolve_Call) Run(run func(ctx context.Context, tokenHash []byte)) *MockSessionSource_Resolve_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 []byte
if args[1] != nil {
arg1 = args[1].([]byte)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockSessionSource_Resolve_Call) Return(session domain.Session, err error) *MockSessionSource_Resolve_Call {
_c.Call.Return(session, err)
return _c
}
func (_c *MockSessionSource_Resolve_Call) RunAndReturn(run func(ctx context.Context, tokenHash []byte) (domain.Session, error)) *MockSessionSource_Resolve_Call {
_c.Call.Return(run)
return _c
}
// Revoke provides a mock function for the type MockSessionSource
func (_mock *MockSessionSource) Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error {
ret := _mock.Called(ctx, userID, tokenHash)
if len(ret) == 0 {
panic("no return value specified for Revoke")
}
var r0 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, []byte) error); ok {
r0 = returnFunc(ctx, userID, tokenHash)
} else {
r0 = ret.Error(0)
}
return r0
}
// MockSessionSource_Revoke_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Revoke'
type MockSessionSource_Revoke_Call struct {
*mock.Call
}
// Revoke is a helper method to define mock.On call
// - ctx context.Context
// - userID uuid.UUID
// - tokenHash []byte
func (_e *MockSessionSource_Expecter) Revoke(ctx any, userID any, tokenHash any) *MockSessionSource_Revoke_Call {
return &MockSessionSource_Revoke_Call{Call: _e.mock.On("Revoke", ctx, userID, tokenHash)}
}
func (_c *MockSessionSource_Revoke_Call) Run(run func(ctx context.Context, userID uuid.UUID, tokenHash []byte)) *MockSessionSource_Revoke_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 uuid.UUID
if args[1] != nil {
arg1 = args[1].(uuid.UUID)
}
var arg2 []byte
if args[2] != nil {
arg2 = args[2].([]byte)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockSessionSource_Revoke_Call) Return(err error) *MockSessionSource_Revoke_Call {
_c.Call.Return(err)
return _c
}
func (_c *MockSessionSource_Revoke_Call) RunAndReturn(run func(ctx context.Context, userID uuid.UUID, tokenHash []byte) error) *MockSessionSource_Revoke_Call {
_c.Call.Return(run)
return _c
}
@@ -1,128 +0,0 @@
package redis
import (
"context"
"encoding/hex"
"encoding/json"
"log/slog"
"time"
"github.com/google/uuid"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/cache"
)
type SessionSource interface {
Credentials(ctx context.Context, username string) (domain.UserCredentials, error)
Create(ctx context.Context, session domain.NewSession) (domain.Session, error)
Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error)
Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error
}
type SessionRepository struct {
source SessionSource
cache cache.Cache
ttlCap time.Duration
log *slog.Logger
}
func NewSessionRepository(
source SessionSource,
cache cache.Cache,
ttlCap time.Duration,
log *slog.Logger,
) *SessionRepository {
return &SessionRepository{source: source, cache: cache, ttlCap: ttlCap, log: log}
}
func (r *SessionRepository) Credentials(ctx context.Context, username string) (domain.UserCredentials, error) {
return r.source.Credentials(ctx, username)
}
func (r *SessionRepository) Create(ctx context.Context, session domain.NewSession) (domain.Session, error) {
return r.source.Create(ctx, session)
}
type cachedSession struct {
ExpiresAt time.Time `json:"expires_at"`
User cachedUser `json:"user"`
}
type cachedUser struct {
ID uuid.UUID `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt time.Time `json:"created_at"`
}
func newCachedSession(session domain.Session) cachedSession {
return cachedSession{
ExpiresAt: session.ExpiresAt,
User: cachedUser{
ID: session.User.ID,
Username: session.User.Username,
DisplayName: session.User.DisplayName,
CreatedAt: session.User.CreatedAt,
},
}
}
func (c cachedSession) toDomain() domain.Session {
return domain.Session{
ExpiresAt: c.ExpiresAt,
User: domain.User{
ID: c.User.ID,
Username: c.User.Username,
DisplayName: c.User.DisplayName,
CreatedAt: c.User.CreatedAt,
},
}
}
func (r *SessionRepository) Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error) {
key := sessionKey(tokenHash)
if cached, err := r.cache.Get(ctx, key); err == nil {
var session cachedSession
if unmarshalErr := json.Unmarshal(cached, &session); unmarshalErr == nil {
if session.User.ID != uuid.Nil && time.Now().Before(session.ExpiresAt) {
return session.toDomain(), nil
}
_ = r.cache.Delete(ctx, key)
}
}
session, err := r.source.Resolve(ctx, tokenHash)
if err != nil {
return domain.Session{}, err
}
if ttl := min(time.Until(session.ExpiresAt), r.ttlCap); ttl > 0 {
if encoded, marshalErr := json.Marshal(newCachedSession(session)); marshalErr == nil {
if err := r.cache.Set(ctx, key, encoded, ttl); err != nil && r.log != nil {
r.log.WarnContext(ctx, "session cache write failed", slog.Any("error", err))
}
}
}
return session, nil
}
func (r *SessionRepository) Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error {
key := sessionKey(tokenHash)
if err := r.cache.Delete(ctx, key); err != nil && r.log != nil {
r.log.WarnContext(ctx, "session cache eviction failed", slog.Any("error", err))
}
if err := r.source.Revoke(ctx, userID, tokenHash); err != nil {
return err
}
return nil
}
func sessionKey(tokenHash []byte) string {
return "session:" + hex.EncodeToString(tokenHash)
}
@@ -1,241 +0,0 @@
//go:build integration
package redis_test
import (
"context"
"encoding/hex"
"os"
"strconv"
"testing"
"time"
"github.com/google/uuid"
goredis "github.com/redis/go-redis/v9"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/platform/cache"
storageredis "mtusi-messenger/internal/storage/redis"
"mtusi-messenger/internal/storage/redis/mocks"
)
const testRedisDB = 1
func redisEnv(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}
func redisEnvInt(key string, fallback int) int {
value := os.Getenv(key)
if value == "" {
return fallback
}
parsed, err := strconv.Atoi(value)
if err != nil {
return fallback
}
return parsed
}
func testRedisConfig() cache.RedisConfig {
return cache.RedisConfig{
Host: redisEnv("TEST_REDIS_HOST", "localhost"),
Port: redisEnvInt("TEST_REDIS_PORT", 6379),
Password: os.Getenv("TEST_REDIS_PASSWORD"),
DB: redisEnvInt("TEST_REDIS_DB", testRedisDB),
MaxRetries: 3,
DialTimeout: 5 * time.Second,
ReadTimeout: 3 * time.Second,
WriteTimeout: 3 * time.Second,
PoolSize: 5,
}
}
type SessionRepositorySuite struct {
suite.Suite
cache *cache.RedisCache
client *goredis.Client
}
func TestSessionRepositorySuite(t *testing.T) {
suite.Run(t, new(SessionRepositorySuite))
}
func (s *SessionRepositorySuite) SetupSuite() {
cfg := testRedisConfig()
var err error
s.cache, err = cache.NewRedis(cfg)
s.Require().NoError(err)
s.client = goredis.NewClient(&goredis.Options{
Addr: cfg.Host + ":" + strconv.Itoa(cfg.Port),
Password: cfg.Password,
DB: cfg.DB,
})
s.Require().NoError(s.client.Ping(s.T().Context()).Err())
}
func (s *SessionRepositorySuite) TearDownSuite() {
if s.client != nil {
s.Require().NoError(s.client.Close())
}
if s.cache != nil {
s.Require().NoError(s.cache.Close())
}
}
func (s *SessionRepositorySuite) SetupTest() {
s.Require().NoError(s.client.FlushDB(s.T().Context()).Err())
}
func (s *SessionRepositorySuite) newRepo(source storageredis.SessionSource) *storageredis.SessionRepository {
s.T().Helper()
return storageredis.NewSessionRepository(source, s.cache, 5*time.Minute, nil)
}
func testSession(userID uuid.UUID, expiresAt time.Time) domain.Session {
return domain.Session{
ExpiresAt: expiresAt,
User: domain.User{
ID: userID,
Username: "alice",
DisplayName: "Алиса",
CreatedAt: time.Now().UTC(),
},
}
}
func (s *SessionRepositorySuite) TestCacheTTLCapAndSessionExpiry() {
ctx := s.T().Context()
for _, remaining := range []time.Duration{time.Hour, time.Minute} {
hash := []byte(uuid.NewString())
session := testSession(uuid.New(), time.Now().UTC().Add(remaining))
source := mocks.NewMockSessionSource(s.T())
source.EXPECT().Resolve(mock.Anything, hash).Return(session, nil).Once()
_, err := s.newRepo(source).Resolve(ctx, hash)
s.Require().NoError(err)
ttl, err := s.client.PTTL(ctx, sessionCacheKey(hash)).Result()
s.Require().NoError(err)
s.Positive(ttl)
s.LessOrEqual(ttl, min(remaining, 5*time.Minute))
}
}
func (s *SessionRepositorySuite) TestResolvePopulatesCacheAndServesFromIt() {
ctx := s.T().Context()
tokenHash := []byte("hash-populate")
session := testSession(uuid.New(), time.Now().UTC().Add(time.Hour))
source := mocks.NewMockSessionSource(s.T())
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(session, nil).Once()
repo := s.newRepo(source)
first, err := repo.Resolve(ctx, tokenHash)
s.Require().NoError(err)
s.Equal(session.User.ID, first.User.ID)
second, err := repo.Resolve(ctx, tokenHash)
s.Require().NoError(err)
s.Equal(session.User.ID, second.User.ID)
}
func (s *SessionRepositorySuite) TestResolveFallsBackToSourceOnMiss() {
ctx := s.T().Context()
tokenHash := []byte("unknown")
source := mocks.NewMockSessionSource(s.T())
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(domain.Session{}, domain.ErrUnauthenticated).Once()
_, err := s.newRepo(source).Resolve(ctx, tokenHash)
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
func (s *SessionRepositorySuite) TestRevokeEvictsCacheAndSource() {
ctx := s.T().Context()
userID := uuid.New()
tokenHash := []byte("hash-revoke")
session := testSession(userID, time.Now().UTC().Add(time.Hour))
source := mocks.NewMockSessionSource(s.T())
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(session, nil).Once()
source.EXPECT().Revoke(mock.Anything, userID, tokenHash).Return(nil).Once()
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(domain.Session{}, domain.ErrUnauthenticated).Once()
repo := s.newRepo(source)
_, err := repo.Resolve(ctx, tokenHash)
s.Require().NoError(err)
s.Require().NoError(repo.Revoke(ctx, userID, tokenHash))
_, err = repo.Resolve(ctx, tokenHash)
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
func (s *SessionRepositorySuite) TestEvictedCacheEntryReloadsFromSource() {
ctx := s.T().Context()
tokenHash := []byte("hash-evicted")
session := testSession(uuid.New(), time.Now().UTC().Add(time.Hour))
source := mocks.NewMockSessionSource(s.T())
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(session, nil).Twice()
repo := s.newRepo(source)
_, err := repo.Resolve(ctx, tokenHash)
s.Require().NoError(err)
// Simulate a Redis flush/restart by dropping the cache entry.
s.Require().NoError(s.client.Del(ctx, sessionCacheKey(tokenHash)).Err())
_, err = repo.Resolve(ctx, tokenHash)
s.Require().NoError(err)
}
func (s *SessionRepositorySuite) TestExpiredSessionIsRejected() {
ctx := s.T().Context()
tokenHash := []byte("hash-expired")
source := mocks.NewMockSessionSource(s.T())
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(domain.Session{}, domain.ErrUnauthenticated).Once()
_, err := s.newRepo(source).Resolve(ctx, tokenHash)
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
func sessionCacheKey(tokenHash []byte) string {
return "session:" + hex.EncodeToString(tokenHash)
}
func flushRedisDB(ctx context.Context) error {
cfg := testRedisConfig()
client := goredis.NewClient(&goredis.Options{
Addr: cfg.Host + ":" + strconv.Itoa(cfg.Port),
Password: cfg.Password,
DB: cfg.DB,
})
defer func() { _ = client.Close() }()
return client.FlushDB(ctx).Err()
}