aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 79c245cf8bb9ce8e5b5a3fc9e2c7a1cd653035db
parent b364b4e801d0e4e90ee7e295cdb12cd17cb5be3d
Author: anon <anon@example.com>
Date:   Sat,  7 Nov 2026 03:00:57 +0000

Add headless game-protocol load driver and baseline comparison

Diffstat:
Atools/stress/README.md | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/stress/hotspot.json | 5+++++
Atools/stress/main.go | 283+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/stress/protocol.go | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atools/stress/protocol_test.go | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5 files changed, 664 insertions(+), 0 deletions(-)

diff --git a/tools/stress/README.md b/tools/stress/README.md @@ -0,0 +1,58 @@ +# Headless server load test + +Build and run against a **disposable server built with `-tags=e2e`**. The setup +API is intentionally absent from normal builds. Each run creates new players; +start each comparison with a fresh database and the same assets. + +```sh +go build -o /tmp/ao-stress ./tools/stress +/tmp/ao-stress -url http://127.0.0.1:PORT -clients 100 -ramp 30s -duration 2m +``` + +The default scenario puts 70% of clients in Omni-1 Entertainment (705), 20% in +Newland City (800), and 10% in the starter backyard (950). `-scenario` accepts a +JSON array of weighted spawn positions in the format of `hotspot.json`. Weights +are assigned deterministically in client order. Add positions to spread clients +within a zone; use equal weights for a balanced comparison. The supplied points +concentrate players together and deliberately exercise dense scene broadcasts. + +Provisioning completes before measurement. The client then schedules connections +throughout the ramp, authenticates through `/browser-world`, waits for the world +snapshot, sends CharacterReady, and waits for its acknowledgement. It continuously +reads the actual game byte stream. Each ready client alternates sitting/standing +once per second and walks forward/backward while standing. Movement inputs precede +the posture probe, so its acknowledgement measures work through the simulation +owner. This is a movement/visibility/recovery workload, not combat, inventory, +team, chat or zone-transfer coverage. It uses the full-width protocol accepted by +the server, without browsers or rendering. + +JSON lines report cumulative admission and action latency, steady-period action +latency, scheduled-action latency including client scheduling delay, received +traffic, ready/disconnected clients, generator heap/goroutines, missed scheduled +actions and unanswered actions. Millisecond histograms have bounded memory; +the 60000 ms bucket includes all larger values. Outstanding actions at the end +are reported separately. Failed connections or incomplete admission produce a +nonzero exit status. Slow responses never silently reduce the expected action +rate: skipped one-second deadlines are counted. A socket ping alone would not +measure simulation work. + +Raise load in steps: 100, 500, 1000, 2000, 5000, 10000, then 20000. For example: + +```sh +/tmp/ao-stress -url http://SERVER:PORT -clients 20000 -ramp 15m -duration 5m > run.jsonl +``` + +20000 is a generator limit, not a claim about server capacity. Check file descriptor +limits and run the generator on another machine for capacity measurements. Capture +both processes' CPU/RSS and the server's slow-lock/tick logs alongside the JSON. +The generator's reported Go heap is not process RSS. Do not run builds or other +benchmarks alongside a measured run. SIGINT cancels connections and joins readers; +it does not stop the external server or delete its database. + +Compare `96de3545` (before the lock initiative), `9cd2d916` (spatial/navigation work +before ownership), the current revision, and the eventual production zone runtime. +Build each revision separately with `-tags=e2e`; use this same client against each. +Keep assets, scenario, hardware, durations and persistence settings fixed. Repeat +runs, compare admission separately from steady load, and retain failures and missed +actions. Current production still uses shared simulation locks, so a speedup at +this point cannot be attributed to a completed zone-owner migration. diff --git a/tools/stress/hotspot.json b/tools/stress/hotspot.json @@ -0,0 +1,5 @@ +[ + {"Weight": 7, "Playfield": 705, "Position": [960, 16.5, 510], "Rotation": [0, 0, 0, 1]}, + {"Weight": 2, "Playfield": 800, "Position": [679.625, 74.75, 537.875], "Rotation": [0, 0, 0, 1]}, + {"Weight": 1, "Playfield": 950, "Position": [52, 14, 56], "Rotation": [0, 0, 0, 1]} +] diff --git a/tools/stress/main.go b/tools/stress/main.go @@ -0,0 +1,283 @@ +// Command stress drives disposable e2e servers through the real game protocol. +package main + +import ( + "bytes" + "context" + "encoding/json" + "flag" + "fmt" + "io" + "net/http" + "os" + "os/signal" + "runtime" + "strings" + "sync" + "syscall" + "time" +) + +type placement struct { + Weight int + Playfield uint32 + Position [3]float32 + Rotation [4]float32 +} + +type visitor struct { + ID uint32 + Cookie string + Place placement +} + +type event struct { + kind string + at time.Time + elapsed time.Duration + missed int + packets, bytes int + err error +} + +func main() { + address := flag.String("url", "", "URL of a disposable server built with -tags=e2e") + clients := flag.Int("clients", 100, "number of clients, up to 20000") + ramp := flag.Duration("ramp", time.Minute, "time over which connections are scheduled") + duration := flag.Duration("duration", time.Minute, "steady load duration after the ramp") + scenario := flag.String("scenario", "tools/stress/hotspot.json", "JSON file of weighted spawn locations") + flag.Parse() + if *address == "" || *clients < 1 || *clients > 20000 || *ramp <= 0 || *duration <= 0 || flag.NArg() != 0 { + fmt.Fprintln(os.Stderr, "provide -url, 1..20000 clients, and positive ramp/duration") + os.Exit(2) + } + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer cancel() + if err := run(ctx, strings.TrimRight(*address, "/"), *clients, *ramp, *duration, *scenario); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func run(ctx context.Context, address string, count int, ramp, duration time.Duration, scenario string) error { + data, err := os.ReadFile(scenario) + if err != nil { + return err + } + var places []placement + if err := json.Unmarshal(data, &places); err != nil { + return err + } + weight := 0 + for _, place := range places { + if place.Weight <= 0 || place.Playfield == 0 || place.Rotation == [4]float32{} { + return fmt.Errorf("each placement needs positive Weight, Playfield and a nonzero Rotation") + } + weight += place.Weight + } + if weight == 0 { + return fmt.Errorf("scenario has no placements") + } + // Provisioning is separate from the measured ramp. Fixture requests never + // mutate connected players. Every run should use a fresh disposable database. + started := time.Now() + visitors := make([]visitor, count) + httpClient := &http.Client{Timeout: 30 * time.Second} + defer httpClient.CloseIdleConnections() + for index := range visitors { + place, slot := places[0], index%weight + for _, candidate := range places { + place = candidate + if slot < candidate.Weight { + break + } + slot -= candidate.Weight + } + visitors[index], err = provision(ctx, httpClient, address, place) + if err != nil { + return fmt.Errorf("provision client %d: %w", index, err) + } + if (index+1)%100 == 0 { + fmt.Fprintf(os.Stderr, "provisioned %d/%d\n", index+1, count) + } + } + json.NewEncoder(os.Stdout).Encode(map[string]any{"phase": "provisioned", "clients": count, "seconds": time.Since(started).Seconds(), "placements": places}) + + started = time.Now() + load, cancel := context.WithDeadline(ctx, started.Add(ramp+duration)) + defer cancel() + events := make(chan event, 1024) + var workers sync.WaitGroup + for index, person := range visitors { + workers.Add(1) + go func(index int, person visitor) { + defer workers.Done() + scheduled := started.Add(time.Duration(index) * ramp / time.Duration(count)) + if !waitUntil(load, scheduled) { + events <- event{kind: "not_started"} + return + } + events <- event{kind: "attempted"} + if err := exercise(load, address, person, scheduled, events); err != nil && load.Err() == nil { + events <- event{kind: "failed", err: fmt.Errorf("client %d: %w", person.ID, err)} + } + }(index, person) + } + go func() { workers.Wait(); close(events) }() + err = collect(events, started, ramp) + if ctx.Err() != nil { + return ctx.Err() + } + return err +} + +func provision(ctx context.Context, client *http.Client, address string, place placement) (visitor, error) { + person := visitor{Place: place} + request, err := http.NewRequestWithContext(ctx, "POST", address+"/browser-launch", nil) + if err != nil { + return person, err + } + response, err := client.Do(request) + if err != nil { + return person, err + } + defer response.Body.Close() + body, err := io.ReadAll(io.LimitReader(response.Body, 4096)) + if err != nil { + return person, err + } + if response.StatusCode != http.StatusOK { + return person, fmt.Errorf("launch: %s: %s", response.Status, body) + } + for _, cookie := range response.Cookies() { + if cookie.Name == "ao_client" { + person.Cookie = cookie.Name + "=" + cookie.Value + } + } + if person.Cookie == "" { + return person, fmt.Errorf("launch did not create a visitor cookie") + } + data, err := json.Marshal(struct { + Playfield uint32 + Position [3]float32 + Rotation [4]float32 + }{place.Playfield, place.Position, place.Rotation}) + if err != nil { + return person, err + } + request, err = http.NewRequestWithContext(ctx, "POST", address+"/_test/player/position", bytes.NewReader(data)) + if err != nil { + return person, err + } + request.Header.Set("Cookie", person.Cookie) + request.Header.Set("Content-Type", "application/json") + response, err = client.Do(request) + if err != nil { + return person, err + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + body, _ := io.ReadAll(io.LimitReader(response.Body, 4096)) + return person, fmt.Errorf("fixture: %s: %s", response.Status, body) + } + if err := json.NewDecoder(response.Body).Decode(&person); err != nil { + return person, err + } + if person.ID == 0 { + return person, fmt.Errorf("fixture returned no player ID") + } + return person, nil +} + +func waitUntil(ctx context.Context, at time.Time) bool { + timer := time.NewTimer(time.Until(at)) + defer timer.Stop() + select { + case <-timer.C: + return true + case <-ctx.Done(): + return false + } +} + +// Histograms use millisecond buckets, capped at 60 seconds. Memory stays bounded +// at 20k connections; the last bucket explicitly includes larger observations. +type histogram [60001]uint64 + +func (h *histogram) add(elapsed time.Duration) { + h[min(max(elapsed.Milliseconds(), 0), 60000)]++ +} + +func (h *histogram) percentiles() map[string]int { + var total uint64 + for _, count := range h { + total += count + } + result := map[string]int{} + for _, percentile := range []int{50, 95, 99} { + var seen uint64 + for ms, count := range h { + seen += count + if total != 0 && seen >= (total*uint64(percentile)+99)/100 { + result[fmt.Sprintf("p%d_ms", percentile)] = ms + break + } + } + } + return result +} + +func collect(events <-chan event, started time.Time, ramp time.Duration) error { + counts := make(map[string]int) + var admission, action, scheduled, steady histogram + var outputError error + ticker := time.NewTicker(5 * time.Second) + defer ticker.Stop() + write := func(phase string) error { + var memory runtime.MemStats + runtime.ReadMemStats(&memory) + return json.NewEncoder(os.Stdout).Encode(map[string]any{"phase": phase, "seconds": time.Since(started).Seconds(), "counts": counts, + "active": counts["ready"] - counts["disconnected"], "admission": admission.percentiles(), "action": action.percentiles(), "scheduled_action": scheduled.percentiles(), "steady_action": steady.percentiles(), "generator_heap_bytes": memory.HeapAlloc, "generator_goroutines": runtime.NumGoroutine()}) + } + for { + select { + case result, ok := <-events: + if !ok { + if err := write("complete"); err != nil { + return err + } + if outputError != nil { + return outputError + } + if counts["failed"] != 0 || counts["not_started"] != 0 || counts["attempted"] != counts["ready"] { + return fmt.Errorf("load incomplete: %d failed, %d not started, %d unready", counts["failed"], counts["not_started"], counts["attempted"]-counts["ready"]) + } + return nil + } + counts[result.kind]++ + counts["missed_actions"] += result.missed + counts["received_packets"] += result.packets + counts["received_bytes"] += result.bytes + switch result.kind { + case "ready": + admission.add(result.elapsed) + case "action": + action.add(result.elapsed) + if !result.at.Before(started.Add(ramp)) { + steady.add(result.elapsed) + counts["steady_actions"]++ + } + case "scheduled_action": + scheduled.add(result.elapsed) + case "failed": + if counts["failed"] <= 10 { + fmt.Fprintln(os.Stderr, result.err) + } + } + case <-ticker.C: + if outputError == nil { + outputError = write("running") + } + } + } +} diff --git a/tools/stress/protocol.go b/tools/stress/protocol.go @@ -0,0 +1,207 @@ +package main + +import ( + "context" + "encoding/binary" + "fmt" + "io" + "math" + "net/http" + "strings" + "time" + + "github.com/coder/websocket" +) + +func packet(kind uint16, opcode uint32, body []byte) []byte { + length := 20 + len(body) + result := make([]byte, (length+3)&^3) + binary.BigEndian.PutUint16(result, 1) + binary.BigEndian.PutUint16(result[2:], kind) + binary.BigEndian.PutUint16(result[4:], 1) + binary.BigEndian.PutUint16(result[6:], uint16(length)) + binary.BigEndian.PutUint32(result[8:], 1) + binary.BigEndian.PutUint32(result[16:], opcode) + copy(result[20:], body) + return result +} + +func command(id, opcode uint32, body []byte) []byte { + prefix := binary.BigEndian.AppendUint32(nil, opcode) + prefix = binary.BigEndian.AppendUint32(prefix, 50000) + prefix = binary.BigEndian.AppendUint32(prefix, id) + prefix = binary.BigEndian.AppendUint32(prefix, 0) + return packet(10, 0, append(prefix, body...)) +} + +func movement(person visitor, action uint32) []byte { + body := binary.BigEndian.AppendUint32(nil, action) + for _, value := range person.Place.Position { + body = binary.BigEndian.AppendUint32(body, math.Float32bits(value)) + } + for _, value := range person.Place.Rotation { + body = binary.BigEndian.AppendUint32(body, math.Float32bits(value)) + } + body = append(body, make([]byte, 8)...) + return command(person.ID, 0x54111123, body) +} + +func readPacket(reader io.Reader) ([]byte, error) { + var header [16]byte + if _, err := io.ReadFull(reader, header[:]); err != nil { + return nil, err + } + length := int(binary.BigEndian.Uint16(header[6:8])) + if length < 20 { + return nil, fmt.Errorf("invalid packet length %d", length) + } + result := make([]byte, (length+3)&^3) + copy(result, header[:]) + if _, err := io.ReadFull(reader, result[16:]); err != nil { + return nil, err + } + return result[:length], nil +} + +type acknowledgement struct{ opcode, action uint32 } + +func exercise(ctx context.Context, address string, person visitor, scheduled time.Time, events chan<- event) error { + dial, cancel := context.WithTimeout(ctx, 30*time.Second) + socket, response, err := websocket.Dial(dial, "ws"+strings.TrimPrefix(address, "http")+"/browser-world", &websocket.DialOptions{HTTPHeader: http.Header{"Cookie": {person.Cookie}}}) + cancel() + if err != nil { + if response != nil { + response.Body.Close() + } + return err + } + defer socket.CloseNow() + connection := websocket.NetConn(ctx, socket, websocket.MessageBinary) + defer connection.Close() + acks := make(chan acknowledgement, 4) + readDone := make(chan struct{}) + var readError error + readerContext, stopReader := context.WithCancel(ctx) + defer stopReader() + go func() { + defer close(readDone) + traffic := event{kind: "traffic"} + reported := time.Now() + defer func() { events <- traffic }() + for { + body, err := readPacket(connection) + if err != nil { + readError = err + return + } + traffic.packets++ + traffic.bytes += len(body) + if time.Since(reported) >= time.Second { + events <- traffic + traffic = event{kind: "traffic"} + reported = time.Now() + } + if binary.BigEndian.Uint16(body[2:4]) != 10 || len(body) < 36 || binary.BigEndian.Uint32(body[28:32]) != person.ID { + continue + } + ack := acknowledgement{opcode: binary.BigEndian.Uint32(body[20:24])} + if ack.opcode == 0x5e477770 && len(body) >= 40 { + ack.action = binary.BigEndian.Uint32(body[36:40]) + } + if ack.opcode != 0x5f52412e && ack.opcode != 0x570c2039 && (ack.opcode != 0x5e477770 || ack.action != 86 && ack.action != 87) { + continue + } + select { + case acks <- ack: + case <-readerContext.Done(): + readError = readerContext.Err() + return + } + } + }() + // Join the reader before the client worker exits, including failed handshakes. + defer func() { stopReader(); socket.CloseNow(); <-readDone }() + write := func(body []byte) error { + if err := connection.SetWriteDeadline(time.Now().Add(30 * time.Second)); err != nil { + return err + } + _, err := connection.Write(body) + return err + } + await := func(want acknowledgement) error { + timer := time.NewTimer(30 * time.Second) + defer timer.Stop() + for { + select { + case got := <-acks: + if got == want { + return nil + } + case <-readDone: + return readError + case <-timer.C: + return fmt.Errorf("game acknowledgement timed out: %#x", want.opcode) + case <-ctx.Done(): + return ctx.Err() + } + } + } + body := binary.BigEndian.AppendUint32(nil, person.ID) + if err := write(packet(1, 0x1b, append(body, make([]byte, 8)...))); err != nil { + return err + } + if err := await(acknowledgement{opcode: 0x5f52412e}); err != nil { + return err + } + if err := write(command(person.ID, 0x570c2039, nil)); err != nil { + return err + } + if err := await(acknowledgement{opcode: 0x570c2039}); err != nil { + return err + } + events <- event{kind: "ready", elapsed: time.Since(scheduled)} + defer func() { events <- event{kind: "disconnected"} }() + + // One scheduled action per second per client. Skipped deadlines are counted; + // a slow reply must not silently turn the test into a lighter workload. + next := time.Now().Add(time.Second) + pending := false + defer func() { + if pending { + events <- event{kind: "unanswered_action"} + } + }() + for step := 0; waitUntil(ctx, next); step++ { + sent := time.Now() + pending = true + for _, action := range []uint32{2, 4} { + if err := write(movement(person, action)); err != nil { + return err + } + } + action := uint32(86 + step%2) + body := binary.BigEndian.AppendUint32(nil, action) + body = append(body, make([]byte, 16)...) + if err := write(command(person.ID, 0x5e477770, body)); err != nil { + return err + } + if err := await(acknowledgement{opcode: 0x5e477770, action: action}); err != nil { + return err + } + pending = false + events <- event{kind: "action", elapsed: time.Since(sent), at: time.Now()} + events <- event{kind: "scheduled_action", elapsed: time.Since(next)} + if action == 87 { + if err := write(movement(person, uint32(1+2*(step/2%2)))); err != nil { + return err + } + } + next = next.Add(time.Second) + if late := time.Since(next); late >= 0 { + missed := int(late/time.Second) + 1 + events <- event{kind: "late", missed: missed} + next = next.Add(time.Duration(missed) * time.Second) + } + } + return nil +} diff --git a/tools/stress/protocol_test.go b/tools/stress/protocol_test.go @@ -0,0 +1,111 @@ +package main + +import ( + "context" + "encoding/binary" + "io" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/coder/websocket" +) + +func TestExerciseWaitsForItsOwnGameAcknowledgementAndStopsReader(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + serverDone := make(chan struct{}) + actions := make(chan uint32, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer close(serverDone) + if r.Header.Get("Cookie") != "ao_client=test" { + t.Error("missing session credential") + return + } + socket, err := websocket.Accept(w, r, nil) + if err != nil { + t.Error(err) + return + } + defer socket.CloseNow() + conn := websocket.NetConn(ctx, socket, websocket.MessageBinary) + for { + body, err := readPacket(conn) + if err != nil { + return + } + switch binary.BigEndian.Uint16(body[2:4]) { + case 1: + if binary.BigEndian.Uint32(body[20:24]) != 42 { + t.Error("wrong authentication identity") + return + } + conn.Write(command(42, 0x5f52412e, make([]byte, 12))) + case 10: + key := binary.BigEndian.Uint32(body[20:24]) + if key == 0x570c2039 { + conn.Write(body) + } + if key == 0x5e477770 { + action := binary.BigEndian.Uint32(body[36:40]) + actions <- action + // An unrelated actor's acknowledgement cannot complete this action. + conn.Write(command(99, key, body[36:])) + conn.Write(body) + } + } + } + })) + defer server.Close() + events := make(chan event, 100) + done := make(chan error, 1) + go func() { + done <- exercise(ctx, server.URL, visitor{ID: 42, Cookie: "ao_client=test", Place: placement{Rotation: [4]float32{0, 0, 0, 1}}}, time.Now(), events) + }() + ready, acknowledged := false, false + for !acknowledged { + select { + case result := <-events: + if result.kind == "ready" { + ready = true + } + if result.kind == "action" { + acknowledged = true + } + case err := <-done: + t.Fatal("client ended before its action", err) + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + } + cancel() + <-done + <-serverDone + if !ready || <-actions != 86 { + t.Fatal("client skipped readiness or sent an invalid action") + } +} + +func TestReadPacketHandlesFragmentedAlignmentAndTruncation(t *testing.T) { + reader, writer := io.Pipe() + go func() { + defer writer.Close() + for _, body := range [][]byte{packet(1, 0x1b, []byte{1}), packet(1, 0x1b, []byte{2, 3})} { + for _, value := range body { + writer.Write([]byte{value}) + } + } + writer.Write([]byte{1, 2, 3}) + }() + defer reader.Close() + for _, length := range []int{21, 22} { + body, err := readPacket(reader) + if err != nil || len(body) != length { + t.Fatal("lost aligned stream boundary", len(body), err) + } + } + if _, err := readPacket(reader); err != io.ErrUnexpectedEOF { + t.Fatal("truncated header was accepted", err) + } +}