lab2
This commit is contained in:
@@ -0,0 +1,183 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"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)
|
||||
ListVersion(ctx context.Context, userID uuid.UUID) (int64, 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.DistributedCache
|
||||
ttl time.Duration
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func NewChatRepository(
|
||||
source ChatSource,
|
||||
cache *cache.DistributedCache,
|
||||
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) {
|
||||
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,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Chat], error) {
|
||||
if after != nil {
|
||||
return r.source.ListVisible(ctx, callerID, after, 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, sourceError{err}
|
||||
}
|
||||
|
||||
return json.Marshal(newChatPageDTO(page))
|
||||
}
|
||||
|
||||
cctx, cancel := context.WithTimeout(ctx, cacheOperationTimeout)
|
||||
defer cancel()
|
||||
|
||||
encoded, err := r.cache.GetOrLoad(cctx, key, r.ttl, loader)
|
||||
if err != nil {
|
||||
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()
|
||||
}
|
||||
} 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 chatListKey(userID uuid.UUID, version int64, limit int) string {
|
||||
return fmt.Sprintf("chat_list:%s:%d:%d", userID, version, 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,428 @@
|
||||
//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())
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
// 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"
|
||||
)
|
||||
|
||||
// NewMockChatSource creates a new instance of MockChatSource. 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 NewMockChatSource(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockChatSource {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockChatSource{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockChatSource is an autogenerated mock type for the ChatSource type
|
||||
type MockChatSource struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockChatSource_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockChatSource) EXPECT() *MockChatSource_Expecter {
|
||||
return &MockChatSource_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockChatSource
|
||||
func (_mock *MockChatSource) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
|
||||
ret := _mock.Called(ctx, draft)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.Chat
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.ChatDraft) (domain.Chat, error)); ok {
|
||||
return returnFunc(ctx, draft)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.ChatDraft) domain.Chat); ok {
|
||||
r0 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Chat)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.ChatDraft) error); ok {
|
||||
r1 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockChatSource_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
|
||||
type MockChatSource_Create_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.ChatDraft
|
||||
func (_e *MockChatSource_Expecter) Create(ctx any, draft any) *MockChatSource_Create_Call {
|
||||
return &MockChatSource_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_Create_Call) Run(run func(ctx context.Context, draft domain.ChatDraft)) *MockChatSource_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.ChatDraft
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.ChatDraft)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_Create_Call) Return(chat domain.Chat, err error) *MockChatSource_Create_Call {
|
||||
_c.Call.Return(chat, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)) *MockChatSource_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// GetVisible provides a mock function for the type MockChatSource
|
||||
func (_mock *MockChatSource) GetVisible(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID) (domain.Chat, error) {
|
||||
ret := _mock.Called(ctx, chatID, callerID)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GetVisible")
|
||||
}
|
||||
|
||||
var r0 domain.Chat
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) (domain.Chat, error)); ok {
|
||||
return returnFunc(ctx, chatID, callerID)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) domain.Chat); ok {
|
||||
r0 = returnFunc(ctx, chatID, callerID)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Chat)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, chatID, callerID)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockChatSource_GetVisible_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetVisible'
|
||||
type MockChatSource_GetVisible_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GetVisible is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - chatID uuid.UUID
|
||||
// - callerID uuid.UUID
|
||||
func (_e *MockChatSource_Expecter) GetVisible(ctx any, chatID any, callerID any) *MockChatSource_GetVisible_Call {
|
||||
return &MockChatSource_GetVisible_Call{Call: _e.mock.On("GetVisible", ctx, chatID, callerID)}
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_GetVisible_Call) Run(run func(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID)) *MockChatSource_GetVisible_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 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_GetVisible_Call) Return(chat domain.Chat, err error) *MockChatSource_GetVisible_Call {
|
||||
_c.Call.Return(chat, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_GetVisible_Call) RunAndReturn(run func(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID) (domain.Chat, error)) *MockChatSource_GetVisible_Call {
|
||||
_c.Call.Return(run)
|
||||
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)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListVisible")
|
||||
}
|
||||
|
||||
var r0 domain.Page[domain.Chat]
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error)); ok {
|
||||
return returnFunc(ctx, callerID, after, limit)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *domain.Cursor, int) domain.Page[domain.Chat]); ok {
|
||||
r0 = returnFunc(ctx, callerID, after, limit)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Page[domain.Chat])
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, *domain.Cursor, int) error); ok {
|
||||
r1 = returnFunc(ctx, callerID, after, limit)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockChatSource_ListVisible_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListVisible'
|
||||
type MockChatSource_ListVisible_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListVisible is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - callerID uuid.UUID
|
||||
// - after *domain.Cursor
|
||||
// - limit int
|
||||
func (_e *MockChatSource_Expecter) ListVisible(ctx any, callerID any, after any, limit any) *MockChatSource_ListVisible_Call {
|
||||
return &MockChatSource_ListVisible_Call{Call: _e.mock.On("ListVisible", ctx, callerID, after, limit)}
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_ListVisible_Call) Run(run func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int)) *MockChatSource_ListVisible_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 *domain.Cursor
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(*domain.Cursor)
|
||||
}
|
||||
var arg3 int
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(int)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_ListVisible_Call) Return(page domain.Page[domain.Chat], err error) *MockChatSource_ListVisible_Call {
|
||||
_c.Call.Return(page, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_ListVisible_Call) RunAndReturn(run func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error)) *MockChatSource_ListVisible_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
Reference in New Issue
Block a user