Реализация на 5

This commit is contained in:
Grbisba
2026-11-17 13:08:13 +03:00
parent 470d9d6f1e
commit 60f48c0337
229 changed files with 74928 additions and 47 deletions
+285
View File
@@ -0,0 +1,285 @@
package tests
import (
"encoding/json"
"fmt"
"github.com/google/uuid"
"io"
"net/http"
"net/url"
"os"
"strings"
"testing"
"time"
)
type apiClient struct {
baseURL string
prefix string
tokens map[string]string
}
type apiResponse struct {
status int
requestID string
instanceID string
body []byte
}
func newAPI(t *testing.T) *apiClient {
t.Helper()
base := os.Getenv("TEST_BASE_URL")
if base == "" {
base = "http://localhost:18086"
}
return &apiClient{baseURL: strings.TrimRight(base, "/"), prefix: uuid.NewString()[:8] + "_", tokens: map[string]string{}}
}
func (api *apiClient) request(t *testing.T, method, path, userID, body string) apiResponse {
return api.requestKey(t, method, path, userID, body, uuid.NewString())
}
func (api *apiClient) requestKey(t *testing.T, method, path, userID, body, key string) apiResponse {
t.Helper()
response, err := api.send(method, path, userID, body, key)
if err != nil {
t.Fatal(err)
}
return response
}
func (api *apiClient) send(method, path, userID, body, key string) (apiResponse, error) {
if path == "/api/v1/users" {
var fields map[string]any
if json.Unmarshal([]byte(body), &fields) == nil {
if name, ok := fields["username"].(string); ok {
fields["username"] = api.prefix + name
data, err := json.Marshal(fields)
if err != nil {
return apiResponse{}, err
}
body = string(data)
}
}
}
req, err := http.NewRequest(method, api.baseURL+path, strings.NewReader(body))
if err != nil {
return apiResponse{}, err
}
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
if userID != "" {
req.Header.Set("Authorization", "Bearer "+api.tokens[userID])
}
if key != "" {
req.Header.Set("Idempotency-Key", key)
}
response, err := (&http.Client{Timeout: 5 * time.Second}).Do(req)
if err != nil {
return apiResponse{}, fmt.Errorf("running lab5 stand required: %w", err)
}
defer response.Body.Close()
data, err := io.ReadAll(response.Body)
if err != nil {
return apiResponse{}, err
}
requestID, instanceID := response.Header.Get("X-Request-Id"), response.Header.Get("X-Instance-Id")
if requestID == "" || instanceID == "" {
return apiResponse{}, fmt.Errorf("%s %s: HTTP %d missing response identity", method, path, response.StatusCode)
}
return apiResponse{status: response.StatusCode, requestID: requestID, instanceID: instanceID, body: data}, nil
}
func jsonString(t *testing.T, value any) string {
t.Helper()
data, err := json.Marshal(value)
if err != nil {
t.Fatalf("encode request: %v", err)
}
return string(data)
}
func decodeOK(t *testing.T, resp apiResponse, wantStatus int, target any) {
t.Helper()
if resp.status != wantStatus {
t.Fatalf("status = %d, want %d; body: %s", resp.status, wantStatus, resp.body)
}
if err := json.Unmarshal(resp.body, target); err != nil {
t.Fatalf("decode response %s: %v", resp.body, err)
}
}
func assertError(t *testing.T, resp apiResponse, wantStatus int, wantCode string) {
t.Helper()
if resp.status != wantStatus {
t.Fatalf("status = %d, want %d; body: %s", resp.status, wantStatus, resp.body)
}
var body struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
} `json:"error"`
}
if err := json.Unmarshal(resp.body, &body); err != nil {
t.Fatalf("decode error response %s: %v", resp.body, err)
}
if body.Error.Code != wantCode || body.Error.Message == "" || body.Error.RequestID != resp.requestID {
t.Fatalf("invalid error response: header request ID %q, body %s", resp.requestID, resp.body)
}
}
func (api *apiClient) createUser(t *testing.T, username string) string {
t.Helper()
resp := api.request(t, http.MethodPost, "/api/v1/users", "", jsonString(t, map[string]string{
"username": username, "display_name": username, "password": "Synthetic-password-123",
}))
var user struct {
ID string `json:"id"`
}
decodeOK(t, resp, http.StatusCreated, &user)
if user.ID == "" {
t.Fatal("created user has no ID")
}
req, _ := http.NewRequest(http.MethodPost, api.baseURL+"/api/v1/auth/sessions", nil)
req.SetBasicAuth(api.prefix+username, "Synthetic-password-123")
sessionResp, err := (&http.Client{Timeout: 5 * time.Second}).Do(req)
if err != nil {
t.Fatal(err)
}
defer sessionResp.Body.Close()
var session struct {
Token string `json:"token"`
}
if err = json.NewDecoder(sessionResp.Body).Decode(&session); err != nil || sessionResp.StatusCode != 201 || session.Token == "" {
t.Fatalf("login failed: status %d, error %v", sessionResp.StatusCode, err)
}
api.tokens[user.ID] = session.Token
return user.ID
}
func (api *apiClient) createChat(t *testing.T, creatorID string, memberIDs ...string) string {
t.Helper()
resp := api.request(t, http.MethodPost, "/api/v1/chats", creatorID, jsonString(t, map[string]any{
"title": "Test chat", "member_ids": memberIDs,
}))
var chat struct {
ID string `json:"id"`
}
decodeOK(t, resp, http.StatusCreated, &chat)
if chat.ID == "" {
t.Fatal("created chat has no ID")
}
return chat.ID
}
func TestInvalidJSON(t *testing.T) {
api := newAPI(t)
for _, tc := range []struct {
name string
body string
}{
{name: "malformed", body: `{"username":`},
{name: "wrong type", body: `{"username":42,"display_name":"Alice"}`},
{name: "unknown field", body: `{"username":"alice","display_name":"Alice","admin":true}`},
} {
t.Run(tc.name, func(t *testing.T) {
resp := api.request(t, http.MethodPost, "/api/v1/users", "", tc.body)
assertError(t, resp, http.StatusBadRequest, "invalid_request")
})
}
}
func TestForeignChatIsHidden(t *testing.T) {
api := newAPI(t)
alice := api.createUser(t, "alice")
bob := api.createUser(t, "bob")
eve := api.createUser(t, "eve")
chatID := api.createChat(t, alice, alice, bob)
for _, tc := range []struct {
method string
path string
body string
}{
{method: http.MethodGet, path: "/api/v1/chats/" + chatID},
{method: http.MethodGet, path: "/api/v1/chats/" + chatID + "/messages"},
{method: http.MethodPost, path: "/api/v1/chats/" + chatID + "/messages", body: `{"text":"secret"}`},
} {
resp := api.request(t, tc.method, tc.path, eve, tc.body)
assertError(t, resp, http.StatusNotFound, "not_found")
}
}
func TestEmptyMessage(t *testing.T) {
api := newAPI(t)
alice := api.createUser(t, "alice")
chatID := api.createChat(t, alice, alice)
path := "/api/v1/chats/" + chatID + "/messages"
for _, body := range []string{`{"text":""}`, `{"text":" \t\n "}`} {
resp := api.request(t, http.MethodPost, path, alice, body)
assertError(t, resp, http.StatusBadRequest, "invalid_request")
}
}
func TestDuplicateUsername(t *testing.T) {
api := newAPI(t)
api.createUser(t, "alice")
resp := api.request(t, http.MethodPost, "/api/v1/users", "", `{"username":"alice","display_name":"Another Alice","password":"Synthetic-password-123"}`)
assertError(t, resp, http.StatusConflict, "conflict")
}
func TestMessagePagination(t *testing.T) {
api := newAPI(t)
alice := api.createUser(t, "alice")
chatID := api.createChat(t, alice, alice)
wantIDs := make(map[string]bool)
for i := range 5 {
resp := api.request(t, http.MethodPost, "/api/v1/chats/"+chatID+"/messages", alice,
jsonString(t, map[string]string{"text": fmt.Sprintf("message %d", i)}))
var message struct {
ID string `json:"id"`
}
decodeOK(t, resp, http.StatusCreated, &message)
if message.ID == "" || wantIDs[message.ID] {
t.Fatalf("invalid or duplicate created message ID %q", message.ID)
}
wantIDs[message.ID] = true
}
seen := make(map[string]bool)
cursor := ""
pages := 0
for {
path := "/api/v1/chats/" + chatID + "/messages?limit=2"
if cursor != "" {
path += "&cursor=" + url.QueryEscape(cursor)
}
resp := api.request(t, http.MethodGet, path, alice, "")
var page struct {
Items []struct {
ID string `json:"id"`
} `json:"items"`
NextCursor *string `json:"next_cursor"`
}
decodeOK(t, resp, http.StatusOK, &page)
pages++
if pages > 3 || len(page.Items) == 0 || len(page.Items) > 2 {
t.Fatalf("unexpected page %d: %s", pages, resp.body)
}
for _, message := range page.Items {
if !wantIDs[message.ID] || seen[message.ID] {
t.Fatalf("unexpected or repeated message ID %q on page %d", message.ID, pages)
}
seen[message.ID] = true
}
if page.NextCursor == nil {
break
}
if *page.NextCursor == "" || *page.NextCursor == cursor {
t.Fatalf("invalid next cursor on page %d: %s", pages, resp.body)
}
cursor = *page.NextCursor
}
if pages != 3 || len(seen) != len(wantIDs) {
t.Fatalf("got %d pages and %d unique messages, want 3 pages and %d messages", pages, len(seen), len(wantIDs))
}
}
+226
View File
@@ -0,0 +1,226 @@
package tests
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"encoding/json"
"hash/crc32"
"image"
"image/jpeg"
"io"
"net/http"
"net/url"
"os"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
)
func (api *apiClient) upload(t *testing.T, chat, user, name, mime string, data []byte, chunked bool) apiResponse {
t.Helper()
req, e := http.NewRequest("POST", api.baseURL+"/api/v1/chats/"+chat+"/attachments?filename="+url.QueryEscape(name), bytes.NewReader(data))
if e != nil {
t.Fatal(e)
}
if chunked {
req.ContentLength = -1
}
req.Header.Set("Content-Type", mime)
if user != "" {
req.Header.Set("Authorization", "Bearer "+api.tokens[user])
}
resp, e := (&http.Client{Timeout: 20 * time.Second}).Do(req)
if e != nil {
t.Fatal(e)
}
defer resp.Body.Close()
body, e := io.ReadAll(resp.Body)
if e != nil {
t.Fatal(e)
}
if resp.Header.Get("X-Instance-Id") == "" {
t.Fatal("missing instance id")
}
return apiResponse{status: resp.StatusCode, body: body, requestID: resp.Header.Get("X-Request-Id"), instanceID: resp.Header.Get("X-Instance-Id")}
}
func fixturePNG(t *testing.T) []byte {
t.Helper()
b, e := os.ReadFile("../../tests/fixtures/sample.png")
if e != nil {
t.Fatal(e)
}
return b
}
func TestAttachmentContractAndErrors(t *testing.T) {
api := newAPI(t)
alice := api.createUser(t, "alice")
bob := api.createUser(t, "bob")
eve := api.createUser(t, "eve")
chat := api.createChat(t, alice, alice, bob)
other := api.createChat(t, alice, alice)
data := fixturePNG(t)
var att struct {
ID string `json:"id"`
Sha string `json:"sha256"`
Size int `json:"size_bytes"`
}
decodeOK(t, api.upload(t, chat, alice, "Файл.png", "image/png", data, false), 202, &att)
hash := sha256.Sum256(data)
if att.Sha != hex.EncodeToString(hash[:]) || att.Size != len(data) {
t.Fatal("original metadata mismatch")
}
waitAttachmentReady(t, api, alice, att.ID)
content := "/api/v1/attachments/" + att.ID + "/content"
got := api.request(t, "GET", content, bob, "")
if got.status != 200 || !bytes.Equal(got.body, data) {
t.Fatal("download changed bytes")
}
for _, suffix := range []string{"", "/content"} {
assertError(t, api.request(t, "GET", "/api/v1/attachments/"+att.ID+suffix, eve, ""), 404, "not_found")
}
assertError(t, api.upload(t, chat, eve, "file.png", "image/png", data, false), 404, "not_found")
assertError(t, api.upload(t, chat, "", "file.png", "image/png", data, false), 401, "unauthorized")
for _, name := range []string{"", " ", "../a.png", "a/b.png", "a\\b.png", "bad\x00.png", "bad\n.png", strings.Repeat("я", 256)} {
assertError(t, api.upload(t, chat, alice, name, "image/png", data, false), 400, "invalid_request")
}
for _, tc := range []struct {
name, mime string
data []byte
}{
{"fake", "image/png", []byte("not an image")},
{"mime mismatch", "image/jpeg", data},
{"wrong type", "application/octet-stream", data},
{"truncated", "image/png", data[:80]},
} {
t.Run(tc.name, func(t *testing.T) {
assertError(t, api.upload(t, chat, alice, "test.png", tc.mime, tc.data, false), 415, "unsupported_media_type")
})
}
bomb := bytes.Clone(data)
binary.BigEndian.PutUint32(bomb[16:20], 40000001)
binary.BigEndian.PutUint32(bomb[20:24], 1)
binary.BigEndian.PutUint32(bomb[29:33], crc32.ChecksumIEEE(bomb[12:29]))
assertError(t, api.upload(t, chat, alice, "bomb.png", "image/png", bomb, false), 413, "payload_too_large")
// A syntactically valid ancillary PNG chunk reaches the exact byte boundary
// without allocating an enormous decoded image.
padding := make([]byte, 10485760-len(data)-12)
chunk := append([]byte("paDd"), padding...)
boundary := append([]byte{}, data[:len(data)-12]...)
boundary = binary.BigEndian.AppendUint32(boundary, uint32(len(padding)))
boundary = append(boundary, chunk...)
boundary = binary.BigEndian.AppendUint32(boundary, crc32.ChecksumIEEE(chunk))
boundary = append(boundary, data[len(data)-12:]...)
var boundaryAtt map[string]any
decodeOK(t, api.upload(t, chat, alice, "boundary.png", "image/png", boundary, false), 202, &boundaryAtt)
oversized := make([]byte, 10485761)
copy(oversized, data)
for _, chunked := range []bool{false, true} {
assertError(t, api.upload(t, chat, alice, "large.png", "image/png", oversized, chunked), 413, "payload_too_large")
}
var jpg bytes.Buffer
if e := jpeg.Encode(&jpg, image.NewRGBA(image.Rect(0, 0, 32, 24)), nil); e != nil {
t.Fatal(e)
}
var jpegAtt map[string]any
decodeOK(t, api.upload(t, chat, bob, "file.jpg", "image/jpeg", jpg.Bytes(), false), 202, &jpegAtt)
imageOnly := `{"text":"","attachment_ids":["` + att.ID + `"]}`
var message map[string]any
key := uuid.NewString()
decodeOK(t, api.requestKey(t, "POST", "/api/v1/chats/"+chat+"/messages", bob, imageOnly, key), 201, &message)
var replay map[string]any
decodeOK(t, api.requestKey(t, "POST", "/api/v1/chats/"+chat+"/messages", bob, imageOnly, key), 201, &replay)
if jsonString(t, message) != jsonString(t, replay) {
t.Fatal("attachment retry changed message")
}
assertError(t, api.requestKey(t, "POST", "/api/v1/chats/"+chat+"/messages", bob, `{"text":"changed","attachment_ids":["`+att.ID+`"]}`, key), 409, "conflict")
assertError(t, api.request(t, "POST", "/api/v1/chats/"+other+"/messages", alice, imageOnly), 404, "not_found")
for _, body := range []string{`{"text":"","attachment_ids":["` + uuid.NewString() + `"]}`} {
assertError(t, api.request(t, "POST", "/api/v1/chats/"+chat+"/messages", alice, body), 404, "not_found")
}
for _, body := range []string{`{"text":""}`, `{"text":" "}`, `{"attachment_ids":["` + att.ID + `"]}`, `{"text":"ok","attachment_ids":null}`, `{"text":"ok","attachment_ids":"bad"}`, `{"text":"ok","attachment_ids":["` + att.ID + `","` + att.ID + `"]}`} {
assertError(t, api.request(t, "POST", "/api/v1/chats/"+chat+"/messages", alice, body), 400, "invalid_request")
}
if got := api.request(t, "GET", content+"?variant=thumbnail", bob, ""); got.status != 200 {
t.Fatal("thumbnail unavailable")
}
}
func TestConcurrentAttachmentMessage(t *testing.T) {
api := newAPI(t)
user := api.createUser(t, "alice")
chat := api.createChat(t, user, user)
var att struct {
ID string `json:"id"`
}
decodeOK(t, api.upload(t, chat, user, "sample.png", "image/png", fixturePNG(t), false), 202, &att)
key := uuid.NewString()
body := `{"text":"","attachment_ids":["` + att.ID + `"]}`
type result struct {
resp apiResponse
err error
}
ch := make(chan result, 16)
var wg sync.WaitGroup
for range 16 {
wg.Go(func() {
resp, e := api.send("POST", "/api/v1/chats/"+chat+"/messages", user, body, key)
ch <- result{resp, e}
})
}
wg.Wait()
close(ch)
seen := map[string]bool{}
var id string
for item := range ch {
if item.err != nil {
t.Fatal(item.err)
}
var msg struct {
ID string `json:"id"`
IDs []string `json:"attachment_ids"`
}
decodeOK(t, item.resp, 201, &msg)
if id != "" && id != msg.ID {
t.Fatal("duplicate attachment message")
}
id = msg.ID
seen[item.resp.instanceID] = true
if len(msg.IDs) != 1 || msg.IDs[0] != att.ID {
t.Fatal("lost attachment")
}
}
if len(seen) < 2 {
t.Fatal("did not exercise two replicas")
}
var page struct {
Items []json.RawMessage `json:"items"`
}
decodeOK(t, api.request(t, "GET", "/api/v1/chats/"+chat+"/messages", user, ""), 200, &page)
if len(page.Items) != 1 {
t.Fatal("duplicate history")
}
}
func waitAttachmentReady(t *testing.T, api *apiClient, user, id string) {
t.Helper()
deadline := time.Now().Add(60 * time.Second)
for time.Now().Before(deadline) {
var att struct {
Status string `json:"status"`
}
decodeOK(t, api.request(t, "GET", "/api/v1/attachments/"+id, user, ""), 200, &att)
if att.Status == "ready" {
return
}
if att.Status == "failed" {
t.Fatal("attachment failed")
}
time.Sleep(100 * time.Millisecond)
}
t.Fatal("attachment readiness deadline")
}
+161
View File
@@ -0,0 +1,161 @@
package tests
import (
"encoding/json"
"fmt"
"github.com/google/uuid"
"io"
"net/http"
"net/url"
"strings"
"sync"
"testing"
"time"
)
type createdMessage struct {
ID string `json:"id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
}
func postMessage(client *http.Client, endpoint, userID, text string) (createdMessage, error) {
body, err := json.Marshal(struct {
Text string `json:"text"`
}{Text: text})
if err != nil {
return createdMessage{}, err
}
req, err := http.NewRequest(http.MethodPost, endpoint, strings.NewReader(string(body)))
if err != nil {
return createdMessage{}, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+userID)
req.Header.Set("Idempotency-Key", uuid.NewString())
resp, err := client.Do(req)
if err != nil {
return createdMessage{}, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return createdMessage{}, err
}
if resp.StatusCode != http.StatusCreated {
return createdMessage{}, fmt.Errorf("POST status %d: %s", resp.StatusCode, data)
}
if resp.Header.Get("X-Request-Id") == "" {
return createdMessage{}, fmt.Errorf("POST response has no X-Request-Id")
}
var message createdMessage
if err := json.Unmarshal(data, &message); err != nil {
return createdMessage{}, fmt.Errorf("decode POST response: %w", err)
}
return message, nil
}
func TestConcurrentMessages(t *testing.T) {
const clients = 10
const messagesPerClient = 10
const total = clients * messagesPerClient
api := newAPI(t)
users := make([]string, clients)
for i := range users {
users[i] = api.createUser(t, fmt.Sprintf("user%02d", i))
}
chatID := api.createChat(t, users[0], users...)
endpoint := api.baseURL + "/api/v1/chats/" + chatID + "/messages"
type result struct {
message createdMessage
wantSenderID string
wantText string
err error
}
results := make(chan result, total)
start := make(chan struct{})
var ready sync.WaitGroup
var workers sync.WaitGroup
ready.Add(clients)
workers.Add(clients)
for i, userID := range users {
go func(workerID int, userID string) {
defer workers.Done()
client := &http.Client{Timeout: 5 * time.Second}
defer client.CloseIdleConnections()
ready.Done()
<-start
for j := range messagesPerClient {
text := fmt.Sprintf("client-%02d-message-%02d", workerID, j)
message, err := postMessage(client, endpoint, api.tokens[userID], text)
results <- result{message: message, wantSenderID: userID, wantText: text, err: err}
}
}(i, userID)
}
ready.Wait()
close(start)
workers.Wait()
close(results)
created := make(map[string]createdMessage, total)
count := 0
for item := range results {
count++
if item.err != nil {
t.Errorf("send %q: %v", item.wantText, item.err)
continue
}
if item.message.ID == "" || item.message.SenderID != item.wantSenderID || item.message.Text != item.wantText {
t.Errorf("unexpected response for %q: %+v", item.wantText, item.message)
continue
}
if _, duplicate := created[item.message.ID]; duplicate {
t.Errorf("duplicate message ID %q", item.message.ID)
continue
}
created[item.message.ID] = item.message
}
if count != total || len(created) != total {
t.Fatalf("sent %d requests, created %d unique messages; want %d", count, len(created), total)
}
seen := make(map[string]bool, total)
cursor := ""
pages := 0
for {
path := "/api/v1/chats/" + chatID + "/messages?limit=17"
if cursor != "" {
path += "&cursor=" + url.QueryEscape(cursor)
}
resp := api.request(t, http.MethodGet, path, users[0], "")
var page struct {
Items []createdMessage `json:"items"`
NextCursor *string `json:"next_cursor"`
}
decodeOK(t, resp, http.StatusOK, &page)
pages++
if pages > total || len(page.Items) == 0 || len(page.Items) > 17 {
t.Fatalf("unexpected page %d: %s", pages, resp.body)
}
for _, message := range page.Items {
want, exists := created[message.ID]
if !exists || seen[message.ID] || message != want {
t.Fatalf("unexpected or repeated message on page %d: %+v", pages, message)
}
seen[message.ID] = true
}
if page.NextCursor == nil {
break
}
if *page.NextCursor == "" || *page.NextCursor == cursor {
t.Fatalf("invalid cursor on page %d: %s", pages, resp.body)
}
cursor = *page.NextCursor
}
if len(seen) != total {
t.Fatalf("history has %d unique messages across %d pages; want %d", len(seen), pages, total)
}
t.Logf("%d clients sent %d messages; history contains %d unique messages across %d pages", clients, total, len(seen), pages)
}
+104
View File
@@ -0,0 +1,104 @@
package tests
import (
"fmt"
"github.com/google/uuid"
"net/http"
"sync"
"testing"
)
func TestIdempotencyContract(t *testing.T) {
api := newAPI(t)
alice := api.createUser(t, "alice")
bob := api.createUser(t, "bob")
eve := api.createUser(t, "eve")
chat := api.createChat(t, alice, alice, bob)
other := api.createChat(t, alice, alice)
path := "/api/v1/chats/" + chat + "/messages"
for _, key := range []string{"", "bad key", "кириллица", string(make([]byte, 129))} {
// NUL cannot be sent by net/http: use an overlength ASCII key instead.
if len(key) == 129 {
key = fmt.Sprintf("%0129d", 1)
}
assertError(t, api.requestKey(t, "POST", path, alice, `{"text":"hello"}`, key), 400, "invalid_request")
}
key := uuid.NewString()
first := api.requestKey(t, "POST", path, alice, `{"text":"hello"}`, key)
var want map[string]any
decodeOK(t, first, 201, &want)
var got map[string]any
decodeOK(t, api.requestKey(t, "POST", path, alice, `{ "text" : "hello" }`, key), 201, &got)
if jsonString(t, want) != jsonString(t, got) {
t.Fatal("replay changed message")
}
assertError(t, api.requestKey(t, "POST", path, alice, `{"text":"changed"}`, key), 409, "conflict")
assertError(t, api.requestKey(t, "POST", path, eve, `{"text":"hello"}`, key), 404, "not_found")
for _, tc := range []struct{ user, path string }{{bob, path}, {alice, "/api/v1/chats/" + other + "/messages"}} {
var msg map[string]any
decodeOK(t, api.requestKey(t, "POST", tc.path, tc.user, `{"text":"hello"}`, key), 201, &msg)
if msg["id"] == want["id"] {
t.Fatal("scope not isolated")
}
}
resp := api.request(t, http.MethodDelete, "/api/v1/auth/sessions/current", alice, "")
if resp.status != 204 {
t.Fatal(resp.status)
}
assertError(t, api.requestKey(t, "POST", path, alice, `{"text":"hello"}`, key), 401, "unauthorized")
}
func TestConcurrentIdempotencyAcrossReplicas(t *testing.T) {
api := newAPI(t)
user := api.createUser(t, "alice")
chat := api.createChat(t, user, user)
path := "/api/v1/chats/" + chat + "/messages"
key := uuid.NewString()
const count = 32
type result struct {
response apiResponse
err error
}
responses := make(chan result, count)
start := make(chan struct{})
var wg sync.WaitGroup
for range count {
wg.Go(func() {
<-start
response, err := api.send("POST", path, user, `{"text":"one logical message"}`, key)
responses <- result{response: response, err: err}
})
}
close(start)
wg.Wait()
close(responses)
instances := map[string]bool{}
var id string
for result := range responses {
if result.err != nil {
t.Fatal(result.err)
}
resp := result.response
var msg struct {
ID string `json:"id"`
}
decodeOK(t, resp, 201, &msg)
if id != "" && id != msg.ID {
t.Fatal("duplicate side effect")
}
id = msg.ID
instances[resp.instanceID] = true
}
if len(instances) < 2 {
t.Fatalf("need at least 2 real API replicas, observed %d", len(instances))
}
var page struct {
Items []struct {
ID string `json:"id"`
} `json:"items"`
}
decodeOK(t, api.request(t, "GET", path, user, ""), 200, &page)
if len(page.Items) != 1 || page.Items[0].ID != id {
t.Fatalf("history contains %d messages", len(page.Items))
}
t.Logf("%d requests across %d replicas created exactly one message", count, len(instances))
}