'use strict'; /* * RemoteController / LocalController without a browser: public/js/controllers.js runs in a vm context with a fake WebSocket, a fake * document/window and a manual clock (timers and performance.now() advance only when the test says so). */ const test = require('node:test'); const assert = require('node:assert/strict'); const fs = require('fs'); const path = require('path'); const vm = require('node:vm'); const TD = require('../public/js/sim.js'); const SRC = fs.readFileSync(path.join(__dirname, '..', 'public', 'js', 'controllers.js'), 'utf8'); function harness() { const H = { now: 1000, timers: [], seq: 0, sockets: [], docAdded: 0, docRemoved: 0, winAdded: 0, winRemoved: 0 }; const timer = (fn, ms, repeat) => { const t = { id: ++H.seq, at: H.now + ms, fn, ms, repeat }; H.timers.push(t); return t.id; }; class FakeWS { constructor(url) { this.url = url; this.readyState = 0; this.sent = []; this.closeCalls = 0; H.sockets.push(this); } send(s) { this.sent.push(JSON.parse(s)); } close() { this.closeCalls++; this.readyState = 2; } // a half-open socket: no close event follows open() { this.readyState = 1; if (this.onopen) this.onopen(); } recv(o) { if (this.onmessage) this.onmessage({ data: JSON.stringify(o) }); } serverClose(code) { this.readyState = 3; if (this.onclose) this.onclose({ code }); } } const sandbox = { TD, console, URL, FakeWS, WebSocket: FakeWS, document: { hidden: false, addEventListener() { H.docAdded++; }, removeEventListener() { H.docRemoved++; } }, performance: { now: () => H.now }, location: { href: 'http://localhost/index.html' }, addEventListener() { H.winAdded++; }, removeEventListener() { H.winRemoved++; }, setTimeout: (fn, ms) => timer(fn, ms, false), clearTimeout: (id) => { H.timers = H.timers.filter((t) => t.id !== id); }, setInterval: (fn, ms) => timer(fn, ms, true), clearInterval: (id) => { H.timers = H.timers.filter((t) => t.id !== id); }, }; sandbox.self = sandbox; vm.runInNewContext(SRC, sandbox, { filename: 'controllers.js' }); H.NW = sandbox.NW; H.advance = (ms) => { // runs the timers that fall due, in order, moving the clock along const end = H.now + ms; for (;;) { const due = H.timers.filter((t) => t.at <= end).sort((a, b) => a.at - b.at || a.id - b.id)[0]; if (!due) break; H.now = Math.max(H.now, due.at); if (due.repeat) due.at += due.ms; else H.timers = H.timers.filter((t) => t !== due); due.fn(); } H.now = end; }; return H; } // What the server would send for a sim in its current state. function joinedMsg(sim, extra) { return Object.assign({ t: 'joined', room: 'ABCD', resumed: false, you: { pid: 'pidpidpid1', slot: 1, host: false }, players: [{ pid: 'pidpidpid1', slot: 1, name: 'Bob', host: false, online: true }, { pid: 'aliasaliasalias', slot: 0, name: 'Alice', host: true, online: true }], state: sim.fullState(), snap: sim.snapshot(), speed: 1, paused: false, }, extra); } let seq = 0; function snapMsg(sim, tw) { const m = Object.assign({ t: 'snap', seq: ++seq }, sim.snapshot(), { ev: [], cur: [], pa: 0, sp: 1 }); if (tw) m.tw = sim.towerList(); return m; } function connected(opts) { const H = harness(); const sim = new TD.Sim({ map: 'open' }); const rc = new H.NW.RemoteController(Object.assign({ pid: 'pidpidpid1', name: 'Bob', room: 'ABCD', url: 'ws://x/ws' }, opts)); rc.connect(); const ws = H.sockets[0]; ws.open(); ws.recv(joinedMsg(sim)); return { H, sim, rc, ws }; } test('coop-1: a burst of snapshots larger than the buffer does not lose the partner\'s tower change', () => { const { H, sim, rc, ws } = connected(); assert.equal(rc.status, 'joined'); ws.recv(snapMsg(sim)); // quiet snapshots, then the partner builds... sim.cmd({ c: 'place', type: 'wall', x: 12, y: 5, by: 0 }); ws.recv(snapMsg(sim, true)); // ...this one carries the tower list (sent exactly once) for (let i = 0; i < 14; i++) ws.recv(snapMsg(sim)); // the page was stalled: 14 more arrive before it renders again assert.ok(rc.buf.length <= 10, 'the buffer is still bounded'); H.advance(500); rc.update(H.now); assert.equal(rc.towers.length, 1, 'the tower is there'); assert.equal(rc.view.towers.length, 1); assert.equal(rc.rev, sim.rev, 'and so is the revision'); assert.ok(rc.board.solid[5 * rc.board.cols + 12], 'the mirror board knows the new wall (route previews are right)'); assert.equal(ws.sent.filter((m) => m.t === 'sync').length, 0, 'no resync was needed'); }); test('coop-1: the NEWEST of several dropped tower lists wins; an older one is never applied over it', () => { const { H, sim, rc, ws } = connected(); sim.cmd({ c: 'place', type: 'wall', x: 12, y: 5, by: 0 }); ws.recv(snapMsg(sim, true)); sim.cmd({ c: 'place', type: 'wall', x: 12, y: 6, by: 1 }); ws.recv(snapMsg(sim, true)); sim.cmd({ c: 'sell', id: 1 }); ws.recv(snapMsg(sim, true)); // list 3: wall 2 only for (let i = 0; i < 20; i++) ws.recv(snapMsg(sim)); H.advance(500); rc.update(H.now); assert.deepEqual([...rc.towers.map((t) => t.id)], [2]); assert.equal(rc.rev, sim.rev); }); test('coop-1: a tower list that never arrives is noticed (revision mismatch) and the full state is requested', () => { const { H, sim, rc, ws } = connected(); sim.cmd({ c: 'place', type: 'wall', x: 12, y: 5, by: 0 }); ws.recv(snapMsg(sim, true)); rc.buf.length = 0; ws.recv(snapMsg(sim)); // (simulate the list being lost on the way) H.advance(500); rc.update(H.now); assert.equal(ws.sent.filter((m) => m.t === 'sync').length, 1); }); test('coop-2: a joined socket that goes silent is abandoned after 5 s: reconnecting at once and a fresh socket, without waiting for a close', () => { const { H, rc, ws } = connected(); const states = []; rc.on('status', (s) => states.push(s)); H.advance(4000); assert.equal(rc.status, 'joined', 'still fine after 4 s of silence'); assert.equal(H.sockets.length, 1); H.advance(2500); assert.equal(rc.status, 'reconnecting', 'the watchdog shows it immediately'); assert.equal(H.sockets.length, 2, 'a new socket was opened without waiting for the dead one to close'); assert.equal(ws.closeCalls, 1, 'the dead one was closed'); assert.equal(ws.onclose, null, 'its handlers are detached: a late close / the server\'s 4001 cannot be mistaken for the new connection'); assert.deepEqual(states, ['reconnecting']); const ws2 = H.sockets[1]; ws2.open(); assert.equal(ws2.sent[0].t, 'join'); assert.equal(ws2.sent[0].room, 'ABCD'); assert.equal(ws2.sent[0].pid, 'pidpidpid1'); ws2.recv(joinedMsg(new TD.Sim({ map: 'open' }), { resumed: true })); assert.equal(rc.status, 'joined'); ws.serverClose(1006); // the old socket finally dies: nothing changes assert.equal(rc.status, 'joined'); assert.equal(H.sockets.length, 2); }); test('coop-2: waking up after a stall abandons a socket that has been silent for 2.5 s', () => { const { H, rc } = connected(); H.now += 3000; // the page was frozen; timers have not run rc._wake(); assert.equal(rc.status, 'reconnecting'); assert.equal(H.sockets.length, 2); }); test('coop-2: a connection attempt that hangs is abandoned after 10 s and retried', () => { const { H, rc } = connected(); H.advance(6000); // watchdog: socket 2 is opened and then hangs (never opens) assert.equal(H.sockets.length, 2); H.advance(10100); assert.equal(rc.status, 'reconnecting'); assert.equal(H.sockets[1].closeCalls, 1, 'the attempt that went nowhere was dropped'); H.advance(500); assert.equal(H.sockets.length, 3, 'and another attempt was made'); }); test('coop-6: "no such room" after a reconnect says the server restarted; on a resume it says the game is gone; a plain join says so', () => { const a = connected(); const fatal = []; a.rc.on('fatal', (f) => fatal.push(f)); a.ws.serverClose(1006); // the server went away... a.H.advance(500); const ws2 = a.H.sockets[1]; ws2.open(); ws2.recv({ t: 'error', code: 'no_room', msg: 'no such room' }); // ...and came back without the room assert.equal(fatal.length, 1); assert.equal(fatal[0].code, 'restarted'); assert.match(fatal[0].msg, /server restarted, your game was lost/); const H = harness(); const resume = new H.NW.RemoteController({ pid: 'pidpidpid1', name: 'Bob', room: 'ZZZZ', url: 'ws://x/ws', resume: true }); const f2 = []; resume.on('fatal', (f) => f2.push(f)); resume.connect(); H.sockets[0].open(); H.sockets[0].recv({ t: 'error', code: 'no_room', msg: 'no such room' }); assert.equal(f2[0].code, 'restarted'); assert.match(f2[0].msg, /gone/); const plain = new H.NW.RemoteController({ pid: 'pidpidpid1', name: 'Bob', room: 'ZZZZ', url: 'ws://x/ws' }); const f3 = []; plain.on('fatal', (f) => f3.push(f)); plain.connect(); H.sockets[1].open(); H.sockets[1].recv({ t: 'error', code: 'no_room', msg: 'no such room' }); assert.equal(f3[0].code, 'no_room'); assert.match(f3[0].msg, /does not exist/); }); test('code-19: listeners are removed when the controller dies and when it is closed', () => { const { H, rc, ws } = connected(); assert.equal(H.docAdded, 1); assert.equal(H.winAdded, 1); ws.recv({ t: 'error', code: 'full', msg: 'x' }); // fatal assert.equal(H.docRemoved, 1); assert.equal(H.winRemoved, 1); const c2 = new H.NW.RemoteController({ pid: 'pidpidpid2', name: 'x', room: 'ABCD', url: 'ws://x/ws' }); c2.close(); assert.equal(H.docRemoved, 2); assert.equal(H.winRemoved, 2); c2.close(); // idempotent assert.equal(H.docRemoved, 2); assert.equal(rc.status, 'closed'); }); test('code-3: a controller that was closed while connecting never emits again (a late "joined" cannot take over a game)', () => { const H = harness(); const rc = new H.NW.RemoteController({ pid: 'pidpidpid1', name: 'Bob', room: null, map: 'open', url: 'ws://x/ws' }); const events = []; for (const e of ['joined', 'players', 'status', 'fatal', 'events']) rc.on(e, () => events.push(e)); rc.connect(); const ws = H.sockets[0]; ws.open(); assert.equal(ws.sent[0].t, 'join'); rc.close(); // (the user pressed Back / Play solo) assert.deepEqual(ws.sent.map((m) => m.t), ['join', 'leave'], 'the room that is being created is left again at once'); events.length = 0; ws.recv(joinedMsg(new TD.Sim({ map: 'open' }))); // the server's answer arrives anyway rc._onMsg(JSON.stringify(joinedMsg(new TD.Sim({ map: 'open' })))); // (even if the browser still delivered a frame already queued) ws.serverClose(1000); assert.deepEqual(events, []); assert.equal(rc.status, 'closed'); }); test('coop-5: Upgrade carries the level that is on screen, Next wave the wave it expects to start; explicit values are kept', () => { const { sim, rc, ws, H } = connected(); sim.gold = 5000; sim.cmd({ c: 'place', type: 'filter', x: 10, y: 8, by: 0 }); sim.cmd({ c: 'upgrade', id: 1 }); ws.recv(snapMsg(sim, true)); H.advance(500); rc.update(H.now); assert.equal(rc.view.towers[0].level, 2); rc.send({ c: 'upgrade', id: 1 }); rc.send({ c: 'wave' }); rc.send({ c: 'upgrade', id: 1, lv: 7 }); rc.send({ c: 'place', type: 'wall', x: 3, y: 3 }); rc.send({ c: 'upgrade', id: 99 }); // a tower this client does not know: no level to carry const cmds = ws.sent.filter((m) => m.t === 'cmd'); assert.deepEqual(cmds[0], { t: 'cmd', c: 'upgrade', id: 1, lv: 2 }); assert.deepEqual(cmds[1], { t: 'cmd', c: 'wave', n: rc.view.wave + 1 }); assert.equal(cmds[2].lv, 7); assert.equal(cmds[3].lv, undefined); assert.equal(cmds[3].n, undefined); assert.equal(cmds[4].lv, undefined); }); test('coop-5: solo too: a second "Next wave" in the same frame (a double tap) is stale, the next frame\'s is not', () => { const H = harness(); const lc = new H.NW.LocalController({ map: 'open' }); const rejects = []; lc.on('reject', (r) => rejects.push(r)); lc.update(1000); assert.equal(lc.send({ c: 'wave' }).ok, true); assert.equal(lc.send({ c: 'wave' }).reason, 'stale'); assert.equal(lc.sim.wave, 1); assert.deepEqual(rejects.map((r) => r.reason), ['stale']); lc.update(1016); assert.equal(lc.send({ c: 'wave' }).ok, true); assert.equal(lc.sim.wave, 2); });