lab2
Application / Lint (pull_request) Canceled after 0s
Application / Unit tests (pull_request) Canceled after 0s
Application / Docker build (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Vladislav Kunetskiy
2026-10-06 18:58:40 +03:00
parent 51b236a69f
commit 1e38dbdf35
127 changed files with 12148 additions and 2139 deletions
+185
View File
@@ -0,0 +1,185 @@
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)
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) {
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 {
if errors.Is(err, cache.ErrLoadInProgress) {
return domain.Page[domain.Chat]{}, fmt.Errorf("load chat list: %w", domain.ErrUnavailable)
}
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,294 @@
//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())
}
+265
View File
@@ -0,0 +1,265 @@
// 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
}
// 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
}
@@ -0,0 +1,310 @@
// 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"
)
// NewMockSessionSource creates a new instance of MockSessionSource. 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 NewMockSessionSource(t interface {
mock.TestingT
Cleanup(func())
}) *MockSessionSource {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock := &MockSessionSource{}
mock.Mock.Test(t)
t.Cleanup(func() {
if helper, ok := t.(interface{ Helper() }); ok {
helper.Helper()
}
mock.AssertExpectations(t)
})
return mock
}
// MockSessionSource is an autogenerated mock type for the SessionSource type
type MockSessionSource struct {
mock.Mock
}
type MockSessionSource_Expecter struct {
mock *mock.Mock
}
func (_m *MockSessionSource) EXPECT() *MockSessionSource_Expecter {
return &MockSessionSource_Expecter{mock: &_m.Mock}
}
// Create provides a mock function for the type MockSessionSource
func (_mock *MockSessionSource) Create(ctx context.Context, session domain.NewSession) (domain.Session, error) {
ret := _mock.Called(ctx, session)
if len(ret) == 0 {
panic("no return value specified for Create")
}
var r0 domain.Session
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewSession) (domain.Session, error)); ok {
return returnFunc(ctx, session)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewSession) domain.Session); ok {
r0 = returnFunc(ctx, session)
} else {
r0 = ret.Get(0).(domain.Session)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.NewSession) error); ok {
r1 = returnFunc(ctx, session)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockSessionSource_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
type MockSessionSource_Create_Call struct {
*mock.Call
}
// Create is a helper method to define mock.On call
// - ctx context.Context
// - session domain.NewSession
func (_e *MockSessionSource_Expecter) Create(ctx any, session any) *MockSessionSource_Create_Call {
return &MockSessionSource_Create_Call{Call: _e.mock.On("Create", ctx, session)}
}
func (_c *MockSessionSource_Create_Call) Run(run func(ctx context.Context, session domain.NewSession)) *MockSessionSource_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.NewSession
if args[1] != nil {
arg1 = args[1].(domain.NewSession)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockSessionSource_Create_Call) Return(session1 domain.Session, err error) *MockSessionSource_Create_Call {
_c.Call.Return(session1, err)
return _c
}
func (_c *MockSessionSource_Create_Call) RunAndReturn(run func(ctx context.Context, session domain.NewSession) (domain.Session, error)) *MockSessionSource_Create_Call {
_c.Call.Return(run)
return _c
}
// Credentials provides a mock function for the type MockSessionSource
func (_mock *MockSessionSource) Credentials(ctx context.Context, username string) (domain.UserCredentials, error) {
ret := _mock.Called(ctx, username)
if len(ret) == 0 {
panic("no return value specified for Credentials")
}
var r0 domain.UserCredentials
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, string) (domain.UserCredentials, error)); ok {
return returnFunc(ctx, username)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, string) domain.UserCredentials); ok {
r0 = returnFunc(ctx, username)
} else {
r0 = ret.Get(0).(domain.UserCredentials)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
r1 = returnFunc(ctx, username)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockSessionSource_Credentials_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Credentials'
type MockSessionSource_Credentials_Call struct {
*mock.Call
}
// Credentials is a helper method to define mock.On call
// - ctx context.Context
// - username string
func (_e *MockSessionSource_Expecter) Credentials(ctx any, username any) *MockSessionSource_Credentials_Call {
return &MockSessionSource_Credentials_Call{Call: _e.mock.On("Credentials", ctx, username)}
}
func (_c *MockSessionSource_Credentials_Call) Run(run func(ctx context.Context, username string)) *MockSessionSource_Credentials_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 string
if args[1] != nil {
arg1 = args[1].(string)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockSessionSource_Credentials_Call) Return(userCredentials domain.UserCredentials, err error) *MockSessionSource_Credentials_Call {
_c.Call.Return(userCredentials, err)
return _c
}
func (_c *MockSessionSource_Credentials_Call) RunAndReturn(run func(ctx context.Context, username string) (domain.UserCredentials, error)) *MockSessionSource_Credentials_Call {
_c.Call.Return(run)
return _c
}
// Resolve provides a mock function for the type MockSessionSource
func (_mock *MockSessionSource) Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error) {
ret := _mock.Called(ctx, tokenHash)
if len(ret) == 0 {
panic("no return value specified for Resolve")
}
var r0 domain.Session
var r1 error
if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) (domain.Session, error)); ok {
return returnFunc(ctx, tokenHash)
}
if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) domain.Session); ok {
r0 = returnFunc(ctx, tokenHash)
} else {
r0 = ret.Get(0).(domain.Session)
}
if returnFunc, ok := ret.Get(1).(func(context.Context, []byte) error); ok {
r1 = returnFunc(ctx, tokenHash)
} else {
r1 = ret.Error(1)
}
return r0, r1
}
// MockSessionSource_Resolve_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Resolve'
type MockSessionSource_Resolve_Call struct {
*mock.Call
}
// Resolve is a helper method to define mock.On call
// - ctx context.Context
// - tokenHash []byte
func (_e *MockSessionSource_Expecter) Resolve(ctx any, tokenHash any) *MockSessionSource_Resolve_Call {
return &MockSessionSource_Resolve_Call{Call: _e.mock.On("Resolve", ctx, tokenHash)}
}
func (_c *MockSessionSource_Resolve_Call) Run(run func(ctx context.Context, tokenHash []byte)) *MockSessionSource_Resolve_Call {
_c.Call.Run(func(args mock.Arguments) {
var arg0 context.Context
if args[0] != nil {
arg0 = args[0].(context.Context)
}
var arg1 []byte
if args[1] != nil {
arg1 = args[1].([]byte)
}
run(
arg0,
arg1,
)
})
return _c
}
func (_c *MockSessionSource_Resolve_Call) Return(session domain.Session, err error) *MockSessionSource_Resolve_Call {
_c.Call.Return(session, err)
return _c
}
func (_c *MockSessionSource_Resolve_Call) RunAndReturn(run func(ctx context.Context, tokenHash []byte) (domain.Session, error)) *MockSessionSource_Resolve_Call {
_c.Call.Return(run)
return _c
}
// Revoke provides a mock function for the type MockSessionSource
func (_mock *MockSessionSource) Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error {
ret := _mock.Called(ctx, userID, tokenHash)
if len(ret) == 0 {
panic("no return value specified for Revoke")
}
var r0 error
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, []byte) error); ok {
r0 = returnFunc(ctx, userID, tokenHash)
} else {
r0 = ret.Error(0)
}
return r0
}
// MockSessionSource_Revoke_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Revoke'
type MockSessionSource_Revoke_Call struct {
*mock.Call
}
// Revoke is a helper method to define mock.On call
// - ctx context.Context
// - userID uuid.UUID
// - tokenHash []byte
func (_e *MockSessionSource_Expecter) Revoke(ctx any, userID any, tokenHash any) *MockSessionSource_Revoke_Call {
return &MockSessionSource_Revoke_Call{Call: _e.mock.On("Revoke", ctx, userID, tokenHash)}
}
func (_c *MockSessionSource_Revoke_Call) Run(run func(ctx context.Context, userID uuid.UUID, tokenHash []byte)) *MockSessionSource_Revoke_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 []byte
if args[2] != nil {
arg2 = args[2].([]byte)
}
run(
arg0,
arg1,
arg2,
)
})
return _c
}
func (_c *MockSessionSource_Revoke_Call) Return(err error) *MockSessionSource_Revoke_Call {
_c.Call.Return(err)
return _c
}
func (_c *MockSessionSource_Revoke_Call) RunAndReturn(run func(ctx context.Context, userID uuid.UUID, tokenHash []byte) error) *MockSessionSource_Revoke_Call {
_c.Call.Return(run)
return _c
}
@@ -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,241 @@
//go:build integration
package redis_test
import (
"context"
"encoding/hex"
"os"
"strconv"
"testing"
"time"
"github.com/google/uuid"
goredis "github.com/redis/go-redis/v9"
"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"
)
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
}
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())
}
func (s *SessionRepositorySuite) newRepo(source storageredis.SessionSource) *storageredis.SessionRepository {
s.T().Helper()
return storageredis.NewSessionRepository(source, s.cache, 5*time.Minute, nil)
}
func testSession(userID uuid.UUID, expiresAt time.Time) domain.Session {
return domain.Session{
ExpiresAt: expiresAt,
User: domain.User{
ID: userID,
Username: "alice",
DisplayName: "Алиса",
CreatedAt: time.Now().UTC(),
},
}
}
func (s *SessionRepositorySuite) TestCacheTTLCapAndSessionExpiry() {
ctx := s.T().Context()
for _, remaining := range []time.Duration{time.Hour, time.Minute} {
hash := []byte(uuid.NewString())
session := testSession(uuid.New(), time.Now().UTC().Add(remaining))
source := mocks.NewMockSessionSource(s.T())
source.EXPECT().Resolve(mock.Anything, hash).Return(session, nil).Once()
_, err := s.newRepo(source).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 := testSession(uuid.New(), time.Now().UTC().Add(time.Hour))
source := mocks.NewMockSessionSource(s.T())
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(session, nil).Once()
repo := s.newRepo(source)
first, err := repo.Resolve(ctx, tokenHash)
s.Require().NoError(err)
s.Equal(session.User.ID, first.User.ID)
second, err := repo.Resolve(ctx, tokenHash)
s.Require().NoError(err)
s.Equal(session.User.ID, second.User.ID)
}
func (s *SessionRepositorySuite) TestResolveFallsBackToSourceOnMiss() {
ctx := s.T().Context()
tokenHash := []byte("unknown")
source := mocks.NewMockSessionSource(s.T())
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(domain.Session{}, domain.ErrUnauthenticated).Once()
_, err := s.newRepo(source).Resolve(ctx, tokenHash)
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
func (s *SessionRepositorySuite) TestRevokeEvictsCacheAndSource() {
ctx := s.T().Context()
userID := uuid.New()
tokenHash := []byte("hash-revoke")
session := testSession(userID, time.Now().UTC().Add(time.Hour))
source := mocks.NewMockSessionSource(s.T())
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(session, nil).Once()
source.EXPECT().Revoke(mock.Anything, userID, tokenHash).Return(nil).Once()
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(domain.Session{}, domain.ErrUnauthenticated).Once()
repo := s.newRepo(source)
_, err := repo.Resolve(ctx, tokenHash)
s.Require().NoError(err)
s.Require().NoError(repo.Revoke(ctx, userID, tokenHash))
_, err = repo.Resolve(ctx, tokenHash)
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
func (s *SessionRepositorySuite) TestEvictedCacheEntryReloadsFromSource() {
ctx := s.T().Context()
tokenHash := []byte("hash-evicted")
session := testSession(uuid.New(), time.Now().UTC().Add(time.Hour))
source := mocks.NewMockSessionSource(s.T())
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(session, nil).Twice()
repo := s.newRepo(source)
_, err := repo.Resolve(ctx, tokenHash)
s.Require().NoError(err)
// Simulate a Redis flush/restart by dropping the cache entry.
s.Require().NoError(s.client.Del(ctx, sessionCacheKey(tokenHash)).Err())
_, err = repo.Resolve(ctx, tokenHash)
s.Require().NoError(err)
}
func (s *SessionRepositorySuite) TestExpiredSessionIsRejected() {
ctx := s.T().Context()
tokenHash := []byte("hash-expired")
source := mocks.NewMockSessionSource(s.T())
source.EXPECT().Resolve(mock.Anything, tokenHash).Return(domain.Session{}, domain.ErrUnauthenticated).Once()
_, err := s.newRepo(source).Resolve(ctx, tokenHash)
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
}
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()
}