diff options
| author | Joel Klinghed <the_jk@spawned.biz> | 2026-11-13 00:04:16 +0100 |
|---|---|---|
| committer | Joel Klinghed <the_jk@spawned.biz> | 2026-11-13 00:04:16 +0100 |
| commit | 3ebbdf6ffa16f751c82e3bd2e74294f4fe843155 (patch) | |
| tree | db4c92ce26f274073453e2a085af3105be823f74 /server/test/net/persistence_test.dart | |
| parent | 808294adad3f378ad8d66b698acf8df7f49c2302 (diff) | |
Phase 2: networking, sessions, secrets over WebSocket (M2)
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.
Diffstat (limited to 'server/test/net/persistence_test.dart')
| -rw-r--r-- | server/test/net/persistence_test.dart | 224 |
1 files changed, 224 insertions, 0 deletions
diff --git a/server/test/net/persistence_test.dart b/server/test/net/persistence_test.dart new file mode 100644 index 0000000..6626840 --- /dev/null +++ b/server/test/net/persistence_test.dart @@ -0,0 +1,224 @@ +/// Phase 2 / Milestone M2: persistence across a server restart +/// (PLAN.md section 3.6) — the state snapshot is saved on every action and +/// restored on startup; seat ownership is restored from `seats.json`. +/// +/// The in-process "crash" here is a clean disconnect: the clients close, +/// the disconnect handlers run (seats released, seat file finalized), and +/// only then is the server killed. A real kill -9 would skip the handlers +/// and leave the last seat write behind — test 2 simulates that case by +/// restoring the pre-crash seat file before the reboot. +library; + +import 'dart:io'; + +import 'package:path/path.dart' as p; +import 'package:test/test.dart'; +import 'package:x_haven_server/core/save_store.dart'; +import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/net/protocol.dart'; +import 'package:x_haven_server/net/seat_store.dart'; + +import 'ws_test_helpers.dart'; + +/// The two players' clients and alice's session id. +class Players { + Players(this.aliceId, this.alice, this.bob); + + final String aliceId; + final TestClient alice; + final TestClient bob; + + List<TestClient> get clients => [alice, bob]; +} + +void main() { + late Directory dir; + + setUp(() { + dir = Directory.systemTemp.createTempSync('x-haven-persist-'); + }); + + tearDown(() { + if (dir.existsSync()) dir.deleteSync(recursive: true); + }); + + /// Two players add characters and enter initiative (optionally draw). + Future<Players> setupPlayers( + TestGameServer server, { + required bool draw, + }) async { + final alice = await TestClient.connect(server.wsUrl); + final bob = await TestClient.connect(server.wsUrl); + alice.sendHello(); + bob.sendHello(); + final aliceId = (await alice.nextOf('welcome'))['session'] as String; + await bob.nextOf('welcome'); + + alice.sendCmd( + 'addCharacter', + {'id': 'Blinkblade', 'edition': 'Frosthaven', 'display': 'Blinky', 'level': 1}, + ); + bob.sendCmd( + 'addCharacter', + {'id': 'Banner Spear', 'edition': 'Frosthaven', 'display': 'Spear', 'level': 1}, + ); + for (final client in [alice, bob]) { + await client.nextOf('update'); + await client.nextOf('seats'); + await client.nextOf('update'); + await client.nextOf('seats'); + } + + alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5}); + for (final client in [alice, bob]) { + await client.nextOf('update'); + } + bob.sendCmd('setInit', {'characterId': 'Banner Spear', 'init': 3}); + for (final client in [alice, bob]) { + await client.nextOf('update'); + } + + if (draw) { + alice.sendCmd('draw'); + for (final client in [alice, bob]) { + await client.nextOf('update'); + } + } + return Players(aliceId, alice, bob); + } + + /// Kills the server after the clients have disconnected cleanly, so the + /// disconnect handlers (seat release + seat-file write) have run and the + /// on-disk state is final before the reboot. + Future<void> crash(TestGameServer server, List<TestClient> clients) async { + for (final client in clients) { + await client.close(); + } + server.gameServer.dispose(); + await server.server.close(force: true); + // Give the disconnect handlers a bounded time to drain; the seat file + // is final by the time the connection table empties. + for (var i = 0; i < 500 && server.gameServer.connectionCount > 0; i++) { + await Future<void>.delayed(const Duration(milliseconds: 10)); + } + await getIt.reset(); + } + + test('state snapshot restored after a server restart', () async { + final serverA = await TestGameServer.boot( + saveStore: FileSaveStore(dir.path), + seatStore: FileSeatStore(dir.path), + ); + final players = await setupPlayers(serverA, draw: true); + + // Both snapshots exist on disk. + expect(File(p.join(dir.path, 'game.json')).existsSync(), isTrue); + expect(File(p.join(dir.path, 'seats.json')).existsSync(), isTrue); + + await crash(serverA, players.clients); + + // Reboot on the same stores. + final serverB = await TestGameServer.boot( + saveStore: FileSaveStore(dir.path), + seatStore: FileSeatStore(dir.path), + ); + addTearDown(serverB.shutdown); + + // The same cookie (session id) reconnects. + final alice2 = + await TestClient.connect(serverB.wsUrl, session: players.aliceId); + alice2.sendHello(); + final welcome = await alice2.nextOf('welcome'); + expect(welcome['session'], players.aliceId); + final state = welcome['state'] as Map<String, dynamic>; + expect(state['roundState'], 1, reason: 'mid playTurns, as before the crash'); + expect( + TestClient.initiativeIn(state, 'Blinkblade'), + 5, + reason: 'initiative was public after the draw', + ); + expect(TestClient.initiativeIn(state, 'Banner Spear'), 3); + + // The command index is per server lifetime: a restored game starts a + // fresh sequence at -1 (the snapshot carries state, not undo history). + expect(welcome['index'], -1); + + // The in-process crash ran the disconnect handlers, so the seat was + // released and the role is back to spectator — re-claim to join again. + expect(welcome['role'], Protocol.roleSpectator); + alice2.sendClaim('Blinkblade'); + final seats = await alice2.nextOf('seats'); + expect(TestClient.seatsOf(seats)['Blinkblade'], players.aliceId); + + // The restored game is playable: a new action executes on top of it. + alice2.sendCmd('turnDone', {'id': 'Banner Spear'}); + final update = await alice2.nextOf('update'); + expect(update['index'], 0, reason: 'fresh server lifetime'); + expect( + TestClient.characterIn( + update['state'] as Map<String, dynamic>, + 'Banner Spear', + )?['turnState'], + 2, + ); + await alice2.close(); + }); + + test('crash-time seat file is restored at startup (kill -9 semantics)', + () async { + final serverA = await TestGameServer.boot( + saveStore: FileSaveStore(dir.path), + seatStore: FileSeatStore(dir.path), + ); + final players = await setupPlayers(serverA, draw: false); + + await crash(serverA, players.clients); + + // A real kill -9 leaves the last pre-crash seat write behind (the + // disconnect handler never runs). The in-process crash above ran it, + // so restore that last write before the reboot. + FileSeatStore(dir.path).write({players.aliceId: ['Blinkblade']}); + + final serverB = await TestGameServer.boot( + saveStore: FileSaveStore(dir.path), + seatStore: FileSeatStore(dir.path), + ); + addTearDown(serverB.shutdown); + + final alice2 = + await TestClient.connect(serverB.wsUrl, session: players.aliceId); + alice2.sendHello(); + final welcome = await alice2.nextOf('welcome'); + + // The seat survived the restart: she is a player again. + expect(welcome['role'], Protocol.rolePlayer); + final seats = TestClient.seatsOf(welcome); + expect(seats['Blinkblade'], players.aliceId); + expect(seats['Banner Spear'], null, reason: 'bob did not re-claim'); + + // Her secret is hers to see again — still masked for the others. + final state = welcome['state'] as Map<String, dynamic>; + expect(state['roundState'], 0, reason: 'still choosing initiative'); + expect( + TestClient.initiativeIn(state, 'Blinkblade'), + 5, + reason: 'the restored owner sees their own value', + ); + expect( + TestClient.initiativeIn(state, 'Banner Spear'), + null, + reason: 'bob\'s value is masked for everyone', + ); + + // And a spectator on the same server sees neither value. + final carol = await TestClient.connect(serverB.wsUrl); + carol.sendHello(); + final carolWelcome = await carol.nextOf('welcome'); + expect(carolWelcome['role'], Protocol.roleSpectator); + final carolState = carolWelcome['state'] as Map<String, dynamic>; + expect(TestClient.initiativeIn(carolState, 'Blinkblade'), null); + expect(TestClient.initiativeIn(carolState, 'Banner Spear'), null); + await carol.close(); + await alice2.close(); + }); +} |
