Сделать отправку сообщения идемпотентной по 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
+9
View File
@@ -0,0 +1,9 @@
package store
// SetAfterClaim installs a hook that runs between the claiming statement and
// the replay lookup of AppendOnce; it returns a function restoring the old one.
func SetAfterClaim(hook func()) (restore func()) {
old := afterClaim
afterClaim = hook
return func() { afterClaim = old }
}
+252
View File
@@ -0,0 +1,252 @@
package store_test
import (
"context"
"sync"
"testing"
"time"
"github.com/google/uuid"
"messenger/internal/chat"
"messenger/internal/chat/store"
)
const keyTTL = time.Hour
// expire makes every stored key older than keyTTL.
func expire(t *testing.T) {
t.Helper()
if _, err := db.Pool.Exec(context.Background(),
`UPDATE message_idempotency_keys SET created_at = now() - interval '2 hours'`); err != nil {
t.Fatal(err)
}
}
func (f fixture) appendOnce(t *testing.T, m chat.Message, key string) chat.Message {
t.Helper()
got, err := f.messages.AppendOnce(f.ctx, m, key, keyTTL)
if err != nil {
t.Fatal(err)
}
return got
}
func (f fixture) count(t *testing.T, chatID uuid.UUID) int {
t.Helper()
got, err := f.messages.ListByChat(f.ctx, chatID, nil, 1000)
if err != nil {
t.Fatal(err)
}
return len(got)
}
func keyTarget(t *testing.T, key string) uuid.UUID {
t.Helper()
var id uuid.UUID
if err := db.Pool.QueryRow(context.Background(),
`SELECT message_id FROM message_idempotency_keys WHERE key = $1`, key).Scan(&id); err != nil {
t.Fatal(err)
}
return id
}
func TestAppendOnceInsertsThenReplays(t *testing.T) {
f := newFixture(t)
alice := f.mustUser(t)
c := f.mustChat(t, alice)
first := f.newMessage(t, c.ID, alice)
if got := f.appendOnce(t, first, "k1"); got.ID != first.ID {
t.Fatalf("first append returned %v, want the new message %v", got.ID, first.ID)
}
retry := f.newMessage(t, c.ID, alice)
got := f.appendOnce(t, retry, "k1")
if got.ID != first.ID || !got.CreatedAt.Equal(first.CreatedAt) || got.Text != first.Text || got.SenderID != alice {
t.Fatalf("replay returned %+v, want the stored %+v", got, first)
}
if n := f.count(t, c.ID); n != 1 {
t.Fatalf("history has %d messages, want 1", n)
}
}
func TestAppendOnceTakesOverExpiredKey(t *testing.T) {
f := newFixture(t)
alice := f.mustUser(t)
c := f.mustChat(t, alice)
f.appendOnce(t, f.newMessage(t, c.ID, alice), "k1")
expire(t)
next := f.newMessage(t, c.ID, alice)
if got := f.appendOnce(t, next, "k1"); got.ID != next.ID {
t.Fatalf("expired key returned %v, want the new message %v", got.ID, next.ID)
}
if n := f.count(t, c.ID); n != 2 {
t.Fatalf("history has %d messages, want 2", n)
}
if target := keyTarget(t, "k1"); target != next.ID {
t.Fatalf("key points to %v, want %v", target, next.ID)
}
}
// A cleaner batch holds the expired key row; the request waits for it and,
// once the row is gone, inserts its message under the now free key.
func TestAppendOnceWaitsForCleanerThenInserts(t *testing.T) {
f := newFixture(t)
alice := f.mustUser(t)
c := f.mustChat(t, alice)
f.appendOnce(t, f.newMessage(t, c.ID, alice), "k1")
expire(t)
tx, err := db.Pool.Begin(f.ctx)
if err != nil {
t.Fatal(err)
}
defer tx.Rollback(f.ctx)
if _, err := tx.Exec(f.ctx, `SELECT 1 FROM message_idempotency_keys WHERE key = 'k1' FOR UPDATE`); err != nil {
t.Fatal(err)
}
next := f.newMessage(t, c.ID, alice)
type result struct {
m chat.Message
err error
}
done := make(chan result, 1)
go func() {
m, err := f.messages.AppendOnce(f.ctx, next, "k1", keyTTL)
done <- result{m, err}
}()
select {
case r := <-done:
t.Fatalf("AppendOnce did not wait for the locked key: %+v", r)
case <-time.After(300 * time.Millisecond):
}
if _, err := tx.Exec(f.ctx, `DELETE FROM message_idempotency_keys WHERE key = 'k1'`); err != nil {
t.Fatal(err)
}
if err := tx.Commit(f.ctx); err != nil {
t.Fatal(err)
}
select {
case r := <-done:
if r.err != nil || r.m.ID != next.ID {
t.Fatalf("after the cleaner: %+v, %v; want the new message %v", r.m, r.err, next.ID)
}
case <-time.After(5 * time.Second):
t.Fatal("AppendOnce did not finish after the cleaner committed")
}
}
// A request holding a key row must not make the cleaner wait: it skips the
// row and deletes it on a later run.
func TestCleanerSkipsRowLockedByRequest(t *testing.T) {
f := newFixture(t)
alice := f.mustUser(t)
c := f.mustChat(t, alice)
f.appendOnce(t, f.newMessage(t, c.ID, alice), "k1")
expire(t)
tx, err := db.Pool.Begin(f.ctx)
if err != nil {
t.Fatal(err)
}
if _, err := tx.Exec(f.ctx, `SELECT 1 FROM message_idempotency_keys WHERE key = 'k1' FOR UPDATE`); err != nil {
t.Fatal(err)
}
start := time.Now()
n, err := f.messages.DeleteExpiredKeys(f.ctx, keyTTL, 1000)
if err != nil || n != 0 {
t.Fatalf("cleaner over a locked row: deleted %d, %v; want 0", n, err)
}
if waited := time.Since(start); waited > time.Second {
t.Fatalf("cleaner waited %v for the locked row", waited)
}
if err := tx.Rollback(f.ctx); err != nil {
t.Fatal(err)
}
if n, err := f.messages.DeleteExpiredKeys(f.ctx, keyTTL, 1000); err != nil || n != 1 {
t.Fatalf("cleaner after release: deleted %d, %v; want 1", n, err)
}
}
// The key is alive when the claim runs but deleted before the replay lookup,
// as by a cleaner whose clock is a moment later at the TTL boundary. The
// operation starts over and stores the new message.
func TestAppendOnceRetriesWhenKeyVanishes(t *testing.T) {
f := newFixture(t)
alice := f.mustUser(t)
c := f.mustChat(t, alice)
f.appendOnce(t, f.newMessage(t, c.ID, alice), "k1")
var once sync.Once
restore := store.SetAfterClaim(func() {
once.Do(func() {
if _, err := db.Pool.Exec(context.Background(), `DELETE FROM message_idempotency_keys WHERE key = 'k1'`); err != nil {
t.Error(err)
}
})
})
defer restore()
next := f.newMessage(t, c.ID, alice)
if got := f.appendOnce(t, next, "k1"); got.ID != next.ID {
t.Fatalf("got %v, want the new message %v", got.ID, next.ID)
}
}
func TestDeleteExpiredKeysOnlyExpiredAndUpToLimit(t *testing.T) {
f := newFixture(t)
alice := f.mustUser(t)
c := f.mustChat(t, alice)
for _, k := range []string{"a", "b", "c"} {
f.appendOnce(t, f.newMessage(t, c.ID, alice), k)
}
expire(t)
f.appendOnce(t, f.newMessage(t, c.ID, alice), "fresh")
if n, err := f.messages.DeleteExpiredKeys(f.ctx, keyTTL, 2); err != nil || n != 2 {
t.Fatalf("first batch deleted %d, %v; want 2", n, err)
}
if n, err := f.messages.DeleteExpiredKeys(f.ctx, keyTTL, 2); err != nil || n != 1 {
t.Fatalf("second batch deleted %d, %v; want 1", n, err)
}
var left int
if err := db.Pool.QueryRow(f.ctx, `SELECT count(*) FROM message_idempotency_keys`).Scan(&left); err != nil || left != 1 {
t.Fatalf("%d keys left, %v; want only the fresh one", left, err)
}
if n := f.count(t, c.ID); n != 4 {
t.Fatalf("cleanup removed messages: %d left, want 4", n)
}
}
// Every request brings its own new message under one key; exactly one is
// stored and all of them get it back. This also proves the key row and the
// message it references are written by one statement.
func TestConcurrentAppendOnceSameKeyStoresOneMessage(t *testing.T) {
f := newFixture(t)
alice := f.mustUser(t)
c := f.mustChat(t, alice)
const requests = 20
ids := make(chan uuid.UUID, requests)
var wg sync.WaitGroup
for range requests {
m := f.newMessage(t, c.ID, alice)
wg.Go(func() {
got, err := f.messages.AppendOnce(f.ctx, m, "same", keyTTL)
if err != nil {
t.Error(err)
return
}
ids <- got.ID
})
}
wg.Wait()
close(ids)
seen := map[uuid.UUID]int{}
for id := range ids {
seen[id]++
}
if len(seen) != 1 {
t.Fatalf("requests got %d different messages, want 1: %v", len(seen), seen)
}
if n := f.count(t, c.ID); n != 1 {
t.Fatalf("history has %d messages, want 1", n)
}
}
+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
+12 -5
View File
@@ -8,6 +8,7 @@ import (
"os"
"sync"
"testing"
"time"
"github.com/google/uuid"
@@ -81,6 +82,12 @@ func (f fixture) newMessage(t *testing.T, chatID, sender uuid.UUID) chat.Message
return m
}
// appendErr stores m under a key of its own, as every send now carries one.
func (f fixture) appendErr(m chat.Message) error {
_, err := f.messages.AppendOnce(f.ctx, m, m.ID.String(), time.Hour)
return err
}
func TestChatCreateThenGetForMember(t *testing.T) {
f := newFixture(t)
alice, bob := f.mustUser(t), f.mustUser(t)
@@ -199,7 +206,7 @@ func TestAppendOutOfOrderIsListedByID(t *testing.T) {
c := f.mustChat(t, alice)
first, second, third := f.newMessage(t, c.ID, alice), f.newMessage(t, c.ID, alice), f.newMessage(t, c.ID, alice)
for _, m := range []chat.Message{third, first, second} {
if err := f.messages.Append(f.ctx, m); err != nil {
if err := f.appendErr(m); err != nil {
t.Fatal(err)
}
}
@@ -221,13 +228,13 @@ func TestPagingWalksWholeHistoryWithoutGapsOrDuplicates(t *testing.T) {
for range total {
m := f.newMessage(t, c.ID, alice)
expected = append(expected, m.ID)
if err := f.messages.Append(f.ctx, m); err != nil {
if err := f.appendErr(m); err != nil {
t.Fatal(err)
}
}
// Another chat's history must not leak into this one.
other := f.mustChat(t, alice)
if err := f.messages.Append(f.ctx, f.newMessage(t, other.ID, alice)); err != nil {
if err := f.appendErr(f.newMessage(t, other.ID, alice)); err != nil {
t.Fatal(err)
}
for _, limit := range []int{1, 7, 100} {
@@ -269,7 +276,7 @@ func TestAfterUnknownIDStartsAtNextGreater(t *testing.T) {
gap := ident.New() // never stored, but sorts between a and b
b := f.newMessage(t, c.ID, alice)
for _, m := range []chat.Message{a, b} {
if err := f.messages.Append(f.ctx, m); err != nil {
if err := f.appendErr(m); err != nil {
t.Fatal(err)
}
}
@@ -291,7 +298,7 @@ func TestConcurrentAppendsKeepEveryMessage(t *testing.T) {
for range clients {
wg.Go(func() {
for range perClient {
if err := f.messages.Append(f.ctx, f.newMessage(t, c.ID, alice)); err != nil {
if err := f.appendErr(f.newMessage(t, c.ID, alice)); err != nil {
t.Error(err)
}
}