1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
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();
});
}
|