feat(storage): lab3 create messages atomically with idempotency key

This commit is contained in:
Голиков Maximillian Антон
2026-10-06 22:25:09 +03:00
parent 65ae23f46e
commit 566ccb28f7
2 changed files with 107 additions and 1 deletions
+12 -1
View File
@@ -1,6 +1,9 @@
package domain
import "context"
import (
"context"
"time"
)
type UserRepository interface {
Create(ctx context.Context, user *User) error
@@ -17,6 +20,14 @@ type ChatRepository interface {
type MessageRepository interface {
Create(ctx context.Context, message *Message) error
ListByChat(ctx context.Context, chatID string, limit int, cursor *string) ([]Message, *string, error)
CreateIdempotent(
ctx context.Context,
scope IdempotencyScope,
requestHash []byte,
fresh *Message,
freshResponse []byte,
ttl time.Duration,
) (*CreateIdempotentResult, error)
}
type SessionRepository interface {
@@ -1,7 +1,9 @@
package postgres
import (
"bytes"
"context"
"net/http"
"time"
"github.com/jackc/pgx/v5"
@@ -35,6 +37,99 @@ func (r *MessageRepo) Create(ctx context.Context, m *domain.Message) error {
}
return nil
}
func (r *MessageRepo) CreateIdempotent(
ctx context.Context,
scope domain.IdempotencyScope,
requestHash []byte,
fresh *domain.Message,
freshResponse []byte,
ttl time.Duration,
) (*domain.CreateIdempotentResult, error) {
tx, err := r.pool.Begin(ctx)
if err != nil {
return nil, mapError(err)
}
defer func() { _ = tx.Rollback(ctx) }()
// 1) Убираем просроченную запись, чтобы ON CONFLICT сработал
// только на живой, а не на истёкшей строке.
if _, err := tx.Exec(ctx, `
DELETE FROM idempotency_keys
WHERE user_id = $1::uuid AND method = $2 AND path = $3 AND key = $4
AND expires_at <= now()
`, scope.UserID, scope.Method, scope.Path, scope.Key); err != nil {
return nil, mapError(err)
}
// 2) Резервируем слот. Если параллельная реплика уже вставила —
// Postgres заблокирует конфликтный INSERT и мы увидим RowsAffected=0
// только после того, как конкурент закоммитит или откатится.
expiresAt := time.Now().UTC().Add(ttl)
tag, err := tx.Exec(ctx, `
INSERT INTO idempotency_keys
(user_id, method, path, key, request_hash, response_status, response_body, expires_at)
VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (user_id, method, path, key) DO NOTHING
`, scope.UserID, scope.Method, scope.Path, scope.Key,
requestHash, http.StatusCreated, freshResponse, expiresAt)
if err != nil {
return nil, mapError(err)
}
// 3) Слот занят — читаем сохранённый ответ в этой же транзакции.
if tag.RowsAffected() == 0 {
var (
storedHash []byte
storedStatus int
storedBody []byte
)
err := tx.QueryRow(ctx, `
SELECT request_hash, response_status, response_body
FROM idempotency_keys
WHERE user_id = $1::uuid AND method = $2 AND path = $3 AND key = $4
`, scope.UserID, scope.Method, scope.Path, scope.Key).
Scan(&storedHash, &storedStatus, &storedBody)
if err != nil {
return nil, mapError(err)
}
if !bytes.Equal(storedHash, requestHash) {
return nil, &domain.IdempotencyConflictError{Key: scope.Key}
}
if err := tx.Commit(ctx); err != nil {
return nil, mapError(err)
}
return &domain.CreateIdempotentResult{
Status: storedStatus,
Body: storedBody,
Replayed: true,
}, nil
}
// 4) Слот наш — вставляем сообщение в той же транзакции.
if _, err := tx.Exec(ctx, `
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
`, fresh.ID, fresh.ChatID, fresh.SenderID, fresh.Text, fresh.CreatedAt); err != nil {
if foreignKeyViolation(err) {
return nil, &domain.NotFoundError{Entity: "chat", ID: fresh.ChatID}
}
if checkViolation(err) {
return nil, &domain.ValidationError{Field: "text", Message: "нарушено ограничение"}
}
return nil, mapError(err)
}
if err := tx.Commit(ctx); err != nil {
return nil, mapError(err)
}
return &domain.CreateIdempotentResult{
Status: http.StatusCreated,
Body: freshResponse,
Replayed: false,
}, nil
}
func (r *MessageRepo) ListByChat(ctx context.Context, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) {
scope := "messages:" + chatID