This commit is contained in:
Vladislav Kunetskiy
2026-10-21 21:22:42 +03:00
parent f4bd361f12
commit 464db7fdd6
238 changed files with 13332 additions and 704 deletions
+8 -2
View File
@@ -15,8 +15,9 @@ import (
)
const (
pgUniqueViolation = "23505"
pgCheckViolation = "23514"
pgUniqueViolation = "23505"
pgForeignKeyViolation = "23503"
pgCheckViolation = "23514"
)
func isUniqueViolation(err error) bool {
@@ -63,6 +64,11 @@ func mapError(err error) error {
switch pgErr.Code {
case pgUniqueViolation:
return domain.ErrConflict
case pgForeignKeyViolation:
// Нарушение внешнего ключа означает ссылку на отсутствующую сущность:
// например, отправка сообщения в несуществующий чат или в чат, где
// отправителя нет. Для клиента это 404, а не 500.
return domain.ErrNotFound
case pgCheckViolation:
return domain.ErrValidation
}
@@ -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,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
}
@@ -8,6 +8,7 @@ import (
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
)
type Chat struct {
@@ -30,6 +31,16 @@ type Message struct {
CreatedAt time.Time
}
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
+14 -1
View File
@@ -227,9 +227,22 @@ func (s *BaseSuite) TearDownTest() {
}
}
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
@@ -237,7 +250,7 @@ func openStore(t *testing.T, database string, override func(*config.Postgres)) *
override(&cfg)
}
store, err := postgres.New(t.Context(), cfg)
store, err := postgres.New(t.Context(), cfg, idempotencyTTL)
require.NoError(t, err)
return store
@@ -1,11 +1,15 @@
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"
@@ -16,16 +20,100 @@ type MessageRepository struct {
}
func (r *MessageRepository) Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error) {
ctx, cancel := r.store.timeout(ctx)
defer cancel()
var created domain.Message
row, err := r.store.queries.CreateMessage(ctx, sqlcgen.CreateMessageParams{
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{}, fmt.Errorf("create message: %w", mapError(err))
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)
}
return mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt), 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)
}
return mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt), nil
@@ -3,6 +3,7 @@
package postgres_test
import (
"crypto/sha256"
"fmt"
"sync"
"testing"
@@ -21,6 +22,23 @@ 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")
@@ -29,11 +47,7 @@ func (s *MessageRepositorySuite) TestCreateAndPagination() {
const total = 5
for i := range total {
message, err := s.store.Messages().Create(s.T().Context(), domain.MessageDraft{
ChatID: chat.ID,
SenderID: alice.ID,
Text: fmt.Sprintf("сообщение %d", i),
})
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())
@@ -69,9 +83,7 @@ func (s *MessageRepositorySuite) TestPaginationWithSharedTimestamp() {
chat := s.createChat(alice)
for range 5 {
_, err := s.store.Messages().Create(s.T().Context(), domain.MessageDraft{
ChatID: chat.ID, SenderID: alice.ID, Text: "same timestamp",
})
_, err := s.store.Messages().Create(s.T().Context(), s.draft(chat.ID, alice.ID, "same timestamp"))
s.Require().NoError(err)
}
@@ -108,11 +120,7 @@ func (s *MessageRepositorySuite) TestAccessIsRestricted() {
chat := s.createChat(alice)
_, err := s.store.Messages().Create(s.T().Context(), domain.MessageDraft{
ChatID: chat.ID,
SenderID: bob.ID,
Text: "чужое",
})
_, 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)
@@ -136,11 +144,7 @@ func (s *MessageRepositorySuite) TestFinishedMessageSurvivesConcurrentReads() {
wg.Go(func() {
for i := range total {
_, err := s.store.Messages().Create(s.T().Context(), domain.MessageDraft{
ChatID: chat.ID,
SenderID: alice.ID,
Text: fmt.Sprintf("message %d", i),
})
_, err := s.store.Messages().Create(s.T().Context(), s.draft(chat.ID, alice.ID, fmt.Sprintf("message %d", i)))
if err != nil {
return
}
@@ -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,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);
+9 -7
View File
@@ -12,9 +12,10 @@ import (
)
type Store struct {
pool *pgxpool.Pool
queries *sqlcgen.Queries
queryTimeout time.Duration
pool *pgxpool.Pool
queries *sqlcgen.Queries
queryTimeout time.Duration
idempotencyTTL time.Duration
users *UserRepository
chats *ChatRepository
@@ -22,7 +23,7 @@ type Store struct {
sessions *SessionRepository
}
func New(ctx context.Context, cfg config.Postgres) (*Store, error) {
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)
@@ -54,9 +55,10 @@ func New(ctx context.Context, cfg config.Postgres) (*Store, error) {
}
store := &Store{
pool: pool,
queries: sqlcgen.New(pool),
queryTimeout: cfg.QueryTimeout,
pool: pool,
queries: sqlcgen.New(pool),
queryTimeout: cfg.QueryTimeout,
idempotencyTTL: idempotencyTTL,
}
store.users = &UserRepository{store: store}