Files
mtusi2026lab3/internal/app/idempotency_test.go
T

154 lines
5.8 KiB
Go

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: 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)
}
}