//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 }