diff options
Diffstat (limited to 'server')
| -rw-r--r-- | server/bin/main.dart | 34 | ||||
| -rw-r--r-- | server/lib/net/app.dart | 55 | ||||
| -rw-r--r-- | server/tool/perf_measure.dart | 312 |
3 files changed, 382 insertions, 19 deletions
diff --git a/server/bin/main.dart b/server/bin/main.dart index 60910a9..36c64c7 100644 --- a/server/bin/main.dart +++ b/server/bin/main.dart @@ -3,6 +3,7 @@ /// Usage (from the server/ directory): /// dart run bin/main.dart /// dart run bin/main.dart --port 8080 --static-dir ../web/dist +/// dart run bin/main.dart --saves-dir /data/saves # e.g. in Docker library; import 'dart:io'; @@ -27,15 +28,20 @@ Future<void> main(List<String> args) async { int.tryParse(Platform.environment['PORT'] ?? '') ?? 4567; final staticDir = _parseString(args, 'static-dir') ?? '../web/dist'; + // The save directory (game state, settings, saves, seats) defaults to + // `saves/` next to the server; override for Docker / multi-game hosts. + final savesDir = _parseString(args, 'saves-dir') ?? 'saves'; + // The game data the engine loads and the client's menus read. + final dataDir = _parseString(args, 'data-dir') ?? 'assets/data/'; - // Boot the game engine (single save in saves/, game data from - // assets/data/), then attach the network layer: the WebSocket game - // server, with seat ownership persisted next to the game state. - await _bootGameCore(); + // Boot the game engine (single save in [savesDir], game data from + // [dataDir]), then attach the network layer: the WebSocket game server, + // with seat ownership persisted next to the game state. + await _bootGameCore(savesDir: savesDir, dataDir: dataDir); final gameServer = GameServer( gameState: getIt<GameState>(), sessions: SessionManager(), - seatStore: FileSeatStore('saves'), + seatStore: FileSeatStore(savesDir), ); final server = await startServer( @@ -43,7 +49,7 @@ Future<void> main(List<String> args) async { staticDir: staticDir, gameServer: gameServer, // The client's menus and artwork read the same assets the engine loads. - dataDir: 'assets/data/', + dataDir: dataDir, imageDir: 'assets/images/', // In-game ability-text translations for the client's card renderer. i18nDir: 'assets/i18n/', @@ -61,19 +67,25 @@ Future<void> main(List<String> args) async { /// Registers the core singletons (file-backed save), loads the game data, /// initializes the game state, and restores the most recent save. -Future<void> _bootGameCore({String dataDir = 'assets/data/'}) async { +Future<void> _bootGameCore({ + required String savesDir, + required String dataDir, +}) async { setupCore( - saveStore: FileSaveStore('saves'), - settingsStore: FileSettingsStore('saves'), + saveStore: FileSaveStore(savesDir), + settingsStore: FileSettingsStore(savesDir), ); await getIt<GameData>().loadData(dataDir); final gameState = getIt<GameState>(); gameState.init(); - // Restore the persisted settings (saves/settings.json; no-op on first + // Restore the persisted settings (<savesDir>/settings.json; no-op on first // run) before the server answers the first `welcome` with them. getIt<Settings>().loadFromDisk(); gameState.load(); - _log.info('game core booted (command index ${gameState.commandIndex})'); + _log.info( + 'game core booted (saves: $savesDir, ' + 'command index ${gameState.commandIndex})', + ); } int? _parseInt(List<String> args, String name) => diff --git a/server/lib/net/app.dart b/server/lib/net/app.dart index 8936104..a57aab0 100644 --- a/server/lib/net/app.dart +++ b/server/lib/net/app.dart @@ -18,6 +18,20 @@ import 'ws_upgrade.dart'; final _log = Logger('server'); +/// One year, in seconds — the cache lifetime for immutable assets +/// (PLAN.md Phase 7 "Performance"). +const int _kCacheYearSeconds = 60 * 60 * 24 * 365; + +/// `Cache-Control` for assets that are never mutated in place: the game +/// data, images, in-game translations, and the content-hashed build +/// outputs. Browsers keep them for a year and never revalidate. +const String _kImmutableCacheControl = + 'public, max-age=${_kCacheYearSeconds}, immutable'; + +/// `Cache-Control` for the SPA entry point: always revalidate, so a +/// rebuilt app reaches open tabs on the next navigation. +const String _kNoCacheControl = 'no-cache'; + /// Builds the HTTP handler for the game server. /// /// [dataDir] (e.g. `assets/data/`) is served read-only at `/data/` when @@ -131,12 +145,18 @@ Handler _createStaticHandler(String staticDir, {bool plain = false}) { ); } if (plain) { - // Plain static serving (no SPA fallback) with long-lived caching — - // the JSON and images are immutable build inputs. - return createStaticHandler( - directory.path, - maxAge: const Duration(days: 1), - ); + // Plain static serving (no SPA fallback) for the game data, images, and + // in-game translations — immutable build inputs: cached for a year + // without revalidation (the 66 MB image set is the big win here). + final inner = createStaticHandler(directory.path); + return (Request request) async { + final response = await inner(request); + if (response.statusCode == 200) { + return response + .change(headers: {'cache-control': _kImmutableCacheControl}); + } + return response; + }; } final staticHandler = createStaticHandler( directory.path, @@ -147,14 +167,33 @@ Handler _createStaticHandler(String staticDir, {bool plain = false}) { if (response.statusCode == 404 && request.method == 'GET' && !request.url.path.contains('.')) { - // SPA fallback: routes without a file extension get index.html. + // SPA fallback: routes without a file extension get index.html — + // no-cache, like the real file, so deploys reach open tabs. final indexFile = File(p.join(directory.path, 'index.html')); if (await indexFile.exists()) { return Response.ok( await indexFile.readAsString(), - headers: {'content-type': 'text/html; charset=utf-8'}, + headers: { + 'content-type': 'text/html; charset=utf-8', + 'cache-control': _kNoCacheControl, + }, ); } + return response; + } + if (response.statusCode == 200) { + // index.html is revalidated every navigation; everything else in the + // build is content-hashed (or a stable font) and immutable. + // (shelf_router strips the `/` mount prefix, so the handler sees + // `index.html` / `` rather than `/index.html` / `/`.) + final path = request.url.path; + final isIndex = + path.isEmpty || path == '/' || path.endsWith('index.html'); + return response.change( + headers: { + 'cache-control': isIndex ? _kNoCacheControl : _kImmutableCacheControl, + }, + ); } return response; }; 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'); +} |
