Сделать отправку сообщения идемпотентной по 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
+8 -1
View File
@@ -50,9 +50,16 @@ type Deps struct {
// request that gives up on a dependency can still write its 503.
const defaultRequestTimeout = 5 * time.Second
// defaultIdempotencyTTL is the contract's retention of message keys.
const defaultIdempotencyTTL = 24 * time.Hour
func New(d Deps) *App {
users := user.NewService(userstore.NewUsers(d.DB))
chats := chat.NewService(chatstore.NewChats(d.DB), chatstore.NewMessages(d.DB), users)
keyTTL := d.IdempotencyTTL
if keyTTL == 0 {
keyTTL = defaultIdempotencyTTL
}
chats := chat.NewService(chatstore.NewChats(d.DB), chatstore.NewMessages(d.DB), users, keyTTL)
engine := httpx.NewEngine(d.Log, d.MaxBodyBytes, d.InstanceID)
probes := health.New(
+10 -3
View File
@@ -18,6 +18,8 @@ import (
"testing"
"time"
"github.com/google/uuid"
"messenger/internal/app"
"messenger/internal/chat"
"messenger/internal/platform/pagination"
@@ -238,11 +240,16 @@ func (ts *tester) chat(token, title string, members ...string) chat.ChatResponse
func (ts *tester) message(token, chatID, text string) chat.MessageResponse {
ts.t.Helper()
res := ts.do(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", token, map[string]string{"text": text}, nil)
res := ts.do(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", token, map[string]string{"text": text}, freshKey())
ts.expect(res, http.StatusCreated, "")
return decode[chat.MessageResponse](ts.t, res)
}
// freshKey is the header of a first attempt: a key never used before.
func freshKey() map[string]string {
return map[string]string{"Idempotency-Key": uuid.NewString()}
}
func (ts *tester) chats(token, query string) pagination.PageResponse[chat.ChatResponse] {
ts.t.Helper()
res := ts.do(http.MethodGet, "/api/v1/chats"+query, token, nil, nil)
@@ -418,7 +425,7 @@ func TestMessagesEndToEnd(t *testing.T) {
t.Fatalf("page2 = %+v", page2)
}
post := func(actor string, body any) response { return ts.do(http.MethodPost, path, actor, body, nil) }
post := func(actor string, body any) response { return ts.do(http.MethodPost, path, actor, body, freshKey()) }
ts.expect(post(alice.token, map[string]string{"text": ""}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.token, map[string]string{"text": " "}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.token, map[string]string{"text": strings.Repeat("я", 4001)}), http.StatusBadRequest, "invalid_request")
@@ -480,7 +487,7 @@ func TestConcurrentSendsProduceExactlyUniqueMessages(t *testing.T) {
for n, c := range clientsList {
wg.Go(func() {
for i := 0; i < perClient; i++ {
res := ts.do(http.MethodPost, "/api/v1/chats/"+room.ID+"/messages", c.token, map[string]string{"text": fmt.Sprintf("c%d-m%d", n, i)}, nil)
res := ts.do(http.MethodPost, "/api/v1/chats/"+room.ID+"/messages", c.token, map[string]string{"text": fmt.Sprintf("c%d-m%d", n, i)}, freshKey())
if res.status != http.StatusCreated {
t.Errorf("client %d: status %d body %s", n, res.status, res.raw)
}
+20 -6
View File
@@ -146,15 +146,29 @@ func TestLogoutRevokesOnlyTheCurrentToken(t *testing.T) {
ts.expect(ts.do(http.MethodGet, "/api/v1/users/me", other.Token, nil, nil), http.StatusOK, "")
}
// The TTL leaves room for a loaded machine: with one second the first request
// after login sometimes arrived too late under -race with all packages
// running at once.
// The expiry is an absolute time written by the application and enforced by
// Valkey's clock. Here the test runs on the Windows host and Valkey in the
// Docker VM, whose clock lags by a fraction of a second, so the test waits
// for the 401 with a tolerance instead of sleeping exactly one TTL. On the
// stand both run in the same VM.
func TestSessionExpiresAfterTTL(t *testing.T) {
ts := newTesterWithTTL(t, 3*time.Second)
const ttl, clockTolerance = 2 * time.Second, 3 * time.Second
ts := newTesterWithTTL(t, ttl)
alice := ts.user("alice", "A")
ts.expect(ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil), http.StatusOK, "")
time.Sleep(3200 * time.Millisecond)
ts.expect(ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil), http.StatusUnauthorized, "unauthorized")
time.Sleep(ttl)
deadline := time.Now().Add(clockTolerance)
for {
res := ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil)
if res.status == http.StatusUnauthorized {
ts.expect(res, http.StatusUnauthorized, "unauthorized")
return
}
if time.Now().After(deadline) {
t.Fatalf("session still valid %v after its TTL of %v", clockTolerance, ttl)
}
time.Sleep(100 * time.Millisecond)
}
}
func TestRegistrationIsPublicAndIgnoresAuthorization(t *testing.T) {
+154
View File
@@ -0,0 +1,154 @@
package app_test
import (
"bytes"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"messenger/internal/app"
)
func (ts *tester) send(token, chatID, key string, body any) response {
ts.t.Helper()
return ts.do(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", token, body, map[string]string{"Idempotency-Key": key})
}
func TestSendIdempotencyKeyValidation(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
room := ts.chat(alice.token, "ключи", alice.ID)
path := "/api/v1/chats/" + room.ID + "/messages"
body := map[string]string{"text": "x"}
ts.expect(ts.do(http.MethodPost, path, alice.token, body, nil), http.StatusBadRequest, "invalid_request")
for name, key := range map[string]string{
"empty": "",
"too long": strings.Repeat("a", 129),
"inner space": "a b",
"non-ascii": "ключ",
"slash": "a/b",
} {
res := ts.send(alice.token, room.ID, key, body)
if res.status != http.StatusBadRequest {
t.Errorf("%s key: status %d, want 400", name, res.status)
}
}
ts.expect(ts.send(alice.token, room.ID, strings.Repeat("a", 128), body), http.StatusCreated, "")
ts.expect(ts.send(alice.token, room.ID, "Az09._:-", body), http.StatusCreated, "")
// Two Idempotency-Key headers are ambiguous: which one names the attempt?
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"text":"x"}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+alice.token)
req.Header.Add("Idempotency-Key", "one")
req.Header.Add("Idempotency-Key", "two")
rec := httptest.NewRecorder()
ts.a.Engine.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("two keys: status %d, want 400", rec.Code)
}
}
func TestReplayReturnsIdenticalBody(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
room := ts.chat(alice.token, "повторы", alice.ID)
first := ts.send(alice.token, room.ID, "retry-1", map[string]string{"text": "Привет 👋"})
ts.expect(first, http.StatusCreated, "")
// The same JSON with other spacing is the same request.
again := ts.send(alice.token, room.ID, "retry-1", ` { "text" : "Привет 👋" } `)
ts.expect(again, http.StatusCreated, "")
if !bytes.Equal(first.raw, again.raw) {
t.Fatalf("replay body differs:\n%s\n%s", first.raw, again.raw)
}
if page := ts.history(alice.token, room.ID, ""); len(page.Items) != 1 {
t.Fatalf("history has %d messages, want 1", len(page.Items))
}
}
func TestReplayWithDifferentBodyIs409(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
room := ts.chat(alice.token, "конфликт", alice.ID)
ts.expect(ts.send(alice.token, room.ID, "k", map[string]string{"text": "первое"}), http.StatusCreated, "")
ts.expect(ts.send(alice.token, room.ID, "k", map[string]string{"text": "второе"}), http.StatusConflict, "conflict")
}
// A replay is a new request: a revoked session cannot fetch the stored result.
func TestReplayRechecksSession(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
room := ts.chat(alice.token, "сессия", alice.ID)
ts.expect(ts.send(alice.token, room.ID, "k", map[string]string{"text": "x"}), http.StatusCreated, "")
ts.expect(ts.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.token, nil, nil), http.StatusNoContent, "")
ts.expect(ts.send(alice.token, room.ID, "k", map[string]string{"text": "x"}), http.StatusUnauthorized, "unauthorized")
}
// The header is checked before access, like the JSON syntax: the answer does
// not depend on the chat, so it reveals nothing about a foreign one.
func TestOutsiderWithoutKeyGets400AndWithKey404(t *testing.T) {
ts := newTester(t)
alice, eve := ts.user("alice", "A"), ts.user("eve", "E")
room := ts.chat(alice.token, "чужой", alice.ID)
path := "/api/v1/chats/" + room.ID + "/messages"
ts.expect(ts.do(http.MethodPost, path, eve.token, map[string]string{"text": "x"}, nil), http.StatusBadRequest, "invalid_request")
ts.expect(ts.send(eve.token, room.ID, "k", map[string]string{"text": "x"}), http.StatusNotFound, "not_found")
}
// Two applications over the same stores stand for two replicas behind the
// balancer: retries of one key alternate between them and still create one
// message.
func TestConcurrentReplaysAcrossTwoAppsCreateOneMessage(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
room := ts.chat(alice.token, "реплики", alice.ID)
other := app.New(app.Deps{
Log: slog.New(slog.NewTextHandler(io.Discard, nil)),
DB: db.Pool,
Sessions: kv.Client,
SessionTTL: time.Hour,
MaxBodyBytes: 64 * 1024,
InstanceID: "00000000000000b2",
})
engines := []http.Handler{ts.a.Engine, other.Engine}
const attempts = 10
type result struct {
status int
body string
instance string
}
results := make([]result, attempts)
var wg sync.WaitGroup
for i := range attempts {
wg.Go(func() {
req := httptest.NewRequest(http.MethodPost, "/api/v1/chats/"+room.ID+"/messages", strings.NewReader(`{"text":"один раз"}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+alice.token)
req.Header.Set("Idempotency-Key", "shared")
rec := httptest.NewRecorder()
engines[i%2].ServeHTTP(rec, req)
results[i] = result{rec.Code, rec.Body.String(), rec.Header().Get("X-Instance-Id")}
})
}
wg.Wait()
instances := map[string]bool{}
for i, r := range results {
if r.status != http.StatusCreated || r.body != results[0].body {
t.Fatalf("attempt %d: %d %s; want 201 %s", i, r.status, r.body, results[0].body)
}
instances[r.instance] = true
}
if len(instances) != 2 {
t.Fatalf("instances %v, want both replicas", instances)
}
if page := ts.history(alice.token, room.ID, ""); len(page.Items) != 1 {
t.Fatalf("history has %d messages, want 1: %+v", len(page.Items), page.Items)
}
}