lab2 fix
This commit is contained in:
@@ -51,6 +51,10 @@ func TestCacheLatencyExperiment(t *testing.T) {
|
||||
var loads atomic.Int32
|
||||
|
||||
source := mocks.NewMockChatSource(t)
|
||||
source.EXPECT().ListVersion(mock.Anything, mock.Anything).RunAndReturn(
|
||||
func(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
return realChats.ListVersion(ctx, userID)
|
||||
}).Maybe()
|
||||
source.EXPECT().ListVisible(mock.Anything, mock.Anything, mock.Anything, mock.Anything).
|
||||
RunAndReturn(func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
|
||||
loads.Add(1)
|
||||
|
||||
@@ -67,6 +67,10 @@ func TestCachePerformanceExperiment(t *testing.T) {
|
||||
var loads atomic.Int32
|
||||
|
||||
source := mocks.NewMockChatSource(t)
|
||||
source.EXPECT().ListVersion(mock.Anything, mock.Anything).RunAndReturn(
|
||||
func(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
return realChats.ListVersion(ctx, userID)
|
||||
}).Maybe()
|
||||
source.EXPECT().ListVisible(mock.Anything, mock.Anything, mock.Anything, mock.Anything).
|
||||
RunAndReturn(func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
|
||||
loads.Add(1)
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -44,6 +46,10 @@ func (r *ChatRepository) Create(ctx context.Context, draft domain.ChatDraft) (do
|
||||
return fmt.Errorf("add chat members: %w", mapError(err))
|
||||
}
|
||||
|
||||
if err := queries.BumpChatListVersions(ctx, sortedUnique(draft.MemberIDs)); err != nil {
|
||||
return fmt.Errorf("bump chat list versions: %w", mapError(err))
|
||||
}
|
||||
|
||||
created = mapChat(row.ID, row.Title, row.CreatedAt, draft.MemberIDs)
|
||||
|
||||
return nil
|
||||
@@ -54,6 +60,27 @@ func (r *ChatRepository) Create(ctx context.Context, draft domain.ChatDraft) (do
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) ListVersion(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
version, err := r.store.queries.GetChatListVersion(ctx, userID)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("get chat list version: %w", mapError(err))
|
||||
}
|
||||
|
||||
return version, nil
|
||||
}
|
||||
|
||||
func sortedUnique(ids []uuid.UUID) []uuid.UUID {
|
||||
sorted := slices.Clone(ids)
|
||||
slices.SortFunc(sorted, func(a, b uuid.UUID) int {
|
||||
return bytes.Compare(a[:], b[:])
|
||||
})
|
||||
|
||||
return slices.Compact(sorted)
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -49,6 +52,85 @@ func (s *ChatRepositorySuite) TestCreateRejectsDuplicateMembers() {
|
||||
s.Require().ErrorIs(err, domain.ErrConflict)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestCreateBumpsMemberListVersions() {
|
||||
ctx := s.T().Context()
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
carol := s.createUser("carol")
|
||||
|
||||
s.createChat(alice, bob)
|
||||
|
||||
aliceVersion, err := s.store.Chats().ListVersion(ctx, alice.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(int64(1), aliceVersion, "creator version must be bumped")
|
||||
|
||||
bobVersion, err := s.store.Chats().ListVersion(ctx, bob.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(int64(1), bobVersion, "member version must be bumped")
|
||||
|
||||
carolVersion, err := s.store.Chats().ListVersion(ctx, carol.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Zero(carolVersion, "non-member version must stay unchanged")
|
||||
|
||||
s.createChat(alice, carol)
|
||||
|
||||
aliceVersion, err = s.store.Chats().ListVersion(ctx, alice.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(int64(2), aliceVersion, "version must grow monotonically")
|
||||
|
||||
carolVersion, err = s.store.Chats().ListVersion(ctx, carol.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(int64(1), carolVersion)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestConcurrentCreateNoDeadlock() {
|
||||
ctx := s.T().Context()
|
||||
|
||||
users := make([]domain.User, 0, 8)
|
||||
for i := range 8 {
|
||||
users = append(users, s.createUser(fmt.Sprintf("member%d", i)))
|
||||
}
|
||||
|
||||
const workers = 16
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
errs := make(chan error, workers)
|
||||
|
||||
wg.Add(workers)
|
||||
|
||||
for w := range workers {
|
||||
go func(w int) {
|
||||
defer wg.Done()
|
||||
|
||||
ids := []uuid.UUID{
|
||||
users[w%len(users)].ID,
|
||||
users[(w+1)%len(users)].ID,
|
||||
users[(w+2)%len(users)].ID,
|
||||
}
|
||||
if w%2 == 1 {
|
||||
slices.Reverse(ids)
|
||||
}
|
||||
|
||||
_, err := s.store.Chats().Create(ctx, domain.ChatDraft{
|
||||
Title: fmt.Sprintf("chat-%d", w),
|
||||
MemberIDs: ids,
|
||||
CallerID: ids[0],
|
||||
})
|
||||
if err != nil {
|
||||
errs <- err
|
||||
}
|
||||
}(w)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
|
||||
for err := range errs {
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestCreateStoresAllMembers() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
|
||||
@@ -28,6 +28,19 @@ func (q *Queries) AddChatMembers(ctx context.Context, arg AddChatMembersParams)
|
||||
return err
|
||||
}
|
||||
|
||||
const bumpChatListVersions = `-- name: BumpChatListVersions :exec
|
||||
INSERT INTO user_chat_versions (user_id, version)
|
||||
SELECT DISTINCT m, 1
|
||||
FROM unnest($1::uuid[]) AS m
|
||||
ORDER BY m
|
||||
ON CONFLICT (user_id) DO UPDATE SET version = user_chat_versions.version + 1
|
||||
`
|
||||
|
||||
func (q *Queries) BumpChatListVersions(ctx context.Context, userIds []uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, bumpChatListVersions, userIds)
|
||||
return err
|
||||
}
|
||||
|
||||
const createChat = `-- name: CreateChat :one
|
||||
INSERT INTO chats (title)
|
||||
VALUES ($1)
|
||||
@@ -81,6 +94,19 @@ func (q *Queries) GetChatForMember(ctx context.Context, arg GetChatForMemberPara
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getChatListVersion = `-- name: GetChatListVersion :one
|
||||
SELECT COALESCE(MAX(version), 0)::bigint AS version
|
||||
FROM user_chat_versions
|
||||
WHERE user_id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetChatListVersion(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, getChatListVersion, userID)
|
||||
var version int64
|
||||
err := row.Scan(&version)
|
||||
return version, err
|
||||
}
|
||||
|
||||
const listChatsForMember = `-- name: ListChatsForMember :many
|
||||
SELECT
|
||||
c.id,
|
||||
|
||||
@@ -44,3 +44,8 @@ type User struct {
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type UserChatVersion struct {
|
||||
UserID uuid.UUID
|
||||
Version int64
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ func (q *Queries) DeleteSession(ctx context.Context, arg DeleteSessionParams) er
|
||||
}
|
||||
|
||||
const getSessionUser = `-- name: GetSessionUser :one
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, u.password_hash, s.expires_at
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1
|
||||
@@ -62,12 +62,11 @@ WHERE s.token_hash = $1
|
||||
`
|
||||
|
||||
type GetSessionUserRow struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
PasswordHash string
|
||||
ExpiresAt time.Time
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) GetSessionUser(ctx context.Context, tokenHash []byte) (GetSessionUserRow, error) {
|
||||
@@ -78,7 +77,6 @@ func (q *Queries) GetSessionUser(ctx context.Context, tokenHash []byte) (GetSess
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.CreatedAt,
|
||||
&i.PasswordHash,
|
||||
&i.ExpiresAt,
|
||||
)
|
||||
return i, err
|
||||
|
||||
@@ -44,6 +44,10 @@ CREATE TABLE sessions (
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE user_chat_versions (
|
||||
user_id uuid PRIMARY KEY REFERENCES users (id) ON DELETE CASCADE,
|
||||
version bigint NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE INDEX messages_chat_id_created_at_id_idx
|
||||
ON messages (chat_id, created_at, id);
|
||||
@@ -54,6 +58,9 @@ CREATE INDEX chat_members_user_id_chat_id_idx
|
||||
CREATE INDEX chats_created_at_id_idx
|
||||
ON chats (created_at, id);
|
||||
|
||||
CREATE INDEX sessions_user_id_idx
|
||||
ON sessions (user_id);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE sessions;
|
||||
@@ -61,3 +68,4 @@ DROP TABLE messages;
|
||||
DROP TABLE chat_members;
|
||||
DROP TABLE chats;
|
||||
DROP TABLE users;
|
||||
DROP TABLE user_chat_versions;
|
||||
|
||||
@@ -14,6 +14,18 @@ FROM unnest(sqlc.arg(user_ids)::uuid[]) AS input(id)
|
||||
LEFT JOIN users u ON u.id = input.id
|
||||
WHERE u.id IS NULL;
|
||||
|
||||
-- name: BumpChatListVersions :exec
|
||||
INSERT INTO user_chat_versions (user_id, version)
|
||||
SELECT DISTINCT m, 1
|
||||
FROM unnest(sqlc.arg(user_ids)::uuid[]) AS m
|
||||
ORDER BY m
|
||||
ON CONFLICT (user_id) DO UPDATE SET version = user_chat_versions.version + 1;
|
||||
|
||||
-- name: GetChatListVersion :one
|
||||
SELECT COALESCE(MAX(version), 0)::bigint AS version
|
||||
FROM user_chat_versions
|
||||
WHERE user_id = sqlc.arg(user_id);
|
||||
|
||||
-- name: GetChatForMember :one
|
||||
SELECT
|
||||
c.id,
|
||||
|
||||
@@ -4,7 +4,7 @@ VALUES (sqlc.arg(token_hash), sqlc.arg(user_id), sqlc.arg(expires_at))
|
||||
RETURNING token_hash, user_id, expires_at;
|
||||
|
||||
-- name: GetSessionUser :one
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, u.password_hash, s.expires_at
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = sqlc.arg(token_hash)
|
||||
|
||||
@@ -80,14 +80,13 @@ func (r *SessionRepository) Resolve(ctx context.Context, tokenHash []byte) (doma
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Revoke is intentionally idempotent: deleting an already absent session is a no-op.
|
||||
// The HTTP contract for DELETE /auth/sessions/current defines only 204/401, so a
|
||||
// missing session must not surface as an error.
|
||||
func (r *SessionRepository) Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
if err := r.store.queries.DeleteSession(ctx, sqlcgen.DeleteSessionParams{TokenHash: tokenHash, UserID: userID}); err != nil {
|
||||
if err := r.store.queries.DeleteSession(
|
||||
ctx, sqlcgen.DeleteSessionParams{TokenHash: tokenHash, UserID: userID},
|
||||
); err != nil {
|
||||
return fmt.Errorf("revoke session: %w", mapError(err))
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
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,
|
||||
@@ -42,20 +43,21 @@ func NewChatRepository(
|
||||
}
|
||||
|
||||
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
|
||||
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,
|
||||
@@ -66,58 +68,54 @@ func (r *ChatRepository) ListVisible(
|
||||
return r.source.ListVisible(ctx, callerID, after, limit)
|
||||
}
|
||||
|
||||
key := chatListKey(callerID, r.generation(ctx, callerID), 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, err
|
||||
return nil, sourceError{err}
|
||||
}
|
||||
|
||||
return json.Marshal(newChatPageDTO(page))
|
||||
}
|
||||
|
||||
encoded, err := r.cache.GetOrLoad(ctx, key, r.ttl, loader)
|
||||
cctx, cancel := context.WithTimeout(ctx, cacheOperationTimeout)
|
||||
defer cancel()
|
||||
|
||||
encoded, err := r.cache.GetOrLoad(cctx, 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)
|
||||
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()
|
||||
}
|
||||
|
||||
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))
|
||||
} 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 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)
|
||||
func chatListKey(userID uuid.UUID, version int64, limit int) string {
|
||||
return fmt.Sprintf("chat_list:%s:%d:%d", userID, version, limit)
|
||||
}
|
||||
|
||||
type chatPageDTO struct {
|
||||
|
||||
@@ -4,6 +4,7 @@ package redis_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
@@ -15,8 +16,9 @@ import (
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
cachemocks "mtusi-messenger/internal/platform/cache/mocks"
|
||||
storageredis "mtusi-messenger/internal/storage/redis"
|
||||
"mtusi-messenger/internal/storage/redis/mocks"
|
||||
storagemocks "mtusi-messenger/internal/storage/redis/mocks"
|
||||
)
|
||||
|
||||
type ChatRepositorySuite struct {
|
||||
@@ -65,7 +67,8 @@ func (s *ChatRepositorySuite) TestFirstPageIsCached() {
|
||||
alice := uuid.New()
|
||||
page := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := mocks.NewMockChatSource(s.T())
|
||||
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)
|
||||
@@ -92,10 +95,14 @@ func (s *ChatRepositorySuite) TestCreateInvalidatesMemberCaches() {
|
||||
}
|
||||
page := domain.Page[domain.Chat]{Items: []domain.Chat{chat}}
|
||||
|
||||
source := mocks.NewMockChatSource(s.T())
|
||||
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()
|
||||
|
||||
@@ -122,13 +129,34 @@ func (s *ChatRepositorySuite) TestCreateInvalidatesMemberCaches() {
|
||||
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 := mocks.NewMockChatSource(s.T())
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, cursor, 50).Return(empty, nil).Twice()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
@@ -144,7 +172,8 @@ func (s *ChatRepositorySuite) TestLimitIsPartOfCacheKey() {
|
||||
alice := uuid.New()
|
||||
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := mocks.NewMockChatSource(s.T())
|
||||
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()
|
||||
|
||||
@@ -161,7 +190,8 @@ func (s *ChatRepositorySuite) TestConcurrentColdReadsAreDeduplicated() {
|
||||
alice := uuid.New()
|
||||
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := mocks.NewMockChatSource(s.T())
|
||||
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)
|
||||
@@ -193,6 +223,7 @@ func (s *ChatRepositorySuite) TestConcurrentColdReadsAreDeduplicated() {
|
||||
wg.Wait()
|
||||
|
||||
s.Require().Zero(failures.Load())
|
||||
s.T().Logf("distributed lock: %d concurrent cold reads -> 1 source load", workers)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestMultipleInstancesShareDistributedLock() {
|
||||
@@ -200,7 +231,8 @@ func (s *ChatRepositorySuite) TestMultipleInstancesShareDistributedLock() {
|
||||
alice := uuid.New()
|
||||
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := mocks.NewMockChatSource(s.T())
|
||||
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)
|
||||
@@ -241,6 +273,108 @@ func (s *ChatRepositorySuite) TestMultipleInstancesShareDistributedLock() {
|
||||
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() {
|
||||
@@ -251,7 +385,7 @@ func (s *ChatRepositorySuite) TestConcurrentColdReadsWithoutProtectionStampede()
|
||||
|
||||
var loads atomic.Int32
|
||||
|
||||
source := mocks.NewMockChatSource(s.T())
|
||||
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)
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -186,6 +186,72 @@ func (_c *MockChatSource_GetVisible_Call) RunAndReturn(run func(ctx context.Cont
|
||||
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)
|
||||
|
||||
@@ -1,310 +0,0 @@
|
||||
// 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
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
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)
|
||||
}
|
||||
@@ -1,241 +0,0 @@
|
||||
//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()
|
||||
}
|
||||
Reference in New Issue
Block a user