Сделать отправку сообщения идемпотентной по Idempotency-Key с общей таблицей ключей и их чисткой

This commit is contained in:
2026-11-02 17:11:04 +03:00
parent 7fa8881eb3
commit 951fd0d517
19 changed files with 856 additions and 40 deletions
+84 -7
View File
@@ -12,6 +12,7 @@ import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
@@ -117,14 +118,90 @@ func NewMessages(pool *pgxpool.Pool) *Messages {
return &Messages{pool: pool}
}
func (r *Messages) Append(ctx context.Context, m chat.Message) error {
_, err := r.pool.Exec(ctx,
`INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5)`,
m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt)
if err != nil {
return fmt.Errorf("insert message: %w", postgres.Classify(err))
// afterClaim runs between the claiming statement and the replay lookup of
// AppendOnce; tests use it to delete the key in that window.
var afterClaim func()
// claimSQL stores the key and the message in one statement. A key older than
// the retention period is taken over for the new message. The key row is
// inserted first: when it already exists and is still valid, claimed is
// empty and so is the message insert. One statement holds the key's lock
// only while the server executes it, never across a round trip to a replica
// that might die in between.
const claimSQL = `
WITH claimed AS (
INSERT INTO message_idempotency_keys AS k (user_id, chat_id, key, message_id)
VALUES ($1, $2, $3, $4)
ON CONFLICT (user_id, chat_id, key) DO UPDATE
SET message_id = EXCLUDED.message_id, created_at = now()
WHERE k.created_at < now() - $5::interval
RETURNING message_id)
INSERT INTO messages (chat_id, id, sender_id, text, created_at)
SELECT $2, message_id, $1, $6, $7 FROM claimed`
// AppendOnce stores m under key unless the sender already used the key in
// this chat within ttl; it returns the message the key is bound to, m itself
// or the earlier one. Deciding whether the earlier message answers the same
// request is the caller's job.
//
// The lookup of an existing key is a second statement: within the claiming
// one, a plain SELECT would see the snapshot taken before a concurrent
// request committed the key. Between the two statements the cleaner may
// delete a key at the ttl boundary; the operation then starts over once,
// which stores m under the now free key.
func (r *Messages) AppendOnce(ctx context.Context, m chat.Message, key string, ttl time.Duration) (chat.Message, error) {
for range 2 {
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
}
if afterClaim != nil {
afterClaim()
}
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)
if errors.Is(err, pgx.ErrNoRows) {
continue
}
if err != nil {
return chat.Message{}, fmt.Errorf("select message by key: %w", postgres.Classify(err))
}
return stored, nil
}
return nil
return chat.Message{}, errors.New("idempotency key vanished twice between claim and lookup")
}
// DeleteExpiredKeys removes up to limit keys older than ttl. SKIP LOCKED lets
// replicas cleaning at the same time, and requests holding a key, pass each
// other instead of waiting.
func (r *Messages) DeleteExpiredKeys(ctx context.Context, ttl time.Duration, limit int) (int64, error) {
tag, err := r.pool.Exec(ctx, `
DELETE FROM message_idempotency_keys
WHERE (user_id, chat_id, key) IN (
SELECT user_id, chat_id, key FROM message_idempotency_keys
WHERE created_at < now() - $1::interval
ORDER BY created_at
LIMIT $2
FOR UPDATE SKIP LOCKED)`,
interval(ttl), limit)
if err != nil {
return 0, fmt.Errorf("delete expired keys: %w", postgres.Classify(err))
}
return tag.RowsAffected(), nil
}
// interval renders d for a ::interval parameter.
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