diff options
| author | Joel Klinghed <the_jk@spawned.biz> | 2026-11-23 00:51:32 +0100 |
|---|---|---|
| committer | Joel Klinghed <the_jk@spawned.biz> | 2026-11-23 00:51:32 +0100 |
| commit | 93970f361b831f17d48ff2a345fc78488ac71fba (patch) | |
| tree | f3844cc343c95dcc19a1444bdb6666e807bc59ef /server/tool | |
| parent | b884441ba0d10bdd3559748507a0991888f66194 (diff) | |
Phase 7: hardening and shipping (M7)
E2E (Playwright, e2e/):
- table fixture: one real compiled server per test (temp saves dir, free
port, workers: 1); a Tab helper drives the real UI (menus, rows,
initiative, draw, seats) over one WS per fresh browser context
- full round: onboarding, secret initiative masked to ?? per connection,
draw revealing on every screen, turns, next round, round-2 secrecy
- seats: claim/re-claim on owner-leave, reload keeps the session and
re-claims, two sessions can't own one character
- resilience: a dropped tab resyncs on reconnect (no drift); a SIGKILL'd
server restarts with state + seats surviving (incl. the owner's secret
initiative and the enabled draw); a throttled tab converges on the same
state as the fast tabs; a double-tapped draw runs once, error sent to
the sender only
- figure edit: set a character level + rename from the status menu
Cross-check vs the reference (feature parity):
- status menu: level pills (setCharacterLevel) + a name field
(changeName), mirroring SetCharacterLevelMenu
- ability-card removal: draw-pile-only "send to bottom"
(reorderAbilityList -> index 0) + "shuffle undrawn cards"
(shuffleDrawnAbilityCard), mirroring RemoveCardMenu
- Add Character: already-added classes disabled (Objective/Escort may be
added repeatedly), matching _characterAlreadyAdded
- every remaining registry command verified reachable from the UI
Session persistence (found by the restart test):
- the client never learned its session id before the first welcome, so a
reconnect minted a new id and orphaned the restored seat; fixed with
establishSessionCookie() (a GET /session before the WS upgrade, plus a
vite /session proxy) so the x-haven-session cookie survives restarts
- the initiative input now prefills from re-synced state (CharacterRow
effect, guarded against clobbering a live edit) so a reload/reconnect
doesn't blank an entry
Performance + deployment:
- immutable asset caching (Cache-Control: 1yr, immutable) for the game
data / images / in-game translations; no-cache for the SPA index.html
so rebuilt apps reach open tabs
- server tool/perf_measure.dart: the performance probe (state payload
size at full-table scale, WS fan-out bytes per action, traffic per
connection)
- Dockerfile (server + built web); docs/DEPLOYMENT.md (Docker,
persistence, reverse proxy, measured performance, smoke-test list)
- README quickstart + production/Docker/testing sections
Server:
- --saves-dir and --data-dir CLI options (Docker / multi-game hosts),
threaded through the stores and data loading
Misc:
- app.css: height 100% on .row so the turn-done tap zone resolves to a
clickable height; fake-socket.ts readyState constants corrected to the
real WebSocket values (0 CONNECTING, 1 OPEN)
- scripts/ci.sh: the Playwright E2E gate (runs when PLAYWRIGHT is set)
- PLAN.md: Phase 7 boxes checked, M7 progress-log entry
Verification: svelte-check 0 errors; web 196/196 tests; vite build OK;
dart analyze 0 errors / 0 warnings; dart test 604/604; Playwright 9/9;
scripts/ci.sh green end-to-end.
Diffstat (limited to 'server/tool')
| -rw-r--r-- | server/tool/perf_measure.dart | 312 |
1 files changed, 312 insertions, 0 deletions
diff --git a/server/tool/perf_measure.dart b/server/tool/perf_measure.dart new file mode 100644 index 0000000..98c5adb --- /dev/null +++ b/server/tool/perf_measure.dart @@ -0,0 +1,312 @@ +// Performance probe (PLAN.md Phase 7 "Performance"). +// +// Boots the real server on a free port with a temp saves dir, connects N +// WebSocket clients (a full table, each a distinct session), plays a +// realistic round, and reports: +// +// * the state payload size at full-table scale (the largest +// `update`/`welcome` frame, and the raw `state` JSON inside it) +// * WS fan-out: bytes delivered to ALL connections per executed action +// * total traffic per connection over the whole round +// +// Run from `server/`: +// +// ```sh +// dart run tool/perf_measure.dart # 6 clients +// dart run tool/perf_measure.dart --clients 8 +// ``` +// +// This is a measurement tool, not part of the product or the test suite. + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:math'; + +Future<void> main(List<String> args) async { + var clients = 6; + for (var i = 0; i < args.length; i++) { + if (args[i] == '--clients' && i + 1 < args.length) { + clients = int.parse(args[i + 1]); + } + } + + final port = await _freePort(); + final savesDir = Directory.systemTemp.createTempSync('xhaven-perf-').path; + final server = await Process.start( + 'dart', + ['run', 'bin/main.dart', '--port=$port', '--saves-dir=$savesDir'], + ); + server.stdout + .transform(utf8.decoder) + .transform(const LineSplitter()) + .listen(stdout.write); + server.stderr + .transform(utf8.decoder) + .transform(const LineSplitter()) + .listen((l) => stderr.writeln('[server] $l')); + + try { + await _waitForHttp('http://127.0.0.1:$port/healthz', 90_000); + await _run(port, clients); + } finally { + server.kill(ProcessSignal.sigkill); + unawaited(server.exitCode + .timeout(const Duration(seconds: 3), onTimeout: () => -1)); + Directory(savesDir).deleteSync(recursive: true); + } + // The measurement is printed; exit regardless of lingering sockets. + exit(0); +} + +Future<void> _run(int port, int clients) async { + // Jaws of the Lion has exactly these four classes, and the reference app + // (and ours) forbids duplicate regular classes, so a JoL table has at most + // four player characters. Extra connections are spectators — which is + // exactly the fan-out we want to measure. + final names = ['Hatchet', 'Demolitionist', 'Red Guard', 'Voidwarden']; + final players = min(clients, names.length); + + final all = <_Client>[]; + for (var i = 0; i < clients; i++) { + final c = _Client(i); + await c.connect('ws://127.0.0.1:$port/ws'); + all.add(c); + } + await Future<void>.delayed(const Duration(milliseconds: 200)); + + // --- setup ---------------------------------------------------------------- + // Every client adds its own character (the onboarding path; each session + // becomes a player). + await _action( + all, + 'setup: $players players add characters', + (i) => i < players + ? all[i].cmd('addCharacter', { + 'id': names[i], + 'edition': 'Jaws of the Lion', + 'level': 1 + }) + : null); + + await _action(all, 'set scenario', + (i) => i == 0 + ? all[0].cmd('setScenario', { + 'scenario': '#1 Roadside Ambush', + 'section': false + }) + : null); + + final monsters = [ + 'Zealot', + 'Vermling Raider', + 'Black Sludge', + 'Rat Monstrosity', + 'Blood Imp', + 'Blood Monstrosity', + 'Chaos Demon', + 'Blood Tumor', + 'Blood Horror', + 'First of the Order' + ]; + for (var m = 0; m < monsters.length; m++) { + await _action( + all, + 'add monster ${m + 1}/${monsters.length}', + (i) => i == 0 + ? all[0].cmd('addMonster', {'name': monsters[m], 'isAlly': false}) + : null); + } + + // --- three full rounds ------------------------------------------------------- + for (var round = 1; round <= 3; round++) { + for (var i = 0; i < players; i++) { + await _action( + all, + 'round $round: player $i sets initiative', + (j) => j == i + ? all[j] + .cmd('setInit', {'characterId': all[j].myCharacterId!, 'init': i + 1}) + : null); + } + await _action(all, 'round $round: draw', + (i) => i == 0 ? all[0].cmd('draw', {}) : null); + for (var i = 0; i < players; i++) { + await _action( + all, + 'round $round: player $i ends turn', + (j) => + j == i ? all[j].cmd('turnDone', {'id': all[j].myCharacterId!}) : null); + } + if (round < 3) { + await _action(all, 'round $round: next round', + (i) => i == 0 ? all[0].cmd('nextRound', {}) : null); + } + } + + await Future<void>.delayed(const Duration(milliseconds: 300)); + + // --- summary ----------------------------------------------------------------- + var maxFrame = 0; + var maxState = 0; + for (final c in all) { + maxFrame = max(maxFrame, c.largestFrameBytes); + maxState = max(maxState, c.lastStateBytes); + } + stdout + ..writeln('') + ..writeln('--- summary ($clients connected clients) ---') + ..writeln(''); + for (final c in all) { + stdout.writeln( + 'client ${c.id}: ${_kb(c.totalReceived)} total ' + 'over ${c.frames} frames ' + '(largest frame ${(c.largestFrameBytes / 1024).toStringAsFixed(1)} kB)'); + } + stdout + ..writeln('') + ..writeln('state JSON at full-table scale: ${_kb(maxState)}') + ..writeln('largest update frame (envelope + state): ${_kb(maxFrame)}') + ..writeln('') + ..writeln('fan-out per executed action: ' + '${_kb(maxFrame)} x $clients = ${_kb(maxFrame * clients)}') + ..writeln('') + ..writeln( + 'note: the full-snapshot protocol trades bandwidth for simplicity — ' + 'every action re-sends the whole state to every connection, so the ' + 'per-action cost is O(state size x connections).'); + // Best-effort teardown; a slow close must not wedge the probe. + for (final c in all) { + unawaited(c.close().timeout(const Duration(seconds: 2), onTimeout: () {})); + } +} + +/// Runs [fn(i)] (one client's command, or null) and resolves when every +/// client has observed the resulting update. Waiters are registered BEFORE +/// the command is sent, so no update can be missed. +Future<void> _action( + List<_Client> all, + String label, + Future<void>? Function(int i) fn, +) async { + final waits = all.map((c) => c.nextUpdate()).toList(); + for (var i = 0; i < all.length; i++) { + await fn(i); // null for the non-senders + } + final sw = Stopwatch()..start(); + await Future.wait(waits).timeout( + const Duration(seconds: 20), + onTimeout: () => + throw TimeoutException('$label: the update never arrived — the ' + 'command was probably rejected (see error output above)')); + stdout.writeln( + '${label.padRight(42)} ' + '${(sw.elapsedMilliseconds / 1000).toStringAsFixed(2)} s wall clock'); +} + +/// One WS client that counts every frame it receives. +class _Client { + final int id; + WebSocket? _ws; + var totalReceived = 0; + var frames = 0; + var largestFrameBytes = 0; + var lastStateBytes = 0; + String? myCharacterId; + final List<Completer<void>> _frameWaiters = []; + + _Client(this.id); + + Future<void> connect(String url) async { + final socket = await WebSocket.connect(url); + _ws = socket; + socket.listen(_onData, onError: (Object e) => stderr.writeln('[c$id] $e')); + await _send({'t': 'hello', 'v': 1}); + await nextUpdate().timeout(const Duration(seconds: 20)); // the welcome + } + + void _onData(Object? data) { + final text = data is String ? data : utf8.decode(data as List<int>); + totalReceived += text.length; + frames++; + largestFrameBytes = max(largestFrameBytes, text.length); + final Map<String, dynamic> msg; + try { + msg = jsonDecode(text) as Map<String, dynamic>; + } catch (_) { + return; // ignore non-JSON frames + } + if (msg['t'] == 'error') { + stderr.writeln('[c$id] error: ${msg['message']}'); + } + if (msg['t'] == 'welcome' || msg['t'] == 'update') { + // The full state travels as a JSON object under `state`. + final state = msg['state']; + if (state is Map) { + lastStateBytes = jsonEncode(state).length; + myCharacterId ??= _firstCharacterId(state); + } + if (_frameWaiters.isNotEmpty) { + _frameWaiters.removeAt(0).complete(); + } + } + } + + /// Resolves on the next state-carrying frame (welcome/update). + Future<void> nextUpdate() { + final completer = Completer<void>(); + _frameWaiters.add(completer); + return completer.future; + } + + Future<void> _send(Map<String, Object?> message) async { + final s = _ws; + if (s == null) throw StateError('not connected'); + s.add(jsonEncode(message)); + } + + Future<void> cmd(String name, Map<String, Object?> args) async { + await _send({'t': 'cmd', 'name': name, 'args': args}); + } + + Future<void> close() async { + await _ws?.close(); + } +} + +String? _firstCharacterId(Map state) { + final list = state['currentList'] as List?; + for (final e in list ?? <dynamic>[]) { + final item = e as Map<String, dynamic>?; + if (item != null && item['characterClass'] != null) { + return item['id'] as String?; + } + } + return null; +} + +String _kb(int bytes) => '${(bytes / 1024).toStringAsFixed(1)} kB'; + +Future<int> _freePort() async { + final s = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + final port = s.port; + await s.close(); + return port; +} + +Future<void> _waitForHttp(String url, int timeoutMs) async { + final deadline = DateTime.now().add(Duration(milliseconds: timeoutMs)); + while (DateTime.now().isBefore(deadline)) { + try { + final client = HttpClient(); + final req = await client.getUrl(Uri.parse(url)) + .timeout(const Duration(seconds: 2)); + final resp = await req.close(); + final code = resp.statusCode; + client.close(); + if (code == 200) return; + } catch (_) {} + await Future<void>.delayed(const Duration(milliseconds: 250)); + } + throw TimeoutException('server did not start: $url'); +} |
