summaryrefslogtreecommitdiff
path: root/server/test/net/multiplayer_test.dart
blob: b336501dffb7fba154b49ac04b16379a86bba78a (plain)
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
/// Phase 2 / Milestone M2: the full multiplayer + secrets scenario over a
/// real WebSocket — two players (alice, bob) and one spectator (carol):
///
/// * secret initiative never reaches non-owners; reveal on draw
/// * rejected duplicate draw (error to the sender only)
/// * draw blocked until all initiative values are entered
/// * spectator role gating (commands forbidden, claim allowed)
/// * claim / release / re-claim of seats
/// * reconnect resync with per-connection masking
/// * undo/redo requested by players, broadcast to everyone
/// * dead-connection cleanup with seat release
library;

import 'package:test/test.dart';
import 'package:x_haven_server/core/service_locator.dart';
import 'package:x_haven_server/core/settings.dart';
import 'package:x_haven_server/net/protocol.dart';

import 'ws_test_helpers.dart';

/// A table with two players and one spectator, mid-setup.
class Table {
  late TestGameServer server;
  late TestClient alice; // will own 'Blinkblade'
  late TestClient bob; // will own 'Banner Spear'
  late TestClient carol; // spectator
  String aliceId = '';
  String bobId = '';
  String carolId = '';

  List<TestClient> get everyone => [alice, bob, carol];

  Future<Table> setup() async {
    server = await TestGameServer.boot();
    try {
      getIt<Settings>().noInit = false; // exercise the initiative gate

      alice = await TestClient.connect(server.wsUrl);
      bob = await TestClient.connect(server.wsUrl);
      carol = await TestClient.connect(server.wsUrl);
      alice.sendHello();
      bob.sendHello();
      carol.sendHello();
      aliceId = (await alice.nextOf('welcome'))['session'] as String;
      bobId = (await bob.nextOf('welcome'))['session'] as String;
      carolId = (await carol.nextOf('welcome'))['session'] as String;

      // Each player adds their own character: the session that adds a
      // character owns it and becomes a player.
      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 everyone) {
        await client.nextOf('update');
        await client.nextOf('seats');
        await client.nextOf('update');
        await client.nextOf('seats');
      }
      return this;
    } catch (_) {
      await server.shutdown();
      rethrow;
    }
  }

  Future<void> teardown() async {
    for (final client in everyone) {
      await client.close();
    }
    await server.shutdown();
  }

  /// Both players enter initiative: alice 5, bob 3. Consumes the updates.
  Future<void> enterInitiative() async {
    alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5});
    bob.sendCmd('setInit', {'characterId': 'Banner Spear', 'init': 3});
    for (final client in everyone) {
      await client.nextOf('update');
      await client.nextOf('update');
    }
  }

  /// alice taps the draw button; consumes the updates on all three screens.
  Future<void> draw() async {
    alice.sendCmd('draw');
    for (final client in everyone) {
      await client.nextOf('update');
    }
  }
}

void main() {
  late Table table;
  var tableBuilt = false;

  setUp(() async {
    table = await Table().setup();
    tableBuilt = true;
  });

  tearDown(() async {
    // When setUp failed before the table was built, setup() has already
    // shut the server down — nothing to tear down.
    if (tableBuilt) {
      await table.teardown();
    }
  });

  Map<String, dynamic> stateOf(Map<String, dynamic> message) =>
      Map<String, dynamic>.from(message['state'] as Map);

  test('secret initiative never reaches non-owners; reveal on draw', () async {
    // --- bob enters 3 ------------------------------------------------------
    table.bob.sendCmd('setInit', {'characterId': 'Banner Spear', 'init': 3});

    // The owner sees their own value; the other player's value is masked.
    expect(
      TestClient.initiativeIn(stateOf(await table.bob.nextOf('update')), 'Banner Spear'),
      3,
      reason: 'bob sees his own initiative',
    );
    expect(
      TestClient.initiativeIn(stateOf(await table.alice.nextOf('update')), 'Banner Spear'),
      null,
      reason: 'bob\'s value is masked for alice',
    );
    expect(
      TestClient.initiativeIn(
        stateOf(await table.carol.nextOf('update')),
        'Banner Spear',
      ),
      null,
      reason: 'the spectator sees no initiative at all',
    );

    // --- alice enters 5 ----------------------------------------------------
    table.alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5});

    expect(
      TestClient.initiativeIn(stateOf(await table.alice.nextOf('update')), 'Blinkblade'),
      5,
    );
    expect(
      TestClient.initiativeIn(
        stateOf(await table.bob.nextOf('update')),
        'Blinkblade',
      ),
      null,
    );
    expect(
      TestClient.initiativeIn(
        stateOf(await table.carol.nextOf('update')),
        'Blinkblade',
      ),
      null,
    );

    // --- draw: initiative becomes public to everyone -----------------------
    await table.draw();

    for (final client in table.everyone) {
      // The draw update was consumed; resync via a fresh welcome to assert
      // the revealed state on every screen.
      client.sendHello();
      final state = stateOf(await client.nextOf('welcome'));
      expect(
        state['roundState'],
        1,
        reason: 'playTurns on every screen',
      );
      expect(
        TestClient.initiativeIn(state, 'Blinkblade'),
        5,
        reason: '${client == table.alice ? 'alice' : client == table.bob ? 'bob' : 'carol'} sees the public value',
      );
      expect(TestClient.initiativeIn(state, 'Banner Spear'), 3);
    }

    // Lower initiative acts first.
    table.alice.sendHello();
    final state = stateOf(await table.alice.nextOf('welcome'));
    expect(
      TestClient.characterIn(state, 'Banner Spear'),
      isNotNull,
    );
    final list = state['currentList'] as List;
    final spearIndex = list.indexWhere((item) => item is Map && item['id'] == 'Banner Spear');
    final blinkIndex = list.indexWhere((item) => item is Map && item['id'] == 'Blinkblade');
    expect(spearIndex, lessThan(blinkIndex), reason: '3 < 5');
  });

  test('duplicate draw is rejected; the error goes to the sender only',
      () async {
    await table.enterInitiative();
    await table.draw();

    table.alice.sendCmd('draw');
    final error = await table.alice.nextOf('error');
    expect(error['code'], Protocol.errRejected);
    expect(error['message'], 'the round has already been drawn');

    // No update, no seats: the other screens never heard about the
    // rejected command.
    await Future<void>.delayed(const Duration(milliseconds: 200));
    expect(table.bob.flush(), isEmpty);
    expect(table.carol.flush(), isEmpty);
  });

  test('draw is blocked until every player has entered initiative', () async {
    table.alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5});
    for (final client in table.everyone) {
      await client.nextOf('update');
    }

    table.alice.sendCmd('draw');
    final error = await table.alice.nextOf('error');
    expect(error['code'], Protocol.errRejected);
    expect(error['message'], contains('initiative'));

    await Future<void>.delayed(const Duration(milliseconds: 200));
    expect(table.bob.flush(), isEmpty);

    table.bob.sendCmd('setInit', {'characterId': 'Banner Spear', 'init': 3});
    for (final client in table.everyone) {
      await client.nextOf('update');
    }

    table.alice.sendCmd('draw');
    final update = await table.alice.nextOf('update');
    expect(stateOf(update)['roundState'], 1);
  });

  test('spectator commands are forbidden; claiming is how they join', () async {
    // A gated command as a spectator: rejected with a role error.
    table.carol.sendCmd(
      'changeHealth',
      {'change': -1, 'figureId': 'Blinkblade'},
    );
    final error = await table.carol.nextOf('error');
    expect(error['code'], Protocol.errForbidden);
    expect(error['message'], contains('claim a character'));

    // Undo/redo are player-only too.
    table.carol.send({'t': 'undo'});
    expect((await table.carol.nextOf('error'))['code'], Protocol.errForbidden);

    // Claiming a character is allowed for spectators — but only if it is
    // unclaimed.
    table.carol.sendClaim('Blinkblade');
    final rejected = await table.carol.nextOf('error');
    expect(rejected['code'], Protocol.errRejected);
    expect(rejected['message'], contains('already claimed'));

    // Unknown character.
    table.carol.sendClaim('Nyx');
    final noSuch = await table.carol.nextOf('error');
    expect(noSuch['code'], Protocol.errRejected);
    expect(noSuch['message'], contains('Nyx'));
  });

  test('nextRound is rejected before the round has started', () async {
    table.alice.sendCmd('nextRound');
    final error = await table.alice.nextOf('error');
    expect(error['code'], Protocol.errRejected);
    expect(error['message'], 'the round has not started yet');
  });

  test('claim flow: disconnect releases the seat; re-claim works', () async {
    // carol cannot claim a character bob owns.
    table.carol.sendClaim('Banner Spear');
    expect((await table.carol.nextOf('error'))['code'], Protocol.errRejected);

    // bob leaves: his character becomes unclaimed.
    await table.bob.close();
    final seatsForAlice = await table.alice.nextOf('seats');
    expect(TestClient.seatsOf(seatsForAlice)['Banner Spear'], null);
    expect(TestClient.seatsOf(seatsForAlice)['Blinkblade'], table.aliceId);
    final seatsForCarol = await table.carol.nextOf('seats');
    expect(TestClient.seatsOf(seatsForCarol)['Banner Spear'], null);

    // carol claims the freed character and becomes its owner.
    table.carol.sendClaim('Banner Spear');
    final seats2 = await table.carol.nextOf('seats');
    expect(TestClient.seatsOf(seats2)['Banner Spear'], table.carolId);
    final seats2ForAlice = await table.alice.nextOf('seats');
    expect(TestClient.seatsOf(seats2ForAlice)['Banner Spear'], table.carolId);

    // Re-asserting an existing ownership is a no-op (no error, same table).
    table.carol.sendClaim('Banner Spear');
    final seats3 = await table.carol.nextOf('seats');
    expect(TestClient.seatsOf(seats3)['Banner Spear'], table.carolId);
    expect(TestClient.seatsOf(seats3)['Blinkblade'], table.aliceId);

    // carol still cannot claim alice's character.
    table.carol.sendClaim('Blinkblade');
    expect((await table.carol.nextOf('error'))['code'], Protocol.errRejected);
  });

  test('reconnect resync: full welcome, released seat, re-claim', () async {
    table.alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5});
    table.bob.sendCmd('setInit', {'characterId': 'Banner Spear', 'init': 3});

    // The last update on every screen carries the index to expect in a
    // fresh welcome.
    var lastUpdateIndex = -1;
    for (final client in table.everyone) {
      await client.nextOf('update');
      final second = await client.nextOf('update');
      lastUpdateIndex = second['index'] as int;
    }

    // alice leaves; her seat is released.
    await table.alice.close();
    final seats = await table.bob.nextOf('seats');
    expect(TestClient.seatsOf(seats)['Blinkblade'], null);

    // Reconnect with the same session id (the cookie's job).
    final alice2 = await TestClient.connect(
      table.server.wsUrl,
      session: table.aliceId,
    );
    alice2.sendHello();
    final welcome = await alice2.nextOf('welcome');
    expect(welcome['session'], table.aliceId);
    expect(welcome['role'], Protocol.roleSpectator, reason: 'seat was released');
    expect(welcome['index'], lastUpdateIndex, reason: 'full resync, same index');

    // While the seat is free, even her own old value is masked for her.
    final welcomeState = stateOf(welcome);
    expect(welcomeState['roundState'], 0, reason: 'still choosing initiative');
    expect(TestClient.initiativeIn(welcomeState, 'Blinkblade'), null);
    expect(TestClient.initiativeIn(welcomeState, 'Banner Spear'), null);

    // Re-claim her character, then resync: the value is hers to see again.
    alice2.sendClaim('Blinkblade');
    await alice2.nextOf('seats');
    await table.bob.nextOf('seats');
    alice2.sendHello();
    final welcome2 = await alice2.nextOf('welcome');
    expect(welcome2['role'], Protocol.rolePlayer);
    expect(
      TestClient.initiativeIn(stateOf(welcome2), 'Blinkblade'),
      5,
      reason: 'the owner sees their own secret again',
    );
    expect(TestClient.initiativeIn(stateOf(welcome2), 'Banner Spear'), null);
    await alice2.close();
  });

  test('undo/redo: player requests, every screen resyncs', () async {
    await table.enterInitiative();
    await table.draw();
    // Initiative order: 'Banner Spear' (3) first, then 'Blinkblade' (5).

    table.bob.sendCmd('turnDone', {'id': 'Banner Spear'});
    final turnDone = await table.bob.nextOf('update');
    // The other screens carry the same update too — drain them so the
    // undo/redo updates below are the only ones queued.
    await table.alice.nextOf('update');
    await table.carol.nextOf('update');
    final indexAtTurnDone = turnDone['index'] as int;
    var state = stateOf(turnDone);
    expect(
      TestClient.characterIn(state, 'Banner Spear')?['turnState'],
      2,
      reason: 'done',
    );
    expect(
      TestClient.characterIn(state, 'Blinkblade')?['turnState'],
      1,
      reason: 'current',
    );

    // undo: the state rolls back. The wire index is the post-decrement one
    // (the reference reports the pre-decrement index — its clients keep
    // local state; our stateless web clients take the index at face value,
    // so it must equal the state position). The description is the undone
    // action's, as in the reference.
    table.bob.send({'t': 'undo'});
    for (final client in table.everyone) {
      final update = await client.nextOf('update');
      state = stateOf(update);
      expect(update['index'], indexAtTurnDone - 1);
      expect(
        TestClient.characterIn(state, 'Banner Spear')?['turnState'],
        1,
        reason: 'current again',
      );
      expect(
        TestClient.characterIn(state, 'Blinkblade')?['turnState'],
        0,
        reason: 'waiting again',
      );
      expect(update['event'], {'type': 'none'});
    }

    // redo: forward again.
    table.bob.send({'t': 'redo'});
    for (final client in table.everyone) {
      final update = await client.nextOf('update');
      state = stateOf(update);
      expect(update['index'], indexAtTurnDone);
      expect(
        TestClient.characterIn(state, 'Banner Spear')?['turnState'],
        2,
      );
      expect(TestClient.characterIn(state, 'Blinkblade')?['turnState'], 1);
    }
  });

  test('dead connection cleanup: a quiet socket is closed, the seat released',
      () async {
    // Short timeouts: the sweep runs every 100 ms, dead after 400 ms quiet.
    await table.teardown();
    table.server = await TestGameServer.boot(
      heartbeatInterval: const Duration(milliseconds: 100),
      deadTimeout: const Duration(milliseconds: 400),
    );
    getIt<Settings>().noInit = false;
    table.alice = await TestClient.connect(table.server.wsUrl);
    table.bob = await TestClient.connect(table.server.wsUrl);
    table.carol = await TestClient.connect(table.server.wsUrl);
    table.alice.sendHello();
    table.bob.sendHello();
    table.carol.sendHello();
    table.aliceId = (await table.alice.nextOf('welcome'))['session'] as String;
    table.bobId = (await table.bob.nextOf('welcome'))['session'] as String;
    table.carolId = (await table.carol.nextOf('welcome'))['session'] as String;

    table.alice.sendCmd(
      'addCharacter',
      {'id': 'Blinkblade', 'edition': 'Frosthaven', 'display': 'Blinky', 'level': 1},
    );
    for (final client in [table.alice, table.bob, table.carol]) {
      await client.nextOf('update');
      await client.nextOf('seats');
    }

    // Keep bob and carol alive so only alice is swept.
    table.bob.send({'t': 'ping'});
    table.carol.send({'t': 'ping'});
    await table.bob.nextOf('pong');
    await table.carol.nextOf('pong');

    // alice goes quiet (no pings) — the sweep must close her and release
    // the seat so the others can re-claim.
    await table.alice.closedFuture.timeout(
      const Duration(seconds: 5),
    );
    final seats = await table.bob.nextOf('seats');
    expect(TestClient.seatsOf(seats)['Blinkblade'], null);
    final seatsForCarol = await table.carol.nextOf('seats');
    expect(TestClient.seatsOf(seatsForCarol)['Blinkblade'], null);

    await table.bob.close();
    await table.carol.close();
    await table.server.shutdown();
  });
}