Добавьте S3-вложения с дедупликацией и безопасной сверкой хранилищ
This commit is contained in:
@@ -19,6 +19,7 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"messenger/internal/chat"
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/postgres"
|
||||
)
|
||||
|
||||
@@ -118,9 +119,8 @@ func NewMessages(pool *pgxpool.Pool) *Messages {
|
||||
return &Messages{pool: pool}
|
||||
}
|
||||
|
||||
// claimSQL binds the key and inserts the message in one statement, so the
|
||||
// key's lock never spans a round trip. An expired key is taken over; a valid
|
||||
// one leaves claimed, and so the message insert, empty.
|
||||
// claimSQL binds the key and inserts the message in one statement. An expired
|
||||
// key is taken over; a valid one leaves claimed and the message insert empty.
|
||||
const claimSQL = `
|
||||
WITH claimed AS (
|
||||
INSERT INTO message_idempotency_keys AS k (user_id, chat_id, key, message_id)
|
||||
@@ -132,30 +132,100 @@ const claimSQL = `
|
||||
INSERT INTO messages (chat_id, id, sender_id, text, created_at)
|
||||
SELECT $2, message_id, $1, $6, $7 FROM claimed`
|
||||
|
||||
// The bound message is read by a second statement: the claim's snapshot
|
||||
// cannot see a key that a concurrent request has just committed.
|
||||
// The transaction keeps attachment readiness, message joins and the key atomic.
|
||||
// The replay uses a new statement snapshot to see a concurrent winner.
|
||||
func (r *Messages) AppendOnce(ctx context.Context, m chat.Message, key string, ttl time.Duration) (chat.Message, error) {
|
||||
tag, err := r.pool.Exec(ctx, claimSQL,
|
||||
m.SenderID, m.ChatID, key, m.ID, interval(ttl), m.Text, m.CreatedAt)
|
||||
if err != nil {
|
||||
return chat.Message{}, fmt.Errorf("insert message: %w", postgres.Classify(err))
|
||||
}
|
||||
if tag.RowsAffected() == 1 {
|
||||
return m, nil
|
||||
}
|
||||
var stored chat.Message
|
||||
err = r.pool.QueryRow(ctx, `
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM message_idempotency_keys k
|
||||
JOIN messages m ON m.chat_id = k.chat_id AND m.id = k.message_id
|
||||
WHERE k.user_id = $1 AND k.chat_id = $2 AND k.key = $3`,
|
||||
m.SenderID, m.ChatID, key).Scan(&stored.ID, &stored.ChatID, &stored.SenderID, &stored.Text, &stored.CreatedAt)
|
||||
err := pgx.BeginFunc(ctx, r.pool, func(tx pgx.Tx) error {
|
||||
if err := validateAttachments(ctx, tx, m.ChatID, m.AttachmentIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
tag, err := tx.Exec(ctx, claimSQL,
|
||||
m.SenderID, m.ChatID, key, m.ID, interval(ttl), m.Text, m.CreatedAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() == 1 {
|
||||
if len(m.AttachmentIDs) > 0 {
|
||||
_, err := tx.Exec(ctx, `
|
||||
INSERT INTO message_attachments (chat_id, message_id, attachment_id, ordinal)
|
||||
SELECT $1, $2, id, (ord - 1)::smallint
|
||||
FROM unnest($3::uuid[]) WITH ORDINALITY AS a(id, ord)`,
|
||||
m.ChatID, m.ID, m.AttachmentIDs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert message attachments: %w", err)
|
||||
}
|
||||
}
|
||||
stored = m
|
||||
return nil
|
||||
}
|
||||
stored, err = scanMessage(tx.QueryRow(ctx, `
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
||||
WHERE a.chat_id = m.chat_id AND a.message_id = m.id ORDER BY a.ordinal)
|
||||
FROM message_idempotency_keys k
|
||||
JOIN messages m ON m.chat_id = k.chat_id AND m.id = k.message_id
|
||||
WHERE k.user_id = $1 AND k.chat_id = $2 AND k.key = $3`,
|
||||
m.SenderID, m.ChatID, key))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
// A vanished key is available again; retry its atomic claim.
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("select message by key: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return chat.Message{}, fmt.Errorf("select message by key: %w", postgres.Classify(err))
|
||||
return chat.Message{}, postgres.Classify(err)
|
||||
}
|
||||
return stored, nil
|
||||
}
|
||||
|
||||
func validateAttachments(ctx context.Context, tx pgx.Tx, chatID uuid.UUID, ids []uuid.UUID) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
// Shared row locks prevent deletion or a readiness change until joins commit.
|
||||
rows, err := tx.Query(ctx, `
|
||||
SELECT f.status
|
||||
FROM attachments a
|
||||
JOIN files f ON f.hash = a.file_hash
|
||||
WHERE a.chat_id = $1 AND a.id = ANY($2::uuid[])
|
||||
ORDER BY a.id
|
||||
FOR SHARE OF a, f`, chatID, ids)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check attachments: %w", err)
|
||||
}
|
||||
statuses, err := pgx.CollectRows(rows, pgx.RowTo[string])
|
||||
if err != nil {
|
||||
return fmt.Errorf("read attachment status: %w", err)
|
||||
}
|
||||
if len(statuses) != len(ids) {
|
||||
return apperr.NotFound("attachment not found")
|
||||
}
|
||||
for _, status := range statuses {
|
||||
if status != "ready" {
|
||||
return apperr.Conflict("attachment is not ready")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func scanMessage(row pgx.Row) (chat.Message, error) {
|
||||
var m chat.Message
|
||||
err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt, &m.AttachmentIDs)
|
||||
if len(m.AttachmentIDs) == 0 {
|
||||
m.AttachmentIDs = nil
|
||||
}
|
||||
return m, err
|
||||
}
|
||||
|
||||
// DeleteExpiredKeys skips rows locked by another cleaner or a request rather
|
||||
// than waiting for them.
|
||||
func (r *Messages) DeleteExpiredKeys(ctx context.Context, olderThan time.Duration, limit int) (int64, error) {
|
||||
@@ -179,14 +249,16 @@ func interval(d time.Duration) string {
|
||||
return fmt.Sprintf("%d milliseconds", d.Milliseconds())
|
||||
}
|
||||
|
||||
// ListByChat is the history query; scripts/explain-history.sql runs the same
|
||||
// statement for the EXPLAIN evidence.
|
||||
// ListByChat keeps keyset pagination on messages and collects each ordered
|
||||
// attachment array in the same statement.
|
||||
func (r *Messages) ListByChat(ctx context.Context, chatID uuid.UUID, after *uuid.UUID, limit int) ([]chat.Message, error) {
|
||||
rows, err := r.pool.Query(ctx, `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND id > COALESCE($2, '00000000-0000-0000-0000-000000000000'::uuid)
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(SELECT a.attachment_id FROM message_attachments a
|
||||
WHERE a.chat_id = m.chat_id AND a.message_id = m.id ORDER BY a.ordinal)
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1
|
||||
AND m.id > COALESCE($2, '00000000-0000-0000-0000-000000000000'::uuid)
|
||||
ORDER BY id
|
||||
LIMIT $3`,
|
||||
chatID, after, limit)
|
||||
@@ -194,9 +266,7 @@ func (r *Messages) ListByChat(ctx context.Context, chatID uuid.UUID, after *uuid
|
||||
return nil, fmt.Errorf("select messages: %w", postgres.Classify(err))
|
||||
}
|
||||
messages, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (chat.Message, error) {
|
||||
var m chat.Message
|
||||
err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt)
|
||||
return m, err
|
||||
return scanMessage(row)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read messages: %w", postgres.Classify(err))
|
||||
|
||||
Reference in New Issue
Block a user