- версия истории чата хранится в PostgreSQL (chats.version, миграция 0003) и растёт в одной транзакции с сообщением; ключ кэша включает её, поэтому ошибка любой команды Redis не может вернуть устаревшую историю - членство и версия читаются одним запросом; INCR/GET версии в Redis удалены - пароль из одних пробельных символов -> 400 (unit-тест validatePassword) - student-tests/regressions.py: сценарий проверки с Redis ACL -incr и пароль - CI: тот же тест против кода до исправления; все серии трека 1 заново
142 lines
5.5 KiB
Go
142 lines
5.5 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"github.com/charawein/mtusi2026lab3/internal/domain"
|
|
"github.com/charawein/mtusi2026lab3/internal/repository"
|
|
)
|
|
|
|
type MessageRepository struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
func NewMessageRepository(pool *pgxpool.Pool) *MessageRepository {
|
|
return &MessageRepository{pool: pool}
|
|
}
|
|
|
|
func (r *MessageRepository) Create(ctx context.Context, msg *domain.Message) error {
|
|
const q = `
|
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
|
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
|
`
|
|
if _, err := r.pool.Exec(ctx, q, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil {
|
|
return fmt.Errorf("insert message: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// CreateIdempotent вставляет сообщение и ключ в одной транзакции.
|
|
// Конкурентные запросы с одним ключом сериализуются уникальным индексом
|
|
// idempotency_keys: второй INSERT ждёт завершения первой транзакции, после
|
|
// COMMIT получает конфликт (DO NOTHING), откатывает своё сообщение и читает
|
|
// уже сохранённое. Если первая транзакция откатилась (транзиентная ошибка),
|
|
// вторая просто продолжает — неуспешный результат не фиксируется.
|
|
func (r *MessageRepository) CreateIdempotent(ctx context.Context, msg *domain.Message, key, requestHash string, ttl time.Duration) (*domain.Message, bool, error) {
|
|
tx, err := r.pool.Begin(ctx)
|
|
if err != nil {
|
|
return nil, false, fmt.Errorf("begin tx: %w", err)
|
|
}
|
|
defer func() { _ = tx.Rollback(ctx) }()
|
|
|
|
// Ключ старше TTL больше не защищает от повтора — освобождаем его.
|
|
const deleteExpired = `
|
|
DELETE FROM idempotency_keys
|
|
WHERE user_id = $1::uuid AND chat_id = $2::uuid AND key = $3
|
|
AND created_at < now() - make_interval(secs => $4)
|
|
`
|
|
if _, err := tx.Exec(ctx, deleteExpired, msg.SenderID, msg.ChatID, key, ttl.Seconds()); err != nil {
|
|
return nil, false, fmt.Errorf("delete expired key: %w", err)
|
|
}
|
|
|
|
const insertMsg = `
|
|
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
|
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
|
`
|
|
if _, err := tx.Exec(ctx, insertMsg, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil {
|
|
return nil, false, fmt.Errorf("insert message: %w", err)
|
|
}
|
|
|
|
const insertKey = `
|
|
INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id)
|
|
VALUES ($1::uuid, $2::uuid, $3, $4, $5::uuid)
|
|
ON CONFLICT (user_id, chat_id, key) DO NOTHING
|
|
`
|
|
tag, err := tx.Exec(ctx, insertKey, msg.SenderID, msg.ChatID, key, requestHash, msg.ID)
|
|
if err != nil {
|
|
return nil, false, fmt.Errorf("insert idempotency key: %w", err)
|
|
}
|
|
if tag.RowsAffected() == 1 {
|
|
// Версия истории растёт атомарно с сообщением: после COMMIT любое чтение
|
|
// увидит новую версию и не попадёт в кэш, записанный до этого сообщения.
|
|
const bumpVersion = `UPDATE chats SET version = version + 1 WHERE id = $1::uuid`
|
|
if _, err := tx.Exec(ctx, bumpVersion, msg.ChatID); err != nil {
|
|
return nil, false, fmt.Errorf("bump chat version: %w", err)
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return nil, false, fmt.Errorf("commit tx: %w", err)
|
|
}
|
|
return msg, true, nil
|
|
}
|
|
|
|
// Ключ уже занят подтверждённой записью: наше сообщение не сохраняем.
|
|
_ = tx.Rollback(ctx)
|
|
|
|
const selectStored = `
|
|
SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
|
FROM idempotency_keys k
|
|
JOIN messages m ON m.id = k.message_id
|
|
WHERE k.user_id = $1::uuid AND k.chat_id = $2::uuid AND k.key = $3
|
|
`
|
|
var storedHash string
|
|
var m domain.Message
|
|
err = r.pool.QueryRow(ctx, selectStored, msg.SenderID, msg.ChatID, key).
|
|
Scan(&storedHash, &m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt)
|
|
if err != nil {
|
|
return nil, false, fmt.Errorf("select stored message: %w", err)
|
|
}
|
|
if storedHash != requestHash {
|
|
return nil, false, repository.ErrConflict
|
|
}
|
|
return &m, false, nil
|
|
}
|
|
|
|
// DeleteExpiredKeys удаляет ключи старше TTL. Безопасно выполнять с любой реплики.
|
|
func (r *MessageRepository) DeleteExpiredKeys(ctx context.Context, ttl time.Duration) (int64, error) {
|
|
const q = `DELETE FROM idempotency_keys WHERE created_at < now() - make_interval(secs => $1)`
|
|
tag, err := r.pool.Exec(ctx, q, ttl.Seconds())
|
|
if err != nil {
|
|
return 0, fmt.Errorf("delete expired keys: %w", err)
|
|
}
|
|
return tag.RowsAffected(), nil
|
|
}
|
|
|
|
func (r *MessageRepository) ListByChat(ctx context.Context, chatID string, cursor time.Time, cursorID string, limit int) ([]*domain.Message, error) {
|
|
const q = `
|
|
SELECT id, chat_id, sender_id, text, created_at
|
|
FROM messages
|
|
WHERE chat_id = $1::uuid
|
|
AND (created_at, id) > ($2::timestamptz, $3::uuid)
|
|
ORDER BY created_at, id
|
|
LIMIT $4
|
|
`
|
|
rows, err := r.pool.Query(ctx, q, chatID, cursor, cursorID, limit)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list messages: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
msgs := []*domain.Message{}
|
|
for rows.Next() {
|
|
var m domain.Message
|
|
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
|
return nil, fmt.Errorf("scan message: %w", err)
|
|
}
|
|
msgs = append(msgs, &m)
|
|
}
|
|
return msgs, rows.Err()
|
|
}
|