lab2
This commit is contained in:
@@ -0,0 +1,180 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
)
|
||||
|
||||
type ChatSource interface {
|
||||
Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)
|
||||
GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error)
|
||||
ListVisible(
|
||||
ctx context.Context,
|
||||
callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Chat], error)
|
||||
}
|
||||
|
||||
type ChatRepository struct {
|
||||
source ChatSource
|
||||
cache *cache.SingleflightCache
|
||||
ttl time.Duration
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func NewChatRepository(
|
||||
source ChatSource,
|
||||
cache *cache.SingleflightCache,
|
||||
ttl time.Duration,
|
||||
log *slog.Logger,
|
||||
) *ChatRepository {
|
||||
return &ChatRepository{source: source, cache: cache, ttl: ttl, log: log}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error) {
|
||||
return r.source.GetVisible(ctx, chatID, callerID)
|
||||
}
|
||||
|
||||
func (r *ChatRepository) ListVisible(
|
||||
ctx context.Context,
|
||||
callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Chat], error) {
|
||||
if after != nil {
|
||||
return r.source.ListVisible(ctx, callerID, after, limit)
|
||||
}
|
||||
|
||||
key := chatListKey(callerID, r.generation(ctx, callerID), limit)
|
||||
|
||||
loader := func(ctx context.Context) ([]byte, error) {
|
||||
page, err := r.source.ListVisible(ctx, callerID, nil, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return json.Marshal(newChatPageDTO(page))
|
||||
}
|
||||
|
||||
encoded, err := r.cache.GetOrLoad(ctx, key, r.ttl, loader)
|
||||
if err != nil {
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
type chatPageDTO struct {
|
||||
Items []chatDTO `json:"items"`
|
||||
Next *cursorDTO `json:"next,omitempty"`
|
||||
}
|
||||
|
||||
type chatDTO struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []uuid.UUID `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type cursorDTO struct {
|
||||
Scope uuid.UUID `json:"scope"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID uuid.UUID `json:"id"`
|
||||
}
|
||||
|
||||
func newChatPageDTO(page domain.Page[domain.Chat]) chatPageDTO {
|
||||
items := make([]chatDTO, 0, len(page.Items))
|
||||
for _, chat := range page.Items {
|
||||
items = append(items, chatDTO{
|
||||
ID: chat.ID,
|
||||
Title: chat.Title,
|
||||
MemberIDs: chat.MemberIDs,
|
||||
CreatedAt: chat.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
var next *cursorDTO
|
||||
if page.Next != nil {
|
||||
next = &cursorDTO{
|
||||
Scope: page.Next.Scope,
|
||||
CreatedAt: page.Next.CreatedAt,
|
||||
ID: page.Next.ID,
|
||||
}
|
||||
}
|
||||
|
||||
return chatPageDTO{Items: items, Next: next}
|
||||
}
|
||||
|
||||
func (d chatPageDTO) toDomain() domain.Page[domain.Chat] {
|
||||
items := make([]domain.Chat, 0, len(d.Items))
|
||||
for _, chat := range d.Items {
|
||||
items = append(items, domain.Chat{
|
||||
ID: chat.ID,
|
||||
Title: chat.Title,
|
||||
MemberIDs: chat.MemberIDs,
|
||||
CreatedAt: chat.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
var next *domain.Cursor
|
||||
if d.Next != nil {
|
||||
next = &domain.Cursor{
|
||||
Scope: d.Next.Scope,
|
||||
CreatedAt: d.Next.CreatedAt,
|
||||
ID: d.Next.ID,
|
||||
}
|
||||
}
|
||||
|
||||
return domain.Page[domain.Chat]{Items: items, Next: next}
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
//go:build integration
|
||||
|
||||
package redis_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
storageredis "mtusi-messenger/internal/storage/redis"
|
||||
)
|
||||
|
||||
type ChatRepositorySuite struct {
|
||||
suite.Suite
|
||||
|
||||
cache *cache.RedisCache
|
||||
source *fakeChatSource
|
||||
repo *storageredis.ChatRepository
|
||||
}
|
||||
|
||||
func TestChatRepositorySuite(t *testing.T) {
|
||||
suite.Run(t, new(ChatRepositorySuite))
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) SetupSuite() {
|
||||
var err error
|
||||
|
||||
s.cache, err = cache.NewRedis(testRedisConfig())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().NoError(s.cache.Ping(s.T().Context()))
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TearDownSuite() {
|
||||
if s.cache != nil {
|
||||
s.Require().NoError(s.cache.Close())
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) SetupTest() {
|
||||
s.source = newFakeChatSource()
|
||||
|
||||
// Flush the test DB so generation markers and list entries do not leak.
|
||||
s.Require().NoError(flushRedisDB(s.T().Context()))
|
||||
|
||||
s.repo = storageredis.NewChatRepository(
|
||||
s.source,
|
||||
cache.WithSingleflight(s.cache),
|
||||
time.Minute,
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestFirstPageIsCached() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
|
||||
first, err := s.repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
s.Empty(first.Items)
|
||||
s.Equal(1, s.source.listCalls())
|
||||
|
||||
second, err := s.repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
s.Empty(second.Items)
|
||||
s.Equal(1, s.source.listCalls(), "second first-page read must be served from cache")
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestCreateInvalidatesMemberCaches() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
bob := uuid.New()
|
||||
|
||||
_, err := s.repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
_, err = s.repo.ListVisible(ctx, bob, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(2, s.source.listCalls())
|
||||
|
||||
_, err = s.repo.Create(ctx, domain.ChatDraft{
|
||||
Title: "Чат",
|
||||
MemberIDs: []uuid.UUID{alice, bob},
|
||||
CallerID: alice,
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
alicePage, err := s.repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
s.Len(alicePage.Items, 1, "creator must observe the new chat immediately")
|
||||
|
||||
bobPage, err := s.repo.ListVisible(ctx, bob, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
s.Len(bobPage.Items, 1, "other member must observe the new chat immediately")
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestDeeperPagesBypassCache() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
|
||||
cursor := &domain.Cursor{Scope: alice, CreatedAt: time.Now().UTC(), ID: uuid.New()}
|
||||
|
||||
_, err := s.repo.ListVisible(ctx, alice, cursor, 50)
|
||||
s.Require().NoError(err)
|
||||
_, err = s.repo.ListVisible(ctx, alice, cursor, 50)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(2, s.source.listCalls(), "paginated reads must not use the cache")
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestLimitIsPartOfCacheKey() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
|
||||
_, err := s.repo.ListVisible(ctx, alice, nil, 10)
|
||||
s.Require().NoError(err)
|
||||
_, err = s.repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(2, s.source.listCalls(), "different limits must not share a cache entry")
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestConcurrentColdReadsAreDeduplicated() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
|
||||
// A realistic source latency keeps late callers inside the first flight.
|
||||
s.source.delay = 25 * time.Millisecond
|
||||
|
||||
const workers = 100
|
||||
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
failures atomic.Int32
|
||||
)
|
||||
|
||||
wg.Add(workers)
|
||||
|
||||
for range workers {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
if _, err := s.repo.ListVisible(ctx, alice, nil, 50); err != nil {
|
||||
failures.Add(1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
s.Require().Zero(failures.Load())
|
||||
s.Equal(1, s.source.listCalls(), "singleflight must collapse 100 cold reads into one source query")
|
||||
s.T().Logf("singleflight: %d concurrent cold reads -> %d source loads", workers, s.source.listCalls())
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestConcurrentColdReadsWithoutProtectionStampede() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
key := "naive:" + alice.String()
|
||||
|
||||
const workers = 100
|
||||
|
||||
var (
|
||||
loads atomic.Int32
|
||||
wg sync.WaitGroup
|
||||
failures atomic.Int32
|
||||
)
|
||||
|
||||
loader := func(ctx context.Context) ([]byte, error) {
|
||||
loads.Add(1)
|
||||
|
||||
if _, err := s.source.ListVisible(ctx, alice, nil, 50); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return []byte("page"), nil
|
||||
}
|
||||
|
||||
wg.Add(workers)
|
||||
|
||||
for range workers {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
// Naive cache-aside without singleflight: every concurrent miss loads.
|
||||
if _, err := s.cache.Get(ctx, key); err != nil {
|
||||
if _, loadErr := loader(ctx); loadErr != nil {
|
||||
failures.Add(1)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
_ = s.cache.Set(ctx, key, []byte("page"), time.Minute)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
s.Require().Zero(failures.Load())
|
||||
s.Greater(loads.Load(), int32(1), "without singleflight concurrent misses stampede the source")
|
||||
s.T().Logf("stampede demonstration: %d concurrent reads -> %d source loads", workers, loads.Load())
|
||||
}
|
||||
|
||||
type fakeChatSource struct {
|
||||
mu sync.Mutex
|
||||
chats []domain.Chat
|
||||
list int
|
||||
delay time.Duration
|
||||
}
|
||||
|
||||
func newFakeChatSource() *fakeChatSource {
|
||||
return &fakeChatSource{}
|
||||
}
|
||||
|
||||
func (f *fakeChatSource) listCalls() int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
|
||||
return f.list
|
||||
}
|
||||
|
||||
func (f *fakeChatSource) Create(_ context.Context, draft domain.ChatDraft) (domain.Chat, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
|
||||
chat := domain.Chat{
|
||||
ID: uuid.New(),
|
||||
Title: draft.Title,
|
||||
MemberIDs: append([]uuid.UUID(nil), draft.MemberIDs...),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
f.chats = append(f.chats, chat)
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (f *fakeChatSource) GetVisible(_ context.Context, chatID, callerID uuid.UUID) (domain.Chat, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
|
||||
for _, chat := range f.chats {
|
||||
if chat.ID == chatID && chat.HasMember(callerID) {
|
||||
return chat, nil
|
||||
}
|
||||
}
|
||||
|
||||
return domain.Chat{}, domain.ErrNotFound
|
||||
}
|
||||
|
||||
func (f *fakeChatSource) ListVisible(
|
||||
_ context.Context,
|
||||
callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Chat], error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
|
||||
f.list++
|
||||
|
||||
delay := f.delay
|
||||
if delay > 0 {
|
||||
time.Sleep(delay)
|
||||
}
|
||||
|
||||
var visible []domain.Chat
|
||||
|
||||
for _, chat := range f.chats {
|
||||
if !chat.HasMember(callerID) {
|
||||
continue
|
||||
}
|
||||
|
||||
if after != nil {
|
||||
if !chat.CreatedAt.After(after.CreatedAt) && chat.ID.String() <= after.ID.String() {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
visible = append(visible, chat)
|
||||
}
|
||||
|
||||
sort.Slice(visible, func(i, j int) bool {
|
||||
if visible[i].CreatedAt.Equal(visible[j].CreatedAt) {
|
||||
return visible[i].ID.String() < visible[j].ID.String()
|
||||
}
|
||||
|
||||
return visible[i].CreatedAt.Before(visible[j].CreatedAt)
|
||||
})
|
||||
|
||||
if len(visible) > limit {
|
||||
visible = visible[:limit]
|
||||
}
|
||||
|
||||
return domain.Page[domain.Chat]{Items: visible}, nil
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
//go:build integration
|
||||
|
||||
package redis_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
storageredis "mtusi-messenger/internal/storage/redis"
|
||||
)
|
||||
|
||||
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
|
||||
source *fakeSource
|
||||
repo *storageredis.SessionRepository
|
||||
}
|
||||
|
||||
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())
|
||||
|
||||
s.source = newFakeSource()
|
||||
s.repo = storageredis.NewSessionRepository(
|
||||
s.source,
|
||||
s.cache,
|
||||
5*time.Minute,
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestCacheTTLCapAndSessionExpiry() {
|
||||
ctx := s.T().Context()
|
||||
for _, remaining := range []time.Duration{time.Hour, time.Minute} {
|
||||
hash := []byte(uuid.NewString())
|
||||
s.source.seed(hash, uuid.New(), time.Now().Add(remaining))
|
||||
_, err := s.repo.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 := s.source.seed(tokenHash, uuid.New(), time.Now().UTC().Add(time.Hour))
|
||||
|
||||
first, err := s.repo.Resolve(ctx, tokenHash)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(session.User.ID, first.User.ID)
|
||||
s.Equal(1, s.source.resolveCount())
|
||||
|
||||
second, err := s.repo.Resolve(ctx, tokenHash)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(session.User.ID, second.User.ID)
|
||||
s.Equal(1, s.source.resolveCount(), "second resolve must be served from cache")
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestResolveFallsBackToSourceOnMiss() {
|
||||
ctx := s.T().Context()
|
||||
|
||||
_, err := s.repo.Resolve(ctx, []byte("unknown"))
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
s.Equal(1, s.source.resolveCount(), "cache miss loads from source")
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestRevokeEvictsCacheAndSource() {
|
||||
ctx := s.T().Context()
|
||||
userID := uuid.New()
|
||||
tokenHash := []byte("hash-revoke")
|
||||
s.source.seed(tokenHash, userID, time.Now().UTC().Add(time.Hour))
|
||||
|
||||
_, err := s.repo.Resolve(ctx, tokenHash)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().NoError(s.repo.Revoke(ctx, userID, tokenHash))
|
||||
|
||||
_, err = s.repo.Resolve(ctx, tokenHash)
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
s.Equal(2, s.source.resolveCount(), "revoked token must not be served from cache")
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestEvictedCacheEntryReloadsFromSource() {
|
||||
ctx := s.T().Context()
|
||||
tokenHash := []byte("hash-evicted")
|
||||
s.source.seed(tokenHash, uuid.New(), time.Now().UTC().Add(time.Hour))
|
||||
|
||||
_, err := s.repo.Resolve(ctx, tokenHash)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(1, s.source.resolveCount())
|
||||
|
||||
// Simulate a Redis flush/restart by dropping the cache entry.
|
||||
s.Require().NoError(s.client.Del(ctx, sessionCacheKey(tokenHash)).Err())
|
||||
|
||||
_, err = s.repo.Resolve(ctx, tokenHash)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(2, s.source.resolveCount(), "evicted entry must be reloaded from source")
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestExpiredSessionIsRejected() {
|
||||
ctx := s.T().Context()
|
||||
tokenHash := []byte("hash-expired")
|
||||
s.source.seed(tokenHash, uuid.New(), time.Now().UTC().Add(-time.Minute))
|
||||
|
||||
_, err := s.repo.Resolve(ctx, tokenHash)
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
s.Equal(1, s.source.resolveCount())
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
// fakeSource is an in-memory SessionSource used to observe cache behaviour.
|
||||
type fakeSource struct {
|
||||
mu sync.Mutex
|
||||
sessions map[string]domain.Session
|
||||
resolves int
|
||||
}
|
||||
|
||||
func newFakeSource() *fakeSource {
|
||||
return &fakeSource{sessions: make(map[string]domain.Session)}
|
||||
}
|
||||
|
||||
func (f *fakeSource) seed(tokenHash []byte, userID uuid.UUID, expiresAt time.Time) domain.Session {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
|
||||
session := domain.Session{
|
||||
ExpiresAt: expiresAt,
|
||||
User: domain.User{
|
||||
ID: userID,
|
||||
Username: "alice",
|
||||
DisplayName: "Алиса",
|
||||
CreatedAt: time.Now().UTC(),
|
||||
},
|
||||
}
|
||||
f.sessions[string(tokenHash)] = session
|
||||
|
||||
return session
|
||||
}
|
||||
|
||||
func (f *fakeSource) resolveCount() int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
|
||||
return f.resolves
|
||||
}
|
||||
|
||||
func (f *fakeSource) Credentials(_ context.Context, _ string) (domain.UserCredentials, error) {
|
||||
return domain.UserCredentials{}, domain.ErrUnauthenticated
|
||||
}
|
||||
|
||||
func (f *fakeSource) Create(_ context.Context, session domain.NewSession) (domain.Session, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
|
||||
stored := domain.Session{ExpiresAt: session.ExpiresAt}
|
||||
f.sessions[string(session.TokenHash)] = stored
|
||||
|
||||
return stored, nil
|
||||
}
|
||||
|
||||
func (f *fakeSource) Resolve(_ context.Context, tokenHash []byte) (domain.Session, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
|
||||
f.resolves++
|
||||
|
||||
session, ok := f.sessions[string(tokenHash)]
|
||||
if !ok || time.Now().UTC().After(session.ExpiresAt) {
|
||||
return domain.Session{}, domain.ErrUnauthenticated
|
||||
}
|
||||
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (f *fakeSource) Revoke(_ context.Context, _ uuid.UUID, tokenHash []byte) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
|
||||
delete(f.sessions, string(tokenHash))
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user