//go:build integration package redis_test import ( "context" "errors" "sync" "sync/atomic" "testing" "time" "github.com/google/uuid" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/suite" "mtusi-messenger/internal/domain" "mtusi-messenger/internal/platform/cache" cachemocks "mtusi-messenger/internal/platform/cache/mocks" storageredis "mtusi-messenger/internal/storage/redis" storagemocks "mtusi-messenger/internal/storage/redis/mocks" ) type ChatRepositorySuite struct { suite.Suite cache *cache.RedisCache } 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())) s.Require().NoError(flushRedisDB(s.T().Context())) } func (s *ChatRepositorySuite) TearDownSuite() { if s.cache != nil { s.Require().NoError(s.cache.Close()) } } func (s *ChatRepositorySuite) newDistributed() *cache.DistributedCache { s.T().Helper() dc, err := cache.NewDistributed(s.cache, cache.DistributedConfig{}, nil) s.Require().NoError(err) return dc } func (s *ChatRepositorySuite) newRepo(source storageredis.ChatSource) *storageredis.ChatRepository { s.T().Helper() return storageredis.NewChatRepository(source, s.newDistributed(), time.Minute, nil) } func (s *ChatRepositorySuite) TestFirstPageIsCached() { 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).Twice() source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(page, nil).Once() repo := s.newRepo(source) first, err := repo.ListVisible(ctx, alice, nil, 50) s.Require().NoError(err) s.Empty(first.Items) second, err := repo.ListVisible(ctx, alice, nil, 50) s.Require().NoError(err) s.Empty(second.Items) } func (s *ChatRepositorySuite) TestCreateInvalidatesMemberCaches() { ctx := s.T().Context() alice := uuid.New() bob := uuid.New() empty := domain.Page[domain.Chat]{Items: []domain.Chat{}} chat := domain.Chat{ ID: uuid.New(), Title: "Чат", MemberIDs: []uuid.UUID{alice, bob}, CreatedAt: time.Now().UTC(), } page := domain.Page[domain.Chat]{Items: []domain.Chat{chat}} 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() repo := s.newRepo(source) _, err := repo.ListVisible(ctx, alice, nil, 50) s.Require().NoError(err) _, err = repo.ListVisible(ctx, bob, nil, 50) s.Require().NoError(err) _, err = repo.Create(ctx, domain.ChatDraft{ Title: "Чат", MemberIDs: []uuid.UUID{alice, bob}, CallerID: alice, }) s.Require().NoError(err) alicePage, err := repo.ListVisible(ctx, alice, nil, 50) s.Require().NoError(err) s.Len(alicePage.Items, 1, "creator must observe the new chat immediately") bobPage, err := 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) 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 := storagemocks.NewMockChatSource(s.T()) source.EXPECT().ListVisible(mock.Anything, alice, cursor, 50).Return(empty, nil).Twice() repo := s.newRepo(source) _, err := repo.ListVisible(ctx, alice, cursor, 50) s.Require().NoError(err) _, err = repo.ListVisible(ctx, alice, cursor, 50) s.Require().NoError(err) } func (s *ChatRepositorySuite) TestLimitIsPartOfCacheKey() { 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), 10).Return(empty, nil).Once() source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(empty, nil).Once() repo := s.newRepo(source) _, err := repo.ListVisible(ctx, alice, nil, 10) s.Require().NoError(err) _, err = repo.ListVisible(ctx, alice, nil, 50) s.Require().NoError(err) } func (s *ChatRepositorySuite) TestConcurrentColdReadsAreDeduplicated() { 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).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) return empty, nil }).Once() repo := s.newRepo(source) const workers = 100 var ( wg sync.WaitGroup failures atomic.Int32 ) wg.Add(workers) for range workers { go func() { defer wg.Done() if _, err := repo.ListVisible(ctx, alice, nil, 50); err != nil { failures.Add(1) } }() } wg.Wait() s.Require().Zero(failures.Load()) s.T().Logf("distributed lock: %d concurrent cold reads -> 1 source load", workers) } func (s *ChatRepositorySuite) TestMultipleInstancesShareDistributedLock() { 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).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) return empty, nil }).Once() const ( instances = 3 workersPerInstance = 30 ) repos := make([]*storageredis.ChatRepository, instances) for i := range repos { repos[i] = s.newRepo(source) } var ( wg sync.WaitGroup failures atomic.Int32 ) wg.Add(instances * workersPerInstance) for i := range repos { repo := repos[i] for range workersPerInstance { go func() { defer wg.Done() if _, err := repo.ListVisible(ctx, alice, nil, 50); err != nil { failures.Add(1) } }() } } 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() { ctx := s.T().Context() alice := uuid.New() key := "naive:" + alice.String() empty := domain.Page[domain.Chat]{Items: []domain.Chat{}} var loads atomic.Int32 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) time.Sleep(2 * time.Millisecond) return empty, nil }).Maybe() const workers = 100 var ( wg sync.WaitGroup failures atomic.Int32 ) wg.Add(workers) for range workers { go func() { defer wg.Done() // Naive cache-aside without distributed coordination: every concurrent miss loads. if _, err := s.cache.Get(ctx, key); err != nil { if _, loadErr := source.ListVisible(ctx, alice, nil, 50); 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 distributed coordination concurrent misses stampede the source") s.T().Logf("stampede demonstration: %d concurrent reads -> %d source loads", workers, loads.Load()) }