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/smoke_test.dart | 115 -------------------------------------------- 1 file changed, 115 deletions(-) delete mode 100644 server/test/smoke_test.dart (limited to 'server/test/smoke_test.dart') diff --git a/server/test/smoke_test.dart b/server/test/smoke_test.dart deleted file mode 100644 index 2ac745e..0000000 --- a/server/test/smoke_test.dart +++ /dev/null @@ -1,115 +0,0 @@ -import 'dart:async'; -import 'dart:convert'; -import 'dart:io'; - -import 'package:test/test.dart'; -import 'package:web_socket_channel/web_socket_channel.dart'; -import 'package:x_haven_server/net/app.dart'; - -/// Reads messages from a [WebSocketChannel] one at a time. The channel's -/// stream is single-subscription, so this reader holds the one subscription -/// for the test's lifetime. -class _MessageReader { - final WebSocketChannel channel; - final StreamIterator> _iterator; - - _MessageReader(this.channel) - : _iterator = StreamIterator( - channel.stream.map( - (Object? raw) => jsonDecode(raw as String) as Map, - ), - ); - - Future> next() async { - final advanced = await _iterator.moveNext().timeout( - const Duration(seconds: 5), - ); - if (!advanced) { - fail('connection closed before the expected message arrived'); - } - return _iterator.current; - } - - Future dispose() => _iterator.cancel(); -} - -void main() { - late HttpServer server; - - setUp(() async { - server = await startServer(port: 0, staticDir: 'nonexistent-static-dir'); - }); - - tearDown(() async { - await server.close(force: true); - }); - - WebSocketChannel connect() { - final channel = WebSocketChannel.connect( - Uri.parse('ws://localhost:${server.port}/ws'), - ); - addTearDown(() => unawaited(channel.sink.close())); - return channel; - } - - test('serves a stub page at / when the static dir is missing', () async { - final client = HttpClient(); - addTearDown(client.close); - final request = await client.getUrl( - Uri.parse('http://localhost:${server.port}/'), - ); - final response = await request.close(); - expect(response.statusCode, 200); - final body = await response.transform(utf8.decoder).join(); - expect(body, contains('X-Haven server')); - }); - - test('answers healthz', () async { - final client = HttpClient(); - addTearDown(client.close); - final request = await client.getUrl( - Uri.parse('http://localhost:${server.port}/healthz'), - ); - final response = await request.close(); - expect(response.statusCode, 200); - final body = jsonDecode(await response.transform(utf8.decoder).join()); - expect(body, {'status': 'ok'}); - }); - - test('answers hello with welcome', () async { - final channel = connect(); - final reader = _MessageReader(channel); - addTearDown(reader.dispose); - - channel.sink.add(jsonEncode({'t': 'hello', 'v': 1})); - final welcome = await reader.next(); - expect(welcome['t'], 'welcome'); - expect(welcome['v'], 1); - expect(welcome['role'], 'spectator'); - expect(welcome['index'], 0); - expect(welcome['state'], isEmpty); - expect(welcome['seats'], isEmpty); - expect(welcome['session'], isNotEmpty); - }); - - test('answers ping with pong', () async { - final channel = connect(); - final reader = _MessageReader(channel); - addTearDown(reader.dispose); - - channel.sink.add(jsonEncode({'t': 'ping'})); - expect(await reader.next(), {'t': 'pong'}); - }); - - test('rejects malformed and unknown messages with error', () async { - final channel = connect(); - final reader = _MessageReader(channel); - addTearDown(reader.dispose); - - channel.sink.add('this is not json'); - expect((await reader.next())['code'], 'badRequest'); - - channel.sink.add(jsonEncode({'t': 'warpSpeed'})); - expect((await reader.next())['code'], 'unknownMessage'); - }); -} -- cgit v1.3.1