towerdef/server/room.js
Claude faf0cfa603 Add co-op server, deploy docs, e2e suite and wire in the music tracks
- server/: Node (ws) static server + authoritative co-op rooms; dual-stack
  listen, proxy-aware client IP and Origin check, keep-alive pings, per-socket
  rate limits, graceful shutdown; 59 node:test tests
- docs/DEPLOY.md + deploy/netwall.service: Debian 13 LXC, systemd, nginx
  Proxy Manager walk-through, path prefix, troubleshooting
- e2e/: Playwright suite (smoke, touch, end flow, two-browser co-op incl.
  reconnect, 14-size layout matrix); npm run e2e
- Music: tracks.json now points at the uploaded theme/battle/boss/win/lose
  files; stingers fade out when a new game starts
- PAUSED indicator, refreshed icon

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
2026-10-09 19:57:27 +00:00

411 lines
16 KiB
JavaScript

'use strict';
/*
* Rooms: one authoritative Sim per room, two player slots, fixed-step tick loop and snapshot broadcast.
* A "conn" is the per-socket context object created in index.js ({ ws, player, room, dead, ... }); this file
* only touches conn.ws, conn.player and conn.room and never throws on a dead socket.
*/
const crypto = require('crypto');
const TD = require('../public/js/sim.js'); // fixed path on purpose: independent of publicDir
const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
const CMDS = new Set(['place', 'sell', 'upgrade', 'target', 'wave', 'auto', 'continue']);
const OPEN = 1; // WebSocket.OPEN
const LOOP_MS = 8; // global tick loop period
const MAX_CATCHUP_S = 0.25; // clamp one loop iteration (stalled event loop)
const STEP_BUDGET_NS = 20000000n; // never spend more than 20 ms stepping one room per iteration
const MARK_GAP_MS = 400;
const MAX_BUFFERED = 512 * 1024; // a socket this far behind is dropped; it reconnects and resumes
const MAX_MONSTER_LOAD = 1500; // monsters + queued spawns; refuse 'wave' beyond this (CPU/bandwidth guard)
const ALIAS_KEY = crypto.randomBytes(32); // per process; see Room.alias()
const nowMs = () => Number(process.hrtime.bigint() / 1000000n);
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
const finite = (v) => typeof v === 'number' && Number.isFinite(v);
const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
const round2 = (v) => Math.round(v * 100) / 100;
function sendRaw(conn, str) {
const ws = conn && conn.ws;
if (!ws || ws.readyState !== OPEN) return false;
try { ws.send(str); return true; } catch (e) { return false; }
}
class Room {
constructor(manager, code, mapId) {
this.manager = manager;
this.code = code;
this.sim = new TD.Sim({ map: mapId });
this.speed = 1;
this.paused = false;
this.seq = 0;
this.players = [null, null]; // slot -> player
this.acc = 0; // accumulated game seconds not yet stepped
this.lastNs = null; // hrtime of the previous loop iteration
this.nextSnapNs = 0n;
this.lastSentRev = this.sim.rev; // 'tw' is attached only when rev moves past this
this.destroyed = false;
this.createdAt = Date.now();
this.emptySince = null; // nowMs() when the last online player went away; null while somebody is online
}
log(msg) { this.manager.log('[' + this.code + '] ' + msg); }
// ---------------------------------------------------------------- players
onlinePlayers() { return this.players.filter((p) => p && p.conn); }
anyPlayers() { return this.players.some(Boolean); }
// A pid is the reconnect secret (whoever presents it takes over the slot), so it only ever goes to its owner.
// The other player appears under a stable alias: unguessable, different per room, useless as a pid.
alias(pid) {
return crypto.createHmac('sha256', ALIAS_KEY).update(this.code + ':' + pid).digest('base64url').slice(0, 22);
}
// The player list as `viewer` may see it: their own entry carries their pid, everyone else's an alias.
publicPlayers(viewer) {
const out = [];
for (const p of this.players) {
if (p) out.push({ pid: p === viewer ? p.pid : p.alias, slot: p.slot, name: p.name, host: p.host, online: !!p.conn });
}
return out;
}
send(player, obj) { return !!player && sendRaw(player.conn, JSON.stringify(obj)); }
// Same string to everyone online (optionally except one conn).
broadcast(obj, exceptConn) {
const str = JSON.stringify(obj);
for (const p of this.players) if (p && p.conn && p.conn !== exceptConn) sendRaw(p.conn, str);
}
// One message per recipient (each sees their own pid), to everyone online except `exceptConn`.
broadcastPlayers(exceptConn) {
for (const p of this.players) {
if (p && p.conn && p.conn !== exceptConn) this.send(p, { t: 'players', players: this.publicPlayers(p) });
}
}
stateMsg(extra) {
return Object.assign({ t: 'state', state: this.sim.fullState(), snap: this.sim.snapshot(), speed: this.speed, paused: this.paused }, extra);
}
joinedMsg(player, resumed) {
return {
t: 'joined', room: this.code, resumed,
you: { pid: player.pid, slot: player.slot, host: player.host },
players: this.publicPlayers(player),
state: this.sim.fullState(), snap: this.sim.snapshot(), speed: this.speed, paused: this.paused,
};
}
// Binds `conn` to a slot. Returns { player, resumed } or null when both slots belong to other pids.
join(pid, name, conn) {
let p = this.players.find((x) => x && x.pid === pid);
let resumed = false;
if (p) {
resumed = true;
if (p.graceTimer) { clearTimeout(p.graceTimer); p.graceTimer = null; }
const old = p.conn;
p.conn = conn;
p.name = name;
if (old && old !== conn) { // a second tab / a reconnect racing the dead socket
old.player = null; old.room = null; old.dead = true;
try { old.ws.close(4001, 'replaced by a newer connection'); } catch (e) { /* already closing */ }
}
} else {
const slot = this.players.indexOf(null);
if (slot < 0) return null;
p = {
pid, alias: this.alias(pid), slot, name, host: !this.players.some((x) => x && x.host),
conn, cursor: null, lastMarkAt: -Infinity, graceTimer: null,
};
this.players[slot] = p;
}
p.cursor = null;
this.touchPresence();
return { player: p, resumed };
}
// Keeps `emptySince` in step with who is online (the manager evicts the longest-abandoned room first).
touchPresence() {
if (this.onlinePlayers().length) this.emptySince = null;
else if (this.emptySince === null) this.emptySince = nowMs();
}
// The socket of `conn` closed (not a deliberate leave): keep the slot for graceMs.
disconnect(conn) {
const p = conn.player;
if (this.destroyed || !p || p.conn !== conn) return;
p.conn = null;
p.cursor = null;
this.touchPresence();
this.log(p.name + ' (slot ' + p.slot + ') disconnected; holding the slot for ' + this.manager.graceMs + ' ms');
p.graceTimer = setTimeout(() => { p.graceTimer = null; this.removePlayer(p, 'grace expired'); }, this.manager.graceMs);
this.broadcastPlayers();
}
// Frees the slot for good, migrates the host, deletes the room when nobody is left.
removePlayer(p, why) {
if (this.destroyed || this.players[p.slot] !== p) return;
if (p.graceTimer) { clearTimeout(p.graceTimer); p.graceTimer = null; }
this.players[p.slot] = null;
p.conn = null;
p.cursor = null;
this.log(p.name + ' (slot ' + p.slot + ') removed: ' + why);
if (!this.anyPlayers()) { this.manager.deleteRoom(this, 'empty'); return; }
if (p.host) {
const next = this.players.find(Boolean);
next.host = true;
this.log('host is now ' + next.name + ' (slot ' + next.slot + ')');
}
this.touchPresence();
this.broadcastPlayers();
}
leave(conn) {
const p = conn.player;
if (!p || p.conn !== conn) return;
conn.player = null; conn.room = null;
this.removePlayer(p, 'left');
}
// ---------------------------------------------------------------- messages after join
// Returns false when the message is malformed (the caller counts those).
handleMessage(p, msg) {
switch (msg.t) {
case 'cmd': return this.handleCmd(p, msg);
case 'ctl': return this.handleCtl(msg);
case 'cursor': return this.handleCursor(p, msg);
case 'mark': return this.handleMark(p, msg);
case 'rtt':
if (!finite(msg.ts) && !(typeof msg.ts === 'string' && msg.ts.length <= 32)) return false;
this.send(p, { t: 'rtt', ts: msg.ts });
return true;
case 'sync': this.send(p, this.stateMsg()); return true;
case 'newgame': return this.handleNewgame(p, msg);
default: return false;
}
}
reject(p, c, reason, msg) {
const out = { t: 'reject', c, reason };
if (msg) {
if (finite(msg.x)) out.x = msg.x;
if (finite(msg.y)) out.y = msg.y;
if (finite(msg.id)) out.id = msg.id;
}
this.send(p, out);
}
handleCmd(p, msg) {
const c = msg.c;
if (typeof c !== 'string' || !CMDS.has(c)) return false;
const sim = this.sim;
if (c === 'wave' && sim.monsters.length + sim.spawnQ.length > MAX_MONSTER_LOAD) {
this.reject(p, c, 'busy', msg);
return true;
}
// Whitelisted fields only; `by` always comes from the socket's slot, never from the client.
const cmd = { c, type: msg.type, x: msg.x, y: msg.y, id: msg.id, mode: msg.mode, v: msg.v, by: p.slot };
let r;
try { r = sim.cmd(cmd); } catch (e) { this.log('sim.cmd threw: ' + (e && e.stack || e)); r = { ok: false, reason: 'error' }; }
if (!r || !r.ok) this.reject(p, c, (r && r.reason) || 'error', msg);
return true;
}
handleCtl(msg) {
if (msg.c === 'pause' && typeof msg.v === 'boolean') { this.paused = msg.v; return true; }
if (msg.c === 'speed' && (msg.v === 1 || msg.v === 2 || msg.v === 3)) { this.speed = msg.v; return true; }
return false;
}
boardPoint(msg) {
const b = this.sim.board;
return [round2(clamp(msg.x, 0, b.cols)), round2(clamp(msg.y, 0, b.rows))];
}
handleCursor(p, msg) {
if (msg.x === null) { p.cursor = null; return true; }
if (!finite(msg.x) || !finite(msg.y)) return false;
p.cursor = this.boardPoint(msg);
return true;
}
handleMark(p, msg) {
if (!finite(msg.x) || !finite(msg.y)) return false;
const now = nowMs(); // monotonic: immune to wall-clock steps
if (now - p.lastMarkAt < MARK_GAP_MS) return true; // rate limited: dropped silently
p.lastMarkAt = now;
const pt = this.boardPoint(msg);
this.broadcast({ t: 'mark', slot: p.slot, x: pt[0], y: pt[1] });
return true;
}
handleNewgame(p, msg) {
if (!p.host) { this.reject(p, 'newgame', 'not_host'); return true; }
const map = msg.map === undefined || msg.map === null ? this.sim.mapId : msg.map;
if (typeof map !== 'string' || !hasOwn(TD.MAPS, map)) { this.reject(p, 'newgame', 'bad_map'); return true; }
this.sim = new TD.Sim({ map });
this.speed = 1; this.paused = false; this.acc = 0;
this.lastSentRev = this.sim.rev; // the 'state' below carries the tower list
this.log('new game on map ' + map + ' started by ' + p.name);
this.broadcast(this.stateMsg({ newgame: true }));
return true;
}
// ---------------------------------------------------------------- loop
// Called every LOOP_MS by the manager with process.hrtime.bigint().
step(now) {
const last = this.lastNs;
this.lastNs = now;
const online = this.onlinePlayers().length > 0;
const sim = this.sim;
if (!online || this.paused || sim.state !== 'playing' || last === null) {
this.acc = 0; // no catch-up after a pause / an empty room
} else {
let dt = Number(now - last) / 1e9;
if (dt > MAX_CATCHUP_S) dt = MAX_CATCHUP_S;
this.acc += dt * this.speed;
let n = 0;
const t0 = process.hrtime.bigint();
while (this.acc >= TD.STEP) {
sim.tick(TD.STEP);
this.acc -= TD.STEP;
if ((++n & 7) === 0 && process.hrtime.bigint() - t0 > STEP_BUDGET_NS) { // overloaded: run slower, do not freeze the server
this.acc = Math.min(this.acc, TD.STEP);
break;
}
}
}
if (!online) { this.nextSnapNs = now; return; }
if (now >= this.nextSnapNs) {
this.broadcastSnap();
this.nextSnapNs += this.manager.snapPeriodNs;
if (this.nextSnapNs <= now) this.nextSnapNs = now + this.manager.snapPeriodNs;
}
}
// Serialised once, the same string goes to every online player.
broadcastSnap() {
const sim = this.sim;
const cur = [];
for (const p of this.players) if (p && p.conn && p.cursor) cur.push([p.slot, p.cursor[0], p.cursor[1]]);
const msg = Object.assign({ t: 'snap', seq: ++this.seq }, sim.snapshot(), {
ev: sim.drainEvents(), cur, pa: this.paused ? 1 : 0, sp: this.speed,
});
if (sim.rev !== this.lastSentRev) { msg.tw = sim.towerList(); this.lastSentRev = sim.rev; }
const str = JSON.stringify(msg);
for (const p of this.players) {
if (!p || !p.conn) continue;
const ws = p.conn.ws;
if (ws.bufferedAmount > MAX_BUFFERED) { // hopelessly behind: dropping a snap could lose 'tw'/'ev'
this.log(p.name + ' is too slow (' + ws.bufferedAmount + ' bytes queued); dropping the connection');
try { ws.terminate(); } catch (e) { /* gone */ }
continue;
}
sendRaw(p.conn, str);
}
}
// Something threw inside the loop: tell everyone and drop the room rather than the whole process.
crash(err) {
this.log('room crashed: ' + (err && err.stack || err));
for (const p of this.players) {
if (!p || !p.conn) continue;
sendRaw(p.conn, JSON.stringify({ t: 'error', code: 'server_error', msg: 'internal error' }));
try { p.conn.ws.close(1011, 'internal error'); } catch (e) { /* gone */ }
}
this.manager.deleteRoom(this, 'crashed');
}
destroy() {
this.destroyed = true;
for (const p of this.players) {
if (p && p.graceTimer) { clearTimeout(p.graceTimer); p.graceTimer = null; }
}
}
}
class RoomManager {
constructor(opts) {
this.rooms = new Map();
this.maxRooms = opts.maxRooms;
this.graceMs = opts.graceMs;
this.snapPeriodNs = BigInt(Math.max(1, Math.round(1e9 / opts.snapshotHz)));
this.log = opts.log;
this.timer = null;
this.closed = false;
}
newCode() {
for (let tries = 0; tries < 200; tries++) {
let c = '';
for (let i = 0; i < 4; i++) c += CODE_ALPHABET[crypto.randomInt(CODE_ALPHABET.length)];
if (!this.rooms.has(c)) return c;
}
return null;
}
get(code) { return this.rooms.get(code); }
// The room nobody has been online in for the longest time, or null.
abandonedRoom() {
let oldest = null;
for (const r of this.rooms.values()) if (r.emptySince !== null && (oldest === null || r.emptySince < oldest.emptySince)) oldest = r;
return oldest;
}
// null when the room limit is reached. A full table first drops a room that nobody is online in (it is only
// being held for its grace period): otherwise one client could fill all slots for a minute at a time by
// creating rooms and closing the sockets, which costs nothing and is not limited by any per-IP socket cap.
create(mapId) {
if (this.closed) return null;
if (this.rooms.size >= this.maxRooms) {
const victim = this.abandonedRoom();
if (!victim) return null;
this.deleteRoom(victim, 'evicted: the server is full and nobody is online in it');
}
const code = this.newCode();
if (!code) return null;
const room = new Room(this, code, mapId);
this.rooms.set(code, room);
room.log('created (map ' + mapId + '); ' + this.rooms.size + ' room(s)');
this.startLoop();
return room;
}
deleteRoom(room, why) {
if (this.rooms.get(room.code) !== room) return;
room.destroy();
this.rooms.delete(room.code);
room.log('deleted (' + why + '); ' + this.rooms.size + ' room(s) left');
if (!this.rooms.size) this.stopLoop();
}
startLoop() {
if (this.timer || this.closed) return;
this.timer = setInterval(() => this.tick(), LOOP_MS);
}
stopLoop() {
if (this.timer) { clearInterval(this.timer); this.timer = null; }
}
tick() {
const now = process.hrtime.bigint();
for (const room of Array.from(this.rooms.values())) {
try { room.step(now); } catch (err) { room.crash(err); }
}
}
close() {
this.closed = true;
this.stopLoop();
for (const room of Array.from(this.rooms.values())) room.destroy();
this.rooms.clear();
}
}
module.exports = { Room, RoomManager, CODE_ALPHABET, CMDS, MAX_MONSTER_LOAD, MAX_BUFFERED };