From 3ebbdf6ffa16f751c82e3bd2e74294f4fe843155 Mon Sep 17 00:00:00 2001 From: Joel Klinghed Date: Fri, 13 Nov 2026 00:04:16 +0100 Subject: Phase 2: networking, sessions, secrets over WebSocket (M2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Server owns all state; browsers send input only. New server/lib/net/ layer on top of the Phase 1 engine: - protocol.dart: JSON wire protocol (v1) — hello/welcome handshake, claim, cmd, undo/redo, ping/pong, update, seats, error - sessions.dart: 32-hex session ids carried in the x-haven-session cookie; role derived from seat ownership (player vs spectator); resolve() adopts a well-formed cookie id so a seat survives restarts - seat_store.dart: seat table persisted to saves/seats.json beside the state snapshot; restored on startup - visibility.dart: per-connection state serialization; the initiative rule masks every non-owned character's initiative to null until the round is drawn — the server never sends a secret to a non-owner - game_server.dart: the command execution path (role check → game-rule guard → registry build → execute → per-connection update broadcast); seat assign/claim/release with seats broadcasts; heartbeat sweep closes dead connections and releases their seats - ws_upgrade.dart: custom WS upgrade handler so the server reads the session cookie (shelf_web_socket hides the Request); app.dart wires shelf + static SPA; bin/main.dart starts the server - game_state.dart: onAction setter so the network layer installs its broadcast hook; save_store.dart / seat_store.dart writes made synchronous (writeAsStringSync) so a snapshot/seat table is on disk when write() returns — the kill -9 persistence test exposed the async write race Server-side guards replace the reference app's 300 ms draw-button lockout: sequential execution makes a duplicate draw deterministically lose, with a clear error to the sender only. The session that adds a character owns it and becomes a player; spectators may only claim/ addCharacter. Command index resets to -1 on restart (the snapshot carries state, not undo history). Tests: 34 new network tests over a real WS stack on an ephemeral port (sessions 9, visibility 5, app 9, multiplayer 9, persistence 2) — secret initiative never reaches non-owners, reveal on draw, reconnect resync, rejected duplicate draw, claim/lose/re-claim seats, undo/redo broadcast to every screen, dead-connection cleanup, snapshot + seat file restored across a restart. Replaces the Phase 0 smoke test. dart analyze warning-free; dart test 591/591; scripts/ci.sh green. --- server/test/net/ws_test_helpers.dart | 246 +++++++++++++++++++++++++++++++++++ 1 file changed, 246 insertions(+) create mode 100644 server/test/net/ws_test_helpers.dart (limited to 'server/test/net/ws_test_helpers.dart') diff --git a/server/test/net/ws_test_helpers.dart b/server/test/net/ws_test_helpers.dart new file mode 100644 index 0000000..cb8af67 --- /dev/null +++ b/server/test/net/ws_test_helpers.dart @@ -0,0 +1,246 @@ +// ignore_for_file: avoid-late-keyword, avoid-top-level-members-in-tests + +/// Shared helpers for the Phase 2 network tests: a [TestGameServer] that +/// boots the real engine + real HTTP/WebSocket stack on an ephemeral port, +/// and a [TestClient] that drives a real WebSocket connection with a +/// message queue. +library; + +import 'dart:async'; +import 'dart:collection'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:collection/collection.dart'; +import 'package:web_socket_channel/web_socket_channel.dart'; +import 'package:x_haven_server/core/game_data.dart'; +import 'package:x_haven_server/core/save_store.dart'; +import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/net/app.dart'; +import 'package:x_haven_server/net/game_server.dart'; +import 'package:x_haven_server/net/protocol.dart'; +import 'package:x_haven_server/net/seat_store.dart'; +import 'package:x_haven_server/net/sessions.dart'; + +/// Boots the engine (test data) and a [GameServer] on an ephemeral port. +class TestGameServer { + TestGameServer._(); + + /// The Dart [HttpServer] on an ephemeral port (port 0). + late HttpServer server; + late GameServer gameServer; + late GameState gameState; + late SessionManager sessions; + late SeatStore seatStore; + + static Future boot({ + SaveStore? saveStore, + SeatStore? seatStore, + Duration heartbeatInterval = const Duration(seconds: 20), + Duration deadTimeout = const Duration(seconds: 90), + String dataDir = 'assets/testData/', + }) async { + // Same bootstrap as test/command/test_helpers.dart's setUpGame(), but + // with the caller's [saveStore] (persistence tests pass a FileSaveStore). + setupCore(saveStore: saveStore ?? InMemorySaveStore()); + final gs = getIt(); + gs.init(); + await getIt().loadData(dataDir); + gs.load(); + final instance = TestGameServer._(); + instance.gameState = gs; + instance.sessions = SessionManager(); + instance.seatStore = seatStore ?? InMemorySeatStore(); + instance.gameServer = GameServer( + gameState: gs, + sessions: instance.sessions, + seatStore: instance.seatStore, + heartbeatInterval: heartbeatInterval, + deadTimeout: deadTimeout, + ); + instance.server = await startServer( + port: 0, + staticDir: 'nonexistent-static-dir', + gameServer: instance.gameServer, + ); + return instance; + } + + /// The `ws://` base url for [TestClient.connect]. + Uri get wsUrl => Uri.parse('ws://localhost:${server.port}/ws'); + + /// The `http://` base url for HTTP helpers. + Uri get httpUrl => Uri.parse('http://localhost:${server.port}'); + + /// Stops the heartbeat, closes the HTTP server, and resets the DI + /// container so the next test can boot a fresh engine. + Future shutdown() async { + gameServer.dispose(); + await server.close(force: true); + await getIt.reset(); + } +} + +/// A fake WS client: a real [WebSocketChannel] with a message queue and +/// typed send helpers. +class TestClient { + TestClient._(this.channel); + + final WebSocketChannel channel; + final Queue> _queue = Queue(); + final List>> _waiters = []; + Completer? _closedCompleter; + bool closed = false; + + static Future connect(Uri url, {String? session}) async { + final uri = + session == null + ? url + : url.replace(queryParameters: {'session': session}); + final channel = WebSocketChannel.connect(uri); + final client = TestClient._(channel); + channel.stream.listen( + (Object? raw) { + final dynamic decoded = jsonDecode(raw as String); + if (decoded is Map) client._deliver(decoded); + }, + onDone: client._markClosed, + onError: (Object _) => client._markClosed(), + ); + await channel.ready; + return client; + } + + void _deliver(Map message) { + final waiter = _waiters.isNotEmpty ? _waiters.removeAt(0) : null; + if (waiter != null) { + waiter.complete(message); + } else { + _queue.add(message); + } + } + + void _markClosed() { + if (closed) return; + closed = true; + _closedCompleter?.complete(); + for (final waiter in _waiters) { + waiter.completeError(StateError('connection closed')); + } + _waiters.clear(); + } + + // --- sending ------------------------------------------------------------- + + void send(Map message) => + channel.sink.add(jsonEncode(message)); + + void sendHello({int version = Protocol.version}) => + send(Protocol.helloMessage()); + + void sendCmd(String name, [Map args = const {}]) => + send(Protocol.commandMessage(name, args)); + + void sendClaim(String characterId) => send(Protocol.claimMessage(characterId)); + + void sendRaw(String raw) => channel.sink.add(raw); + + /// Closes the socket from the client side. + Future close() => channel.sink.close(); + + /// Completes when the connection is closed (by either side). + Future get closedFuture => (_closedCompleter ??= Completer()).future; + + // --- receiving ----------------------------------------------------------- + + /// The next message, with a timeout. + Future> next({ + Duration timeout = const Duration(seconds: 10), + }) async { + if (_queue.isNotEmpty) return _queue.removeFirst(); + final completer = Completer>(); + _waiters.add(completer); + return completer.future.timeout( + timeout, + onTimeout: () => + throw TimeoutException('waiting for a message', timeout), + ); + } + + /// The next message satisfying [test]; earlier non-matching messages are + /// kept (in order) for later [next] calls. + Future> nextWhere( + bool Function(Map) test, { + Duration timeout = const Duration(seconds: 10), + String why = '', + }) async { + final skipped = >[]; + while (true) { + final Map message; + if (_queue.isNotEmpty) { + message = _queue.removeFirst(); + } else { + final completer = Completer>(); + _waiters.add(completer); + try { + message = await completer.future.timeout( + timeout, + onTimeout: () => + throw TimeoutException('nextWhere($why)', timeout), + ); + } catch (_) { + _waiters.remove(completer); + rethrow; + } + } + if (test(message)) { + _queue.addAll(skipped); + return message; + } + skipped.add(message); + } + } + + /// The next message of type [type] (e.g. `'update'`, `'seats'`). + Future> nextOf( + String type, { + Duration timeout = const Duration(seconds: 10), + }) => + nextWhere((m) => m['t'] == type, timeout: timeout, why: type); + + /// Drains and returns all messages currently buffered. + List> flush() { + final result = _queue.toList(); + _queue.clear(); + return result; + } + + // --- convenience ----------------------------------------------------------- + + /// The character entry of [characterId] in a state payload. + static Map? characterIn( + Map state, + String characterId, + ) { + final list = state['currentList']; + if (list is! List) return null; + return list.firstWhereOrNull( + (item) => item is Map && item['id'] == characterId, + ) as Map?; + } + + /// The initiative value as delivered on the wire for [characterId] + /// (null = masked or absent). + static int? initiativeIn(Map state, String characterId) { + final character = characterIn(state, characterId); + final characterState = character?['characterState']; + if (characterState is! Map) return null; + final initiative = characterState['initiative']; + return initiative is int ? initiative : null; + } + + /// The seats payload of a `seats` (or `welcome`) message. + static Map seatsOf(Map message) => + Map.from(message['seats'] as Map); +} -- cgit v1.3.1