lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
@@ -0,0 +1,162 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
storageredis "mtusi-messenger/internal/storage/redis"
|
||||
"mtusi-messenger/internal/storage/redis/mocks"
|
||||
)
|
||||
|
||||
func TestCacheLatencyExperiment(t *testing.T) {
|
||||
suite := new(BaseSuite)
|
||||
suite.SetT(t)
|
||||
suite.SetupTest()
|
||||
defer suite.TearDownTest()
|
||||
|
||||
ctx := context.Background()
|
||||
redisConfig := cache.RedisConfig{
|
||||
Host: envOr("TEST_REDIS_HOST", "localhost"),
|
||||
Port: envInt("TEST_REDIS_PORT", 6379),
|
||||
Username: envOr("TEST_REDIS_USERNAME", "operator"),
|
||||
Password: os.Getenv("TEST_REDIS_PASSWORD"),
|
||||
DB: envInt("TEST_REDIS_DB", 7),
|
||||
DialTimeout: 5 * time.Second,
|
||||
ReadTimeout: 3 * time.Second,
|
||||
WriteTimeout: 3 * time.Second,
|
||||
PoolSize: 5,
|
||||
}
|
||||
require.NotZero(t, redisConfig.DB, "cache experiment must not use production redis db 0")
|
||||
redisCache, err := cache.NewRedis(ctx, redisConfig)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = redisCache.Close() }()
|
||||
|
||||
alice := suite.createUser("latency_alice")
|
||||
for range 20 {
|
||||
suite.createChat(alice)
|
||||
}
|
||||
|
||||
realChats := suite.store.Chats()
|
||||
|
||||
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)
|
||||
|
||||
return realChats.ListVisible(ctx, callerID, after, limit)
|
||||
}).Maybe()
|
||||
|
||||
for range 50 {
|
||||
_, err := source.ListVisible(ctx, alice.ID, nil, 50)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
loads.Store(0)
|
||||
baseline := measureLatency(ctx, t, source.ListVisible, &loads, alice.ID, 1000)
|
||||
|
||||
distributed, err := cache.NewDistributed(redisCache, cache.DistributedConfig{}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
cached := storageredis.NewChatRepository(
|
||||
source,
|
||||
distributed,
|
||||
time.Minute,
|
||||
nil,
|
||||
)
|
||||
loads.Store(0)
|
||||
cachedStats := measureCachedLatency(ctx, t, cached, alice.ID, 1000)
|
||||
cachedStats.Loads = int(loads.Load())
|
||||
require.Equal(t, 1000, baseline.Loads)
|
||||
require.Equal(t, 1, cachedStats.Loads)
|
||||
|
||||
t.Logf("baseline: %s", formatLatency(baseline))
|
||||
t.Logf("redis cache: %s", formatLatency(cachedStats))
|
||||
}
|
||||
|
||||
func measureLatency(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
list func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error),
|
||||
loads *atomic.Int32,
|
||||
callerID uuid.UUID,
|
||||
requests int,
|
||||
) latencyStats {
|
||||
t.Helper()
|
||||
values := make([]time.Duration, 0, requests)
|
||||
for range requests {
|
||||
started := time.Now()
|
||||
_, err := list(ctx, callerID, nil, 50)
|
||||
require.NoError(t, err)
|
||||
values = append(values, time.Since(started))
|
||||
}
|
||||
|
||||
return makeLatencyStats(values, int(loads.Load()))
|
||||
}
|
||||
|
||||
func measureCachedLatency(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
repository *storageredis.ChatRepository,
|
||||
callerID uuid.UUID,
|
||||
requests int,
|
||||
) latencyStats {
|
||||
t.Helper()
|
||||
values := make([]time.Duration, 0, requests)
|
||||
for range requests {
|
||||
started := time.Now()
|
||||
_, err := repository.ListVisible(ctx, callerID, nil, 50)
|
||||
require.NoError(t, err)
|
||||
values = append(values, time.Since(started))
|
||||
}
|
||||
|
||||
return makeLatencyStats(values, 0)
|
||||
}
|
||||
|
||||
type latencyStats struct {
|
||||
Requests int
|
||||
Loads int
|
||||
P50 time.Duration
|
||||
P95 time.Duration
|
||||
P99 time.Duration
|
||||
}
|
||||
|
||||
func makeLatencyStats(values []time.Duration, loads int) latencyStats {
|
||||
sort.Slice(values, func(i, j int) bool { return values[i] < values[j] })
|
||||
percentile := func(percent int) time.Duration {
|
||||
index := (len(values)*percent + 99) / 100
|
||||
if index > 0 {
|
||||
index--
|
||||
}
|
||||
return values[index]
|
||||
}
|
||||
|
||||
return latencyStats{
|
||||
Requests: len(values), Loads: loads,
|
||||
P50: percentile(50), P95: percentile(95), P99: percentile(99),
|
||||
}
|
||||
}
|
||||
|
||||
func formatLatency(value latencyStats) string {
|
||||
return fmt.Sprintf(
|
||||
"requests=%d source_loads=%d p50=%s p95=%s p99=%s",
|
||||
value.Requests, value.Loads, value.P50, value.P95, value.P99,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
storageredis "mtusi-messenger/internal/storage/redis"
|
||||
"mtusi-messenger/internal/storage/redis/mocks"
|
||||
)
|
||||
|
||||
func TestCachePerformanceExperiment(t *testing.T) {
|
||||
suite := new(BaseSuite)
|
||||
suite.SetT(t)
|
||||
suite.SetupTest()
|
||||
defer suite.TearDownTest()
|
||||
|
||||
ctx := context.Background()
|
||||
redisConfig := cache.RedisConfig{
|
||||
Host: envOr("TEST_REDIS_HOST", "localhost"),
|
||||
Port: envInt("TEST_REDIS_PORT", 6379),
|
||||
Username: envOr("TEST_REDIS_USERNAME", "operator"),
|
||||
Password: os.Getenv("TEST_REDIS_PASSWORD"),
|
||||
DB: envInt("TEST_REDIS_DB", 7),
|
||||
DialTimeout: 5 * time.Second,
|
||||
ReadTimeout: 3 * time.Second,
|
||||
WriteTimeout: 3 * time.Second,
|
||||
PoolSize: 10,
|
||||
}
|
||||
require.NotZero(t, redisConfig.DB, "cache experiment must not use production redis db 0")
|
||||
redisCache, err := cache.NewRedis(ctx, redisConfig)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = redisCache.Close() }()
|
||||
|
||||
alice := suite.createUser("perf_alice")
|
||||
bob := suite.createUser("perf_bob")
|
||||
carol := suite.createUser("perf_carol")
|
||||
|
||||
for i := range 150 {
|
||||
title := fmt.Sprintf("Chat %d with Alice", i+1)
|
||||
members := []uuid.UUID{alice.ID}
|
||||
if i%3 == 0 {
|
||||
members = append(members, bob.ID)
|
||||
}
|
||||
if i%5 == 0 {
|
||||
members = append(members, carol.ID)
|
||||
}
|
||||
_, err := suite.store.Chats().Create(ctx, domain.ChatDraft{
|
||||
Title: title,
|
||||
MemberIDs: members,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
realChats := suite.store.Chats()
|
||||
|
||||
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)
|
||||
|
||||
return realChats.ListVisible(ctx, callerID, after, limit)
|
||||
}).Maybe()
|
||||
|
||||
distributed, err := cache.NewDistributed(redisCache, cache.DistributedConfig{}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
cached := storageredis.NewChatRepository(
|
||||
source,
|
||||
distributed,
|
||||
time.Minute,
|
||||
nil,
|
||||
)
|
||||
|
||||
baselineStats := benchmarkConcurrent(ctx, t, func(ctx context.Context) error {
|
||||
_, err := source.ListVisible(ctx, alice.ID, nil, 50)
|
||||
return err
|
||||
}, 50, 200)
|
||||
|
||||
baselineStats.SQLQueries = int(loads.Load())
|
||||
loads.Store(0)
|
||||
cachedStats := benchmarkConcurrent(ctx, t, func(ctx context.Context) error {
|
||||
_, err := cached.ListVisible(ctx, alice.ID, nil, 50)
|
||||
return err
|
||||
}, 50, 200)
|
||||
|
||||
cachedStats.SQLQueries = int(loads.Load())
|
||||
loads.Store(0)
|
||||
|
||||
_, err = cached.ListVisible(ctx, alice.ID, nil, 50)
|
||||
require.NoError(t, err)
|
||||
|
||||
cachedHotStats := benchmarkConcurrent(ctx, t, func(ctx context.Context) error {
|
||||
_, err := cached.ListVisible(ctx, alice.ID, nil, 50)
|
||||
return err
|
||||
}, 50, 200)
|
||||
cachedHotStats.SQLQueries = int(loads.Load())
|
||||
|
||||
t.Logf("baseline (no cache): %s", formatPerfStats(baselineStats))
|
||||
t.Logf("redis cache (cold): %s", formatPerfStats(cachedStats))
|
||||
t.Logf("redis cache (hot): %s", formatPerfStats(cachedHotStats))
|
||||
}
|
||||
|
||||
type perfStats struct {
|
||||
TotalRequests int
|
||||
Concurrency int
|
||||
SQLQueries int
|
||||
Duration time.Duration
|
||||
RPS float64
|
||||
P50 time.Duration
|
||||
P95 time.Duration
|
||||
P99 time.Duration
|
||||
}
|
||||
|
||||
func benchmarkConcurrent(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
operation func(context.Context) error,
|
||||
concurrency int,
|
||||
requestsPerWorker int,
|
||||
) perfStats {
|
||||
t.Helper()
|
||||
|
||||
totalRequests := concurrency * requestsPerWorker
|
||||
latencies := make([]time.Duration, totalRequests)
|
||||
var wg sync.WaitGroup
|
||||
var failures atomic.Int32
|
||||
started := time.Now()
|
||||
|
||||
for worker := range concurrency {
|
||||
wg.Add(1)
|
||||
go func(workerID int) {
|
||||
defer wg.Done()
|
||||
offset := workerID * requestsPerWorker
|
||||
for i := range requestsPerWorker {
|
||||
reqStart := time.Now()
|
||||
err := operation(ctx)
|
||||
if err != nil {
|
||||
failures.Add(1)
|
||||
}
|
||||
latencies[offset+i] = time.Since(reqStart)
|
||||
}
|
||||
}(worker)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
require.Zero(t, failures.Load(), "some requests failed")
|
||||
duration := time.Since(started)
|
||||
|
||||
sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] })
|
||||
percentile := func(p int) time.Duration {
|
||||
index := (len(latencies)*p + 99) / 100
|
||||
if index > 0 {
|
||||
index--
|
||||
}
|
||||
return latencies[index]
|
||||
}
|
||||
|
||||
return perfStats{
|
||||
TotalRequests: totalRequests,
|
||||
Concurrency: concurrency,
|
||||
Duration: duration,
|
||||
RPS: float64(totalRequests) / duration.Seconds(),
|
||||
P50: percentile(50),
|
||||
P95: percentile(95),
|
||||
P99: percentile(99),
|
||||
}
|
||||
}
|
||||
|
||||
func formatPerfStats(s perfStats) string {
|
||||
return fmt.Sprintf(
|
||||
"requests=%d concurrency=%d sql=%d duration=%s rps=%.0f p50=%s p95=%s p99=%s",
|
||||
s.TotalRequests, s.Concurrency, s.SQLQueries, s.Duration.Round(time.Millisecond),
|
||||
s.RPS, s.P50, s.P95, s.P99,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
|
||||
)
|
||||
|
||||
type ChatRepository struct {
|
||||
store *Store
|
||||
}
|
||||
|
||||
func (r *ChatRepository) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var created domain.Chat
|
||||
|
||||
if err := r.store.RunInTx(ctx, func(queries *sqlcgen.Queries) error {
|
||||
missing, err := queries.ListMissingUserIDs(ctx, draft.MemberIDs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check chat members: %w", mapError(err))
|
||||
}
|
||||
|
||||
if len(missing) > 0 {
|
||||
return domain.ErrUnknownMember
|
||||
}
|
||||
|
||||
row, err := queries.CreateChat(ctx, draft.Title)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create chat: %w", mapError(err))
|
||||
}
|
||||
|
||||
if err := queries.AddChatMembers(ctx, sqlcgen.AddChatMembersParams{
|
||||
ChatID: row.ID,
|
||||
UserIds: draft.MemberIDs,
|
||||
}); err != nil {
|
||||
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
|
||||
}); err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
|
||||
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()
|
||||
|
||||
row, err := r.store.queries.GetChatForMember(ctx, sqlcgen.GetChatForMemberParams{
|
||||
UserID: callerID,
|
||||
ID: chatID,
|
||||
})
|
||||
if err != nil {
|
||||
mapped := mapError(err)
|
||||
if errors.Is(mapped, domain.ErrNotFound) {
|
||||
return domain.Chat{}, fmt.Errorf("%w: chat %s for user %s", domain.ErrNotFound, chatID, callerID)
|
||||
}
|
||||
|
||||
return domain.Chat{}, fmt.Errorf("get chat: %w", mapped)
|
||||
}
|
||||
|
||||
return mapChat(row.ID, row.Title, row.CreatedAt, row.MemberIds), nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) ListVisible(
|
||||
ctx context.Context,
|
||||
callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Chat], error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
limit = clampLimit(limit)
|
||||
fetch := int32(limit + 1) //nolint:gosec // limit is clamped to maxPageSize
|
||||
|
||||
var rows []domain.Chat
|
||||
|
||||
if after == nil {
|
||||
pageRows, err := r.store.queries.ListChatsForMember(ctx, sqlcgen.ListChatsForMemberParams{
|
||||
UserID: callerID,
|
||||
RowLimit: fetch,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, fmt.Errorf("list chats: %w", mapError(err))
|
||||
}
|
||||
|
||||
rows = mapAll(pageRows, mapChatRow)
|
||||
} else {
|
||||
pageRows, err := r.store.queries.ListChatsForMemberAfter(ctx, sqlcgen.ListChatsForMemberAfterParams{
|
||||
UserID: callerID,
|
||||
AfterCreatedAt: after.CreatedAt,
|
||||
AfterID: after.ID,
|
||||
RowLimit: fetch,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, fmt.Errorf("list chats: %w", mapError(err))
|
||||
}
|
||||
|
||||
rows = mapAll(pageRows, mapChatRowAfter)
|
||||
}
|
||||
|
||||
return buildPage(rows, limit, func(chat domain.Chat) domain.Cursor {
|
||||
return domain.Cursor{Scope: callerID, CreatedAt: chat.CreatedAt, ID: chat.ID}
|
||||
}), nil
|
||||
}
|
||||
|
||||
func mapChatRow(row sqlcgen.ListChatsForMemberRow) domain.Chat {
|
||||
return mapChat(row.ID, row.Title, row.CreatedAt, row.MemberIds)
|
||||
}
|
||||
|
||||
func mapChatRowAfter(row sqlcgen.ListChatsForMemberAfterRow) domain.Chat {
|
||||
return mapChat(row.ID, row.Title, row.CreatedAt, row.MemberIds)
|
||||
}
|
||||
|
||||
func mapChat(id uuid.UUID, title string, createdAt time.Time, memberIDs []uuid.UUID) domain.Chat {
|
||||
return domain.Chat{
|
||||
ID: id,
|
||||
Title: title,
|
||||
MemberIDs: memberIDs,
|
||||
CreatedAt: toUTCTime(createdAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type ChatRepositorySuite struct {
|
||||
BaseSuite
|
||||
}
|
||||
|
||||
func TestChatRepositorySuite(t *testing.T) {
|
||||
suite.Run(t, new(ChatRepositorySuite))
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestCreateRejectsUnknownMemberAtomically() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
_, err := s.store.Chats().Create(s.T().Context(), domain.ChatDraft{
|
||||
Title: "С неизвестным участником",
|
||||
MemberIDs: []uuid.UUID{alice.ID, uuid.New()},
|
||||
CallerID: alice.ID,
|
||||
})
|
||||
s.Require().ErrorIs(err, domain.ErrUnknownMember)
|
||||
|
||||
var chats int
|
||||
s.Require().NoError(s.pool.QueryRow(s.T().Context(), "SELECT count(*) FROM chats").Scan(&chats))
|
||||
s.Zero(chats, "неуспешное создание чата не оставляет строк")
|
||||
|
||||
var members int
|
||||
s.Require().NoError(s.pool.QueryRow(s.T().Context(), "SELECT count(*) FROM chat_members").Scan(&members))
|
||||
s.Zero(members)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestCreateRejectsDuplicateMembers() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
_, err := s.store.Chats().Create(s.T().Context(), domain.ChatDraft{
|
||||
Title: "Дубликаты",
|
||||
MemberIDs: []uuid.UUID{alice.ID, alice.ID},
|
||||
CallerID: alice.ID,
|
||||
})
|
||||
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")
|
||||
eve := s.createUser("eve")
|
||||
|
||||
chat := s.createChat(alice, bob, eve)
|
||||
s.Equal(uuid.Version(7), chat.ID.Version())
|
||||
s.False(chat.CreatedAt.IsZero())
|
||||
|
||||
visible, err := s.store.Chats().GetVisible(s.T().Context(), chat.ID, bob.ID)
|
||||
s.Require().NoError(err)
|
||||
s.ElementsMatch([]uuid.UUID{alice.ID, bob.ID, eve.ID}, visible.MemberIDs)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestVisibility() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
eve := s.createUser("eve")
|
||||
|
||||
chat := s.createChat(alice, bob)
|
||||
|
||||
visible, err := s.store.Chats().GetVisible(s.T().Context(), chat.ID, bob.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(chat.ID, visible.ID)
|
||||
s.ElementsMatch([]uuid.UUID{alice.ID, bob.ID}, visible.MemberIDs)
|
||||
|
||||
_, err = s.store.Chats().GetVisible(s.T().Context(), chat.ID, eve.ID)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
|
||||
page, err := s.store.Chats().ListVisible(s.T().Context(), eve.ID, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
s.Empty(page.Items)
|
||||
|
||||
page, err = s.store.Chats().ListVisible(s.T().Context(), alice.ID, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(page.Items, 1)
|
||||
s.ElementsMatch([]uuid.UUID{alice.ID, bob.ID}, page.Items[0].MemberIDs)
|
||||
s.Nil(page.Next)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestListPagination() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
const total = 5
|
||||
for range total {
|
||||
s.createChat(alice)
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, total)
|
||||
|
||||
var cursor *domain.Cursor
|
||||
|
||||
for {
|
||||
page, err := s.store.Chats().ListVisible(s.T().Context(), alice.ID, cursor, 2)
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotEmpty(page.Items)
|
||||
|
||||
for _, chat := range page.Items {
|
||||
_, duplicate := seen[chat.ID]
|
||||
s.Require().False(duplicate)
|
||||
seen[chat.ID] = struct{}{}
|
||||
}
|
||||
|
||||
if page.Next == nil {
|
||||
break
|
||||
}
|
||||
|
||||
cursor = page.Next
|
||||
}
|
||||
|
||||
s.Len(seen, total)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestListPaginationWithSharedTimestamp() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
for range 5 {
|
||||
s.createChat(alice)
|
||||
}
|
||||
|
||||
_, err := s.pool.Exec(s.T().Context(), "UPDATE chats SET created_at = '2026-01-01 00:00:00+00'")
|
||||
s.Require().NoError(err)
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, 5)
|
||||
|
||||
var cursor *domain.Cursor
|
||||
|
||||
for {
|
||||
page, err := s.store.Chats().ListVisible(s.T().Context(), alice.ID, cursor, 2)
|
||||
s.Require().NoError(err)
|
||||
|
||||
for _, chat := range page.Items {
|
||||
_, duplicate := seen[chat.ID]
|
||||
s.Require().False(duplicate)
|
||||
seen[chat.ID] = struct{}{}
|
||||
}
|
||||
|
||||
if page.Next == nil {
|
||||
break
|
||||
}
|
||||
|
||||
cursor = page.Next
|
||||
}
|
||||
|
||||
s.Len(seen, 5)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/platform/tlsconfig"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultHost = "localhost"
|
||||
defaultPort = 5432
|
||||
defaultDatabase = "messenger"
|
||||
defaultMaxConns = int32(10)
|
||||
defaultMinConns = int32(1)
|
||||
defaultMaxConnLifetime = time.Hour
|
||||
defaultMaxConnIdleTime = 30 * time.Minute
|
||||
defaultConnectTimeout = 5 * time.Second
|
||||
defaultQueryTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
func normalize(cfg config.Postgres) (config.Postgres, error) {
|
||||
if cfg.Host == "" {
|
||||
cfg.Host = defaultHost
|
||||
}
|
||||
|
||||
if strings.ContainsAny(cfg.Host, "/, \t\r\n") {
|
||||
return cfg, errors.New("postgres: host must be a single tcp hostname or ip address")
|
||||
}
|
||||
if cfg.Port == 0 {
|
||||
cfg.Port = defaultPort
|
||||
}
|
||||
|
||||
if cfg.Database == "" {
|
||||
cfg.Database = defaultDatabase
|
||||
}
|
||||
|
||||
if cfg.User == "" || cfg.Password == "" {
|
||||
return cfg, errors.New("postgres: user and password are required")
|
||||
}
|
||||
if cfg.SSLMode == "" {
|
||||
cfg.SSLMode = "verify-full"
|
||||
}
|
||||
if cfg.SSLMode != "verify-full" {
|
||||
return cfg, errors.New("postgres: ssl_mode must be verify-full")
|
||||
}
|
||||
|
||||
if cfg.MaxConns == 0 {
|
||||
cfg.MaxConns = defaultMaxConns
|
||||
}
|
||||
|
||||
if cfg.MinConns == 0 {
|
||||
cfg.MinConns = defaultMinConns
|
||||
}
|
||||
|
||||
if cfg.MaxConnLifetime == 0 {
|
||||
cfg.MaxConnLifetime = defaultMaxConnLifetime
|
||||
}
|
||||
|
||||
if cfg.MaxConnIdleTime == 0 {
|
||||
cfg.MaxConnIdleTime = defaultMaxConnIdleTime
|
||||
}
|
||||
|
||||
if cfg.ConnectTimeout == 0 {
|
||||
cfg.ConnectTimeout = defaultConnectTimeout
|
||||
}
|
||||
|
||||
if cfg.QueryTimeout == 0 {
|
||||
cfg.QueryTimeout = defaultQueryTimeout
|
||||
}
|
||||
|
||||
if cfg.MinConns > cfg.MaxConns {
|
||||
return cfg, errors.New("postgres: min_conns must not exceed max_conns")
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// PoolConfig is shared by application pools and operator migration connections.
|
||||
// Every new connection verifies the hostname, current trust bundle and CRLs.
|
||||
func PoolConfig(cfg config.Postgres) (*pgxpool.Config, error) {
|
||||
cfg, err := normalize(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return poolConfig(cfg)
|
||||
}
|
||||
|
||||
func poolConfig(cfg config.Postgres) (*pgxpool.Config, error) {
|
||||
clientTLS, err := tlsconfig.NewClientFromEnv(cfg.Host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
poolCfg, err := pgxpool.ParseConfig(cfg.DSN())
|
||||
if err != nil {
|
||||
// pgx parse errors include the DSN, which contains a password.
|
||||
return nil, errors.New("postgres: invalid connection configuration")
|
||||
}
|
||||
poolCfg.ConnConfig.TLSConfig = clientTLS
|
||||
poolCfg.ConnConfig.Fallbacks = nil
|
||||
poolCfg.MaxConns = cfg.MaxConns
|
||||
poolCfg.MinConns = cfg.MinConns
|
||||
poolCfg.MaxConnLifetime = cfg.MaxConnLifetime
|
||||
poolCfg.MaxConnIdleTime = cfg.MaxConnIdleTime
|
||||
poolCfg.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
|
||||
return poolCfg, nil
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
)
|
||||
|
||||
func TestNormalizeKeepsProvidedValues(t *testing.T) {
|
||||
cfg, err := normalize(config.Postgres{
|
||||
Host: "db",
|
||||
Port: 6543,
|
||||
Database: "app",
|
||||
User: "app",
|
||||
Password: "database-secret",
|
||||
SSLMode: "verify-full",
|
||||
MaxConns: 7,
|
||||
MinConns: 2,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, "db", cfg.Host)
|
||||
require.Equal(t, 6543, cfg.Port)
|
||||
require.Equal(t, "app", cfg.Database)
|
||||
require.Equal(t, "verify-full", cfg.SSLMode)
|
||||
require.Equal(t, int32(7), cfg.MaxConns)
|
||||
}
|
||||
|
||||
func TestNormalizeRejectsMinGreaterThanMax(t *testing.T) {
|
||||
_, err := normalize(config.Postgres{User: "app", Password: "secret", MinConns: 5, MaxConns: 2})
|
||||
require.ErrorContains(t, err, "min_conns must not exceed max_conns")
|
||||
}
|
||||
|
||||
func TestNormalizeRequiresCredentials(t *testing.T) {
|
||||
for _, cfg := range []config.Postgres{{User: "app"}, {Password: "secret"}} {
|
||||
_, err := normalize(cfg)
|
||||
require.ErrorContains(t, err, "user and password are required")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRejectsUnverifiedTLS(t *testing.T) {
|
||||
for _, mode := range []string{"disable", "allow", "prefer", "require", "verify-ca"} {
|
||||
_, err := normalize(config.Postgres{User: "app", Password: "secret", SSLMode: mode})
|
||||
require.ErrorContains(t, err, "ssl_mode must be verify-full")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRejectsNonTCPHost(t *testing.T) {
|
||||
for _, host := range []string{"/var/run/postgresql", "db,other", "db\n"} {
|
||||
_, err := normalize(config.Postgres{Host: host, User: "app", Password: "secret"})
|
||||
require.ErrorContains(t, err, "single tcp hostname")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"syscall"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
pgUniqueViolation = "23505"
|
||||
pgForeignKeyViolation = "23503"
|
||||
pgCheckViolation = "23514"
|
||||
)
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
|
||||
return errors.As(err, &pgErr) && pgErr.Code == pgUniqueViolation
|
||||
}
|
||||
|
||||
// isUnavailable reports whether err is a transport-level failure — the server is
|
||||
// down, the connection dropped, or the pool/query deadline expired — rather than
|
||||
// a statement-level error. Such failures are dependency outages, not caller errors.
|
||||
func isUnavailable(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
switch pgErr.Code {
|
||||
// Class 08 — connection exception. 57P01/57P02/57P03 are the
|
||||
// server-side shutdown/startup states; 53300 is "too many
|
||||
// connections". All are dependency outages, not caller errors.
|
||||
case "57P01", "57P02", "57P03", "53300":
|
||||
return true
|
||||
}
|
||||
if len(pgErr.Code) >= 2 && pgErr.Code[:2] == "08" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
connectErr *pgconn.ConnectError
|
||||
netErr net.Error
|
||||
)
|
||||
|
||||
return errors.As(err, &connectErr) ||
|
||||
errors.As(err, &netErr) ||
|
||||
errors.Is(err, context.DeadlineExceeded) ||
|
||||
errors.Is(err, syscall.ECONNREFUSED) ||
|
||||
errors.Is(err, syscall.ECONNRESET) ||
|
||||
errors.Is(err, syscall.EPIPE) ||
|
||||
errors.Is(err, io.EOF) ||
|
||||
errors.Is(err, io.ErrUnexpectedEOF) ||
|
||||
errors.Is(err, pgx.ErrTxClosed) ||
|
||||
errors.Is(err, pgx.ErrTxCommitRollback)
|
||||
}
|
||||
|
||||
func mapError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.ErrNotFound
|
||||
}
|
||||
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
|
||||
switch pgErr.Code {
|
||||
case pgUniqueViolation:
|
||||
return domain.ErrConflict
|
||||
case pgForeignKeyViolation:
|
||||
// Нарушение внешнего ключа означает ссылку на отсутствующую сущность:
|
||||
// например, отправка сообщения в несуществующий чат или в чат, где
|
||||
// отправителя нет. Для клиента это 404, а не 500.
|
||||
return domain.ErrNotFound
|
||||
case pgCheckViolation:
|
||||
return domain.ErrValidation
|
||||
}
|
||||
}
|
||||
|
||||
if isUnavailable(err) {
|
||||
return fmt.Errorf("%w: %w", domain.ErrUnavailable, err)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
func TestIsUnavailablePostgresConnectionClasses(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, code := range []string{"08000", "08006", "57P01", "57P02", "57P03", "53300"} {
|
||||
if !isUnavailable(&pgconn.PgError{Code: code}) {
|
||||
t.Errorf("code %s was not classified as unavailable", code)
|
||||
}
|
||||
}
|
||||
if isUnavailable(&pgconn.PgError{Code: "23505"}) {
|
||||
t.Error("unique violation was classified as unavailable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapErrorConnectionClassIsUnavailable(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
err := mapError(&pgconn.PgError{Code: "57P03"})
|
||||
if !errors.Is(err, domain.ErrUnavailable) {
|
||||
t.Fatalf("mapError = %v, want ErrUnavailable", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type IdempotencySuite struct {
|
||||
BaseSuite
|
||||
}
|
||||
|
||||
func TestIdempotencySuite(t *testing.T) {
|
||||
suite.Run(t, new(IdempotencySuite))
|
||||
}
|
||||
|
||||
func messageDraft(chat domain.Chat, sender domain.User, key, text string) domain.MessageDraft {
|
||||
return domain.MessageDraft{
|
||||
ChatID: chat.ID,
|
||||
SenderID: sender.ID,
|
||||
Text: text,
|
||||
Idempotency: domain.MessageIdempotency{
|
||||
Key: key,
|
||||
RequestHash: sha256.Sum256([]byte(text)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) history(chat domain.Chat, actor domain.User) []domain.Message {
|
||||
s.T().Helper()
|
||||
|
||||
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, actor.ID, nil, 100)
|
||||
s.Require().NoError(err)
|
||||
|
||||
return page.Items
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestReplayReturnsStoredMessage() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
chat := s.createChat(alice, bob)
|
||||
draft := messageDraft(chat, alice, "key-1", "привет")
|
||||
|
||||
created, err := s.store.Messages().Create(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
|
||||
replayed, err := s.store.Messages().Create(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Equal(created, replayed, "повтор с тем же ключом и payload возвращает исходное сообщение")
|
||||
s.Len(s.history(chat, bob), 1, "повтор не создаёт дубль")
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestSameKeyWithAnotherPayloadConflicts() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
chat := s.createChat(alice, bob)
|
||||
|
||||
created, err := s.store.Messages().Create(s.T().Context(), messageDraft(chat, alice, "key-1", "привет"))
|
||||
s.Require().NoError(err)
|
||||
|
||||
_, err = s.store.Messages().Create(s.T().Context(), messageDraft(chat, alice, "key-1", "другое"))
|
||||
s.Require().ErrorIs(err, domain.ErrIdempotency)
|
||||
|
||||
history := s.history(chat, bob)
|
||||
s.Require().Len(history, 1, "конфликт не создаёт сообщение")
|
||||
s.Equal(created.ID, history[0].ID, "исходное сообщение не изменено")
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestConcurrentReplaysCreateOneMessage() {
|
||||
const callers = 8
|
||||
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
chat := s.createChat(alice, bob)
|
||||
draft := messageDraft(chat, alice, "key-concurrent", "конкурентный повтор")
|
||||
|
||||
ctx := s.T().Context()
|
||||
results := make([]domain.Message, callers)
|
||||
errs := make([]error, callers)
|
||||
|
||||
start := make(chan struct{})
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for i := range callers {
|
||||
wg.Add(1)
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
<-start
|
||||
|
||||
results[i], errs[i] = s.store.Messages().Create(ctx, draft)
|
||||
}()
|
||||
}
|
||||
|
||||
close(start)
|
||||
wg.Wait()
|
||||
|
||||
for i := range callers {
|
||||
s.Require().NoError(errs[i], "caller %d", i)
|
||||
s.Equal(results[0].ID, results[i].ID, "все одновременные повторы получают одно сообщение")
|
||||
}
|
||||
|
||||
s.Len(s.history(chat, bob), 1, "конкурентный повтор создаёт ровно одно сообщение")
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestKeyIsScopedToActorAndChat() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
carol := s.createUser("carol")
|
||||
|
||||
first := s.createChat(alice, bob)
|
||||
second := s.createChat(alice, carol)
|
||||
|
||||
mine, err := s.store.Messages().Create(s.T().Context(), messageDraft(first, alice, "shared-key", "от Алисы"))
|
||||
s.Require().NoError(err)
|
||||
|
||||
byBob, err := s.store.Messages().Create(s.T().Context(), messageDraft(first, bob, "shared-key", "от Боба"))
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.NotEqual(mine.ID, byBob.ID, "одинаковый ключ разных пользователей независим")
|
||||
|
||||
another, err := s.store.Messages().Create(s.T().Context(), messageDraft(second, alice, "shared-key", "в другом чате"))
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.NotEqual(mine.ID, another.ID, "одинаковый ключ в другом чате независим")
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestExpiredKeyIsReplaced() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
chat := s.createChat(alice, bob)
|
||||
draft := messageDraft(chat, alice, "key-expiring", "первое")
|
||||
|
||||
// Отрицательный TTL: записи идемпотентности истекают сразу.
|
||||
expiring := openStoreWithTTL(s.T(), s.db, -time.Second, nil)
|
||||
s.T().Cleanup(expiring.Close)
|
||||
|
||||
created, err := expiring.Messages().Create(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
|
||||
replaced, err := expiring.Messages().Create(s.T().Context(), messageDraft(chat, alice, "key-expiring", "второе"))
|
||||
s.Require().NoError(err, "истёкший ключ можно использовать с другим payload")
|
||||
s.NotEqual(created.ID, replaced.ID)
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestClaimForMissingChatIsNotFound() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
// Чат не существует: claim ключа ссылается на chats(id), поэтому наружу
|
||||
// должен уйти 404, а не 500 из-за нарушения внешнего ключа.
|
||||
_, err := s.store.Messages().Create(
|
||||
s.T().Context(),
|
||||
messageDraft(domain.Chat{ID: uuid.New()}, alice, "key-1", "привет"),
|
||||
)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestFailedAttemptLeavesNoClaim() {
|
||||
alice := s.createUser("alice")
|
||||
outsider := s.createUser("outsider")
|
||||
chat := s.createChat(alice)
|
||||
|
||||
_, err := s.store.Messages().Create(s.T().Context(), messageDraft(chat, outsider, "key-1", "привет"))
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
|
||||
var claims int
|
||||
|
||||
s.Require().NoError(
|
||||
s.pool.QueryRow(s.T().Context(), "SELECT count(*) FROM message_idempotency").Scan(&claims),
|
||||
)
|
||||
s.Zero(claims, "отклонённая попытка не оставляет claim: транзакция откатывается целиком")
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: attachments.sql
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const attachToMessage = `-- name: AttachToMessage :exec
|
||||
INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
VALUES ($1, $2, $3)
|
||||
`
|
||||
|
||||
type AttachToMessageParams struct {
|
||||
MessageID uuid.UUID
|
||||
AttachmentID uuid.UUID
|
||||
Position int16
|
||||
}
|
||||
|
||||
func (q *Queries) AttachToMessage(ctx context.Context, arg AttachToMessageParams) error {
|
||||
_, err := q.db.Exec(ctx, attachToMessage, arg.MessageID, arg.AttachmentID, arg.Position)
|
||||
return err
|
||||
}
|
||||
|
||||
const listMessageAttachments = `-- name: ListMessageAttachments :many
|
||||
SELECT message_id, attachment_id
|
||||
FROM message_attachments
|
||||
WHERE message_id = ANY($1::uuid[])
|
||||
ORDER BY message_id, position
|
||||
`
|
||||
|
||||
type ListMessageAttachmentsRow struct {
|
||||
MessageID uuid.UUID
|
||||
AttachmentID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) ListMessageAttachments(ctx context.Context, messageIds []uuid.UUID) ([]ListMessageAttachmentsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listMessageAttachments, messageIds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListMessageAttachmentsRow{}
|
||||
for rows.Next() {
|
||||
var i ListMessageAttachmentsRow
|
||||
if err := rows.Scan(&i.MessageID, &i.AttachmentID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: chats.sql
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const addChatMembers = `-- name: AddChatMembers :exec
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
SELECT $1, members.member_id
|
||||
FROM unnest($2::uuid[]) AS members(member_id)
|
||||
`
|
||||
|
||||
type AddChatMembersParams struct {
|
||||
ChatID uuid.UUID
|
||||
UserIds []uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) AddChatMembers(ctx context.Context, arg AddChatMembersParams) error {
|
||||
_, err := q.db.Exec(ctx, addChatMembers, arg.ChatID, arg.UserIds)
|
||||
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)
|
||||
RETURNING id, title, created_at
|
||||
`
|
||||
|
||||
func (q *Queries) CreateChat(ctx context.Context, title string) (Chat, error) {
|
||||
row := q.db.QueryRow(ctx, createChat, title)
|
||||
var i Chat
|
||||
err := row.Scan(&i.ID, &i.Title, &i.CreatedAt)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getChatForMember = `-- name: GetChatForMember :one
|
||||
SELECT
|
||||
c.id,
|
||||
c.title,
|
||||
c.created_at,
|
||||
(
|
||||
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
|
||||
FROM chat_members m
|
||||
WHERE m.chat_id = c.id
|
||||
)::uuid[] AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members visible
|
||||
ON visible.chat_id = c.id AND visible.user_id = $1
|
||||
WHERE c.id = $2
|
||||
`
|
||||
|
||||
type GetChatForMemberParams struct {
|
||||
UserID uuid.UUID
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
type GetChatForMemberRow struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
CreatedAt time.Time
|
||||
MemberIds []uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetChatForMember(ctx context.Context, arg GetChatForMemberParams) (GetChatForMemberRow, error) {
|
||||
row := q.db.QueryRow(ctx, getChatForMember, arg.UserID, arg.ID)
|
||||
var i GetChatForMemberRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Title,
|
||||
&i.CreatedAt,
|
||||
&i.MemberIds,
|
||||
)
|
||||
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,
|
||||
c.title,
|
||||
c.created_at,
|
||||
(
|
||||
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
|
||||
FROM chat_members m
|
||||
WHERE m.chat_id = c.id
|
||||
)::uuid[] AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members visible ON visible.chat_id = c.id
|
||||
WHERE visible.user_id = $1
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $2
|
||||
`
|
||||
|
||||
type ListChatsForMemberParams struct {
|
||||
UserID uuid.UUID
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
type ListChatsForMemberRow struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
CreatedAt time.Time
|
||||
MemberIds []uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) ListChatsForMember(ctx context.Context, arg ListChatsForMemberParams) ([]ListChatsForMemberRow, error) {
|
||||
rows, err := q.db.Query(ctx, listChatsForMember, arg.UserID, arg.RowLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListChatsForMemberRow{}
|
||||
for rows.Next() {
|
||||
var i ListChatsForMemberRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Title,
|
||||
&i.CreatedAt,
|
||||
&i.MemberIds,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listChatsForMemberAfter = `-- name: ListChatsForMemberAfter :many
|
||||
SELECT
|
||||
c.id,
|
||||
c.title,
|
||||
c.created_at,
|
||||
(
|
||||
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
|
||||
FROM chat_members m
|
||||
WHERE m.chat_id = c.id
|
||||
)::uuid[] AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members visible ON visible.chat_id = c.id
|
||||
WHERE visible.user_id = $1
|
||||
AND (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4
|
||||
`
|
||||
|
||||
type ListChatsForMemberAfterParams struct {
|
||||
UserID uuid.UUID
|
||||
AfterCreatedAt time.Time
|
||||
AfterID uuid.UUID
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
type ListChatsForMemberAfterRow struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
CreatedAt time.Time
|
||||
MemberIds []uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) ListChatsForMemberAfter(ctx context.Context, arg ListChatsForMemberAfterParams) ([]ListChatsForMemberAfterRow, error) {
|
||||
rows, err := q.db.Query(ctx, listChatsForMemberAfter,
|
||||
arg.UserID,
|
||||
arg.AfterCreatedAt,
|
||||
arg.AfterID,
|
||||
arg.RowLimit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListChatsForMemberAfterRow{}
|
||||
for rows.Next() {
|
||||
var i ListChatsForMemberAfterRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Title,
|
||||
&i.CreatedAt,
|
||||
&i.MemberIds,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listMissingUserIDs = `-- name: ListMissingUserIDs :many
|
||||
SELECT input.id::uuid AS missing_id
|
||||
FROM unnest($1::uuid[]) AS input(id)
|
||||
LEFT JOIN users u ON u.id = input.id
|
||||
WHERE u.id IS NULL
|
||||
`
|
||||
|
||||
func (q *Queries) ListMissingUserIDs(ctx context.Context, userIds []uuid.UUID) ([]uuid.UUID, error) {
|
||||
rows, err := q.db.Query(ctx, listMissingUserIDs, userIds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []uuid.UUID{}
|
||||
for rows.Next() {
|
||||
var missing_id uuid.UUID
|
||||
if err := rows.Scan(&missing_id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, missing_id)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
type DBTX interface {
|
||||
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
|
||||
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
|
||||
QueryRow(context.Context, string, ...interface{}) pgx.Row
|
||||
}
|
||||
|
||||
func New(db DBTX) *Queries {
|
||||
return &Queries{db: db}
|
||||
}
|
||||
|
||||
type Queries struct {
|
||||
db DBTX
|
||||
}
|
||||
|
||||
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
|
||||
return &Queries{
|
||||
db: tx,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: idempotency.sql
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const claimMessageIdempotency = `-- name: ClaimMessageIdempotency :one
|
||||
INSERT INTO message_idempotency (actor_id, chat_id, key, request_hash, expires_at)
|
||||
VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5
|
||||
)
|
||||
ON CONFLICT (actor_id, chat_id, key) DO UPDATE
|
||||
SET request_hash = EXCLUDED.request_hash,
|
||||
expires_at = EXCLUDED.expires_at,
|
||||
message_id = NULL
|
||||
WHERE message_idempotency.expires_at <= now()
|
||||
RETURNING key
|
||||
`
|
||||
|
||||
type ClaimMessageIdempotencyParams struct {
|
||||
ActorID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
Key string
|
||||
RequestHash []byte
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
// Claims the key for this actor/chat and returns whether this request owns it.
|
||||
// A live record wins: the statement returns nothing and the caller replays the
|
||||
// stored message. An expired record is replaced in place.
|
||||
func (q *Queries) ClaimMessageIdempotency(ctx context.Context, arg ClaimMessageIdempotencyParams) (string, error) {
|
||||
row := q.db.QueryRow(ctx, claimMessageIdempotency,
|
||||
arg.ActorID,
|
||||
arg.ChatID,
|
||||
arg.Key,
|
||||
arg.RequestHash,
|
||||
arg.ExpiresAt,
|
||||
)
|
||||
var key string
|
||||
err := row.Scan(&key)
|
||||
return key, err
|
||||
}
|
||||
|
||||
const completeMessageIdempotency = `-- name: CompleteMessageIdempotency :exec
|
||||
UPDATE message_idempotency
|
||||
SET message_id = $1
|
||||
WHERE actor_id = $2
|
||||
AND chat_id = $3
|
||||
AND key = $4
|
||||
`
|
||||
|
||||
type CompleteMessageIdempotencyParams struct {
|
||||
MessageID pgtype.UUID
|
||||
ActorID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
Key string
|
||||
}
|
||||
|
||||
func (q *Queries) CompleteMessageIdempotency(ctx context.Context, arg CompleteMessageIdempotencyParams) error {
|
||||
_, err := q.db.Exec(ctx, completeMessageIdempotency,
|
||||
arg.MessageID,
|
||||
arg.ActorID,
|
||||
arg.ChatID,
|
||||
arg.Key,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const getMessageByID = `-- name: GetMessageByID :one
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetMessageByID(ctx context.Context, id uuid.UUID) (Message, error) {
|
||||
row := q.db.QueryRow(ctx, getMessageByID, id)
|
||||
var i Message
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.SenderID,
|
||||
&i.Text,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getMessageIdempotency = `-- name: GetMessageIdempotency :one
|
||||
SELECT message_id, request_hash
|
||||
FROM message_idempotency
|
||||
WHERE actor_id = $1
|
||||
AND chat_id = $2
|
||||
AND key = $3
|
||||
FOR UPDATE
|
||||
`
|
||||
|
||||
type GetMessageIdempotencyParams struct {
|
||||
ActorID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
Key string
|
||||
}
|
||||
|
||||
type GetMessageIdempotencyRow struct {
|
||||
MessageID pgtype.UUID
|
||||
RequestHash []byte
|
||||
}
|
||||
|
||||
// Concurrent duplicates block here until the owner commits, then read the
|
||||
// result it stored in the same transaction.
|
||||
func (q *Queries) GetMessageIdempotency(ctx context.Context, arg GetMessageIdempotencyParams) (GetMessageIdempotencyRow, error) {
|
||||
row := q.db.QueryRow(ctx, getMessageIdempotency, arg.ActorID, arg.ChatID, arg.Key)
|
||||
var i GetMessageIdempotencyRow
|
||||
err := row.Scan(&i.MessageID, &i.RequestHash)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const lookupMessageIdempotency = `-- name: LookupMessageIdempotency :one
|
||||
SELECT message_id, request_hash
|
||||
FROM message_idempotency
|
||||
WHERE actor_id = $1
|
||||
AND chat_id = $2
|
||||
AND key = $3
|
||||
AND expires_at > now()
|
||||
`
|
||||
|
||||
type LookupMessageIdempotencyParams struct {
|
||||
ActorID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
Key string
|
||||
}
|
||||
|
||||
type LookupMessageIdempotencyRow struct {
|
||||
MessageID pgtype.UUID
|
||||
RequestHash []byte
|
||||
}
|
||||
|
||||
// Read-only replay lookup used before attachment-state validation. A live key
|
||||
// returns the stored message; an expired key is ignored and may be claimed.
|
||||
func (q *Queries) LookupMessageIdempotency(ctx context.Context, arg LookupMessageIdempotencyParams) (LookupMessageIdempotencyRow, error) {
|
||||
row := q.db.QueryRow(ctx, lookupMessageIdempotency, arg.ActorID, arg.ChatID, arg.Key)
|
||||
var i LookupMessageIdempotencyRow
|
||||
err := row.Scan(&i.MessageID, &i.RequestHash)
|
||||
return i, err
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: messages.sql
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const createMessage = `-- name: CreateMessage :one
|
||||
INSERT INTO messages (chat_id, sender_id, text)
|
||||
SELECT $1, $2, $3
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1
|
||||
AND user_id = $2
|
||||
)
|
||||
RETURNING id, chat_id, sender_id, text, created_at
|
||||
`
|
||||
|
||||
type CreateMessageParams struct {
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
}
|
||||
|
||||
func (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) {
|
||||
row := q.db.QueryRow(ctx, createMessage, arg.ChatID, arg.SenderID, arg.Text)
|
||||
var i Message
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.SenderID,
|
||||
&i.Text,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const isChatMember = `-- name: IsChatMember :one
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1
|
||||
AND user_id = $2
|
||||
) AS is_member
|
||||
`
|
||||
|
||||
type IsChatMemberParams struct {
|
||||
ChatID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) IsChatMember(ctx context.Context, arg IsChatMemberParams) (bool, error) {
|
||||
row := q.db.QueryRow(ctx, isChatMember, arg.ChatID, arg.UserID)
|
||||
var is_member bool
|
||||
err := row.Scan(&is_member)
|
||||
return is_member, err
|
||||
}
|
||||
|
||||
const listMessagesForChat = `-- name: ListMessagesForChat :many
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM messages m
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = m.chat_id
|
||||
AND cm.user_id = $1
|
||||
WHERE m.chat_id = $2
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $3
|
||||
`
|
||||
|
||||
type ListMessagesForChatParams struct {
|
||||
CallerID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
func (q *Queries) ListMessagesForChat(ctx context.Context, arg ListMessagesForChatParams) ([]Message, error) {
|
||||
rows, err := q.db.Query(ctx, listMessagesForChat, arg.CallerID, arg.ChatID, arg.RowLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []Message{}
|
||||
for rows.Next() {
|
||||
var i Message
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.SenderID,
|
||||
&i.Text,
|
||||
&i.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listMessagesForChatAfter = `-- name: ListMessagesForChatAfter :many
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM messages m
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = m.chat_id
|
||||
AND cm.user_id = $1
|
||||
WHERE m.chat_id = $2
|
||||
AND (m.created_at, m.id) > ($3::timestamptz, $4::uuid)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $5
|
||||
`
|
||||
|
||||
type ListMessagesForChatAfterParams struct {
|
||||
CallerID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
AfterCreatedAt time.Time
|
||||
AfterID uuid.UUID
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
func (q *Queries) ListMessagesForChatAfter(ctx context.Context, arg ListMessagesForChatAfterParams) ([]Message, error) {
|
||||
rows, err := q.db.Query(ctx, listMessagesForChatAfter,
|
||||
arg.CallerID,
|
||||
arg.ChatID,
|
||||
arg.AfterCreatedAt,
|
||||
arg.AfterID,
|
||||
arg.RowLimit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []Message{}
|
||||
for rows.Next() {
|
||||
var i Message
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.SenderID,
|
||||
&i.Text,
|
||||
&i.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type Attachment struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
ObjectKey string
|
||||
Filename string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Sha256 string
|
||||
Status string
|
||||
ErrorCode pgtype.Text
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
PipelineVersion int32
|
||||
StagingKey pgtype.Text
|
||||
ReadyAt pgtype.Timestamptz
|
||||
FailedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AttachmentJob struct {
|
||||
JobID uuid.UUID
|
||||
AttachmentID uuid.UUID
|
||||
PipelineVersion int32
|
||||
SourceKey string
|
||||
Attempt int32
|
||||
MaxAttempts int32
|
||||
Status string
|
||||
AvailableAt time.Time
|
||||
LeaseOwner pgtype.Text
|
||||
LeaseExpiresAt pgtype.Timestamptz
|
||||
LastErrorCode pgtype.Text
|
||||
ReplayCount int32
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
CompletedAt pgtype.Timestamptz
|
||||
Traceparent string
|
||||
Tracestate string
|
||||
TtrMissedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AttachmentJobEvent struct {
|
||||
ID int64
|
||||
JobID uuid.UUID
|
||||
Event string
|
||||
Attempt pgtype.Int4
|
||||
Detail []byte
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type AttachmentVariant struct {
|
||||
AttachmentID uuid.UUID
|
||||
PipelineVersion int32
|
||||
Name string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Width int32
|
||||
Height int32
|
||||
Sha256 string
|
||||
ObjectKey string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type ChatMember struct {
|
||||
ChatID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type LoginLimit struct {
|
||||
KeyHash string
|
||||
Count int64
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type MessageAttachment struct {
|
||||
MessageID uuid.UUID
|
||||
AttachmentID uuid.UUID
|
||||
Position int16
|
||||
}
|
||||
|
||||
type MessageIdempotency struct {
|
||||
ActorID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
Key string
|
||||
RequestHash []byte
|
||||
MessageID pgtype.UUID
|
||||
CreatedAt time.Time
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
type OutboxMessage struct {
|
||||
ID int64
|
||||
JobID uuid.UUID
|
||||
Attempt int32
|
||||
Kind string
|
||||
RoutingKey string
|
||||
Payload []byte
|
||||
AvailableAt time.Time
|
||||
PublishedAt pgtype.Timestamptz
|
||||
ClaimedBy pgtype.Text
|
||||
ClaimedUntil pgtype.Timestamptz
|
||||
PublishAttempts int32
|
||||
LastError pgtype.Text
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
TokenHash []byte
|
||||
UserID uuid.UUID
|
||||
ExpiresAt time.Time
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
PasswordHash string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type UserChatVersion struct {
|
||||
UserID uuid.UUID
|
||||
Version int64
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: sessions.sql
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const createSession = `-- name: CreateSession :one
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING token_hash, user_id, expires_at
|
||||
`
|
||||
|
||||
type CreateSessionParams struct {
|
||||
TokenHash []byte
|
||||
UserID uuid.UUID
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
type CreateSessionRow struct {
|
||||
TokenHash []byte
|
||||
UserID uuid.UUID
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) (CreateSessionRow, error) {
|
||||
row := q.db.QueryRow(ctx, createSession, arg.TokenHash, arg.UserID, arg.ExpiresAt)
|
||||
var i CreateSessionRow
|
||||
err := row.Scan(&i.TokenHash, &i.UserID, &i.ExpiresAt)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const deleteSession = `-- name: DeleteSession :exec
|
||||
DELETE FROM sessions
|
||||
WHERE token_hash = $1
|
||||
AND user_id = $2
|
||||
`
|
||||
|
||||
type DeleteSessionParams struct {
|
||||
TokenHash []byte
|
||||
UserID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) DeleteSession(ctx context.Context, arg DeleteSessionParams) error {
|
||||
_, err := q.db.Exec(ctx, deleteSession, arg.TokenHash, arg.UserID)
|
||||
return err
|
||||
}
|
||||
|
||||
const getSessionUser = `-- name: GetSessionUser :one
|
||||
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
|
||||
AND s.expires_at > now()
|
||||
`
|
||||
|
||||
type GetSessionUserRow struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) GetSessionUser(ctx context.Context, tokenHash []byte) (GetSessionUserRow, error) {
|
||||
row := q.db.QueryRow(ctx, getSessionUser, tokenHash)
|
||||
var i GetSessionUserRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.CreatedAt,
|
||||
&i.ExpiresAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const updatePasswordHash = `-- name: UpdatePasswordHash :execrows
|
||||
UPDATE users
|
||||
SET password_hash = $1
|
||||
WHERE id = $2
|
||||
AND password_hash = $3
|
||||
`
|
||||
|
||||
type UpdatePasswordHashParams struct {
|
||||
NewHash string
|
||||
UserID uuid.UUID
|
||||
OldHash string
|
||||
}
|
||||
|
||||
func (q *Queries) UpdatePasswordHash(ctx context.Context, arg UpdatePasswordHashParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, updatePasswordHash, arg.NewHash, arg.UserID, arg.OldHash)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: users.sql
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const createUser = `-- name: CreateUser :one
|
||||
INSERT INTO users (username, display_name, password_hash)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id, username, display_name, created_at, password_hash
|
||||
`
|
||||
|
||||
type CreateUserParams struct {
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
type CreateUserRow struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (CreateUserRow, error) {
|
||||
row := q.db.QueryRow(ctx, createUser, arg.Username, arg.DisplayName, arg.PasswordHash)
|
||||
var i CreateUserRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.CreatedAt,
|
||||
&i.PasswordHash,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getUserByID = `-- name: GetUserByID :one
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
type GetUserByIDRow struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
func (q *Queries) GetUserByID(ctx context.Context, id uuid.UUID) (GetUserByIDRow, error) {
|
||||
row := q.db.QueryRow(ctx, getUserByID, id)
|
||||
var i GetUserByIDRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.CreatedAt,
|
||||
&i.PasswordHash,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getUserByUsername = `-- name: GetUserByUsername :one
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
`
|
||||
|
||||
type GetUserByUsernameRow struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
func (q *Queries) GetUserByUsername(ctx context.Context, username string) (GetUserByUsernameRow, error) {
|
||||
row := q.db.QueryRow(ctx, getUserByUsername, username)
|
||||
var i GetUserByUsernameRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.CreatedAt,
|
||||
&i.PasswordHash,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/pressly/goose/v3"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
"mtusi-messenger/internal/storage/postgres"
|
||||
"mtusi-messenger/internal/storage/postgres/migrations"
|
||||
)
|
||||
|
||||
const templateDB = "messenger_template"
|
||||
|
||||
var adminPool *pgxpool.Pool
|
||||
|
||||
func envOr(key, fallback string) string {
|
||||
if value := os.Getenv(key); value != "" {
|
||||
return value
|
||||
}
|
||||
|
||||
return fallback
|
||||
}
|
||||
|
||||
func envInt(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 testConfig() config.Postgres {
|
||||
return config.Postgres{
|
||||
Host: envOr("TEST_POSTGRES_HOST", "localhost"),
|
||||
Port: envInt("TEST_POSTGRES_PORT", 5432),
|
||||
Database: envOr("TEST_POSTGRES_DATABASE", "messenger"),
|
||||
User: envOr("TEST_POSTGRES_USER", "lab_operator"),
|
||||
Password: os.Getenv("TEST_POSTGRES_PASSWORD"),
|
||||
SSLMode: envOr("TEST_POSTGRES_SSL_MODE", "verify-full"),
|
||||
MaxConns: 5,
|
||||
MinConns: 1,
|
||||
MaxConnLifetime: time.Hour,
|
||||
MaxConnIdleTime: 30 * time.Minute,
|
||||
ConnectTimeout: 5 * time.Second,
|
||||
QueryTimeout: 5 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
func poolConfigFor(database string) (*pgxpool.Config, error) {
|
||||
cfg := testConfig()
|
||||
cfg.Database = database
|
||||
|
||||
return postgres.PoolConfig(cfg)
|
||||
}
|
||||
|
||||
func configureOperatorTLS() error {
|
||||
identity, err := filepath.Abs("../../../secrets/lab7/pki/operator/current")
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve operator identity: %w", err)
|
||||
}
|
||||
for key, filename := range map[string]string{
|
||||
"TLS_CA_FILE": "ca.crt", "TLS_CERT_FILE": "tls.crt",
|
||||
"TLS_KEY_FILE": "tls.key", "TLS_CRL_FILE": "ca.crl",
|
||||
} {
|
||||
if os.Getenv(key) == "" {
|
||||
if err := os.Setenv(key, filepath.Join(identity, filename)); err != nil {
|
||||
return fmt.Errorf("set operator tls path: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if os.Getenv("TLS_VERSION_FILE") == "" {
|
||||
if err := os.Setenv("TLS_VERSION_FILE", filepath.Join(filepath.Dir(identity), "current-version")); err != nil {
|
||||
return fmt.Errorf("set operator tls selector: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
ctx := context.Background()
|
||||
|
||||
if err := configureOperatorTLS(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "operator tls:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
poolCfg, err := poolConfigFor(testConfig().Database)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "operator pool configuration:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
adminPool, err = pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "admin pool:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if err := waitForDatabase(ctx, adminPool); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "database is not ready:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if err := recreateTemplate(ctx); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "create template:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
code := m.Run()
|
||||
|
||||
adminPool.Close()
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func waitForDatabase(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
var lastErr error
|
||||
|
||||
for range 60 {
|
||||
err := pool.Ping(ctx)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
lastErr = err
|
||||
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
|
||||
return lastErr
|
||||
}
|
||||
|
||||
func adminExec(ctx context.Context, query string) error {
|
||||
conn, err := adminPool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer conn.Release()
|
||||
|
||||
_, err = conn.Conn().PgConn().Exec(ctx, query).ReadAll()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
const templateLockKey int64 = 0x6d657373656e6765
|
||||
|
||||
func withAdvisoryLock(ctx context.Context, shared bool, fn func() error) error {
|
||||
conn, err := adminPool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer conn.Release()
|
||||
|
||||
lock, unlock := "pg_advisory_lock", "pg_advisory_unlock"
|
||||
if shared {
|
||||
lock, unlock = "pg_advisory_lock_shared", "pg_advisory_unlock_shared"
|
||||
}
|
||||
|
||||
if _, err := conn.Exec(ctx, "SELECT "+lock+"($1)", templateLockKey); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() { _, _ = conn.Exec(context.WithoutCancel(ctx), "SELECT "+unlock+"($1)", templateLockKey) }()
|
||||
|
||||
return fn()
|
||||
}
|
||||
|
||||
func recreateTemplate(ctx context.Context) error {
|
||||
return withAdvisoryLock(ctx, false, func() error {
|
||||
if err := adminExec(ctx, "DROP DATABASE IF EXISTS "+templateDB+" WITH (FORCE)"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := adminExec(ctx, "CREATE DATABASE "+templateDB); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
poolCfg, err := poolConfigFor(templateDB)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
db := stdlib.OpenDB(*poolCfg.ConnConfig)
|
||||
|
||||
defer func() { _ = db.Close() }()
|
||||
|
||||
if err := db.PingContext(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
goose.SetBaseFS(migrations.FS)
|
||||
|
||||
if err := goose.SetDialect("postgres"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return goose.Up(db, ".")
|
||||
})
|
||||
}
|
||||
|
||||
type BaseSuite struct {
|
||||
suite.Suite
|
||||
|
||||
store *postgres.Store
|
||||
pool *pgxpool.Pool
|
||||
db string
|
||||
}
|
||||
|
||||
func (s *BaseSuite) SetupTest() {
|
||||
ctx := s.T().Context()
|
||||
s.db = "test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
|
||||
s.Require().NoError(withAdvisoryLock(ctx, true, func() error {
|
||||
return adminExec(ctx, "CREATE DATABASE "+s.db+" TEMPLATE "+templateDB)
|
||||
}))
|
||||
|
||||
poolCfg, err := poolConfigFor(s.db)
|
||||
s.Require().NoError(err)
|
||||
s.pool, err = pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.store = openStore(s.T(), s.db, nil)
|
||||
}
|
||||
|
||||
func (s *BaseSuite) TearDownTest() {
|
||||
if s.store != nil {
|
||||
s.store.Close()
|
||||
}
|
||||
|
||||
if s.pool != nil {
|
||||
s.pool.Close()
|
||||
}
|
||||
|
||||
if s.db != "" {
|
||||
s.Require().NoError(adminExec(s.T().Context(), "DROP DATABASE "+s.db+" WITH (FORCE)"))
|
||||
}
|
||||
}
|
||||
|
||||
const testIdempotencyTTL = 24 * time.Hour
|
||||
|
||||
func openStore(t *testing.T, database string, override func(*config.Postgres)) *postgres.Store {
|
||||
t.Helper()
|
||||
|
||||
return openStoreWithTTL(t, database, testIdempotencyTTL, override)
|
||||
}
|
||||
|
||||
func openStoreWithTTL(
|
||||
t *testing.T,
|
||||
database string,
|
||||
idempotencyTTL time.Duration,
|
||||
override func(*config.Postgres),
|
||||
) *postgres.Store {
|
||||
t.Helper()
|
||||
|
||||
cfg := testConfig()
|
||||
cfg.Database = database
|
||||
|
||||
if override != nil {
|
||||
override(&cfg)
|
||||
}
|
||||
|
||||
store, err := postgres.New(t.Context(), cfg, idempotencyTTL)
|
||||
require.NoError(t, err)
|
||||
|
||||
return store
|
||||
}
|
||||
|
||||
func (s *BaseSuite) createUser(username string) domain.User {
|
||||
s.T().Helper()
|
||||
|
||||
hash, err := password.Hash("strong-test-password")
|
||||
s.Require().NoError(err)
|
||||
|
||||
user, err := s.store.Users().Create(s.T().Context(), domain.NewUser{
|
||||
Username: username,
|
||||
DisplayName: "Пользователь " + username,
|
||||
PasswordHash: hash,
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
func (s *BaseSuite) createChat(owner domain.User, members ...domain.User) domain.Chat {
|
||||
s.T().Helper()
|
||||
|
||||
ids := []uuid.UUID{owner.ID}
|
||||
for _, member := range members {
|
||||
ids = append(ids, member.ID)
|
||||
}
|
||||
|
||||
chat, err := s.store.Chats().Create(s.T().Context(), domain.ChatDraft{
|
||||
Title: "Чат",
|
||||
MemberIDs: ids,
|
||||
CallerID: owner.ID,
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
return chat
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package postgres
|
||||
|
||||
import "time"
|
||||
|
||||
func toUTCTime(t time.Time) time.Time {
|
||||
if t.Location() == time.UTC {
|
||||
return t
|
||||
}
|
||||
|
||||
return t.UTC()
|
||||
}
|
||||
|
||||
func mapAll[S, D any](rows []S, mapRow func(S) D) []D {
|
||||
mapped := make([]D, 0, len(rows))
|
||||
|
||||
for _, row := range rows {
|
||||
mapped = append(mapped, mapRow(row))
|
||||
}
|
||||
|
||||
return mapped
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
|
||||
)
|
||||
|
||||
type MessageRepository struct {
|
||||
store *Store
|
||||
}
|
||||
|
||||
func (r *MessageRepository) IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
member, err := r.store.queries.IsChatMember(ctx, sqlcgen.IsChatMemberParams{
|
||||
ChatID: chatID,
|
||||
UserID: userID,
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("check chat membership: %w", mapError(err))
|
||||
}
|
||||
|
||||
return member, nil
|
||||
}
|
||||
|
||||
func (r *MessageRepository) Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error) {
|
||||
var created domain.Message
|
||||
|
||||
err := r.store.RunInTx(ctx, func(queries *sqlcgen.Queries) error {
|
||||
message, err := createIdempotent(ctx, queries, draft, r.store.idempotencyTTL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
created = message
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
// mapError нужен и здесь: отказ BEGIN/COMMIT (недоступная БД, исчерпанный
|
||||
// пул, истёкший контекст) обязан давать 503, а не 500.
|
||||
return domain.Message{}, fmt.Errorf("create message: %w", mapError(err))
|
||||
}
|
||||
|
||||
return created, nil
|
||||
}
|
||||
|
||||
// Replay returns the stored message for a live Idempotency-Key without
|
||||
// touching attachment state. The caller uses it before attachment validation so
|
||||
// a replay stays 201 even if a linked attachment later failed.
|
||||
func (r *MessageRepository) Replay(
|
||||
ctx context.Context,
|
||||
draft domain.MessageDraft,
|
||||
) (domain.Message, bool, error) {
|
||||
var (
|
||||
replayed domain.Message
|
||||
found bool
|
||||
)
|
||||
|
||||
err := r.store.RunInTx(ctx, func(queries *sqlcgen.Queries) error {
|
||||
stored, err := queries.LookupMessageIdempotency(ctx, sqlcgen.LookupMessageIdempotencyParams{
|
||||
ActorID: draft.SenderID,
|
||||
ChatID: draft.ChatID,
|
||||
Key: draft.Idempotency.Key,
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(stored.RequestHash, draft.Idempotency.RequestHash[:]) {
|
||||
return domain.ErrIdempotency
|
||||
}
|
||||
|
||||
if !stored.MessageID.Valid {
|
||||
return errors.New("idempotency record without a message")
|
||||
}
|
||||
|
||||
row, err := queries.GetMessageByID(ctx, uuid.UUID(stored.MessageID.Bytes))
|
||||
if err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
replayed = mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt)
|
||||
replayed.AttachmentIDs, err = listAttachmentIDs(ctx, queries, row.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
found = true
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, false, fmt.Errorf("replay idempotent message: %w", mapError(err))
|
||||
}
|
||||
|
||||
return replayed, found, nil
|
||||
}
|
||||
|
||||
// createIdempotent stores the message and its Idempotency-Key in one
|
||||
// transaction: either both are committed or neither, so a replay never observes
|
||||
// a claimed key whose message is missing. Claiming is a single statement, so
|
||||
// concurrent duplicates with the same key wait for the winner and then replay
|
||||
// the message it stored.
|
||||
func createIdempotent(
|
||||
ctx context.Context,
|
||||
queries *sqlcgen.Queries,
|
||||
draft domain.MessageDraft,
|
||||
ttl time.Duration,
|
||||
) (domain.Message, error) {
|
||||
_, err := queries.ClaimMessageIdempotency(ctx, sqlcgen.ClaimMessageIdempotencyParams{
|
||||
ActorID: draft.SenderID,
|
||||
ChatID: draft.ChatID,
|
||||
Key: draft.Idempotency.Key,
|
||||
RequestHash: draft.Idempotency.RequestHash[:],
|
||||
ExpiresAt: time.Now().Add(ttl),
|
||||
})
|
||||
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows): // the key is still live: replay it
|
||||
return replayIdempotent(ctx, queries, draft)
|
||||
case err != nil:
|
||||
return domain.Message{}, mapError(err)
|
||||
default:
|
||||
return createClaimed(ctx, queries, draft)
|
||||
}
|
||||
}
|
||||
|
||||
func createClaimed(ctx context.Context, queries *sqlcgen.Queries, draft domain.MessageDraft) (domain.Message, error) {
|
||||
row, err := queries.CreateMessage(ctx, sqlcgen.CreateMessageParams{
|
||||
ChatID: draft.ChatID,
|
||||
SenderID: draft.SenderID,
|
||||
Text: draft.Text,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, mapError(err)
|
||||
}
|
||||
|
||||
for position, attachmentID := range draft.AttachmentIDs {
|
||||
if err := queries.AttachToMessage(ctx, sqlcgen.AttachToMessageParams{
|
||||
MessageID: row.ID,
|
||||
AttachmentID: attachmentID,
|
||||
Position: int16(position),
|
||||
}); err != nil {
|
||||
return domain.Message{}, mapError(err)
|
||||
}
|
||||
}
|
||||
|
||||
err = queries.CompleteMessageIdempotency(ctx, sqlcgen.CompleteMessageIdempotencyParams{
|
||||
MessageID: pgtype.UUID{Bytes: row.ID, Valid: true},
|
||||
ActorID: draft.SenderID,
|
||||
ChatID: draft.ChatID,
|
||||
Key: draft.Idempotency.Key,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, mapError(err)
|
||||
}
|
||||
|
||||
created := mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt)
|
||||
created.AttachmentIDs = make([]uuid.UUID, 0, len(draft.AttachmentIDs))
|
||||
created.AttachmentIDs = append(created.AttachmentIDs, draft.AttachmentIDs...)
|
||||
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func replayIdempotent(ctx context.Context, queries *sqlcgen.Queries, draft domain.MessageDraft) (domain.Message, error) {
|
||||
stored, err := queries.GetMessageIdempotency(ctx, sqlcgen.GetMessageIdempotencyParams{
|
||||
ActorID: draft.SenderID,
|
||||
ChatID: draft.ChatID,
|
||||
Key: draft.Idempotency.Key,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, mapError(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(stored.RequestHash, draft.Idempotency.RequestHash[:]) {
|
||||
return domain.Message{}, domain.ErrIdempotency
|
||||
}
|
||||
|
||||
if !stored.MessageID.Valid {
|
||||
return domain.Message{}, errors.New("idempotency record without a message")
|
||||
}
|
||||
|
||||
row, err := queries.GetMessageByID(ctx, uuid.UUID(stored.MessageID.Bytes))
|
||||
if err != nil {
|
||||
return domain.Message{}, mapError(err)
|
||||
}
|
||||
|
||||
replayed := mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt)
|
||||
replayed.AttachmentIDs, err = listAttachmentIDs(ctx, queries, row.ID)
|
||||
if err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
|
||||
return replayed, nil
|
||||
}
|
||||
|
||||
// listAttachmentIDs returns attachment IDs in the order the sender supplied
|
||||
// them. An empty result is normalised to an empty slice, never nil: the
|
||||
// contract marks attachment_ids as required.
|
||||
func listAttachmentIDs(
|
||||
ctx context.Context,
|
||||
queries *sqlcgen.Queries,
|
||||
messageID uuid.UUID,
|
||||
) ([]uuid.UUID, error) {
|
||||
rows, err := queries.ListMessageAttachments(ctx, []uuid.UUID{messageID})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list message attachments: %w", mapError(err))
|
||||
}
|
||||
|
||||
ids := make([]uuid.UUID, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
ids = append(ids, row.AttachmentID)
|
||||
}
|
||||
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func (r *MessageRepository) ListVisible(
|
||||
ctx context.Context,
|
||||
chatID, callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Message], error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
limit = clampLimit(limit)
|
||||
fetch := int32(limit + 1) //nolint:gosec // limit is clamped to maxPageSize
|
||||
|
||||
messages, err := r.fetch(ctx, chatID, callerID, after, fetch)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
|
||||
if len(messages) == 0 {
|
||||
member, err := r.store.queries.IsChatMember(ctx, sqlcgen.IsChatMemberParams{
|
||||
ChatID: chatID,
|
||||
UserID: callerID,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, fmt.Errorf("check chat membership: %w", mapError(err))
|
||||
}
|
||||
|
||||
if !member {
|
||||
return domain.Page[domain.Message]{}, fmt.Errorf(
|
||||
"%w: chat %s for user %s",
|
||||
domain.ErrNotFound, chatID, callerID,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return buildPage(messages, limit, func(message domain.Message) domain.Cursor {
|
||||
return domain.Cursor{Scope: chatID, CreatedAt: message.CreatedAt, ID: message.ID}
|
||||
}), nil
|
||||
}
|
||||
|
||||
func (r *MessageRepository) fetch(
|
||||
ctx context.Context,
|
||||
chatID, callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
fetch int32,
|
||||
) ([]domain.Message, error) {
|
||||
var messages []domain.Message
|
||||
|
||||
if after == nil {
|
||||
rows, err := r.store.queries.ListMessagesForChat(ctx, sqlcgen.ListMessagesForChatParams{
|
||||
ChatID: chatID,
|
||||
CallerID: callerID,
|
||||
RowLimit: fetch,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list messages: %w", mapError(err))
|
||||
}
|
||||
|
||||
messages = mapAll(rows, mapMessageRow)
|
||||
} else {
|
||||
rows, err := r.store.queries.ListMessagesForChatAfter(ctx, sqlcgen.ListMessagesForChatAfterParams{
|
||||
ChatID: chatID,
|
||||
CallerID: callerID,
|
||||
AfterCreatedAt: after.CreatedAt,
|
||||
AfterID: after.ID,
|
||||
RowLimit: fetch,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list messages: %w", mapError(err))
|
||||
}
|
||||
|
||||
messages = mapAll(rows, mapMessageRow)
|
||||
}
|
||||
|
||||
if err := attachMessageLinks(ctx, r.store.queries, messages); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// attachMessageLinks fetches all links for a page in one query and normalises
|
||||
// absent lists to empty slices.
|
||||
func attachMessageLinks(
|
||||
ctx context.Context,
|
||||
queries *sqlcgen.Queries,
|
||||
messages []domain.Message,
|
||||
) error {
|
||||
if len(messages) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
ids := make([]uuid.UUID, 0, len(messages))
|
||||
for index := range messages {
|
||||
ids = append(ids, messages[index].ID)
|
||||
messages[index].AttachmentIDs = []uuid.UUID{}
|
||||
}
|
||||
|
||||
rows, err := queries.ListMessageAttachments(ctx, ids)
|
||||
if err != nil {
|
||||
return fmt.Errorf("list message attachments: %w", mapError(err))
|
||||
}
|
||||
|
||||
byMessage := make(map[uuid.UUID][]uuid.UUID, len(messages))
|
||||
for _, row := range rows {
|
||||
byMessage[row.MessageID] = append(byMessage[row.MessageID], row.AttachmentID)
|
||||
}
|
||||
|
||||
for index := range messages {
|
||||
if linked, ok := byMessage[messages[index].ID]; ok {
|
||||
messages[index].AttachmentIDs = linked
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func mapMessageRow(row sqlcgen.Message) domain.Message {
|
||||
return mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt)
|
||||
}
|
||||
|
||||
func mapMessage(id, chatID, senderID uuid.UUID, text string, createdAt time.Time) domain.Message {
|
||||
return domain.Message{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: toUTCTime(createdAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type MessageRepositorySuite struct {
|
||||
BaseSuite
|
||||
}
|
||||
|
||||
func TestMessageRepositorySuite(t *testing.T) {
|
||||
suite.Run(t, new(MessageRepositorySuite))
|
||||
}
|
||||
|
||||
// draft builds a message draft with a fresh Idempotency-Key (lab3 contract).
|
||||
func (s *MessageRepositorySuite) draft(chatID, senderID uuid.UUID, text string) domain.MessageDraft {
|
||||
s.T().Helper()
|
||||
|
||||
key := uuid.NewString()
|
||||
|
||||
return domain.MessageDraft{
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
Idempotency: domain.MessageIdempotency{
|
||||
Key: key,
|
||||
RequestHash: sha256.Sum256([]byte(key + text)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessageRepositorySuite) TestCreateAndPagination() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
|
||||
chat := s.createChat(alice, bob)
|
||||
|
||||
const total = 5
|
||||
for i := range total {
|
||||
message, err := s.store.Messages().Create(s.T().Context(), s.draft(chat.ID, alice.ID, fmt.Sprintf("сообщение %d", i)))
|
||||
s.Require().NoError(err)
|
||||
s.Equal(uuid.Version(7), message.ID.Version())
|
||||
s.False(message.CreatedAt.IsZero())
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, total)
|
||||
|
||||
var cursor *domain.Cursor
|
||||
|
||||
for {
|
||||
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, alice.ID, cursor, 2)
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotEmpty(page.Items)
|
||||
|
||||
for _, message := range page.Items {
|
||||
_, duplicate := seen[message.ID]
|
||||
s.Require().False(duplicate, "keyset-пагинация не повторяет сообщения")
|
||||
seen[message.ID] = struct{}{}
|
||||
}
|
||||
|
||||
if page.Next == nil {
|
||||
break
|
||||
}
|
||||
|
||||
cursor = page.Next
|
||||
}
|
||||
|
||||
s.Len(seen, total)
|
||||
}
|
||||
|
||||
func (s *MessageRepositorySuite) TestPaginationWithSharedTimestamp() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
|
||||
for range 5 {
|
||||
_, err := s.store.Messages().Create(s.T().Context(), s.draft(chat.ID, alice.ID, "same timestamp"))
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
_, err := s.pool.Exec(s.T().Context(), "UPDATE messages SET created_at = '2026-01-01 00:00:00+00'")
|
||||
s.Require().NoError(err)
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, 5)
|
||||
|
||||
var cursor *domain.Cursor
|
||||
|
||||
for {
|
||||
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, alice.ID, cursor, 2)
|
||||
s.Require().NoError(err)
|
||||
|
||||
for _, message := range page.Items {
|
||||
_, duplicate := seen[message.ID]
|
||||
s.Require().False(duplicate)
|
||||
seen[message.ID] = struct{}{}
|
||||
}
|
||||
|
||||
if page.Next == nil {
|
||||
break
|
||||
}
|
||||
|
||||
cursor = page.Next
|
||||
}
|
||||
|
||||
s.Len(seen, 5)
|
||||
}
|
||||
|
||||
func (s *MessageRepositorySuite) TestAccessIsRestricted() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
|
||||
chat := s.createChat(alice)
|
||||
|
||||
_, err := s.store.Messages().Create(s.T().Context(), s.draft(chat.ID, bob.ID, "чужое"))
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound, "не участник не может писать в чат")
|
||||
|
||||
_, err = s.store.Messages().ListVisible(s.T().Context(), chat.ID, bob.ID, nil, 50)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound, "не участник не может читать историю")
|
||||
}
|
||||
|
||||
func (s *MessageRepositorySuite) TestListingForMissingChatReturnsNotFound() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
_, err := s.store.Messages().ListVisible(s.T().Context(), uuid.New(), alice.ID, nil, 50)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *MessageRepositorySuite) TestFinishedMessageSurvivesConcurrentReads() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
|
||||
const total = 20
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
wg.Go(func() {
|
||||
for i := range total {
|
||||
_, err := s.store.Messages().Create(s.T().Context(), s.draft(chat.ID, alice.ID, fmt.Sprintf("message %d", i)))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
for range total {
|
||||
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, alice.ID, nil, 100)
|
||||
s.Require().NoError(err)
|
||||
s.LessOrEqual(len(page.Items), total)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
-- +goose Up
|
||||
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY DEFAULT uuidv7(),
|
||||
username text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
display_name text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
|
||||
CONSTRAINT users_username_key UNIQUE (username),
|
||||
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
CONSTRAINT users_display_name_not_blank CHECK (btrim(display_name) <> ''),
|
||||
CONSTRAINT users_display_name_length CHECK (char_length(display_name) BETWEEN 1 AND 100)
|
||||
);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY DEFAULT uuidv7(),
|
||||
title text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT chats_title_not_blank CHECK (btrim(title) <> '')
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY DEFAULT uuidv7(),
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
sender_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT messages_text_not_blank CHECK (btrim(text) <> ''),
|
||||
CONSTRAINT messages_text_length CHECK (char_length(text) <= 4000)
|
||||
);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
token_hash bytea PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
expires_at timestamptz NOT NULL,
|
||||
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);
|
||||
|
||||
CREATE INDEX chat_members_user_id_chat_id_idx
|
||||
ON chat_members (user_id, chat_id);
|
||||
|
||||
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;
|
||||
DROP TABLE messages;
|
||||
DROP TABLE chat_members;
|
||||
DROP TABLE chats;
|
||||
DROP TABLE users;
|
||||
DROP TABLE user_chat_versions;
|
||||
@@ -0,0 +1,25 @@
|
||||
-- +goose Up
|
||||
-- Версия 3, а не 2: в базе, перенесённой из лабораторной 2, goose уже содержит
|
||||
-- запись версии 2 (другая миграция того же репозитория), и одноимённый номер был
|
||||
-- бы молча пропущен при обновлении существующего стенда до ЛР3.
|
||||
|
||||
CREATE TABLE message_idempotency (
|
||||
actor_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
key text NOT NULL,
|
||||
request_hash bytea NOT NULL,
|
||||
message_id uuid REFERENCES messages (id) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
|
||||
PRIMARY KEY (actor_id, chat_id, key),
|
||||
CONSTRAINT message_idempotency_key_length CHECK (char_length(key) BETWEEN 1 AND 128)
|
||||
);
|
||||
|
||||
-- Expired records are replaced lazily by a new claim, the index keeps that
|
||||
-- lookup and a future sweep cheap.
|
||||
CREATE INDEX message_idempotency_expires_at_idx ON message_idempotency (expires_at);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE message_idempotency;
|
||||
@@ -0,0 +1,55 @@
|
||||
-- +goose Up
|
||||
-- Attachment metadata lives in PostgreSQL; the original bytes live only in S3.
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
owner_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
|
||||
object_key text NOT NULL,
|
||||
filename text NOT NULL,
|
||||
content_type text NOT NULL,
|
||||
size_bytes bigint NOT NULL,
|
||||
sha256 text NOT NULL,
|
||||
status text NOT NULL,
|
||||
error_code text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
|
||||
CONSTRAINT attachments_object_key_key UNIQUE (object_key),
|
||||
CONSTRAINT attachments_status_check CHECK (status IN ('pending', 'ready', 'failed')),
|
||||
CONSTRAINT attachments_content_type_check CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
CONSTRAINT attachments_filename_length CHECK (char_length(filename) BETWEEN 1 AND 255),
|
||||
CONSTRAINT attachments_size_check CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
CONSTRAINT attachments_sha256_check CHECK (sha256 ~ '^[0-9a-f]{64}$'),
|
||||
CONSTRAINT attachments_error_consistency CHECK (
|
||||
(status = 'ready' AND error_code IS NULL) OR
|
||||
(status = 'failed' AND error_code IS NOT NULL) OR
|
||||
status = 'pending'
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX attachments_chat_id_created_at_id_idx ON attachments (chat_id, created_at, id);
|
||||
CREATE INDEX attachments_status_created_at_idx ON attachments (status, created_at);
|
||||
|
||||
CREATE TABLE message_attachments (
|
||||
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE RESTRICT,
|
||||
position smallint NOT NULL,
|
||||
|
||||
PRIMARY KEY (message_id, attachment_id),
|
||||
CONSTRAINT message_attachments_position_check CHECK (position BETWEEN 0 AND 9),
|
||||
CONSTRAINT message_attachments_position_key UNIQUE (message_id, position)
|
||||
);
|
||||
|
||||
CREATE INDEX message_attachments_attachment_id_idx ON message_attachments (attachment_id);
|
||||
|
||||
-- Lab1-3 messages must stay valid. Attachment-only messages use text = '';
|
||||
-- the "text OR attachment" rule is enforced by the service and ogen.
|
||||
ALTER TABLE messages DROP CONSTRAINT messages_text_not_blank;
|
||||
|
||||
-- +goose Down
|
||||
-- WARNING: fails if attachment-only messages already exist. Roll back such
|
||||
-- rows or the constraint cannot be restored.
|
||||
ALTER TABLE messages ADD CONSTRAINT messages_text_not_blank CHECK (btrim(text) <> '');
|
||||
|
||||
DROP TABLE message_attachments;
|
||||
DROP TABLE attachments;
|
||||
@@ -0,0 +1,150 @@
|
||||
-- +goose Up
|
||||
-- Lab5 async attachment pipeline: durable intent (jobs + transactional outbox),
|
||||
-- per-version results (variants), and operator audit (events).
|
||||
|
||||
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check CHECK (
|
||||
status IN ('pending', 'queued', 'processing', 'ready', 'failed')
|
||||
) NOT VALID;
|
||||
ALTER TABLE attachments VALIDATE CONSTRAINT attachments_status_check;
|
||||
|
||||
ALTER TABLE attachments DROP CONSTRAINT attachments_error_consistency;
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_error_consistency CHECK (
|
||||
(status IN ('ready', 'queued', 'processing') AND error_code IS NULL) OR
|
||||
(status = 'failed' AND error_code IS NOT NULL) OR
|
||||
status = 'pending'
|
||||
) NOT VALID;
|
||||
ALTER TABLE attachments VALIDATE CONSTRAINT attachments_error_consistency;
|
||||
|
||||
ALTER TABLE attachments
|
||||
ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1
|
||||
CHECK (pipeline_version >= 1),
|
||||
ADD COLUMN staging_key text,
|
||||
ADD COLUMN ready_at timestamptz,
|
||||
ADD COLUMN failed_at timestamptz;
|
||||
|
||||
CREATE UNIQUE INDEX attachments_staging_key_key
|
||||
ON attachments (staging_key)
|
||||
WHERE staging_key IS NOT NULL;
|
||||
|
||||
CREATE INDEX attachments_pipeline_status_idx
|
||||
ON attachments (status, pipeline_version);
|
||||
|
||||
-- One logical job per (attachment, pipeline version). job_id is stable across
|
||||
-- redelivery; attempt is the managed attempt number (1-based).
|
||||
CREATE TABLE attachment_jobs (
|
||||
job_id uuid PRIMARY KEY,
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE,
|
||||
pipeline_version integer NOT NULL CHECK (pipeline_version >= 1),
|
||||
source_key text NOT NULL,
|
||||
attempt integer NOT NULL DEFAULT 1 CHECK (attempt >= 1),
|
||||
max_attempts integer NOT NULL CHECK (max_attempts BETWEEN 1 AND 100),
|
||||
status text NOT NULL CHECK (
|
||||
status IN ('queued', 'processing', 'ready', 'failed', 'superseded')
|
||||
),
|
||||
available_at timestamptz NOT NULL DEFAULT now(),
|
||||
lease_owner text,
|
||||
lease_expires_at timestamptz,
|
||||
last_error_code text,
|
||||
replay_count integer NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
completed_at timestamptz,
|
||||
|
||||
CONSTRAINT attachment_jobs_attachment_version_key UNIQUE (attachment_id, pipeline_version),
|
||||
CONSTRAINT attachment_jobs_lease_consistency CHECK (
|
||||
(status = 'processing' AND lease_owner IS NOT NULL AND lease_expires_at IS NOT NULL) OR
|
||||
(status <> 'processing')
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX attachment_jobs_due_idx
|
||||
ON attachment_jobs (status, available_at);
|
||||
|
||||
CREATE INDEX attachment_jobs_lease_idx
|
||||
ON attachment_jobs (status, lease_expires_at);
|
||||
|
||||
-- Delivery ledger. available_at is the only retry scheduler; RabbitMQ is the
|
||||
-- durable transport. No UNIQUE(job_id, attempt): a graceful shutdown may
|
||||
-- re-publish the same attempt, and duplicates are harmless (worker CAS).
|
||||
CREATE TABLE outbox_messages (
|
||||
id bigserial PRIMARY KEY,
|
||||
job_id uuid NOT NULL REFERENCES attachment_jobs (job_id) ON DELETE CASCADE,
|
||||
attempt integer NOT NULL CHECK (attempt >= 1),
|
||||
kind text NOT NULL DEFAULT 'publish',
|
||||
routing_key text NOT NULL,
|
||||
payload jsonb NOT NULL,
|
||||
available_at timestamptz NOT NULL DEFAULT now(),
|
||||
published_at timestamptz,
|
||||
claimed_by text,
|
||||
claimed_until timestamptz,
|
||||
publish_attempts integer NOT NULL DEFAULT 0,
|
||||
last_error text,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX outbox_due_idx
|
||||
ON outbox_messages (available_at, id)
|
||||
WHERE published_at IS NULL;
|
||||
|
||||
CREATE INDEX outbox_claim_expiry_idx
|
||||
ON outbox_messages (claimed_until)
|
||||
WHERE published_at IS NULL AND claimed_by IS NOT NULL;
|
||||
|
||||
-- Effect key (attachment_id, pipeline_version, name). The primary key is the
|
||||
-- idempotency boundary for redelivery and versioned pipelines.
|
||||
CREATE TABLE attachment_variants (
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE,
|
||||
pipeline_version integer NOT NULL CHECK (pipeline_version >= 1),
|
||||
name text NOT NULL CHECK (name IN ('thumbnail', 'crop', 'optimized')),
|
||||
content_type text NOT NULL CHECK (
|
||||
content_type IN ('image/jpeg', 'image/png', 'image/webp')
|
||||
),
|
||||
size_bytes bigint NOT NULL CHECK (size_bytes > 0),
|
||||
width integer NOT NULL CHECK (width > 0),
|
||||
height integer NOT NULL CHECK (height > 0),
|
||||
sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'),
|
||||
object_key text NOT NULL UNIQUE,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
|
||||
PRIMARY KEY (attachment_id, pipeline_version, name)
|
||||
);
|
||||
|
||||
CREATE TABLE attachment_job_events (
|
||||
id bigserial PRIMARY KEY,
|
||||
job_id uuid NOT NULL REFERENCES attachment_jobs (job_id) ON DELETE CASCADE,
|
||||
event text NOT NULL,
|
||||
attempt integer,
|
||||
detail jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX attachment_job_events_job_idx
|
||||
ON attachment_job_events (job_id, created_at);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE attachment_job_events;
|
||||
DROP TABLE attachment_variants;
|
||||
DROP TABLE outbox_messages;
|
||||
DROP TABLE attachment_jobs;
|
||||
|
||||
DROP INDEX attachments_pipeline_status_idx;
|
||||
DROP INDEX attachments_staging_key_key;
|
||||
|
||||
ALTER TABLE attachments
|
||||
DROP COLUMN failed_at,
|
||||
DROP COLUMN ready_at,
|
||||
DROP COLUMN staging_key,
|
||||
DROP COLUMN pipeline_version;
|
||||
|
||||
ALTER TABLE attachments DROP CONSTRAINT attachments_error_consistency;
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_error_consistency CHECK (
|
||||
(status = 'ready' AND error_code IS NULL) OR
|
||||
(status = 'failed' AND error_code IS NOT NULL) OR
|
||||
status = 'pending'
|
||||
) NOT VALID;
|
||||
|
||||
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check CHECK (
|
||||
status IN ('pending', 'ready', 'failed')
|
||||
) NOT VALID;
|
||||
@@ -0,0 +1,12 @@
|
||||
-- +goose Up
|
||||
-- Preserve the originating request trace context on the durable job. The
|
||||
-- lease reaper and reconciliation path need an original parent even after the
|
||||
-- API span and the relay process have ended.
|
||||
ALTER TABLE attachment_jobs
|
||||
ADD COLUMN traceparent text NOT NULL DEFAULT '',
|
||||
ADD COLUMN tracestate text NOT NULL DEFAULT '';
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE attachment_jobs
|
||||
DROP COLUMN IF EXISTS tracestate,
|
||||
DROP COLUMN IF EXISTS traceparent;
|
||||
@@ -0,0 +1,14 @@
|
||||
-- +goose Up
|
||||
-- One-shot TTR miss marker. The relay (which does not stop with the worker)
|
||||
-- sweeps old non-ready jobs and increments a counter, so the TTR SLI can fire
|
||||
-- while the worker is down.
|
||||
ALTER TABLE attachment_jobs
|
||||
ADD COLUMN ttr_missed_at timestamptz;
|
||||
|
||||
CREATE INDEX attachment_jobs_ttr_missed_idx
|
||||
ON attachment_jobs (created_at)
|
||||
WHERE ttr_missed_at IS NULL;
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX IF EXISTS attachment_jobs_ttr_missed_idx;
|
||||
ALTER TABLE attachment_jobs DROP COLUMN IF EXISTS ttr_missed_at;
|
||||
@@ -0,0 +1,12 @@
|
||||
-- +goose Up
|
||||
DROP INDEX IF EXISTS attachment_jobs_ttr_missed_idx;
|
||||
CREATE INDEX attachment_jobs_ttr_open_idx
|
||||
ON attachment_jobs (created_at)
|
||||
WHERE ttr_missed_at IS NULL AND status IN ('queued', 'processing');
|
||||
CREATE INDEX attachment_jobs_ttr_completed_idx
|
||||
ON attachment_jobs (completed_at)
|
||||
WHERE ttr_missed_at IS NULL;
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX IF EXISTS attachment_jobs_ttr_completed_idx;
|
||||
DROP INDEX IF EXISTS attachment_jobs_ttr_open_idx;
|
||||
@@ -0,0 +1,10 @@
|
||||
-- +goose Up
|
||||
CREATE TABLE login_limits (
|
||||
key_hash text PRIMARY KEY CHECK (key_hash ~ '^[0-9a-f]{64}$'),
|
||||
count bigint NOT NULL CHECK (count >= 0),
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX login_limits_expires_at_idx ON login_limits (expires_at, key_hash);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE login_limits;
|
||||
@@ -0,0 +1,6 @@
|
||||
package migrations
|
||||
|
||||
import "embed"
|
||||
|
||||
//go:embed *.sql
|
||||
var FS embed.FS
|
||||
@@ -0,0 +1,25 @@
|
||||
package postgres
|
||||
|
||||
import "mtusi-messenger/internal/domain"
|
||||
|
||||
const (
|
||||
minPageSize = 1
|
||||
maxPageSize = 100
|
||||
)
|
||||
|
||||
func clampLimit(limit int) int {
|
||||
return min(max(limit, minPageSize), maxPageSize)
|
||||
}
|
||||
|
||||
func buildPage[T any](items []T, limit int, cursor func(item T) domain.Cursor) domain.Page[T] {
|
||||
if len(items) > limit {
|
||||
next := cursor(items[limit-1])
|
||||
|
||||
return domain.Page[T]{
|
||||
Items: append([]T(nil), items[:limit]...),
|
||||
Next: &next,
|
||||
}
|
||||
}
|
||||
|
||||
return domain.Page[T]{Items: append([]T(nil), items...)}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,586 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type PipelineSuite struct {
|
||||
BaseSuite
|
||||
}
|
||||
|
||||
func TestPipelineSuite(t *testing.T) {
|
||||
suite.Run(t, new(PipelineSuite))
|
||||
}
|
||||
|
||||
func (s *PipelineSuite) attachmentDraft(chat domain.Chat, owner domain.User, version int) (domain.AttachmentDraft, domain.Job) {
|
||||
s.T().Helper()
|
||||
|
||||
id, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
jobID, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
draft := domain.AttachmentDraft{
|
||||
ID: id,
|
||||
ChatID: chat.ID,
|
||||
OwnerID: owner.ID,
|
||||
ObjectKey: domain.OriginalObjectKey(chat.ID, id),
|
||||
StagingKey: domain.StagingUploadKey(chat.ID, id),
|
||||
Filename: "photo.png",
|
||||
ContentType: "image/png",
|
||||
SizeBytes: 10,
|
||||
SHA256: strings.Repeat("a", 64),
|
||||
Status: domain.AttachmentQueued,
|
||||
PipelineVersion: version,
|
||||
}
|
||||
|
||||
job := domain.Job{
|
||||
ID: jobID,
|
||||
AttachmentID: id,
|
||||
PipelineVersion: version,
|
||||
SourceKey: draft.StagingKey,
|
||||
Attempt: 1,
|
||||
MaxAttempts: 5,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
return draft, job
|
||||
}
|
||||
|
||||
func (s *PipelineSuite) TestCreateClaimCompleteAndIdempotentRedelivery() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
chat := s.createChat(alice, bob)
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
created, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentQueued, created.Status)
|
||||
s.Equal(1, created.PipelineVersion)
|
||||
|
||||
message := domain.NewJobMessage(job)
|
||||
claim, err := repo.ClaimJob(s.T().Context(), message, "lease-1", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
s.Equal(domain.AttachmentProcessing, claim.Attachment.Status)
|
||||
|
||||
duplicate, err := repo.ClaimJob(s.T().Context(), message, "lease-2", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimBusyLease, duplicate.Outcome)
|
||||
|
||||
variants := []domain.Variant{
|
||||
{
|
||||
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
|
||||
Width: 256, Height: 160, SHA256: strings.Repeat("b", 64),
|
||||
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 1, domain.VariantThumbnail),
|
||||
},
|
||||
}
|
||||
|
||||
ok, err := repo.CompleteJob(s.T().Context(), job.ID, 1, "lease-1", variants)
|
||||
s.Require().NoError(err)
|
||||
s.True(ok)
|
||||
|
||||
ready, err := repo.GetForMember(s.T().Context(), bob.ID, draft.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentReady, ready.Status)
|
||||
|
||||
stored, err := repo.ListVariants(s.T().Context(), draft.ID, 1)
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(stored, 1)
|
||||
s.Equal(domain.VariantThumbnail, stored[0].Name)
|
||||
|
||||
// A redelivery after ready is a no-op, even with the same attempt.
|
||||
again, err := repo.ClaimJob(s.T().Context(), message, "lease-3", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAlreadyReady, again.Outcome)
|
||||
}
|
||||
|
||||
func (s *PipelineSuite) TestLeaseExpiryIsBoundedByMaxAttempts() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
job.MaxAttempts = 1
|
||||
|
||||
repo := s.store.Pipeline()
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease", time.Millisecond)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
|
||||
reaped, err := repo.ReapExpiredLeases(s.T().Context(), 10)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(1, reaped)
|
||||
|
||||
dead, err := repo.GetJob(s.T().Context(), job.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.JobFailed, dead.Status)
|
||||
s.NotNil(dead.LastErrorCode)
|
||||
s.Equal("retry_exhausted", *dead.LastErrorCode)
|
||||
}
|
||||
|
||||
func (s *PipelineSuite) TestAdmissionCountsPendingPresignAndIsAtomic() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
draft, _ := s.attachmentDraft(chat, alice, 1)
|
||||
draft.ObjectKey = "staging/presign/" + chat.ID.String() + "/" + draft.ID.String()
|
||||
draft.StagingKey = draft.ObjectKey
|
||||
draft.Status = domain.AttachmentPending
|
||||
|
||||
limits := domain.AdmissionLimits{PerUser: 1, Total: 10}
|
||||
|
||||
_, err := repo.CreatePresign(s.T().Context(), draft, limits)
|
||||
s.Require().NoError(err)
|
||||
|
||||
second, _ := s.attachmentDraft(chat, alice, 1)
|
||||
second.ObjectKey = "staging/presign/" + chat.ID.String() + "/" + second.ID.String()
|
||||
second.StagingKey = second.ObjectKey
|
||||
second.Status = domain.AttachmentPending
|
||||
|
||||
_, err = repo.CreatePresign(s.T().Context(), second, limits)
|
||||
s.Require().ErrorIs(err, domain.ErrRateLimited)
|
||||
}
|
||||
|
||||
// A queued upload whose worker never ran still has its verified bytes only in
|
||||
// staging. Reprocessing it must use staging as the source; pointing at the
|
||||
// not-yet-written final original left the attachment queued forever after the
|
||||
// v1 job was superseded (v2 then failed with source_missing).
|
||||
func (s *PipelineSuite) TestReprocessQueuedUsesStagingSource() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
chat := s.createChat(alice, bob)
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
reprocessID, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
created, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(2, created.PipelineVersion)
|
||||
s.Equal(draft.StagingKey, created.SourceKey)
|
||||
}
|
||||
|
||||
// Once a pipeline has published the final original, the staging copy may be
|
||||
// past its retention window; a reprocess of a ready attachment must source
|
||||
// from the final object that actually exists.
|
||||
func (s *PipelineSuite) TestReprocessReadyUsesObjectSource() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
message := domain.NewJobMessage(job)
|
||||
claim, err := repo.ClaimJob(s.T().Context(), message, "lease-1", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
variants := []domain.Variant{
|
||||
{
|
||||
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
|
||||
Width: 256, Height: 160, SHA256: strings.Repeat("b", 64),
|
||||
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 1, domain.VariantThumbnail),
|
||||
},
|
||||
}
|
||||
|
||||
ok, err := repo.CompleteJob(s.T().Context(), job.ID, 1, "lease-1", variants)
|
||||
s.Require().NoError(err)
|
||||
s.True(ok)
|
||||
|
||||
reprocessID, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
created, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(2, created.PipelineVersion)
|
||||
s.Equal(draft.ObjectKey, created.SourceKey)
|
||||
}
|
||||
|
||||
// A reprocess failure before any version was published must settle the
|
||||
// attachment as failed instead of leaving it queued with no active jobs.
|
||||
func (s *PipelineSuite) TestReprocessFailureSettlesUnpublishedAttachment() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
reprocessID, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
reprocess, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(reprocess), "lease-2", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
failed, err := repo.FailJob(s.T().Context(), reprocess.ID, 1, "lease-2", "invalid_image")
|
||||
s.Require().NoError(err)
|
||||
s.True(failed)
|
||||
|
||||
current, err := repo.GetForOwner(s.T().Context(), alice.ID, draft.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentFailed, current.Status)
|
||||
s.Require().NotNil(current.ErrorCode)
|
||||
s.Equal("invalid_image", *current.ErrorCode)
|
||||
}
|
||||
|
||||
// A reprocess failure while an older ready version is serving must keep that
|
||||
// version ready and downloadable; only the new job fails.
|
||||
func (s *PipelineSuite) TestReprocessFailureKeepsReadyServingVersion() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease-1", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
variants := []domain.Variant{
|
||||
{
|
||||
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
|
||||
Width: 256, Height: 160, SHA256: strings.Repeat("b", 64),
|
||||
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 1, domain.VariantThumbnail),
|
||||
},
|
||||
}
|
||||
|
||||
ok, err := repo.CompleteJob(s.T().Context(), job.ID, 1, "lease-1", variants)
|
||||
s.Require().NoError(err)
|
||||
s.True(ok)
|
||||
|
||||
reprocessID, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
reprocess, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err = repo.ClaimJob(s.T().Context(), domain.NewJobMessage(reprocess), "lease-2", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
failed, err := repo.FailJob(s.T().Context(), reprocess.ID, 1, "lease-2", "invalid_image")
|
||||
s.Require().NoError(err)
|
||||
s.True(failed)
|
||||
|
||||
current, err := repo.GetForOwner(s.T().Context(), alice.ID, draft.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentReady, current.Status)
|
||||
s.Equal(1, current.PipelineVersion)
|
||||
s.Nil(current.ErrorCode)
|
||||
}
|
||||
|
||||
// Replaying a failed newer version must clear the stale terminal projection
|
||||
// for an attachment that never published any version.
|
||||
func (s *PipelineSuite) TestReplayNewerFailedVersionRequeuesUnpublishedAttachment() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
reprocessID, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
reprocess, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(reprocess), "lease-2", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
failed, err := repo.FailJob(s.T().Context(), reprocess.ID, 1, "lease-2", "invalid_image")
|
||||
s.Require().NoError(err)
|
||||
s.True(failed)
|
||||
|
||||
current, err := repo.GetForOwner(s.T().Context(), alice.ID, draft.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentFailed, current.Status)
|
||||
|
||||
replayed, err := repo.ReplayJob(s.T().Context(), reprocess.ID, 2)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(2, replayed.Attempt)
|
||||
|
||||
current, err = repo.GetForOwner(s.T().Context(), alice.ID, draft.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentQueued, current.Status)
|
||||
s.Nil(current.ErrorCode)
|
||||
|
||||
claim, err = repo.ClaimJob(s.T().Context(), domain.NewJobMessage(replayed), "lease-3", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
variants := []domain.Variant{
|
||||
{
|
||||
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
|
||||
Width: 256, Height: 160, SHA256: strings.Repeat("c", 64),
|
||||
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 2, domain.VariantThumbnail),
|
||||
},
|
||||
}
|
||||
|
||||
ok, err := repo.CompleteJob(s.T().Context(), replayed.ID, replayed.Attempt, "lease-3", variants)
|
||||
s.Require().NoError(err)
|
||||
s.True(ok)
|
||||
|
||||
current, err = repo.GetForOwner(s.T().Context(), alice.ID, draft.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentReady, current.Status)
|
||||
s.Equal(2, current.PipelineVersion)
|
||||
}
|
||||
|
||||
// Replaying a failed newer version must not disturb a published ready
|
||||
// serving version; only the new job returns to queued.
|
||||
func (s *PipelineSuite) TestReplayNewerFailedVersionKeepsReadyServingVersion() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease-1", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
variants := []domain.Variant{
|
||||
{
|
||||
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
|
||||
Width: 256, Height: 160, SHA256: strings.Repeat("b", 64),
|
||||
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 1, domain.VariantThumbnail),
|
||||
},
|
||||
}
|
||||
|
||||
ok, err := repo.CompleteJob(s.T().Context(), job.ID, 1, "lease-1", variants)
|
||||
s.Require().NoError(err)
|
||||
s.True(ok)
|
||||
|
||||
reprocessID, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
reprocess, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err = repo.ClaimJob(s.T().Context(), domain.NewJobMessage(reprocess), "lease-2", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
failed, err := repo.FailJob(s.T().Context(), reprocess.ID, 1, "lease-2", "invalid_image")
|
||||
s.Require().NoError(err)
|
||||
s.True(failed)
|
||||
|
||||
replayed, err := repo.ReplayJob(s.T().Context(), reprocess.ID, 1)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(2, replayed.Attempt)
|
||||
|
||||
current, err := repo.GetForOwner(s.T().Context(), alice.ID, draft.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentReady, current.Status)
|
||||
s.Equal(1, current.PipelineVersion)
|
||||
s.Nil(current.ErrorCode)
|
||||
}
|
||||
|
||||
// Replaying an older failed version is refused while a newer job exists,
|
||||
// even before that newer version becomes the published serving version.
|
||||
func (s *PipelineSuite) TestReplayOlderFailedVersionRefusedWhenNewerJobExists() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease-1", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
failed, err := repo.FailJob(s.T().Context(), job.ID, 1, "lease-1", "invalid_image")
|
||||
s.Require().NoError(err)
|
||||
s.True(failed)
|
||||
|
||||
reprocessID, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
_, err = repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
|
||||
s.Require().NoError(err)
|
||||
|
||||
_, err = repo.ReplayJob(s.T().Context(), job.ID, 1)
|
||||
s.Require().ErrorIs(err, domain.ErrConflict)
|
||||
|
||||
var v1Status string
|
||||
s.Require().NoError(s.pool.QueryRow(s.T().Context(),
|
||||
`SELECT status FROM attachment_jobs WHERE job_id = $1`, job.ID).Scan(&v1Status))
|
||||
s.Equal(string(domain.JobFailed), v1Status)
|
||||
}
|
||||
|
||||
// A queued job for an older version is retired on claim instead of being
|
||||
// acknowledged and republished by reconciliation forever.
|
||||
func (s *PipelineSuite) TestClaimRetiresVersionStaleQueuedJob() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
reprocessID, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
reprocess, err := repo.Reprocess(s.T().Context(), draft.ID, 2, 5, reprocessID)
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(reprocess), "lease-2", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
variants := []domain.Variant{
|
||||
{
|
||||
Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 11,
|
||||
Width: 256, Height: 160, SHA256: strings.Repeat("d", 64),
|
||||
ObjectKey: domain.VariantObjectKey(chat.ID, draft.ID, 2, domain.VariantThumbnail),
|
||||
},
|
||||
}
|
||||
|
||||
ok, err := repo.CompleteJob(s.T().Context(), reprocess.ID, 1, "lease-2", variants)
|
||||
s.Require().NoError(err)
|
||||
s.True(ok)
|
||||
|
||||
// Simulate a legacy/racing replay that left the old version queued.
|
||||
_, err = s.pool.Exec(s.T().Context(), `
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'queued', attempt = 1, last_error_code = NULL
|
||||
WHERE job_id = $1`, job.ID)
|
||||
s.Require().NoError(err)
|
||||
|
||||
stale, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease-3", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimVersionStale, stale.Outcome)
|
||||
|
||||
var status string
|
||||
s.Require().NoError(s.pool.QueryRow(s.T().Context(),
|
||||
`SELECT status FROM attachment_jobs WHERE job_id = $1`, job.ID).Scan(&status))
|
||||
s.Equal(string(domain.JobSuperseded), status)
|
||||
|
||||
var supersededEvents int
|
||||
s.Require().NoError(s.pool.QueryRow(s.T().Context(), `
|
||||
SELECT count(*) FROM attachment_job_events
|
||||
WHERE job_id = $1 AND event = $2`,
|
||||
job.ID, string(domain.EventSuperseded)).Scan(&supersededEvents))
|
||||
s.Equal(2, supersededEvents)
|
||||
}
|
||||
|
||||
func (s *PipelineSuite) TestReconcileQueuedJobsRepublishesLostIntent() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
claimed, err := repo.ClaimOutbox(s.T().Context(), "relay", time.Minute, 10)
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(claimed, 1)
|
||||
s.Require().NoError(repo.MarkPublished(s.T().Context(), []int64{claimed[0].ID}))
|
||||
|
||||
reconciled, err := repo.ReconcileQueuedJobs(s.T().Context(), 0, 10, "", "")
|
||||
s.Require().NoError(err)
|
||||
s.Equal(1, reconciled)
|
||||
|
||||
pending, err := repo.ClaimOutbox(s.T().Context(), "relay", time.Minute, 10)
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(pending, 1)
|
||||
s.Equal("reconcile", pending[0].Kind)
|
||||
s.Equal(job.ID, pending[0].JobID)
|
||||
}
|
||||
|
||||
func (s *PipelineSuite) TestFailedStagingStaysReferencedUntilRetention() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
_, err := repo.CreateQueued(s.T().Context(), draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
|
||||
claim, err := repo.ClaimJob(s.T().Context(), domain.NewJobMessage(job), "lease", time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.ClaimAcquired, claim.Outcome)
|
||||
|
||||
ok, err := repo.FailJob(s.T().Context(), job.ID, 1, "lease", "invalid_image")
|
||||
s.Require().NoError(err)
|
||||
s.True(ok)
|
||||
|
||||
keys, err := repo.ListReferencedKeys(s.T().Context(), "", 100)
|
||||
s.Require().NoError(err)
|
||||
s.Contains(keys, draft.StagingKey)
|
||||
}
|
||||
|
||||
func (s *PipelineSuite) TestMarkTTRMissedCountsEachJobOnce() {
|
||||
ctx := s.T().Context()
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
repo := s.store.Pipeline()
|
||||
|
||||
makeJob := func(status string, createdAt, completedAt time.Time) uuid.UUID {
|
||||
s.T().Helper()
|
||||
draft, job := s.attachmentDraft(chat, alice, 1)
|
||||
_, err := repo.CreateQueued(ctx, draft, job, domain.AdmissionLimits{})
|
||||
s.Require().NoError(err)
|
||||
_, err = s.pool.Exec(ctx, `UPDATE attachment_jobs
|
||||
SET status=$2, created_at=$3, completed_at=NULLIF($4, '0001-01-01'::timestamptz)
|
||||
WHERE job_id=$1`, job.ID, status, createdAt, completedAt)
|
||||
s.Require().NoError(err)
|
||||
return job.ID
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
old := now.Add(-40 * time.Second)
|
||||
makeJob("queued", old, time.Time{})
|
||||
makeJob("ready", old, now)
|
||||
makeJob("failed", now, now)
|
||||
makeJob("ready", now, now)
|
||||
makeJob("superseded", old, now)
|
||||
|
||||
count, err := repo.MarkTTRMissed(ctx, 30*time.Second)
|
||||
s.Require().NoError(err)
|
||||
s.EqualValues(3, count)
|
||||
again, err := repo.MarkTTRMissed(ctx, 30*time.Second)
|
||||
s.Require().NoError(err)
|
||||
s.Zero(again)
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
-- name: AttachToMessage :exec
|
||||
INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
VALUES (sqlc.arg(message_id), sqlc.arg(attachment_id), sqlc.arg(position));
|
||||
|
||||
-- name: ListMessageAttachments :many
|
||||
SELECT message_id, attachment_id
|
||||
FROM message_attachments
|
||||
WHERE message_id = ANY(sqlc.arg(message_ids)::uuid[])
|
||||
ORDER BY message_id, position;
|
||||
@@ -0,0 +1,75 @@
|
||||
-- name: CreateChat :one
|
||||
INSERT INTO chats (title)
|
||||
VALUES (sqlc.arg(title))
|
||||
RETURNING id, title, created_at;
|
||||
|
||||
-- name: AddChatMembers :exec
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
SELECT sqlc.arg(chat_id), members.member_id
|
||||
FROM unnest(sqlc.arg(user_ids)::uuid[]) AS members(member_id);
|
||||
|
||||
-- name: ListMissingUserIDs :many
|
||||
SELECT input.id::uuid AS missing_id
|
||||
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,
|
||||
c.title,
|
||||
c.created_at,
|
||||
(
|
||||
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
|
||||
FROM chat_members m
|
||||
WHERE m.chat_id = c.id
|
||||
)::uuid[] AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members visible
|
||||
ON visible.chat_id = c.id AND visible.user_id = sqlc.arg(user_id)
|
||||
WHERE c.id = sqlc.arg(id);
|
||||
|
||||
-- name: ListChatsForMember :many
|
||||
SELECT
|
||||
c.id,
|
||||
c.title,
|
||||
c.created_at,
|
||||
(
|
||||
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
|
||||
FROM chat_members m
|
||||
WHERE m.chat_id = c.id
|
||||
)::uuid[] AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members visible ON visible.chat_id = c.id
|
||||
WHERE visible.user_id = sqlc.arg(user_id)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- name: ListChatsForMemberAfter :many
|
||||
SELECT
|
||||
c.id,
|
||||
c.title,
|
||||
c.created_at,
|
||||
(
|
||||
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
|
||||
FROM chat_members m
|
||||
WHERE m.chat_id = c.id
|
||||
)::uuid[] AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members visible ON visible.chat_id = c.id
|
||||
WHERE visible.user_id = sqlc.arg(user_id)
|
||||
AND (c.created_at, c.id) > (sqlc.arg(after_created_at)::timestamptz, sqlc.arg(after_id)::uuid)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
@@ -0,0 +1,50 @@
|
||||
-- Claims the key for this actor/chat and returns whether this request owns it.
|
||||
-- A live record wins: the statement returns nothing and the caller replays the
|
||||
-- stored message. An expired record is replaced in place.
|
||||
-- name: ClaimMessageIdempotency :one
|
||||
INSERT INTO message_idempotency (actor_id, chat_id, key, request_hash, expires_at)
|
||||
VALUES (
|
||||
sqlc.arg(actor_id),
|
||||
sqlc.arg(chat_id),
|
||||
sqlc.arg(key),
|
||||
sqlc.arg(request_hash),
|
||||
sqlc.arg(expires_at)
|
||||
)
|
||||
ON CONFLICT (actor_id, chat_id, key) DO UPDATE
|
||||
SET request_hash = EXCLUDED.request_hash,
|
||||
expires_at = EXCLUDED.expires_at,
|
||||
message_id = NULL
|
||||
WHERE message_idempotency.expires_at <= now()
|
||||
RETURNING key;
|
||||
|
||||
-- Concurrent duplicates block here until the owner commits, then read the
|
||||
-- result it stored in the same transaction.
|
||||
-- name: GetMessageIdempotency :one
|
||||
SELECT message_id, request_hash
|
||||
FROM message_idempotency
|
||||
WHERE actor_id = sqlc.arg(actor_id)
|
||||
AND chat_id = sqlc.arg(chat_id)
|
||||
AND key = sqlc.arg(key)
|
||||
FOR UPDATE;
|
||||
|
||||
-- name: CompleteMessageIdempotency :exec
|
||||
UPDATE message_idempotency
|
||||
SET message_id = sqlc.arg(message_id)
|
||||
WHERE actor_id = sqlc.arg(actor_id)
|
||||
AND chat_id = sqlc.arg(chat_id)
|
||||
AND key = sqlc.arg(key);
|
||||
|
||||
-- name: GetMessageByID :one
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE id = sqlc.arg(id);
|
||||
|
||||
-- Read-only replay lookup used before attachment-state validation. A live key
|
||||
-- returns the stored message; an expired key is ignored and may be claimed.
|
||||
-- name: LookupMessageIdempotency :one
|
||||
SELECT message_id, request_hash
|
||||
FROM message_idempotency
|
||||
WHERE actor_id = sqlc.arg(actor_id)
|
||||
AND chat_id = sqlc.arg(chat_id)
|
||||
AND key = sqlc.arg(key)
|
||||
AND expires_at > now();
|
||||
@@ -0,0 +1,39 @@
|
||||
-- name: CreateMessage :one
|
||||
INSERT INTO messages (chat_id, sender_id, text)
|
||||
SELECT sqlc.arg(chat_id), sqlc.arg(sender_id), sqlc.arg(text)
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = sqlc.arg(chat_id)
|
||||
AND user_id = sqlc.arg(sender_id)
|
||||
)
|
||||
RETURNING id, chat_id, sender_id, text, created_at;
|
||||
|
||||
-- name: IsChatMember :one
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = sqlc.arg(chat_id)
|
||||
AND user_id = sqlc.arg(user_id)
|
||||
) AS is_member;
|
||||
|
||||
-- name: ListMessagesForChat :many
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM messages m
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = m.chat_id
|
||||
AND cm.user_id = sqlc.arg(caller_id)
|
||||
WHERE m.chat_id = sqlc.arg(chat_id)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- name: ListMessagesForChatAfter :many
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM messages m
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = m.chat_id
|
||||
AND cm.user_id = sqlc.arg(caller_id)
|
||||
WHERE m.chat_id = sqlc.arg(chat_id)
|
||||
AND (m.created_at, m.id) > (sqlc.arg(after_created_at)::timestamptz, sqlc.arg(after_id)::uuid)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
@@ -0,0 +1,22 @@
|
||||
-- name: CreateSession :one
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at)
|
||||
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, s.expires_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = sqlc.arg(token_hash)
|
||||
AND s.expires_at > now();
|
||||
|
||||
-- name: DeleteSession :exec
|
||||
DELETE FROM sessions
|
||||
WHERE token_hash = sqlc.arg(token_hash)
|
||||
AND user_id = sqlc.arg(user_id);
|
||||
|
||||
-- name: UpdatePasswordHash :execrows
|
||||
UPDATE users
|
||||
SET password_hash = sqlc.arg(new_hash)
|
||||
WHERE id = sqlc.arg(user_id)
|
||||
AND password_hash = sqlc.arg(old_hash);
|
||||
@@ -0,0 +1,14 @@
|
||||
-- name: CreateUser :one
|
||||
INSERT INTO users (username, display_name, password_hash)
|
||||
VALUES (sqlc.arg(username), sqlc.arg(display_name), sqlc.arg(password_hash))
|
||||
RETURNING id, username, display_name, created_at, password_hash;
|
||||
|
||||
-- name: GetUserByID :one
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users
|
||||
WHERE id = sqlc.arg(id);
|
||||
|
||||
-- name: GetUserByUsername :one
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users
|
||||
WHERE username = sqlc.arg(username);
|
||||
@@ -0,0 +1,141 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/ratelimit"
|
||||
)
|
||||
|
||||
var nextLoginLimitCleanup atomic.Int64
|
||||
|
||||
var _ ratelimit.Limiter = (*Store)(nil)
|
||||
|
||||
type loginCounter struct {
|
||||
limit ratelimit.Limit
|
||||
count int64
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
// Reserve uses sorted row locks, including newly created counters, so requests
|
||||
// on different replicas consume every dimension together or none of them.
|
||||
func (s *Store) Reserve(ctx context.Context, limits []ratelimit.Limit) (retryAfter time.Duration, err error) {
|
||||
if len(limits) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
counters := make([]loginCounter, len(limits))
|
||||
for i, limit := range limits {
|
||||
if limit.Key == "" || limit.Count <= 0 || limit.Window < time.Microsecond {
|
||||
return 0, fmt.Errorf("login admission: %w: invalid limit", domain.ErrUnavailable)
|
||||
}
|
||||
digest := sha256.Sum256([]byte(limit.Key))
|
||||
limit.Key = hex.EncodeToString(digest[:])
|
||||
counters[i].limit = limit
|
||||
}
|
||||
slices.SortFunc(counters, func(a, b loginCounter) int {
|
||||
switch {
|
||||
case a.limit.Key < b.limit.Key:
|
||||
return -1
|
||||
case a.limit.Key > b.limit.Key:
|
||||
return 1
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
})
|
||||
for i := 1; i < len(counters); i++ {
|
||||
if counters[i-1].limit.Key == counters[i].limit.Key {
|
||||
return 0, fmt.Errorf("login admission: %w: duplicate limit", domain.ErrUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
ctx, cancel := s.timeout(ctx)
|
||||
defer cancel()
|
||||
if err := s.cleanupLoginLimits(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return 0, loginLimitError("begin admission", err)
|
||||
}
|
||||
defer func() {
|
||||
rollbackCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), time.Second)
|
||||
defer cancel()
|
||||
if rollbackErr := tx.Rollback(rollbackCtx); rollbackErr != nil && !errors.Is(rollbackErr, pgx.ErrTxClosed) {
|
||||
err = errors.Join(err, loginLimitError("rollback admission", rollbackErr))
|
||||
}
|
||||
}()
|
||||
|
||||
for i := range counters {
|
||||
counter := &counters[i]
|
||||
if err := tx.QueryRow(ctx, `
|
||||
INSERT INTO login_limits (key_hash, count, expires_at)
|
||||
VALUES ($1, 0, 'epoch')
|
||||
ON CONFLICT (key_hash) DO UPDATE SET key_hash = EXCLUDED.key_hash
|
||||
RETURNING count, expires_at`, counter.limit.Key).Scan(&counter.count, &counter.expiresAt); err != nil {
|
||||
return 0, loginLimitError("lock admission counter", err)
|
||||
}
|
||||
}
|
||||
// Read the database clock only after acquiring every dimension's lock.
|
||||
var now time.Time
|
||||
if err := tx.QueryRow(ctx, "SELECT clock_timestamp()").Scan(&now); err != nil {
|
||||
return 0, loginLimitError("read admission clock", err)
|
||||
}
|
||||
for i := range counters {
|
||||
counter := &counters[i]
|
||||
if !counter.expiresAt.After(now) {
|
||||
counter.count = 0
|
||||
counter.expiresAt = now.Add(counter.limit.Window)
|
||||
}
|
||||
if counter.count >= int64(counter.limit.Count) {
|
||||
retryAfter = max(retryAfter, counter.expiresAt.Sub(now))
|
||||
}
|
||||
}
|
||||
if retryAfter > 0 {
|
||||
return retryAfter, nil
|
||||
}
|
||||
for _, counter := range counters {
|
||||
if _, err := tx.Exec(ctx, `
|
||||
UPDATE login_limits SET count = $2, expires_at = $3
|
||||
WHERE key_hash = $1`, counter.limit.Key, counter.count+1, counter.expiresAt); err != nil {
|
||||
return 0, loginLimitError("reserve admission counter", err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return 0, loginLimitError("commit admission", err)
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (s *Store) cleanupLoginLimits(ctx context.Context) error {
|
||||
now := time.Now().UnixNano()
|
||||
next := nextLoginLimitCleanup.Load()
|
||||
if now < next || !nextLoginLimitCleanup.CompareAndSwap(next, now+int64(time.Second)) {
|
||||
return nil
|
||||
}
|
||||
// Its own short transaction avoids mixing cleanup locks with the sorted
|
||||
// reservation locks. SKIP LOCKED never waits for an in-flight admission.
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
WITH expired AS (
|
||||
SELECT key_hash FROM login_limits
|
||||
WHERE expires_at <= now()
|
||||
ORDER BY expires_at, key_hash LIMIT 64 FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
DELETE FROM login_limits l USING expired e WHERE l.key_hash = e.key_hash`)
|
||||
if err != nil {
|
||||
return loginLimitError("clean admission counters", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func loginLimitError(operation string, err error) error {
|
||||
return fmt.Errorf("%s: %w: %w", operation, domain.ErrUnavailable, err)
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/ratelimit"
|
||||
)
|
||||
|
||||
type LoginLimitSuite struct {
|
||||
BaseSuite
|
||||
}
|
||||
|
||||
func TestLoginLimitSuite(t *testing.T) {
|
||||
suite.Run(t, new(LoginLimitSuite))
|
||||
}
|
||||
|
||||
func (s *LoginLimitSuite) TestConcurrentReservationsAreSharedAndAtomic() {
|
||||
other := openStore(s.T(), s.db, nil)
|
||||
defer other.Close()
|
||||
const attempts, capacity = 32, 8
|
||||
type result struct {
|
||||
retry time.Duration
|
||||
err error
|
||||
}
|
||||
results := make(chan result, attempts)
|
||||
start := make(chan struct{})
|
||||
var group sync.WaitGroup
|
||||
for i := range attempts {
|
||||
group.Go(func() {
|
||||
<-start
|
||||
limits := []ratelimit.Limit{
|
||||
{Key: fmt.Sprintf("private-account-%d", i), Count: 1, Window: time.Minute},
|
||||
{Key: "private-source", Count: 100, Window: time.Minute},
|
||||
{Key: "global", Count: capacity, Window: time.Minute},
|
||||
}
|
||||
store := s.store
|
||||
if i%2 != 0 {
|
||||
store = other
|
||||
slices.Reverse(limits)
|
||||
}
|
||||
retry, err := store.Reserve(s.T().Context(), limits)
|
||||
results <- result{retry: retry, err: err}
|
||||
})
|
||||
}
|
||||
close(start)
|
||||
group.Wait()
|
||||
close(results)
|
||||
admitted := 0
|
||||
for result := range results {
|
||||
s.Require().NoError(result.err)
|
||||
if result.retry == 0 {
|
||||
admitted++
|
||||
} else {
|
||||
s.Positive(result.retry)
|
||||
}
|
||||
}
|
||||
s.Equal(capacity, admitted)
|
||||
var rows, consumed int64
|
||||
s.Require().NoError(s.pool.QueryRow(s.T().Context(),
|
||||
"SELECT count(*), sum(count) FROM login_limits").Scan(&rows, &consumed))
|
||||
// Rejected requests must not even persist their newly inserted account row.
|
||||
s.Equal(int64(capacity+2), rows)
|
||||
s.Equal(int64(capacity*3), consumed)
|
||||
var unhashed int
|
||||
s.Require().NoError(s.pool.QueryRow(s.T().Context(),
|
||||
"SELECT count(*) FROM login_limits WHERE key_hash !~ '^[0-9a-f]{64}$'").Scan(&unhashed))
|
||||
s.Zero(unhashed)
|
||||
}
|
||||
|
||||
func (s *LoginLimitSuite) TestRejectedDimensionDoesNotConsumeOtherDimensions() {
|
||||
blocked := ratelimit.Limit{Key: "blocked", Count: 1, Window: time.Minute}
|
||||
retry, err := s.store.Reserve(s.T().Context(), []ratelimit.Limit{blocked})
|
||||
s.Require().NoError(err)
|
||||
s.Zero(retry)
|
||||
fresh := ratelimit.Limit{Key: "fresh", Count: 1, Window: time.Minute}
|
||||
retry, err = s.store.Reserve(s.T().Context(), []ratelimit.Limit{fresh, blocked})
|
||||
s.Require().NoError(err)
|
||||
s.Positive(retry)
|
||||
var rows int
|
||||
s.Require().NoError(s.pool.QueryRow(s.T().Context(), "SELECT count(*) FROM login_limits").Scan(&rows))
|
||||
s.Equal(1, rows)
|
||||
retry, err = s.store.Reserve(s.T().Context(), []ratelimit.Limit{fresh})
|
||||
s.Require().NoError(err)
|
||||
s.Zero(retry)
|
||||
}
|
||||
|
||||
func (s *LoginLimitSuite) TestExpiredCounterStartsFreshWindow() {
|
||||
limits := []ratelimit.Limit{{Key: "account", Count: 1, Window: time.Minute}}
|
||||
retry, err := s.store.Reserve(s.T().Context(), limits)
|
||||
s.Require().NoError(err)
|
||||
s.Zero(retry)
|
||||
_, err = s.pool.Exec(s.T().Context(), "UPDATE login_limits SET expires_at = now() - interval '1 second'")
|
||||
s.Require().NoError(err)
|
||||
retry, err = s.store.Reserve(s.T().Context(), limits)
|
||||
s.Require().NoError(err)
|
||||
s.Zero(retry)
|
||||
var count int64
|
||||
var isFuture bool
|
||||
s.Require().NoError(s.pool.QueryRow(s.T().Context(),
|
||||
"SELECT count, expires_at > now() FROM login_limits").Scan(&count, &isFuture))
|
||||
s.Equal(int64(1), count)
|
||||
s.True(isFuture)
|
||||
}
|
||||
|
||||
func (s *LoginLimitSuite) TestMissingCounterTableFailsClosed() {
|
||||
_, err := s.pool.Exec(s.T().Context(), "DROP TABLE login_limits")
|
||||
s.Require().NoError(err)
|
||||
retry, err := s.store.Reserve(s.T().Context(), []ratelimit.Limit{{
|
||||
Key: "account", Count: 1, Window: time.Minute,
|
||||
}})
|
||||
s.Require().ErrorIs(err, domain.ErrUnavailable)
|
||||
s.Zero(retry)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
|
||||
)
|
||||
|
||||
type SessionRepository struct {
|
||||
store *Store
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Credentials(ctx context.Context, username string) (domain.UserCredentials, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.GetUserByUsername(ctx, username)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.UserCredentials{}, fmt.Errorf("%w", domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
return domain.UserCredentials{}, fmt.Errorf("load credentials: %w", mapError(err))
|
||||
}
|
||||
|
||||
return domain.UserCredentials{
|
||||
User: domain.User{
|
||||
ID: row.ID,
|
||||
Username: row.Username,
|
||||
DisplayName: row.DisplayName,
|
||||
CreatedAt: toUTCTime(row.CreatedAt),
|
||||
},
|
||||
PasswordHash: row.PasswordHash,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *SessionRepository) UpdatePasswordHash(
|
||||
ctx context.Context, userID uuid.UUID, oldHash, newHash string,
|
||||
) (bool, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := r.store.queries.UpdatePasswordHash(ctx, sqlcgen.UpdatePasswordHashParams{
|
||||
NewHash: newHash,
|
||||
UserID: userID,
|
||||
OldHash: oldHash,
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("update password hash: %w", mapError(err))
|
||||
}
|
||||
return rows != 0, nil
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Create(ctx context.Context, session domain.NewSession) (domain.Session, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.CreateSession(ctx, sqlcgen.CreateSessionParams{
|
||||
TokenHash: session.TokenHash,
|
||||
UserID: session.UserID,
|
||||
ExpiresAt: session.ExpiresAt,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Session{}, fmt.Errorf("create session: %w", mapError(err))
|
||||
}
|
||||
|
||||
return domain.Session{ExpiresAt: toUTCTime(row.ExpiresAt)}, nil
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.GetSessionUser(ctx, tokenHash)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Session{}, fmt.Errorf("%w: session not found or expired", domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
return domain.Session{}, fmt.Errorf("resolve session: %w", mapError(err))
|
||||
}
|
||||
|
||||
return domain.Session{
|
||||
ExpiresAt: toUTCTime(row.ExpiresAt),
|
||||
User: domain.User{
|
||||
ID: row.ID,
|
||||
Username: row.Username,
|
||||
DisplayName: row.DisplayName,
|
||||
CreatedAt: toUTCTime(row.CreatedAt),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
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 {
|
||||
return fmt.Errorf("revoke session: %w", mapError(err))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"golang.org/x/crypto/argon2"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
"mtusi-messenger/internal/platform/token"
|
||||
"mtusi-messenger/internal/service/session"
|
||||
)
|
||||
|
||||
type SessionRepositorySuite struct {
|
||||
BaseSuite
|
||||
}
|
||||
|
||||
func TestSessionRepositorySuite(t *testing.T) {
|
||||
suite.Run(t, new(SessionRepositorySuite))
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestCredentials() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
credentials, err := s.store.Sessions().Credentials(s.T().Context(), "alice")
|
||||
s.Require().NoError(err)
|
||||
s.Equal(alice.ID, credentials.User.ID)
|
||||
verified, err := password.Verify("strong-test-password", credentials.PasswordHash)
|
||||
s.Require().NoError(err)
|
||||
s.True(verified.Match)
|
||||
verified, err = password.Verify("wrong-password-value", credentials.PasswordHash)
|
||||
s.Require().NoError(err)
|
||||
s.False(verified.Match)
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestCredentialsUnknownUser() {
|
||||
_, err := s.store.Sessions().Credentials(s.T().Context(), "nobody")
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestCreateResolveRevoke() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
_, hash, err := token.New().Generate()
|
||||
s.Require().NoError(err)
|
||||
|
||||
expiresAt := time.Now().UTC().Add(time.Hour).Truncate(time.Microsecond)
|
||||
|
||||
created, err := s.store.Sessions().Create(s.T().Context(), domain.NewSession{
|
||||
TokenHash: hash,
|
||||
UserID: alice.ID,
|
||||
ExpiresAt: expiresAt,
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
s.Equal(expiresAt, created.ExpiresAt)
|
||||
|
||||
resolved, err := s.store.Sessions().Resolve(s.T().Context(), hash)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(alice.ID, resolved.User.ID)
|
||||
s.Equal(created.ExpiresAt, resolved.ExpiresAt)
|
||||
|
||||
s.Require().NoError(s.store.Sessions().Revoke(s.T().Context(), alice.ID, hash))
|
||||
|
||||
_, err = s.store.Sessions().Resolve(s.T().Context(), hash)
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestResolveRejectsExpiredToken() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
_, hash, err := token.New().Generate()
|
||||
s.Require().NoError(err)
|
||||
|
||||
_, err = s.store.Sessions().Create(s.T().Context(), domain.NewSession{
|
||||
TokenHash: hash,
|
||||
UserID: alice.ID,
|
||||
ExpiresAt: time.Now().UTC().Add(-time.Minute),
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
_, err = s.store.Sessions().Resolve(s.T().Context(), hash)
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestConcurrentPasswordUpgradeDoesNotOverwriteWinner() {
|
||||
alice := s.createUser("alice")
|
||||
credentials, err := s.store.Sessions().Credentials(s.T().Context(), "alice")
|
||||
s.Require().NoError(err)
|
||||
first, err := password.Hash("strong-test-password")
|
||||
s.Require().NoError(err)
|
||||
second, err := password.Hash("strong-test-password")
|
||||
s.Require().NoError(err)
|
||||
type result struct {
|
||||
hash string
|
||||
updated bool
|
||||
err error
|
||||
}
|
||||
results := make(chan result, 2)
|
||||
start := make(chan struct{})
|
||||
var group sync.WaitGroup
|
||||
for _, hash := range []string{first, second} {
|
||||
group.Go(func() {
|
||||
<-start
|
||||
updated, err := s.store.Sessions().UpdatePasswordHash(
|
||||
s.T().Context(), alice.ID, credentials.PasswordHash, hash,
|
||||
)
|
||||
results <- result{hash: hash, updated: updated, err: err}
|
||||
})
|
||||
}
|
||||
close(start)
|
||||
group.Wait()
|
||||
close(results)
|
||||
winner := ""
|
||||
for result := range results {
|
||||
s.Require().NoError(result.err)
|
||||
if result.updated {
|
||||
s.Empty(winner)
|
||||
winner = result.hash
|
||||
}
|
||||
}
|
||||
s.NotEmpty(winner)
|
||||
updated, err := s.store.Sessions().UpdatePasswordHash(
|
||||
s.T().Context(), alice.ID, credentials.PasswordHash, credentials.PasswordHash,
|
||||
)
|
||||
s.Require().NoError(err)
|
||||
s.False(updated)
|
||||
stored, err := s.store.Sessions().Credentials(s.T().Context(), "alice")
|
||||
s.Require().NoError(err)
|
||||
s.Equal(winner, stored.PasswordHash)
|
||||
}
|
||||
|
||||
type simultaneousCredentials struct {
|
||||
session.Repository
|
||||
loaded chan struct{}
|
||||
ready chan struct{}
|
||||
}
|
||||
|
||||
func (r *simultaneousCredentials) Credentials(ctx context.Context, username string) (domain.UserCredentials, error) {
|
||||
credentials, err := r.Repository.Credentials(ctx, username)
|
||||
if err != nil {
|
||||
return domain.UserCredentials{}, err
|
||||
}
|
||||
r.loaded <- struct{}{}
|
||||
select {
|
||||
case <-r.ready:
|
||||
return credentials, nil
|
||||
case <-ctx.Done():
|
||||
return domain.UserCredentials{}, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestConcurrentLegacyLoginsBothSucceedAndUpgrade() {
|
||||
alice := s.createUser("alice")
|
||||
plain := "strong-test-password"
|
||||
var salt [16]byte
|
||||
hash := argon2.IDKey([]byte(plain), salt[:], 1, 64*1024, 4, 32)
|
||||
legacy := "argon2id$" + base64.RawStdEncoding.EncodeToString(salt[:]) + "$" +
|
||||
base64.RawStdEncoding.EncodeToString(hash)
|
||||
_, err := s.pool.Exec(s.T().Context(), "UPDATE users SET password_hash = $1 WHERE id = $2", legacy, alice.ID)
|
||||
s.Require().NoError(err)
|
||||
repository := &simultaneousCredentials{
|
||||
Repository: s.store.Sessions(),
|
||||
loaded: make(chan struct{}, 2),
|
||||
ready: make(chan struct{}),
|
||||
}
|
||||
service := session.NewService(repository, token.New(), time.Hour)
|
||||
ctx, cancel := context.WithTimeout(s.T().Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
results := make(chan error, 2)
|
||||
var group sync.WaitGroup
|
||||
for range 2 {
|
||||
group.Go(func() {
|
||||
user, err := service.Authenticate(ctx, "alice", plain)
|
||||
if err == nil && user.ID != alice.ID {
|
||||
err = domain.ErrUnauthenticated
|
||||
}
|
||||
results <- err
|
||||
})
|
||||
}
|
||||
for range 2 {
|
||||
select {
|
||||
case <-repository.loaded:
|
||||
case <-ctx.Done():
|
||||
close(repository.ready)
|
||||
group.Wait()
|
||||
s.T().Fatal("concurrent credential loads did not complete")
|
||||
}
|
||||
}
|
||||
close(repository.ready)
|
||||
group.Wait()
|
||||
close(results)
|
||||
for err := range results {
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
stored, err := s.store.Sessions().Credentials(s.T().Context(), "alice")
|
||||
s.Require().NoError(err)
|
||||
verified, err := password.Verify(plain, stored.PasswordHash)
|
||||
s.Require().NoError(err)
|
||||
s.True(verified.Match)
|
||||
s.False(verified.NeedsRehash)
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
queries *sqlcgen.Queries
|
||||
queryTimeout time.Duration
|
||||
idempotencyTTL time.Duration
|
||||
|
||||
users *UserRepository
|
||||
chats *ChatRepository
|
||||
messages *MessageRepository
|
||||
sessions *SessionRepository
|
||||
pipeline *PipelineRepository
|
||||
}
|
||||
|
||||
type options struct {
|
||||
queryTracer pgx.QueryTracer
|
||||
}
|
||||
|
||||
// Option customizes the PostgreSQL store without leaking telemetry into the
|
||||
// storage package's public API.
|
||||
type Option func(*options)
|
||||
|
||||
// WithQueryTracer installs a pgx tracer (nil means no tracing).
|
||||
func WithQueryTracer(tracer pgx.QueryTracer) Option {
|
||||
return func(o *options) { o.queryTracer = tracer }
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration, opts ...Option) (*Store, error) {
|
||||
options := options{}
|
||||
for _, opt := range opts {
|
||||
opt(&options)
|
||||
}
|
||||
|
||||
cfg, err := normalize(cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("normalize database config: %w", err)
|
||||
}
|
||||
|
||||
poolCfg, err := poolConfig(cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("configure database connection: %w", err)
|
||||
}
|
||||
if options.queryTracer != nil {
|
||||
poolCfg.ConnConfig.Tracer = options.queryTracer
|
||||
}
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pool: %w", err)
|
||||
}
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(ctx, cfg.ConnectTimeout)
|
||||
defer cancel()
|
||||
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
|
||||
return nil, fmt.Errorf("ping database: %w", err)
|
||||
}
|
||||
|
||||
store := &Store{
|
||||
pool: pool,
|
||||
queries: sqlcgen.New(pool),
|
||||
queryTimeout: cfg.QueryTimeout,
|
||||
idempotencyTTL: idempotencyTTL,
|
||||
}
|
||||
|
||||
store.users = &UserRepository{store: store}
|
||||
store.chats = &ChatRepository{store: store}
|
||||
store.messages = &MessageRepository{store: store}
|
||||
store.sessions = &SessionRepository{store: store}
|
||||
store.pipeline = &PipelineRepository{store: store}
|
||||
|
||||
return store, nil
|
||||
}
|
||||
|
||||
func (s *Store) Users() *UserRepository { return s.users }
|
||||
|
||||
func (s *Store) Chats() *ChatRepository { return s.chats }
|
||||
|
||||
func (s *Store) Messages() *MessageRepository { return s.messages }
|
||||
|
||||
func (s *Store) Sessions() *SessionRepository { return s.sessions }
|
||||
|
||||
func (s *Store) Pipeline() *PipelineRepository { return s.pipeline }
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := s.pool.Ping(pingCtx); err != nil {
|
||||
return fmt.Errorf("ping database: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// PoolStats exposes a point-in-time pgxpool snapshot for telemetry callbacks.
|
||||
func (s *Store) PoolStats() *pgxpool.Stat { return s.pool.Stat() }
|
||||
|
||||
func (s *Store) Close() { s.pool.Close() }
|
||||
|
||||
// sweepLockKey is a process-independent constant: every replica contends for the
|
||||
// same PostgreSQL session lock, so only one sweeper runs at a time.
|
||||
const sweepLockKey int64 = 0x4c414234 // "LAB4"
|
||||
|
||||
// AcquireSweepLock holds a session-level advisory lock on a dedicated
|
||||
// connection. The returned release function must be called on that same
|
||||
// connection before it is returned to the pool.
|
||||
func (s *Store) AcquireSweepLock(ctx context.Context) (func(), bool, error) {
|
||||
conn, err := s.pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("acquire sweep connection: %w", err)
|
||||
}
|
||||
|
||||
var acquired bool
|
||||
if err := conn.QueryRow(ctx, "SELECT pg_try_advisory_lock($1)", sweepLockKey).Scan(&acquired); err != nil {
|
||||
conn.Release()
|
||||
|
||||
return nil, false, fmt.Errorf("acquire sweep lock: %w", err)
|
||||
}
|
||||
|
||||
if !acquired {
|
||||
conn.Release()
|
||||
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
release := func() {
|
||||
unlockCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, _ = conn.Exec(unlockCtx, "SELECT pg_advisory_unlock($1)", sweepLockKey)
|
||||
conn.Release()
|
||||
}
|
||||
|
||||
return release, true, nil
|
||||
}
|
||||
|
||||
func (s *Store) timeout(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
if s.queryTimeout <= 0 {
|
||||
return context.WithCancel(ctx)
|
||||
}
|
||||
|
||||
return context.WithTimeout(ctx, s.queryTimeout)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
|
||||
)
|
||||
|
||||
func (s *Store) RunInTx(ctx context.Context, fn func(queries *sqlcgen.Queries) error) error {
|
||||
ctx, cancel := s.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin transaction: %w", err)
|
||||
}
|
||||
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
if err := fn(s.queries.WithTx(tx)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit transaction: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
|
||||
)
|
||||
|
||||
type UserRepository struct {
|
||||
store *Store
|
||||
}
|
||||
|
||||
func (r *UserRepository) Create(ctx context.Context, draft domain.NewUser) (domain.User, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.CreateUser(ctx, sqlcgen.CreateUserParams{
|
||||
Username: draft.Username,
|
||||
DisplayName: draft.DisplayName,
|
||||
PasswordHash: draft.PasswordHash,
|
||||
})
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return domain.User{}, fmt.Errorf("%w: username %q", domain.ErrUsernameTaken, draft.Username)
|
||||
}
|
||||
|
||||
return domain.User{}, fmt.Errorf("create user: %w", mapError(err))
|
||||
}
|
||||
|
||||
return domain.User{
|
||||
ID: row.ID,
|
||||
Username: row.Username,
|
||||
DisplayName: row.DisplayName,
|
||||
CreatedAt: toUTCTime(row.CreatedAt),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetByID(ctx context.Context, id uuid.UUID) (domain.User, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.GetUserByID(ctx, id)
|
||||
if err != nil {
|
||||
mapped := mapError(err)
|
||||
if errors.Is(mapped, domain.ErrNotFound) {
|
||||
return domain.User{}, fmt.Errorf("%w: user %s", domain.ErrNotFound, id)
|
||||
}
|
||||
|
||||
return domain.User{}, fmt.Errorf("get user: %w", mapped)
|
||||
}
|
||||
|
||||
return domain.User{
|
||||
ID: row.ID,
|
||||
Username: row.Username,
|
||||
DisplayName: row.DisplayName,
|
||||
CreatedAt: toUTCTime(row.CreatedAt),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
)
|
||||
|
||||
type UserRepositorySuite struct {
|
||||
BaseSuite
|
||||
}
|
||||
|
||||
func TestUserRepositorySuite(t *testing.T) {
|
||||
suite.Run(t, new(UserRepositorySuite))
|
||||
}
|
||||
|
||||
func (s *UserRepositorySuite) TestCreateAndLookup() {
|
||||
created := s.createUser("alice")
|
||||
s.NotEqual(uuid.Nil, created.ID)
|
||||
s.Equal(uuid.Version(7), created.ID.Version())
|
||||
s.Equal("alice", created.Username)
|
||||
s.False(created.CreatedAt.IsZero())
|
||||
|
||||
found, err := s.store.Users().GetByID(s.T().Context(), created.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(created, found)
|
||||
|
||||
_, err = s.store.Users().GetByID(s.T().Context(), uuid.New())
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *UserRepositorySuite) TestDuplicateUsernameConflicts() {
|
||||
s.createUser("alice")
|
||||
|
||||
hash, err := password.Hash("strong-test-password")
|
||||
s.Require().NoError(err)
|
||||
|
||||
_, err = s.store.Users().Create(s.T().Context(), domain.NewUser{
|
||||
Username: "alice",
|
||||
DisplayName: "Другая Алиса",
|
||||
PasswordHash: hash,
|
||||
})
|
||||
s.Require().ErrorIs(err, domain.ErrUsernameTaken)
|
||||
}
|
||||
|
||||
func (s *UserRepositorySuite) TestConcurrentRegistrationCreatesSingleUser() {
|
||||
hash, err := password.Hash("strong-test-password")
|
||||
s.Require().NoError(err)
|
||||
|
||||
const attempts = 8
|
||||
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
mu sync.Mutex
|
||||
successes int
|
||||
failures []error
|
||||
)
|
||||
|
||||
for range attempts {
|
||||
wg.Go(func() {
|
||||
_, err := s.store.Users().Create(s.T().Context(), domain.NewUser{
|
||||
Username: "racer",
|
||||
DisplayName: "Racer",
|
||||
PasswordHash: hash,
|
||||
})
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
if err == nil {
|
||||
successes++
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
failures = append(failures, err)
|
||||
})
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
s.Equal(1, successes, "ровно одна регистрация выигрывает гонку")
|
||||
s.Len(failures, attempts-1)
|
||||
|
||||
for _, failure := range failures {
|
||||
ok := errors.Is(failure, domain.ErrUsernameTaken) || errors.Is(failure, domain.ErrConflict)
|
||||
s.True(ok, "проигравшая регистрация должна давать конфликт, получено: %v", failure)
|
||||
}
|
||||
|
||||
var count int
|
||||
s.Require().NoError(s.pool.QueryRow(s.T().Context(), "SELECT count(*) FROM users WHERE username = 'racer'").Scan(&count))
|
||||
s.Equal(1, count)
|
||||
}
|
||||
|
||||
func (s *UserRepositorySuite) TestQueryTimeoutReturnsError() {
|
||||
store := openStore(s.T(), s.db, func(cfg *config.Postgres) {
|
||||
cfg.QueryTimeout = time.Nanosecond
|
||||
})
|
||||
defer store.Close()
|
||||
|
||||
_, err := store.Users().GetByID(s.T().Context(), uuid.New())
|
||||
s.Require().Error(err)
|
||||
s.NotErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
Reference in New Issue
Block a user