//go:build integration package redis_test import ( "context" "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" storageredis "mtusi-messenger/internal/storage/redis" "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 := mocks.NewMockChatSource(s.T()) 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 := mocks.NewMockChatSource(s.T()) 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().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) 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.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 := mocks.NewMockChatSource(s.T()) 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 := mocks.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) { 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()) } func (s *ChatRepositorySuite) TestMultipleInstancesShareDistributedLock() { ctx := s.T().Context() alice := uuid.New() empty := domain.Page[domain.Chat]{Items: []domain.Chat{}} source := mocks.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) { 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()) } 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 := mocks.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()) }