lab2
This commit is contained in:
@@ -0,0 +1,159 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"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),
|
||||
Password: envOr("TEST_REDIS_PASSWORD", ""),
|
||||
DB: envInt("TEST_REDIS_DB", 2),
|
||||
DialTimeout: 5 * time.Second,
|
||||
ReadTimeout: 3 * time.Second,
|
||||
WriteTimeout: 3 * time.Second,
|
||||
PoolSize: 5,
|
||||
}
|
||||
redisCache, err := cache.NewRedis(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,192 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"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),
|
||||
Password: envOr("TEST_REDIS_PASSWORD", ""),
|
||||
DB: envInt("TEST_REDIS_DB", 2),
|
||||
DialTimeout: 5 * time.Second,
|
||||
ReadTimeout: 3 * time.Second,
|
||||
WriteTimeout: 3 * time.Second,
|
||||
PoolSize: 10,
|
||||
}
|
||||
redisCache, err := cache.NewRedis(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,74 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultHost = "localhost"
|
||||
defaultPort = 5432
|
||||
defaultDatabase = "messenger"
|
||||
defaultUser = "messenger"
|
||||
defaultSSLMode = "disable"
|
||||
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 cfg.Port == 0 {
|
||||
cfg.Port = defaultPort
|
||||
}
|
||||
|
||||
if cfg.Database == "" {
|
||||
cfg.Database = defaultDatabase
|
||||
}
|
||||
|
||||
if cfg.User == "" {
|
||||
cfg.User = defaultUser
|
||||
}
|
||||
|
||||
if cfg.SSLMode == "" {
|
||||
cfg.SSLMode = defaultSSLMode
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
)
|
||||
|
||||
func TestNormalizeAppliesDefaults(t *testing.T) {
|
||||
cfg, err := normalize(config.Postgres{})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, "localhost", cfg.Host)
|
||||
require.Equal(t, 5432, cfg.Port)
|
||||
require.Equal(t, "messenger", cfg.Database)
|
||||
require.Equal(t, "messenger", cfg.User)
|
||||
require.Equal(t, "disable", cfg.SSLMode)
|
||||
require.Equal(t, int32(10), cfg.MaxConns)
|
||||
require.Equal(t, int32(1), cfg.MinConns)
|
||||
require.Equal(t, time.Hour, cfg.MaxConnLifetime)
|
||||
require.Equal(t, 5*time.Second, cfg.ConnectTimeout)
|
||||
}
|
||||
|
||||
func TestNormalizeKeepsProvidedValues(t *testing.T) {
|
||||
cfg, err := normalize(config.Postgres{
|
||||
Host: "db",
|
||||
Port: 6543,
|
||||
Database: "app",
|
||||
User: "app",
|
||||
SSLMode: "require",
|
||||
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, "require", cfg.SSLMode)
|
||||
require.Equal(t, int32(7), cfg.MaxConns)
|
||||
}
|
||||
|
||||
func TestNormalizeRejectsMinGreaterThanMax(t *testing.T) {
|
||||
_, err := normalize(config.Postgres{MinConns: 5, MaxConns: 2})
|
||||
require.Error(t, err)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
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"
|
||||
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 (
|
||||
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 pgCheckViolation:
|
||||
return domain.ErrValidation
|
||||
}
|
||||
}
|
||||
|
||||
if isUnavailable(err) {
|
||||
return fmt.Errorf("%w: %w", domain.ErrUnavailable, err)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -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,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,51 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Chat struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type ChatMember struct {
|
||||
ChatID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
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,83 @@
|
||||
// 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
|
||||
}
|
||||
@@ -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,278 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"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"
|
||||
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
)
|
||||
|
||||
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", "messenger"),
|
||||
Password: envOr("TEST_POSTGRES_PASSWORD", "messenger"),
|
||||
SSLMode: envOr("TEST_POSTGRES_SSL_MODE", "disable"),
|
||||
MaxConns: 5,
|
||||
MinConns: 1,
|
||||
MaxConnLifetime: time.Hour,
|
||||
MaxConnIdleTime: 30 * time.Minute,
|
||||
ConnectTimeout: 5 * time.Second,
|
||||
QueryTimeout: 5 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
func dsnFor(database string) string {
|
||||
cfg := testConfig()
|
||||
cfg.Database = database
|
||||
|
||||
return cfg.DSN()
|
||||
}
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
ctx := context.Background()
|
||||
|
||||
var err error
|
||||
|
||||
adminPool, err = pgxpool.New(ctx, dsnFor(testConfig().Database))
|
||||
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
|
||||
}
|
||||
|
||||
db, err := sql.Open("pgx", dsnFor(templateDB))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
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)
|
||||
}))
|
||||
|
||||
var err error
|
||||
|
||||
s.pool, err = pgxpool.New(ctx, dsnFor(s.db))
|
||||
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)"))
|
||||
}
|
||||
}
|
||||
|
||||
func openStore(t *testing.T, database string, 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)
|
||||
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,118 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
|
||||
)
|
||||
|
||||
type MessageRepository struct {
|
||||
store *Store
|
||||
}
|
||||
|
||||
func (r *MessageRepository) Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.CreateMessage(ctx, sqlcgen.CreateMessageParams{
|
||||
ChatID: draft.ChatID,
|
||||
SenderID: draft.SenderID,
|
||||
Text: draft.Text,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("create message: %w", mapError(err))
|
||||
}
|
||||
|
||||
return mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt), 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) {
|
||||
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))
|
||||
}
|
||||
|
||||
return mapAll(rows, mapMessageRow), nil
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
return mapAll(rows, mapMessageRow), 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,157 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"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))
|
||||
}
|
||||
|
||||
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(), domain.MessageDraft{
|
||||
ChatID: chat.ID,
|
||||
SenderID: alice.ID,
|
||||
Text: 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(), domain.MessageDraft{
|
||||
ChatID: chat.ID, SenderID: alice.ID, Text: "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(), domain.MessageDraft{
|
||||
ChatID: chat.ID,
|
||||
SenderID: bob.ID,
|
||||
Text: "чужое",
|
||||
})
|
||||
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(), domain.MessageDraft{
|
||||
ChatID: chat.ID,
|
||||
SenderID: alice.ID,
|
||||
Text: 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,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...)}
|
||||
}
|
||||
@@ -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,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,16 @@
|
||||
-- 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);
|
||||
@@ -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,94 @@
|
||||
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: username %q", domain.ErrUnauthenticated, username)
|
||||
}
|
||||
|
||||
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) 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,81 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
"mtusi-messenger/internal/platform/token"
|
||||
)
|
||||
|
||||
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)
|
||||
s.True(password.Verify("strong-test-password", credentials.PasswordHash))
|
||||
s.False(password.Verify("wrong-password-value", credentials.PasswordHash))
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"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
|
||||
|
||||
users *UserRepository
|
||||
chats *ChatRepository
|
||||
messages *MessageRepository
|
||||
sessions *SessionRepository
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg config.Postgres) (*Store, error) {
|
||||
cfg, err := normalize(cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("normalize database config: %w", err)
|
||||
}
|
||||
|
||||
poolCfg, err := pgxpool.ParseConfig(cfg.DSN())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse database dsn: %w", err)
|
||||
}
|
||||
|
||||
poolCfg.MaxConns = cfg.MaxConns
|
||||
poolCfg.MinConns = cfg.MinConns
|
||||
poolCfg.MaxConnLifetime = cfg.MaxConnLifetime
|
||||
poolCfg.MaxConnIdleTime = cfg.MaxConnIdleTime
|
||||
poolCfg.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
store.users = &UserRepository{store: store}
|
||||
store.chats = &ChatRepository{store: store}
|
||||
store.messages = &MessageRepository{store: store}
|
||||
store.sessions = &SessionRepository{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) Ping(ctx context.Context) error {
|
||||
if err := s.pool.Ping(ctx); err != nil {
|
||||
return fmt.Errorf("ping database: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) Close() { s.pool.Close() }
|
||||
|
||||
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