228 lines
6.6 KiB
Go
228 lines
6.6 KiB
Go
// Command concurrency is the black-box race check from the grading rubric:
|
|
// N clients send M messages each into one chat at the same time, then the
|
|
// history is paged and must contain exactly N*M unique messages in id order.
|
|
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"flag"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"messenger/internal/chat"
|
|
"messenger/internal/platform/pagination"
|
|
"messenger/internal/user"
|
|
)
|
|
|
|
// Report is the machine readable outcome saved as evidence.
|
|
type Report struct {
|
|
BaseURL string `json:"base_url"`
|
|
StartedAt time.Time `json:"started_at"`
|
|
Clients int `json:"clients"`
|
|
PerClient int `json:"per_client"`
|
|
Expected int `json:"expected_messages"`
|
|
Created int `json:"created_201"`
|
|
Failed int `json:"failed_posts"`
|
|
Listed int `json:"listed_messages"`
|
|
Unique int `json:"unique_ids"`
|
|
Missing int `json:"created_but_not_listed"`
|
|
Ordered bool `json:"history_ordered_by_id"`
|
|
Pages int `json:"pages_read"`
|
|
ElapsedSeconds float64 `json:"elapsed_seconds"`
|
|
Passed bool `json:"passed"`
|
|
}
|
|
|
|
func main() {
|
|
baseURL := flag.String("base-url", "http://localhost:8080", "API base URL")
|
|
clients := flag.Int("clients", 10, "number of concurrent clients")
|
|
perClient := flag.Int("per-client", 10, "messages sent by each client")
|
|
output := flag.String("output", "", "optional path for the JSON report")
|
|
flag.Parse()
|
|
|
|
report, err := run(*baseURL, *clients, *perClient)
|
|
if err != nil {
|
|
fail(err)
|
|
}
|
|
text, _ := json.MarshalIndent(report, "", " ")
|
|
fmt.Println(string(text))
|
|
if *output != "" {
|
|
if err := writeReport(*output, text); err != nil {
|
|
fail(err)
|
|
}
|
|
}
|
|
if !report.Passed {
|
|
fail(fmt.Errorf("concurrency invariants violated"))
|
|
}
|
|
fmt.Printf("PASS: %d clients x %d messages produced exactly %d unique ordered messages\n",
|
|
report.Clients, report.PerClient, report.Unique)
|
|
}
|
|
|
|
func fail(err error) {
|
|
fmt.Fprintln(os.Stderr, "FAIL:", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
func writeReport(path string, text []byte) error {
|
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
|
return err
|
|
}
|
|
return os.WriteFile(path, append(text, '\n'), 0o644)
|
|
}
|
|
|
|
func run(baseURL string, clients, perClient int) (Report, error) {
|
|
if clients < 1 || perClient < 1 {
|
|
return Report{}, fmt.Errorf("clients and per-client must be positive")
|
|
}
|
|
report := Report{
|
|
BaseURL: baseURL,
|
|
StartedAt: time.Now().UTC(),
|
|
Clients: clients,
|
|
PerClient: perClient,
|
|
Expected: clients * perClient,
|
|
}
|
|
api := newClient(baseURL)
|
|
runID := uuid.NewString()[:8]
|
|
|
|
members, tokens, err := registerClients(api, runID, clients)
|
|
if err != nil {
|
|
return report, err
|
|
}
|
|
room, err := createChat(api, runID, members, tokens[0])
|
|
if err != nil {
|
|
return report, err
|
|
}
|
|
|
|
started := time.Now()
|
|
created, failed := sendConcurrently(baseURL, room.ID, tokens, perClient)
|
|
report.ElapsedSeconds = time.Since(started).Seconds()
|
|
report.Created = len(created)
|
|
report.Failed = failed
|
|
|
|
listed, pages, err := readHistory(api, room.ID, tokens[0])
|
|
if err != nil {
|
|
return report, err
|
|
}
|
|
report.Pages = pages
|
|
report.Listed = len(listed)
|
|
report.Unique, report.Missing = compare(created, listed)
|
|
report.Ordered = sort.StringsAreSorted(listed)
|
|
report.Passed = report.Failed == 0 &&
|
|
report.Created == report.Expected &&
|
|
report.Listed == report.Expected &&
|
|
report.Unique == report.Expected &&
|
|
report.Missing == 0 &&
|
|
report.Ordered
|
|
return report, nil
|
|
}
|
|
|
|
// clientPassword is shared by the synthetic clients of one run.
|
|
const clientPassword = "concurrency-check-password"
|
|
|
|
// registerClients registers and logs in n clients, returning their ids and
|
|
// bearer tokens in the same order.
|
|
func registerClients(api *client, runID string, n int) (ids, tokens []string, err error) {
|
|
for i := range n {
|
|
var created user.Response
|
|
username := fmt.Sprintf("load_%s_%d", runID, i)
|
|
body := map[string]string{
|
|
"username": username,
|
|
"display_name": fmt.Sprintf("Load client %d", i),
|
|
"password": clientPassword,
|
|
}
|
|
if err := api.post("/api/v1/users", "", body, &created); err != nil {
|
|
return nil, nil, fmt.Errorf("register client %d: %w", i, err)
|
|
}
|
|
token, err := api.login(username, clientPassword)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("log in client %d: %w", i, err)
|
|
}
|
|
ids = append(ids, created.ID)
|
|
tokens = append(tokens, token)
|
|
}
|
|
return ids, tokens, nil
|
|
}
|
|
|
|
func createChat(api *client, runID string, members []string, creatorToken string) (chat.ChatResponse, error) {
|
|
var created chat.ChatResponse
|
|
body := map[string]any{"title": "Concurrency check " + runID, "member_ids": members}
|
|
if err := api.post("/api/v1/chats", creatorToken, body, &created); err != nil {
|
|
return chat.ChatResponse{}, fmt.Errorf("create chat: %w", err)
|
|
}
|
|
return created, nil
|
|
}
|
|
|
|
// sendConcurrently gives every member its own HTTP client and releases them
|
|
// together, so the server sees genuinely parallel writes to one chat.
|
|
func sendConcurrently(baseURL, chatID string, tokens []string, perClient int) (map[string]struct{}, int) {
|
|
var mu sync.Mutex
|
|
created := make(map[string]struct{}, len(tokens)*perClient)
|
|
failed := 0
|
|
|
|
var wg sync.WaitGroup
|
|
start := make(chan struct{})
|
|
for i, token := range tokens {
|
|
wg.Add(1)
|
|
go func(n int, token string) {
|
|
defer wg.Done()
|
|
own := newClient(baseURL)
|
|
<-start
|
|
for m := range perClient {
|
|
var msg chat.MessageResponse
|
|
body := map[string]string{"text": fmt.Sprintf("client %d message %d", n, m)}
|
|
err := own.post("/api/v1/chats/"+chatID+"/messages", token, body, &msg)
|
|
mu.Lock()
|
|
if err != nil {
|
|
failed++
|
|
} else {
|
|
created[msg.ID] = struct{}{}
|
|
}
|
|
mu.Unlock()
|
|
}
|
|
}(i, token)
|
|
}
|
|
close(start)
|
|
wg.Wait()
|
|
return created, failed
|
|
}
|
|
|
|
func readHistory(api *client, chatID, token string) ([]string, int, error) {
|
|
var ids []string
|
|
pages := 0
|
|
cursor := ""
|
|
for {
|
|
var page pagination.PageResponse[chat.MessageResponse]
|
|
if err := api.get("/api/v1/chats/"+chatID+"/messages", token, cursor, &page); err != nil {
|
|
return nil, pages, fmt.Errorf("read history: %w", err)
|
|
}
|
|
pages++
|
|
for _, m := range page.Items {
|
|
ids = append(ids, m.ID)
|
|
}
|
|
if page.NextCursor == nil {
|
|
return ids, pages, nil
|
|
}
|
|
cursor = *page.NextCursor
|
|
}
|
|
}
|
|
|
|
// compare returns how many distinct ids the history holds and how many
|
|
// acknowledged ids never showed up in it.
|
|
func compare(created map[string]struct{}, listed []string) (unique, missing int) {
|
|
seen := make(map[string]struct{}, len(listed))
|
|
for _, id := range listed {
|
|
seen[id] = struct{}{}
|
|
}
|
|
for id := range created {
|
|
if _, ok := seen[id]; !ok {
|
|
missing++
|
|
}
|
|
}
|
|
return len(seen), missing
|
|
}
|