// 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 main(List 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 _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.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.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 _action( List<_Client> all, String label, Future? 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> _frameWaiters = []; _Client(this.id); Future 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); totalReceived += text.length; frames++; largestFrameBytes = max(largestFrameBytes, text.length); final Map msg; try { msg = jsonDecode(text) as Map; } 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 nextUpdate() { final completer = Completer(); _frameWaiters.add(completer); return completer.future; } Future _send(Map message) async { final s = _ws; if (s == null) throw StateError('not connected'); s.add(jsonEncode(message)); } Future cmd(String name, Map args) async { await _send({'t': 'cmd', 'name': name, 'args': args}); } Future close() async { await _ws?.close(); } } String? _firstCharacterId(Map state) { final list = state['currentList'] as List?; for (final e in list ?? []) { final item = e as Map?; if (item != null && item['characterClass'] != null) { return item['id'] as String?; } } return null; } String _kb(int bytes) => '${(bytes / 1024).toStringAsFixed(1)} kB'; Future _freePort() async { final s = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); final port = s.port; await s.close(); return port; } Future _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.delayed(const Duration(milliseconds: 250)); } throw TimeoutException('server did not start: $url'); }