net.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. import { Packr } from 'msgpackr';
  2. import { afterEach, describe, expect, it } from 'vitest';
  3. import WebSocket from 'ws';
  4. import { loadCharacterStats, loadMap } from '../src/server/assets';
  5. import { Game } from '../src/server/game';
  6. import { GameServer, type GameServerOptions } from '../src/server/net';
  7. import { HASH_CHECK_INTERVAL_S, PROTOCOL_VERSION, START_COUNTDOWN_S, TICK_RATE } from '../src/shared/constants';
  8. import { Button } from '../src/shared/input';
  9. import type { ClientMessage, ServerMessage } from '../src/shared/protocol';
  10. import type { TerrainBitmap } from '../src/shared/terrain/bitmap';
  11. import { applyTerrainEvent } from '../src/shared/terrain/events';
  12. import { ASSETS, realMaterials } from './helpers';
  13. const packr = new Packr({ useRecords: false });
  14. const materials = realMaterials();
  15. const freshTerrain = (): TerrainBitmap => loadMap(ASSETS, 'gateau-etages', materials).terrain;
  16. const flush = (ms = 30): Promise<void> => new Promise((r) => setTimeout(r, ms));
  17. /** Waits until `cond` holds (messages arrive asynchronously; fixed delays are flaky under load). */
  18. async function until(cond: () => boolean, timeoutMs = 3000): Promise<void> {
  19. const end = Date.now() + timeoutMs;
  20. while (!cond()) {
  21. if (Date.now() > end) throw new Error('until: timed out');
  22. await flush(10);
  23. }
  24. }
  25. /** A headless client that keeps its own bitmap in sync, like the renderer does. */
  26. class TestClient {
  27. readonly messages: ServerMessage[] = [];
  28. readonly socket: WebSocket;
  29. terrain = freshTerrain();
  30. mapId = 'gateau-etages';
  31. lastSeq = 0;
  32. playerId = -1;
  33. hashChecks: { seq: number; server: number; mine: number }[] = [];
  34. constructor(port: number) {
  35. this.socket = new WebSocket(`ws://127.0.0.1:${port}`);
  36. this.socket.on('message', (data: Buffer) => this.onMessage(packr.unpack(data) as ServerMessage));
  37. }
  38. async hello(name: string, characterId = 'generic', version = PROTOCOL_VERSION): Promise<void> {
  39. await new Promise((r) => this.socket.once('open', r));
  40. this.send({ t: 'hello', version, name, characterId });
  41. }
  42. send(msg: ClientMessage): void {
  43. this.socket.send(packr.pack(msg));
  44. }
  45. last<T extends ServerMessage['t']>(t: T): Extract<ServerMessage, { t: T }> | undefined {
  46. return [...this.messages].reverse().find((m) => m.t === t) as Extract<ServerMessage, { t: T }> | undefined;
  47. }
  48. private onMessage(msg: ServerMessage): void {
  49. this.messages.push(msg);
  50. if (msg.t === 'welcome') {
  51. this.playerId = msg.playerId;
  52. for (const { seq, ev } of msg.events) this.apply(seq, ev);
  53. } else if (msg.t === 'start') {
  54. this.mapId = msg.mapId;
  55. this.terrain = loadMap(ASSETS, msg.mapId, materials).terrain;
  56. this.lastSeq = 0;
  57. } else if (msg.t === 'terrain') {
  58. this.apply(msg.seq, msg.ev);
  59. } else if (msg.t === 'hash') {
  60. expect(this.lastSeq).toBe(msg.seq);
  61. this.hashChecks.push({ seq: msg.seq, server: msg.hash, mine: this.terrain.hash() });
  62. }
  63. }
  64. private apply(seq: number, ev: Parameters<typeof applyTerrainEvent>[1]): void {
  65. expect(seq).toBe(this.lastSeq + 1);
  66. this.lastSeq = seq;
  67. applyTerrainEvent(this.terrain, ev, materials);
  68. }
  69. }
  70. describe('LAN server (M3)', () => {
  71. let server: GameServer | null = null;
  72. const clients: TestClient[] = [];
  73. afterEach(() => {
  74. for (const c of clients) c.socket.close();
  75. clients.length = 0;
  76. server?.close();
  77. server = null;
  78. });
  79. async function startServer(pacing: Partial<GameServerOptions> = {}): Promise<GameServer> {
  80. await new Promise<void>((resolve) => {
  81. server = new GameServer({
  82. maps: [
  83. { id: 'gateau-etages', name: 'Le Gâteau à Étages' },
  84. { id: 'mille-feuille', name: 'Le Mille-Feuille' },
  85. { id: 'piece-montee', name: 'La Pièce Montée' },
  86. ],
  87. ...pacing,
  88. createGame: (seed, rules, stats, mapId) => {
  89. const { definition, terrain } = loadMap(ASSETS, mapId, materials);
  90. return new Game({ map: definition, terrain, materials, seed, rules, stats, loadCharacter: (id) => loadCharacterStats(ASSETS, id) });
  91. },
  92. seed: 42,
  93. port: 0,
  94. host: '127.0.0.1',
  95. onListening: resolve,
  96. });
  97. });
  98. return server!;
  99. }
  100. function tick(n: number): void {
  101. for (let i = 0; i < n; i++) server!.tickOnce();
  102. }
  103. it('rejects a client with another protocol version', async () => {
  104. const s = await startServer();
  105. const c = new TestClient(s.port);
  106. clients.push(c);
  107. await c.hello('Vieux', 'generic', PROTOCOL_VERSION - 1);
  108. await flush();
  109. expect(c.last('reject')).toMatchObject({ reason: 'version', serverVersion: PROTOCOL_VERSION });
  110. });
  111. it('lobby → everyone ready → countdown → match on a fresh map, clients stay bit-identical', async () => {
  112. const s = await startServer();
  113. const a = new TestClient(s.port);
  114. const b = new TestClient(s.port);
  115. clients.push(a, b);
  116. await a.hello('Alice');
  117. await b.hello('Bob', 'castor');
  118. await until(() => a.last('lobby')?.players.length === 2);
  119. expect(a.last('lobby')).toMatchObject({ phase: 'lobby', countdown: null });
  120. expect(a.last('lobby')!.players.map((p) => p.name)).toEqual(['Alice', 'Bob']);
  121. // Warm-up destruction, then only one player ready: no countdown.
  122. tick(120);
  123. a.send({ t: 'ready', ready: true });
  124. await flush();
  125. tick(1);
  126. await flush();
  127. expect(b.last('lobby')).toMatchObject({ countdown: null });
  128. b.send({ t: 'ready', ready: true });
  129. await flush();
  130. expect(a.last('lobby')!.countdown).toBe(START_COUNTDOWN_S);
  131. tick(START_COUNTDOWN_S * TICK_RATE);
  132. await flush();
  133. expect(a.last('start')).toBeDefined();
  134. expect(b.last('start')!.players.map((p) => p.id).sort()).toEqual([a.playerId, b.playerId].sort());
  135. expect(a.last('lobby')).toMatchObject({ phase: 'playing' });
  136. // Both dig for a while; snapshots, terrain events and hash checks flow to both clients.
  137. for (let i = 0; i < HASH_CHECK_INTERVAL_S * TICK_RATE * 2; i++) {
  138. if (i % 10 === 0) {
  139. const snap = a.last('snapshot');
  140. for (const [c, dy] of [
  141. [a, 40],
  142. [b, 60],
  143. ] as const) {
  144. const me = snap?.players.find((p) => p.id === c.playerId);
  145. if (me) c.send({ t: 'input', buttons: c === a ? Button.Attack : Button.Special, aimX: Math.round(me.x), aimY: Math.round(me.y + dy) });
  146. }
  147. await flush(5);
  148. }
  149. tick(1);
  150. }
  151. await flush(100);
  152. expect(a.lastSeq).toBeGreaterThan(5);
  153. for (const c of [a, b]) {
  154. expect(c.hashChecks.length).toBeGreaterThanOrEqual(2);
  155. for (const h of c.hashChecks) expect(h.mine).toBe(h.server);
  156. }
  157. expect(a.terrain.hash()).toBe(b.terrain.hash());
  158. });
  159. it('a player leaving is announced and an empty server goes back to the lobby', async () => {
  160. const s = await startServer();
  161. const a = new TestClient(s.port);
  162. const b = new TestClient(s.port);
  163. clients.push(a, b);
  164. await a.hello('Alice');
  165. await b.hello('Bob');
  166. await flush();
  167. b.socket.close();
  168. await flush();
  169. expect(a.last('playerLeft')).toMatchObject({ id: b.playerId });
  170. expect(a.last('lobby')!.players).toHaveLength(1);
  171. a.socket.close();
  172. await flush();
  173. expect(s.currentPhase).toBe('lobby');
  174. expect(s.playerCount).toBe(0);
  175. });
  176. it('a whole match: rounds with results in between, final results with trophies, then back to the lobby', async () => {
  177. const s = await startServer({ rounds: 2, roundDuration: 1, roundEndPause: 0.25, matchEndPause: 0.25 });
  178. const a = new TestClient(s.port);
  179. clients.push(a);
  180. await a.hello('Alice', 'castor');
  181. await flush();
  182. a.send({ t: 'ready', ready: true });
  183. await flush();
  184. tick(START_COUNTDOWN_S * TICK_RATE);
  185. await flush();
  186. expect(a.last('start')).toMatchObject({ round: 1, rounds: 2 });
  187. // Alice eats the cake during round 1 so she earns a trophy.
  188. for (let i = 0; i < TICK_RATE + 2; i++) {
  189. const me = a.last('snapshot')?.players.find((p) => p.id === a.playerId);
  190. if (me && i % 10 === 0) {
  191. a.send({ t: 'input', buttons: Button.Special, aimX: Math.round(me.x), aimY: Math.round(me.y + 100) });
  192. await flush(5);
  193. }
  194. tick(1);
  195. }
  196. await flush();
  197. expect(a.last('roundEnd')).toMatchObject({ round: 1, rounds: 2 });
  198. expect(a.last('lobby')).toMatchObject({ phase: 'roundEnd' });
  199. tick(Math.round(0.25 * TICK_RATE));
  200. await flush();
  201. expect(a.last('start')).toMatchObject({ round: 2 });
  202. tick(TICK_RATE + 2);
  203. await flush();
  204. const end = a.last('matchEnd')!;
  205. expect(end).toBeDefined();
  206. expect(end.results.map((r) => r.id)).toEqual([a.playerId]);
  207. expect(end.trophies).toContainEqual(expect.objectContaining({ id: 'glutton', playerId: a.playerId }));
  208. tick(Math.round(0.25 * TICK_RATE));
  209. await flush();
  210. expect(a.last('start')).toMatchObject({ round: 0 });
  211. expect(a.last('lobby')).toMatchObject({ phase: 'lobby' });
  212. expect(a.last('lobby')!.players[0].ready).toBe(false);
  213. });
  214. it('only the host sets the rotation; the warm-up moves to its first map', async () => {
  215. const s = await startServer();
  216. const host = new TestClient(s.port);
  217. const guest = new TestClient(s.port);
  218. clients.push(host, guest);
  219. await host.hello('Hote');
  220. await guest.hello('Invite');
  221. await flush();
  222. expect(guest.last('lobby')).toMatchObject({ hostId: host.playerId, rotation: { mode: 'all' } });
  223. expect(guest.last('lobby')!.maps.map((m) => m.id)).toEqual(['gateau-etages', 'mille-feuille', 'piece-montee']);
  224. guest.send({ t: 'rotation', rotation: { mode: 'selection', selection: ['piece-montee'] } });
  225. await flush();
  226. expect(host.last('lobby')!.rotation.mode).toBe('all');
  227. host.send({ t: 'rotation', rotation: { mode: 'selection', selection: ['piece-montee', 'nope'] } });
  228. await flush(400); // the warm-up map is reloaded: give the server time to decode it
  229. expect(guest.last('lobby')!.rotation).toEqual({ mode: 'selection', selection: ['piece-montee'] });
  230. expect(guest.last('start')).toMatchObject({ mapId: 'piece-montee', round: 0 });
  231. });
  232. it('the last-placed player picks the next map during the round results', async () => {
  233. const s = await startServer({ rounds: 2, roundDuration: 1, roundEndPause: 1, matchEndPause: 0.25 });
  234. const a = new TestClient(s.port);
  235. const b = new TestClient(s.port);
  236. clients.push(a, b);
  237. await a.hello('Alice');
  238. await b.hello('Bob');
  239. await flush();
  240. a.send({ t: 'ready', ready: true });
  241. b.send({ t: 'ready', ready: true });
  242. await flush();
  243. tick(START_COUNTDOWN_S * TICK_RATE);
  244. await flush();
  245. expect(a.last('start')).toMatchObject({ round: 1, mapId: 'gateau-etages' });
  246. tick(TICK_RATE + 2);
  247. await flush();
  248. const end = a.last('roundEnd')!;
  249. // Nobody scored: the tie goes to the latest to join.
  250. expect(end.picker).toBe(b.playerId);
  251. expect(end.choices).toHaveLength(3);
  252. // The leader is Alice (tie broken by id), the picker Bob: he imposes her character.
  253. expect(end.leader).toBe(a.playerId);
  254. expect(end.characters).toEqual(expect.arrayContaining(['castor', 'mamie', 'pyromanchot']));
  255. a.send({ t: 'pickMap', mapId: 'piece-montee' }); // not Alice's call
  256. a.send({ t: 'imposeCharacter', characterId: 'mamie' }); // nor this
  257. b.send({ t: 'pickMap', mapId: 'mille-feuille' });
  258. b.send({ t: 'imposeCharacter', characterId: 'pyromanchot' });
  259. await flush();
  260. expect(a.last('mapPicked')).toEqual({ t: 'mapPicked', mapId: 'mille-feuille', by: b.playerId });
  261. expect(a.last('characterImposed')).toEqual({ t: 'characterImposed', playerId: a.playerId, characterId: 'pyromanchot', by: b.playerId });
  262. tick(TICK_RATE);
  263. await until(() => a.last('start')?.round === 2);
  264. const start = a.last('start')!;
  265. expect(start.mapId).toBe('mille-feuille');
  266. expect(b.mapId).toBe('mille-feuille');
  267. expect(start.players.find((p) => p.id === a.playerId)!.characterId).toBe('pyromanchot');
  268. expect(start.players.find((p) => p.id === b.playerId)!.characterId).toBe('generic');
  269. // The imposed character lasts one round: back in the lobby Alice has her own again.
  270. tick(TICK_RATE + 2);
  271. await flush();
  272. tick(Math.round(0.25 * TICK_RATE) + 1);
  273. await until(() => a.last('start')?.round === 0);
  274. expect(a.last('start')!.players.find((p) => p.id === a.playerId)!.characterId).toBe('generic');
  275. });
  276. it('the host can stop a match: everyone goes back to the warm-up', async () => {
  277. const s = await startServer({ rounds: 4, roundDuration: 60 });
  278. const host = new TestClient(s.port);
  279. const guest = new TestClient(s.port);
  280. clients.push(host, guest);
  281. await host.hello('Hote');
  282. await guest.hello('Invite');
  283. await flush();
  284. host.send({ t: 'ready', ready: true });
  285. guest.send({ t: 'ready', ready: true });
  286. await flush();
  287. tick(START_COUNTDOWN_S * TICK_RATE);
  288. await until(() => guest.last('start')?.round === 1);
  289. guest.send({ t: 'stopMatch' }); // not the host: ignored
  290. await flush();
  291. tick(1);
  292. expect(s.currentPhase).toBe('playing');
  293. host.send({ t: 'stopMatch' });
  294. await until(() => guest.last('matchStopped') !== undefined);
  295. await until(() => guest.last('start')?.round === 0);
  296. expect(s.currentPhase).toBe('lobby');
  297. expect(guest.last('lobby')).toMatchObject({ phase: 'lobby', countdown: null });
  298. });
  299. it('players change character during the warm-up, a random pick is drawn each round', async () => {
  300. const s = await startServer();
  301. const a = new TestClient(s.port);
  302. const b = new TestClient(s.port);
  303. clients.push(a, b);
  304. await a.hello('Alice', 'random');
  305. await b.hello('Bob', 'castor');
  306. await until(() => a.last('welcome') !== undefined && b.last('welcome') !== undefined);
  307. const drawn = a.last('welcome')!.players.find((p) => p.id === a.playerId)!.characterId;
  308. expect(['castor', 'mamie', 'pyromanchot', 'gege', 'pompier', 'prout', 'chat', 'magicien']).toContain(drawn);
  309. b.send({ t: 'character', characterId: 'chat' });
  310. // (Bob's own arrival was announced as a playerJoined too, with his first character.)
  311. await until(() => a.last('playerJoined')?.player.characterId === 'chat');
  312. expect(a.last('playerJoined')!.player.id).toBe(b.playerId);
  313. await until(() => a.last('lobby')!.players.find((p) => p.id === b.playerId)!.characterId === 'chat');
  314. // Two players on the same character get different color variants.
  315. a.send({ t: 'character', characterId: 'chat' });
  316. await until(() => b.last('playerJoined')?.player.id === a.playerId);
  317. expect(b.last('playerJoined')!.player).toMatchObject({ characterId: 'chat', variant: 1 });
  318. });
  319. });