diff options
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(); + }); +} |
