Implement lab3 scaling, shared idempotency, failure research and defense guide
This commit is contained in:
@@ -0,0 +1,163 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mtusi/messenger/internal/database"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Real PostgreSQL + HTTP + the race detector, in the optional Compose tests
|
||||
// service. Local go test skips this test unless the DB secret path is supplied.
|
||||
func TestDatabaseConcurrentHTTP(t *testing.T) {
|
||||
path := os.Getenv("DATABASE_TEST_URL_FILE")
|
||||
if path == "" {
|
||||
t.Skip("run make test-race for real PostgreSQL HTTP integration")
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
pool, err := database.Open(ctx, strings.TrimSpace(string(raw)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err = database.Migrate(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
api := New(pool, nil, make([]byte, 32), 3600, nil)
|
||||
ts := httptest.NewServer(api)
|
||||
defer ts.Close()
|
||||
call := func(method, path, body, auth string, status int) map[string]any {
|
||||
t.Helper()
|
||||
r, err := http.NewRequest(method, ts.URL+path, strings.NewReader(body))
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return nil
|
||||
}
|
||||
if body != "" {
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
r.Header.Set("Authorization", auth)
|
||||
if method == "POST" && strings.HasSuffix(path, "/messages") {
|
||||
r.Header.Set("Idempotency-Key", uuid())
|
||||
}
|
||||
response, err := ts.Client().Do(r)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return nil
|
||||
}
|
||||
defer response.Body.Close()
|
||||
b, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return nil
|
||||
}
|
||||
if response.StatusCode != status {
|
||||
t.Errorf("%s %s: want %d got %d", method, path, status, response.StatusCode)
|
||||
return nil
|
||||
}
|
||||
var v map[string]any
|
||||
if err = json.Unmarshal(b, &v); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
username := "go_" + strings.ReplaceAll(uuid(), "-", "")[:20]
|
||||
user := call("POST", "/api/v1/users", fmt.Sprintf(`{"username":%q,"display_name":"Race","password":"Synthetic-Go-Test-123"}`, username), "", 201)
|
||||
if user == nil {
|
||||
t.Fatal("create failed")
|
||||
}
|
||||
basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":Synthetic-Go-Test-123"))
|
||||
session := call("POST", "/api/v1/auth/sessions", "", basic, 201)
|
||||
if session == nil {
|
||||
t.Fatal("login failed")
|
||||
}
|
||||
bearer := "Bearer " + session["token"].(string)
|
||||
chat := call("POST", "/api/v1/chats", fmt.Sprintf(`{"title":"Race","member_ids":[%q]}`, user["id"]), bearer, 201)
|
||||
if chat == nil {
|
||||
t.Fatal("chat failed")
|
||||
}
|
||||
messages := "/api/v1/chats/" + chat["id"].(string) + "/messages"
|
||||
var wg sync.WaitGroup
|
||||
for worker := 0; worker < 10; worker++ {
|
||||
wg.Add(1)
|
||||
go func(worker int) {
|
||||
defer wg.Done()
|
||||
for j := 0; j < 10; j++ {
|
||||
call("POST", messages, fmt.Sprintf(`{"text":"worker-%d-message-%d"}`, worker, j), bearer, 201)
|
||||
}
|
||||
}(worker)
|
||||
}
|
||||
wg.Wait()
|
||||
page := call("GET", messages+"?limit=100", "", bearer, 200)
|
||||
if page == nil {
|
||||
t.Fatal("history failed")
|
||||
}
|
||||
items := page["items"].([]any)
|
||||
if len(items) != 100 {
|
||||
t.Fatalf("expected 100 messages, got %d", len(items))
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, v := range items {
|
||||
m := v.(map[string]any)
|
||||
id := m["id"].(string)
|
||||
if seen[id] {
|
||||
t.Fatal("duplicate ID")
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
// Race a single key through the real server, then verify only one side effect.
|
||||
var repeatWG sync.WaitGroup
|
||||
ids := make(chan string, 12)
|
||||
for i := 0; i < 12; i++ {
|
||||
repeatWG.Add(1)
|
||||
go func() {
|
||||
defer repeatWG.Done()
|
||||
req, _ := http.NewRequest("POST", ts.URL+messages, strings.NewReader(`{"text":"one key"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", bearer)
|
||||
req.Header.Set("Idempotency-Key", "same-concurrent-key")
|
||||
res, err := ts.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
defer res.Body.Close()
|
||||
var m Message
|
||||
if res.StatusCode != 201 || json.NewDecoder(res.Body).Decode(&m) != nil {
|
||||
t.Error("repeat failed")
|
||||
return
|
||||
}
|
||||
ids <- m.ID
|
||||
}()
|
||||
}
|
||||
repeatWG.Wait()
|
||||
close(ids)
|
||||
var expected string
|
||||
for id := range ids {
|
||||
if expected == "" {
|
||||
expected = id
|
||||
}
|
||||
if id != expected {
|
||||
t.Error("idempotency duplicate")
|
||||
}
|
||||
}
|
||||
var count int
|
||||
if err := pool.QueryRow(context.Background(), "SELECT count(*) FROM messages WHERE chat_id=$1", chat["id"]).Scan(&count); err != nil || count != 101 {
|
||||
t.Errorf("want 101 persisted messages, got %d: %v", count, err)
|
||||
}
|
||||
t.Log("100 confirmed messages from 10 clients through real HTTP and PostgreSQL; race detector enabled")
|
||||
}
|
||||
Reference in New Issue
Block a user