lab4
This commit is contained in:
@@ -0,0 +1,215 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
|
||||
)
|
||||
|
||||
type AttachmentRepository struct {
|
||||
store *Store
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) 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 *AttachmentRepository) Create(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.CreateAttachment(ctx, sqlcgen.CreateAttachmentParams{
|
||||
ID: draft.ID,
|
||||
ChatID: draft.ChatID,
|
||||
OwnerID: draft.OwnerID,
|
||||
ObjectKey: draft.ObjectKey,
|
||||
Filename: draft.Filename,
|
||||
ContentType: draft.ContentType,
|
||||
SizeBytes: draft.SizeBytes,
|
||||
Sha256: draft.SHA256,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("create attachment: %w", mapError(err))
|
||||
}
|
||||
|
||||
return mapAttachment(row), nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) MarkReady(
|
||||
ctx context.Context,
|
||||
id uuid.UUID,
|
||||
objectKey string,
|
||||
) (domain.Attachment, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.MarkAttachmentReady(ctx, sqlcgen.MarkAttachmentReadyParams{
|
||||
ID: id,
|
||||
ObjectKey: objectKey,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("mark attachment ready: %w", mapError(err))
|
||||
}
|
||||
|
||||
return mapAttachment(row), nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) DeletePending(ctx context.Context, id uuid.UUID) error {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
if err := r.store.queries.DeletePendingAttachment(ctx, id); err != nil {
|
||||
return fmt.Errorf("delete pending attachment: %w", mapError(err))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) GetForMember(
|
||||
ctx context.Context,
|
||||
userID, id uuid.UUID,
|
||||
) (domain.Attachment, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.GetAttachmentForMember(ctx, sqlcgen.GetAttachmentForMemberParams{
|
||||
ID: id,
|
||||
UserID: userID,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("get attachment for member: %w", mapError(err))
|
||||
}
|
||||
|
||||
return mapAttachment(row), nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) GetForOwner(
|
||||
ctx context.Context,
|
||||
ownerID, id uuid.UUID,
|
||||
) (domain.Attachment, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.GetAttachmentForOwner(ctx, sqlcgen.GetAttachmentForOwnerParams{
|
||||
ID: id,
|
||||
OwnerID: ownerID,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("get attachment for owner: %w", mapError(err))
|
||||
}
|
||||
|
||||
return mapAttachment(row), nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) ListStates(
|
||||
ctx context.Context,
|
||||
chatID uuid.UUID,
|
||||
ids []uuid.UUID,
|
||||
) ([]domain.AttachmentState, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := r.store.queries.ListAttachmentStatesForChat(ctx, sqlcgen.ListAttachmentStatesForChatParams{
|
||||
ChatID: chatID,
|
||||
Ids: ids,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list attachment states: %w", mapError(err))
|
||||
}
|
||||
|
||||
states := make([]domain.AttachmentState, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
states = append(states, domain.AttachmentState{
|
||||
ID: row.ID,
|
||||
Status: domain.AttachmentStatus(row.Status),
|
||||
})
|
||||
}
|
||||
|
||||
return states, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) ListStalePending(
|
||||
ctx context.Context,
|
||||
createdBefore time.Time,
|
||||
limit int32,
|
||||
) ([]domain.Attachment, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := r.store.queries.ListStalePendingAttachments(ctx, sqlcgen.ListStalePendingAttachmentsParams{
|
||||
CreatedBefore: createdBefore,
|
||||
RowLimit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list stale attachments: %w", mapError(err))
|
||||
}
|
||||
|
||||
return mapAll(rows, mapAttachment), nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) ListKeys(
|
||||
ctx context.Context,
|
||||
limit, offset int32,
|
||||
) ([]domain.AttachmentKey, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := r.store.queries.ListAttachmentKeys(ctx, sqlcgen.ListAttachmentKeysParams{
|
||||
RowLimit: limit,
|
||||
RowOffset: offset,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list attachment keys: %w", mapError(err))
|
||||
}
|
||||
|
||||
keys := make([]domain.AttachmentKey, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
keys = append(keys, domain.AttachmentKey{
|
||||
ID: row.ID,
|
||||
ObjectKey: row.ObjectKey,
|
||||
Status: domain.AttachmentStatus(row.Status),
|
||||
CreatedAt: toUTCTime(row.CreatedAt),
|
||||
})
|
||||
}
|
||||
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
func mapAttachment(row sqlcgen.Attachment) domain.Attachment {
|
||||
attachment := domain.Attachment{
|
||||
ID: row.ID,
|
||||
ChatID: row.ChatID,
|
||||
OwnerID: row.OwnerID,
|
||||
ObjectKey: row.ObjectKey,
|
||||
Filename: row.Filename,
|
||||
ContentType: row.ContentType,
|
||||
SizeBytes: row.SizeBytes,
|
||||
SHA256: row.Sha256,
|
||||
Status: domain.AttachmentStatus(row.Status),
|
||||
CreatedAt: toUTCTime(row.CreatedAt),
|
||||
UpdatedAt: toUTCTime(row.UpdatedAt),
|
||||
}
|
||||
|
||||
if row.ErrorCode.Valid {
|
||||
code := row.ErrorCode.String
|
||||
attachment.ErrorCode = &code
|
||||
}
|
||||
|
||||
return attachment
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type AttachmentRepositorySuite struct {
|
||||
BaseSuite
|
||||
}
|
||||
|
||||
func TestAttachmentRepositorySuite(t *testing.T) {
|
||||
suite.Run(t, new(AttachmentRepositorySuite))
|
||||
}
|
||||
|
||||
func (s *AttachmentRepositorySuite) TestLifecycleAndMessageLinks() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
eve := s.createUser("eve")
|
||||
chat := s.createChat(alice, bob)
|
||||
|
||||
id, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
objectKey := "attachments/" + chat.ID.String() + "/" + id.String()
|
||||
digest := strings.Repeat("a", 64)
|
||||
|
||||
created, err := s.store.Attachments().Create(s.T().Context(), domain.AttachmentDraft{
|
||||
ID: id,
|
||||
ChatID: chat.ID,
|
||||
OwnerID: alice.ID,
|
||||
ObjectKey: objectKey,
|
||||
Filename: "photo.png",
|
||||
ContentType: "image/png",
|
||||
SizeBytes: 123,
|
||||
SHA256: digest,
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentPending, created.Status)
|
||||
|
||||
visible, err := s.store.Attachments().GetForMember(s.T().Context(), bob.ID, id)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(alice.ID, visible.OwnerID)
|
||||
|
||||
_, err = s.store.Attachments().GetForMember(s.T().Context(), eve.ID, id)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
|
||||
ready, err := s.store.Attachments().MarkReady(s.T().Context(), id, objectKey)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentReady, ready.Status)
|
||||
|
||||
states, err := s.store.Attachments().ListStates(
|
||||
s.T().Context(), chat.ID, []uuid.UUID{id},
|
||||
)
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(states, 1)
|
||||
s.Equal(domain.AttachmentReady, states[0].Status)
|
||||
|
||||
key := uuid.NewString()
|
||||
draft := domain.MessageDraft{
|
||||
ChatID: chat.ID,
|
||||
SenderID: alice.ID,
|
||||
Text: "",
|
||||
AttachmentIDs: []uuid.UUID{id},
|
||||
Idempotency: domain.MessageIdempotency{
|
||||
Key: key,
|
||||
RequestHash: [32]byte{1},
|
||||
},
|
||||
}
|
||||
|
||||
message, err := s.store.Messages().Create(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
s.Equal([]uuid.UUID{id}, message.AttachmentIDs)
|
||||
|
||||
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, bob.ID, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(page.Items, 1)
|
||||
s.Equal([]uuid.UUID{id}, page.Items[0].AttachmentIDs)
|
||||
s.Empty(page.Items[0].Text)
|
||||
|
||||
replayed, err := s.store.Messages().Create(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(message.ID, replayed.ID)
|
||||
s.Equal([]uuid.UUID{id}, replayed.AttachmentIDs)
|
||||
}
|
||||
@@ -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,82 @@
|
||||
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 (
|
||||
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,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,367 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: attachments.sql
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"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 createAttachment = `-- name: CreateAttachment :one
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256, status
|
||||
)
|
||||
VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7,
|
||||
$8,
|
||||
'pending'
|
||||
)
|
||||
RETURNING id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256,
|
||||
status, error_code, created_at, updated_at
|
||||
`
|
||||
|
||||
type CreateAttachmentParams struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
ObjectKey string
|
||||
Filename string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Sha256 string
|
||||
}
|
||||
|
||||
func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentParams) (Attachment, error) {
|
||||
row := q.db.QueryRow(ctx, createAttachment,
|
||||
arg.ID,
|
||||
arg.ChatID,
|
||||
arg.OwnerID,
|
||||
arg.ObjectKey,
|
||||
arg.Filename,
|
||||
arg.ContentType,
|
||||
arg.SizeBytes,
|
||||
arg.Sha256,
|
||||
)
|
||||
var i Attachment
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.ObjectKey,
|
||||
&i.Filename,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.Status,
|
||||
&i.ErrorCode,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const deletePendingAttachment = `-- name: DeletePendingAttachment :exec
|
||||
DELETE FROM attachments
|
||||
WHERE id = $1
|
||||
AND status = 'pending'
|
||||
`
|
||||
|
||||
func (q *Queries) DeletePendingAttachment(ctx context.Context, id uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, deletePendingAttachment, id)
|
||||
return err
|
||||
}
|
||||
|
||||
const getAttachmentForMember = `-- name: GetAttachmentForMember :one
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.object_key, a.filename, a.content_type,
|
||||
a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = a.chat_id
|
||||
AND cm.user_id = $1
|
||||
WHERE a.id = $2
|
||||
`
|
||||
|
||||
type GetAttachmentForMemberParams struct {
|
||||
UserID uuid.UUID
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetAttachmentForMember(ctx context.Context, arg GetAttachmentForMemberParams) (Attachment, error) {
|
||||
row := q.db.QueryRow(ctx, getAttachmentForMember, arg.UserID, arg.ID)
|
||||
var i Attachment
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.ObjectKey,
|
||||
&i.Filename,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.Status,
|
||||
&i.ErrorCode,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getAttachmentForOwner = `-- name: GetAttachmentForOwner :one
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.object_key, a.filename, a.content_type,
|
||||
a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = a.chat_id
|
||||
AND cm.user_id = a.owner_id
|
||||
WHERE a.id = $1
|
||||
AND a.owner_id = $2
|
||||
`
|
||||
|
||||
type GetAttachmentForOwnerParams struct {
|
||||
ID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetAttachmentForOwner(ctx context.Context, arg GetAttachmentForOwnerParams) (Attachment, error) {
|
||||
row := q.db.QueryRow(ctx, getAttachmentForOwner, arg.ID, arg.OwnerID)
|
||||
var i Attachment
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.ObjectKey,
|
||||
&i.Filename,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.Status,
|
||||
&i.ErrorCode,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const listAttachmentKeys = `-- name: ListAttachmentKeys :many
|
||||
SELECT id, object_key, status, created_at
|
||||
FROM attachments
|
||||
ORDER BY id
|
||||
LIMIT $2 OFFSET $1
|
||||
`
|
||||
|
||||
type ListAttachmentKeysParams struct {
|
||||
RowOffset int32
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
type ListAttachmentKeysRow struct {
|
||||
ID uuid.UUID
|
||||
ObjectKey string
|
||||
Status string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) ListAttachmentKeys(ctx context.Context, arg ListAttachmentKeysParams) ([]ListAttachmentKeysRow, error) {
|
||||
rows, err := q.db.Query(ctx, listAttachmentKeys, arg.RowOffset, arg.RowLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListAttachmentKeysRow{}
|
||||
for rows.Next() {
|
||||
var i ListAttachmentKeysRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.ObjectKey,
|
||||
&i.Status,
|
||||
&i.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listAttachmentStatesForChat = `-- name: ListAttachmentStatesForChat :many
|
||||
SELECT id, status
|
||||
FROM attachments
|
||||
WHERE chat_id = $1
|
||||
AND id = ANY($2::uuid[])
|
||||
`
|
||||
|
||||
type ListAttachmentStatesForChatParams struct {
|
||||
ChatID uuid.UUID
|
||||
Ids []uuid.UUID
|
||||
}
|
||||
|
||||
type ListAttachmentStatesForChatRow struct {
|
||||
ID uuid.UUID
|
||||
Status string
|
||||
}
|
||||
|
||||
func (q *Queries) ListAttachmentStatesForChat(ctx context.Context, arg ListAttachmentStatesForChatParams) ([]ListAttachmentStatesForChatRow, error) {
|
||||
rows, err := q.db.Query(ctx, listAttachmentStatesForChat, arg.ChatID, arg.Ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListAttachmentStatesForChatRow{}
|
||||
for rows.Next() {
|
||||
var i ListAttachmentStatesForChatRow
|
||||
if err := rows.Scan(&i.ID, &i.Status); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
const listStalePendingAttachments = `-- name: ListStalePendingAttachments :many
|
||||
SELECT id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256,
|
||||
status, error_code, created_at, updated_at
|
||||
FROM attachments
|
||||
WHERE status = 'pending'
|
||||
AND created_at < $1
|
||||
ORDER BY created_at
|
||||
LIMIT $2
|
||||
`
|
||||
|
||||
type ListStalePendingAttachmentsParams struct {
|
||||
CreatedBefore time.Time
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
func (q *Queries) ListStalePendingAttachments(ctx context.Context, arg ListStalePendingAttachmentsParams) ([]Attachment, error) {
|
||||
rows, err := q.db.Query(ctx, listStalePendingAttachments, arg.CreatedBefore, arg.RowLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []Attachment{}
|
||||
for rows.Next() {
|
||||
var i Attachment
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.ObjectKey,
|
||||
&i.Filename,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.Status,
|
||||
&i.ErrorCode,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const markAttachmentReady = `-- name: MarkAttachmentReady :one
|
||||
UPDATE attachments
|
||||
SET status = 'ready',
|
||||
object_key = $1,
|
||||
updated_at = now()
|
||||
WHERE id = $2
|
||||
AND status = 'pending'
|
||||
RETURNING id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256,
|
||||
status, error_code, created_at, updated_at
|
||||
`
|
||||
|
||||
type MarkAttachmentReadyParams struct {
|
||||
ObjectKey string
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) MarkAttachmentReady(ctx context.Context, arg MarkAttachmentReadyParams) (Attachment, error) {
|
||||
row := q.db.QueryRow(ctx, markAttachmentReady, arg.ObjectKey, arg.ID)
|
||||
var i Attachment
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.ObjectKey,
|
||||
&i.Filename,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.Status,
|
||||
&i.ErrorCode,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, 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,128 @@
|
||||
// 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
|
||||
}
|
||||
@@ -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,83 @@
|
||||
// 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
|
||||
}
|
||||
|
||||
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 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 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,291 @@
|
||||
//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)"))
|
||||
}
|
||||
}
|
||||
|
||||
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,306 @@
|
||||
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
|
||||
}
|
||||
|
||||
// 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,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,82 @@
|
||||
-- name: CreateAttachment :one
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256, status
|
||||
)
|
||||
VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(chat_id),
|
||||
sqlc.arg(owner_id),
|
||||
sqlc.arg(object_key),
|
||||
sqlc.arg(filename),
|
||||
sqlc.arg(content_type),
|
||||
sqlc.arg(size_bytes),
|
||||
sqlc.arg(sha256),
|
||||
'pending'
|
||||
)
|
||||
RETURNING id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256,
|
||||
status, error_code, created_at, updated_at;
|
||||
|
||||
-- name: MarkAttachmentReady :one
|
||||
UPDATE attachments
|
||||
SET status = 'ready',
|
||||
object_key = sqlc.arg(object_key),
|
||||
updated_at = now()
|
||||
WHERE id = sqlc.arg(id)
|
||||
AND status = 'pending'
|
||||
RETURNING id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256,
|
||||
status, error_code, created_at, updated_at;
|
||||
|
||||
-- name: GetAttachmentForMember :one
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.object_key, a.filename, a.content_type,
|
||||
a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = a.chat_id
|
||||
AND cm.user_id = sqlc.arg(user_id)
|
||||
WHERE a.id = sqlc.arg(id);
|
||||
|
||||
-- name: GetAttachmentForOwner :one
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.object_key, a.filename, a.content_type,
|
||||
a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = a.chat_id
|
||||
AND cm.user_id = a.owner_id
|
||||
WHERE a.id = sqlc.arg(id)
|
||||
AND a.owner_id = sqlc.arg(owner_id);
|
||||
|
||||
-- name: ListAttachmentStatesForChat :many
|
||||
SELECT id, status
|
||||
FROM attachments
|
||||
WHERE chat_id = sqlc.arg(chat_id)
|
||||
AND id = ANY(sqlc.arg(ids)::uuid[]);
|
||||
|
||||
-- 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;
|
||||
|
||||
-- name: DeletePendingAttachment :exec
|
||||
DELETE FROM attachments
|
||||
WHERE id = sqlc.arg(id)
|
||||
AND status = 'pending';
|
||||
|
||||
-- name: ListStalePendingAttachments :many
|
||||
SELECT id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256,
|
||||
status, error_code, created_at, updated_at
|
||||
FROM attachments
|
||||
WHERE status = 'pending'
|
||||
AND created_at < sqlc.arg(created_before)
|
||||
ORDER BY created_at
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- name: ListAttachmentKeys :many
|
||||
SELECT id, object_key, status, created_at
|
||||
FROM attachments
|
||||
ORDER BY id
|
||||
LIMIT sqlc.arg(row_limit) OFFSET sqlc.arg(row_offset);
|
||||
@@ -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,40 @@
|
||||
-- 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);
|
||||
@@ -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,137 @@
|
||||
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
|
||||
idempotencyTTL time.Duration
|
||||
|
||||
users *UserRepository
|
||||
chats *ChatRepository
|
||||
messages *MessageRepository
|
||||
sessions *SessionRepository
|
||||
attachments *AttachmentRepository
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration) (*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,
|
||||
idempotencyTTL: idempotencyTTL,
|
||||
}
|
||||
|
||||
store.users = &UserRepository{store: store}
|
||||
store.chats = &ChatRepository{store: store}
|
||||
store.messages = &MessageRepository{store: store}
|
||||
store.sessions = &SessionRepository{store: store}
|
||||
store.attachments = &AttachmentRepository{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) Attachments() *AttachmentRepository { return s.attachments }
|
||||
|
||||
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() }
|
||||
|
||||
// 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