Begin Wyrm from the game kit

This commit is contained in:
Eric Wagoner committed 2026-10-26 16:08:50 -04:00
commit d91b95cfab
73 files changed
+10509

No files matched your search

+408
View File
@@ -0,0 +1,408 @@
// The front door for games between people. Plain HTTP for actions, a
// websocket only to say "something changed, fetch the view again".
//
// POST /api/rooms {name, size?, options?} create a room and take seat A; options are the game's table choices
// GET /api/rooms/:id?token= the view for that seat; without a token, the gallery's view
// POST /api/rooms/:id/join {name} take the next seat
// POST /api/rooms/:id/bot {token} the host seats a bot, before the game begins
// POST /api/rooms/:id/unseat {token, seat} the host sends a bot away before the game begins
// POST /api/rooms/:id/begin {token} the host begins with the players seated so far
// POST /api/rooms/:id/rank {token, ranking} a seat ranks the table's choices, best first, where the table asks for it
// POST /api/rooms/:id/turn {token, input} this seat's move
// POST /api/rooms/:id/hurry {token} a table the bots are playing on plays the rest at once
// POST /api/rooms/:id/say {token, text, to?} table talk, from a seat to the whole room, or privately to the seats in `to`;
// {name, text} or from the gallery, signed, when the host allows it
// POST /api/rooms/:id/gallery {token, on} the host lets the Peanut Gallery talk, or hushes it
// POST /api/rooms/:id/challenge {token} call the keeper to a held seat; their phone rings
// POST /api/rooms/:id/rematch {token} a finished table opens the next one
// POST /api/rooms/:id/transfer {token} mint a phrase that carries this seat to another device
// POST /api/rooms/:id/phrase {token, seat} the host mints one for another person's seat, which re-seats it when claimed
// POST /api/rooms/:id/standin {token, seat} the host gives a person's seat to a bot for the rest of the game
// POST /api/transfer {phrase} claim one
// POST /api/rooms/:id/report {token?, happened, expected} a report to the keeper, pinned to the round
// POST /api/reports/:id/image <image bytes> a screenshot for a report just filed
// POST /api/reports/:id/answer {roomId, token, text} your word under the keeper's reply
// POST /api/reports/mine {seats: [{roomId, token}]} your reports and the keeper's replies
// GET /api/tally what the ledgers add up to, for the hall
// WS /ws?room=:id&token= {type:"update", seq} whenever the room changes; without a token,
// a seat in the Peanut Gallery, counted for the table
//
// Caddy serves the static site and proxies /api and /ws here. The keeper's
// door answers only on the host itself, and only to the key in KEEPER_KEY_FILE
// (deploy/wyrm-reseat.sh sends it):
//
// GET /keeper/rooms/:id who sits at the table, and when each person last moved or spoke
// POST /keeper/rooms/:id/reseat {seat} a new token for a player locked out, as a link to send them
// POST /keeper/rooms/:id/say {text} a word from the keeper in the table's talk
import * as Sentry from '@sentry/node';
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { timingSafeEqual } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { dirname } from 'node:path';
import { WebSocketServer, WebSocket } from 'ws';
import { game } from '../../src/lib/game';
import { RateLimit } from './ratelimit';
import { IMAGE_MAX_BYTES, Reports } from './reports';
import { RoomError, Rooms, SPECTATOR } from './rooms';
import { Store } from './store';
import { Tallies } from './tally';
const PORT = Number(process.env.PORT ?? '8791');
const HOST = process.env.HOST ?? '127.0.0.1';
const DATA_DIR = process.env.DATA_DIR ?? '../data/rooms';
const PUBLIC_URL = (process.env.PUBLIC_URL ?? 'https://wyrm.kestrelsnest.social').replace(/\/$/, '');
/** The keeper of the site, whom a table may call to a seat, and where they sleep. */
const KEEPER = process.env.KEEPER ?? 'the keeper';
const KEEPER_TZ = process.env.KEEPER_TZ ?? 'America/New_York';
/** The keeper's key, readable by root and this game's user alone, so another service on the host cannot use the keeper's door. Absent, the door stays shut. */
const KEEPER_KEY_FILE = process.env.KEEPER_KEY_FILE ?? '/etc/wyrm/keeper.key';
const BODY_LIMIT = 16 * 1024;
// Errors go to Sentry when a DSN is set; the SDK drops them otherwise.
if (process.env.SENTRY_DSN) {
Sentry.init({ dsn: process.env.SENTRY_DSN, environment: 'production', tracesSampleRate: 0 });
}
process.on('unhandledRejection', (reason) => {
console.error(reason);
Sentry.captureException(reason);
});
const store = new Store(DATA_DIR);
const rooms = new Rooms(game, store, { name: KEEPER, zone: KEEPER_TZ });
/** Reports live beside the room ledgers, not among them. */
const reports = new Reports(dirname(DATA_DIR));
const tallies = new Tallies(game, store);
/** Opening rooms and taking seats are open to anyone; a script gets a few dozen an hour, not thousands. */
const doors = new RateLimit(40, 60 * 60 * 1000);
/** Table talk: a lively table says a few lines a minute, not hundreds. */
const voices = new RateLimit(240, 60 * 60 * 1000);
/** Reports, answers and pictures: a few an hour from one address; each rings the keeper's phone. */
const desk = new RateLimit(6, 60 * 60 * 1000);
/** The gallery talks under a tighter rein than the table: no seat, no token, one address. */
const galleryVoices = new RateLimit(30, 10 * 60 * 1000);
/** Calls to the keeper: a real person's phone rings for each. */
const bells = new RateLimit(3, 60 * 60 * 1000);
/** Claims on transfer phrases: a phrase is guessed, not brute-forced. */
const claims = new RateLimit(10, 10 * 60 * 1000);
const MAX_AUDIENCE = 30;
/** How often each socket is asked to answer; one silent through a whole round is a browser gone, and is closed. */
const PING_MS = Number(process.env.PING_MS ?? 30_000);
const IDLE_ROOM_MS = 7 * 24 * 60 * 60 * 1000;
setInterval(() => {
const n = rooms.evictIdle(IDLE_ROOM_MS);
doors.prune();
voices.prune();
desk.prune();
galleryVoices.prune();
bells.prune();
claims.prune();
if (n) console.log(`evicted ${n} idle room${n === 1 ? '' : 's'} from memory; ${rooms.loaded} loaded`);
}, 60 * 60 * 1000).unref();
/** The visitor's address as Caddy reports it, or the socket's when unproxied. */
function clientOf(req: IncomingMessage): string {
const forwarded = req.headers['x-forwarded-for'];
const first = (Array.isArray(forwarded) ? forwarded[0] : forwarded)?.split(',')[0].trim();
return first || req.socket.remoteAddress || '?';
}
function send(res: ServerResponse, status: number, body: unknown): void {
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
res.end(status === 204 ? undefined : JSON.stringify(body));
}
function readBytes(req: IncomingMessage, limit: number, tooBig: string): Promise<Buffer> {
return new Promise((resolve, reject) => {
const declared = Number(req.headers['content-length'] ?? 0);
if (declared > limit) {
reject(new RoomError(tooBig, 413));
req.destroy();
return;
}
let size = 0;
const chunks: Buffer[] = [];
req.on('data', (chunk: Buffer) => {
size += chunk.length;
if (size > limit) {
reject(new RoomError(tooBig, 413));
req.destroy();
return;
}
chunks.push(chunk);
});
req.on('end', () => resolve(Buffer.concat(chunks)));
req.on('error', reject);
});
}
async function readBody(req: IncomingMessage): Promise<Record<string, unknown>> {
const bytes = await readBytes(req, BODY_LIMIT, 'That is more than a move needs.');
if (bytes.length === 0) return {};
try {
return JSON.parse(bytes.toString('utf8')) as Record<string, unknown>;
} catch {
throw new RoomError('The request was not JSON.');
}
}
/** A report, an answer, or a call to the table is worth waking the keeper for; the desk's own replies are not. */
function ringBell(title: string, detail: { fingerprint: string[]; tags: Record<string, string>; extra: Record<string, unknown> }): void {
Sentry.captureMessage(title, { level: 'error', ...detail });
}
/** The seats a browser claims, kept to the ones its tokens prove. */
function provenSeats(raw: unknown): { roomId: string; seat: string }[] {
const claims = Array.isArray(raw) ? raw.slice(0, 50) : [];
const proven: { roomId: string; seat: string }[] = [];
for (const claim of claims) {
if (typeof claim !== 'object' || claim === null) continue;
const c = claim as Record<string, unknown>;
try {
const room = rooms.get(String(c.roomId ?? ''));
proven.push({ roomId: room.id, seat: rooms.seatOf(room, typeof c.token === 'string' ? c.token : undefined).id });
} catch {
// A seat this browser cannot prove is not its business.
}
}
return proven;
}
const DESK_BUSY = 'The desk has plenty from here for now; more in an hour.';
async function handleReports(req: IncomingMessage, res: ServerResponse, parts: string[]): Promise<void> {
if (req.method !== 'POST') throw new RoomError('Not here.', 404);
if (parts[2] === 'mine' && parts.length === 3) {
const body = await readBody(req);
return send(res, 200, { reports: reports.mine(provenSeats(body.seats)) });
}
const report = reports.find(parts[2] ?? '');
if (!report) throw new RoomError('No such report.', 404);
if (parts[3] === 'image') {
if (!desk.allow(clientOf(req))) throw new RoomError(DESK_BUSY, 429);
reports.attachImage(report, await readBytes(req, IMAGE_MAX_BYTES, 'A picture of 2.5 MB at most.'));
return send(res, 204, {});
}
if (parts[3] === 'answer') {
if (!desk.allow(clientOf(req))) throw new RoomError(DESK_BUSY, 429);
const body = await readBody(req);
const room = rooms.get(String(body.roomId ?? report.roomId));
const seat = rooms.seatOf(room, typeof body.token === 'string' ? body.token : undefined);
if (room.id !== report.roomId) throw new RoomError('That report is not yours to answer.', 403);
reports.answer(report, seat, body.text);
ringBell(`${seat.name} answers on report ${report.id} (${room.id}): ${String(body.text ?? '').slice(0, 100)}`, {
fingerprint: ['report-answer', report.id, new Date().toISOString()],
tags: { room: room.id, report: report.id, player: seat.name },
extra: { text: body.text, link: `${PUBLIC_URL}/join/${room.id}` }
});
return send(res, 200, { ok: true });
}
throw new RoomError('Not here.', 404);
}
/** The key the keeper's door asks for, read on each knock so a key written after the server started is honoured. */
function keeperKeyGiven(req: IncomingMessage): boolean {
let key: Buffer;
try {
key = Buffer.from(readFileSync(KEEPER_KEY_FILE, 'utf8').trim());
} catch {
return false;
}
const given = Buffer.from(String(req.headers['x-keeper-key'] ?? ''));
return key.length > 0 && given.length === key.length && timingSafeEqual(given, key);
}
/**
* The keeper's door. Caddy proxies only /api and /ws, so it is reached from the host alone; a request Caddy
* forwarded is turned away besides, and so is one without the keeper's key.
*/
async function handleKeeper(req: IncomingMessage, res: ServerResponse, parts: string[]): Promise<void> {
if (req.headers['x-forwarded-for'] || parts[1] !== 'rooms' || !keeperKeyGiven(req)) throw new RoomError('Not here.', 404);
const room = rooms.get(parts[2] ?? '');
if (parts.length === 3 && req.method === 'GET') return send(res, 200, { roomId: room.id, started: !!room.state, seats: rooms.seatsForKeeper(room) });
if (parts[3] === 'reseat' && parts.length === 4 && req.method === 'POST') {
const body = await readBody(req);
const { seat, token } = rooms.reseat(room, body.seat);
// The token rides the fragment, which the browser keeps to itself: it reaches neither Caddy's log nor this server.
return send(res, 200, { name: seat.name, link: `${PUBLIC_URL}/join/${room.id}#seat=${seat.id}.${token}` });
}
if (parts[3] === 'say' && parts.length === 4 && req.method === 'POST') {
const body = await readBody(req);
rooms.keeperSays(room, body.text);
return send(res, 204, {});
}
throw new RoomError('Not here.', 404);
}
async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
const url = new URL(req.url ?? '/', 'http://localhost');
const parts = url.pathname.split('/').filter(Boolean);
if (parts[0] === 'keeper') return handleKeeper(req, res, parts);
if (parts[0] === 'api' && parts[1] === 'reports') return handleReports(req, res, parts);
if (parts[0] === 'api' && parts[1] === 'tally' && parts.length === 2 && req.method === 'GET') return send(res, 200, tallies.get());
if (parts[0] === 'api' && parts[1] === 'transfer' && parts.length === 2 && req.method === 'POST') {
if (!claims.allow(clientOf(req))) throw new RoomError('Too many claims from here just now; try again later.', 429);
const body = await readBody(req);
return send(res, 200, rooms.claim(body.phrase));
}
if (parts[0] !== 'api' || parts[1] !== 'rooms') throw new RoomError('Not here.', 404);
if (parts.length === 2 && req.method === 'POST') {
if (!doors.allow(clientOf(req))) throw new RoomError('Too many rooms opened from here just now; try again later.', 429);
const body = await readBody(req);
const { room, seat, token } = rooms.create(String(body.name ?? ''), Number(body.size ?? game.minSeats), body.options);
return send(res, 201, { seat: seat.id, token, view: rooms.view(room, seat.id) });
}
const room = rooms.get(parts[2] ?? '');
const action = parts[3];
if (!action && req.method === 'GET') {
const token = url.searchParams.get('token');
if (!token) return send(res, 200, rooms.view(room, SPECTATOR));
return send(res, 200, rooms.view(room, rooms.seatOf(room, token).id));
}
if (req.method !== 'POST') throw new RoomError('Not here.', 404);
const body = await readBody(req);
const token = typeof body.token === 'string' && body.token ? body.token : undefined;
if (action === 'join') {
if (!doors.allow(clientOf(req))) throw new RoomError('Too many seats taken from here just now; try again later.', 429);
const { seat, token: minted } = rooms.join(room, String(body.name ?? ''));
return send(res, 200, { seat: seat.id, token: minted, view: rooms.view(room, seat.id) });
}
if (action === 'bot') {
rooms.addBot(room, token);
return send(res, 200, rooms.view(room, rooms.seatOf(room, token).id));
}
if (action === 'unseat') {
rooms.unseat(room, token, body.seat);
return send(res, 200, rooms.view(room, rooms.seatOf(room, token).id));
}
if (action === 'begin') {
rooms.begin(room, token);
return send(res, 200, rooms.view(room, rooms.seatOf(room, token).id));
}
if (action === 'rank') {
rooms.rank(room, token, body.ranking);
return send(res, 200, rooms.view(room, rooms.seatOf(room, token).id));
}
if (action === 'hurry') {
rooms.hurry(room, token);
return send(res, 200, rooms.view(room, rooms.seatOf(room, token).id));
}
if (action === 'turn') {
rooms.submit(room, token, body.input, body.resolved);
return send(res, 200, rooms.view(room, rooms.seatOf(room, token).id));
}
if (action === 'say') {
if (!token) {
if (!galleryVoices.allow(clientOf(req))) throw new RoomError('The gallery has said plenty from here for now.', 429);
rooms.sayFromGallery(room, body.name, body.text);
return send(res, 200, rooms.view(room, SPECTATOR));
}
if (!voices.allow(clientOf(req))) throw new RoomError('The table has heard enough from here for now.', 429);
rooms.say(room, token, body.text, body.to);
return send(res, 200, rooms.view(room, rooms.seatOf(room, token).id));
}
if (action === 'gallery') {
rooms.setGalleryTalk(room, token, body.on === true);
return send(res, 200, rooms.view(room, rooms.seatOf(room, token).id));
}
if (action === 'challenge') {
if (!bells.allow(clientOf(req))) throw new RoomError('The keeper has been called enough from here for one hour.', 429);
const seat = rooms.seatOf(room, token);
rooms.callKeeper(room, token, KEEPER);
const link = `${PUBLIC_URL}/join/${room.id}`;
// One issue per table, so each call rings once, with the door in the message.
ringBell(`${seat.name} challenges ${KEEPER} to a game — ${link}`, {
fingerprint: ['challenge', room.id],
tags: { room: room.id, challenger: seat.name },
extra: { link, players: room.seats.map((s) => s.name).join(', ') }
});
return send(res, 200, rooms.view(room, seat.id));
}
if (action === 'rematch') {
const next = rooms.rematch(room, token);
return send(res, next.created ? 201 : 200, { roomId: next.roomId, seat: next.seat?.id ?? null, token: next.token, created: next.created });
}
if (action === 'transfer') {
return send(res, 200, rooms.transfer(room, token));
}
if (action === 'phrase') {
return send(res, 200, rooms.hostPhrase(room, token, body.seat));
}
if (action === 'standin') {
rooms.standIn(room, token, body.seat);
return send(res, 200, rooms.view(room, rooms.seatOf(room, token).id));
}
if (action === 'report') {
if (!desk.allow(clientOf(req))) throw new RoomError(DESK_BUSY, 429);
const seat = token ? rooms.seatOf(room, token) : null;
const turn = room.state ? game.turn(room.state) : null;
const report = reports.file(room, seat, turn, body.happened, body.expected);
ringBell(`Report from ${report.player} in ${room.id}: ${report.happened.slice(0, 100)}`, {
fingerprint: ['report', report.id],
tags: { room: room.id, report: report.id, player: report.player },
extra: { happened: report.happened, expected: report.expected, turn: report.turn, seq: report.seq, link: `${PUBLIC_URL}/join/${room.id}` }
});
return send(res, 201, { id: report.id });
}
throw new RoomError('Not here.', 404);
}
const server = createServer((req, res) => {
handle(req, res).catch((err: unknown) => {
if (err instanceof RoomError) return send(res, err.status, { error: err.message });
console.error(err);
Sentry.captureException(err, { extra: { url: req.url, method: req.method } });
send(res, 500, { error: 'Something went wrong on the server.' });
});
});
// The socket only ever speaks to the browser; anything the browser sends is ignored, so it may send almost nothing.
const wss = new WebSocketServer({ noServer: true, maxPayload: 1024 });
server.on('upgrade', (req, socket, head) => {
const url = new URL(req.url ?? '/', 'http://localhost');
if (url.pathname !== '/ws') return socket.destroy();
let seatId: string;
let room: ReturnType<typeof rooms.get>;
try {
room = rooms.get(url.searchParams.get('room') ?? '');
const token = url.searchParams.get('token');
seatId = token ? rooms.seatOf(room, token).id : SPECTATOR;
if (seatId === SPECTATOR && rooms.audience(room) >= MAX_AUDIENCE) throw new RoomError('The gallery is full.', 429);
} catch {
return socket.destroy();
}
wss.handleUpgrade(req, socket, head, (ws: WebSocket) => {
const onChange = (changed: ReturnType<typeof rooms.get>) => {
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: 'update', seq: changed.seq }));
};
const unsubscribe = seatId === SPECTATOR ? rooms.watch(room, onChange) : rooms.subscribe(room.id, onChange);
ws.on('close', unsubscribe);
answered.set(ws, true);
ws.on('pong', () => answered.set(ws, true));
// A socket's own error (a message over the limit, a malformed frame) closes that socket, never the server.
ws.on('error', () => ws.terminate());
});
});
/**
* A browser that died without closing (a crashed tab, a sleeping laptop, a dropped network) leaves its socket
* open until TCP gives up, counted in the gallery all the while. The protocol's own ping, which every browser
* answers by itself, finds it within two rounds.
*/
const answered = new WeakMap<WebSocket, boolean>();
setInterval(() => {
for (const ws of wss.clients) {
if (!answered.get(ws)) {
ws.terminate();
continue;
}
answered.set(ws, false);
ws.ping();
}
}, PING_MS).unref();
server.listen(PORT, HOST, () => {
console.log(`wyrm server listening on http://${HOST}:${PORT}, rooms in ${DATA_DIR}`);
});
+31
View File
@@ -0,0 +1,31 @@
// A sliding-window count per key, for the doors a stranger can knock on.
export class RateLimit {
private hits = new Map<string, number[]>();
constructor(
private limit: number,
private windowMs: number
) {}
/** True if the key may act now; the act is recorded when it is allowed. */
allow(key: string, now = Date.now()): boolean {
const since = now - this.windowMs;
const recent = (this.hits.get(key) ?? []).filter((t) => t > since);
if (recent.length >= this.limit) {
this.hits.set(key, recent);
return false;
}
recent.push(now);
this.hits.set(key, recent);
if (this.hits.size > 10000) this.prune(now);
return true;
}
prune(now = Date.now()): void {
const since = now - this.windowMs;
for (const [key, times] of this.hits) {
if (!times.some((t) => t > since)) this.hits.delete(key);
}
}
}
+132
View File
@@ -0,0 +1,132 @@
// The reports desk: what a player says went wrong, pinned to the room and
// the turn so the moment can be replayed. One JSONL file beside the room
// ledgers; replies from the keeper and answers from the player fold onto
// the report they name, and a screenshot sits in a folder next to it.
import { randomBytes } from 'node:crypto';
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { SeatId } from '../../src/lib/game/spec';
import type { Report } from '../../src/lib/net/view';
import { RoomError, type Room, type Seat } from './rooms';
const TEXT_MAX = 2000;
export const IMAGE_MAX_BYTES = 2_500_000;
/** How long after filing a picture may still be attached. */
const IMAGE_WINDOW_MS = 60 * 60 * 1000;
function cleanText(raw: unknown): string {
return String(raw ?? '')
.replace(/[\u0000-\u0009\u000b-\u001f\u007f]/g, ' ')
.trim()
.slice(0, TEXT_MAX);
}
export class Reports {
private path: string;
private imageDir: string;
constructor(dir: string) {
mkdirSync(dir, { recursive: true });
this.path = join(dir, 'feedback.jsonl');
this.imageDir = join(dir, 'feedback-images');
}
private append(entry: Record<string, unknown>): void {
appendFileSync(this.path, JSON.stringify(entry) + '\n');
}
read(): Report[] {
if (!existsSync(this.path)) return [];
const reports = new Map<string, Report>();
for (const raw of readFileSync(this.path, 'utf8').split('\n')) {
if (!raw.trim()) continue;
let line: Record<string, unknown>;
try {
line = JSON.parse(raw) as Record<string, unknown>;
} catch {
continue;
}
if (typeof line.reportId === 'string') {
const report = reports.get(line.reportId);
if (!report) continue;
if (typeof line.image === 'string') report.image = line.image;
else if (line.from === 'player') report.thread.push({ at: String(line.at ?? ''), text: String(line.text ?? ''), from: 'player' });
else report.thread.push({ at: String(line.at ?? ''), text: String(line.text ?? ''), from: 'desk', status: String(line.status ?? 'open') });
continue;
}
if (typeof line.id !== 'string') continue;
reports.set(line.id, {
id: line.id,
at: String(line.at ?? ''),
roomId: String(line.roomId ?? ''),
player: String(line.player ?? '?'),
seat: typeof line.seat === 'string' ? line.seat : null,
turn: typeof line.turn === 'number' ? line.turn : null,
seq: Number(line.seq ?? 0),
happened: String(line.happened ?? ''),
expected: String(line.expected ?? ''),
thread: []
});
}
return [...reports.values()];
}
find(id: string): Report | undefined {
return this.read().find((r) => r.id === id);
}
/** File a report from a seat, or from the gallery when there is none, pinned to the round being written. */
file(room: Room<unknown>, seat: Seat | null, turn: number | null, rawHappened: unknown, rawExpected: unknown): Report {
const happened = cleanText(rawHappened);
if (!happened) throw new RoomError('Say what happened.');
const report: Report = {
id: randomBytes(4).toString('hex'),
at: new Date().toISOString(),
roomId: room.id,
player: seat?.name ?? '(gallery)',
seat: seat?.id ?? null,
turn,
seq: room.seq,
happened,
expected: cleanText(rawExpected),
thread: []
};
const { thread: _thread, ...line } = report;
this.append(line);
return report;
}
/** The player's word under the keeper's reply; only the seat that filed it may answer. */
answer(report: Report, seat: Seat, rawText: unknown): void {
if (report.seat !== seat.id) throw new RoomError('That report is not yours to answer.', 403);
const text = cleanText(rawText);
if (!text) throw new RoomError('Say something.');
this.append({ reportId: report.id, from: 'player', player: seat.name, text, at: new Date().toISOString() });
}
/** One picture per report, soon after filing, a PNG, JPEG or WebP by its own first bytes. */
attachImage(report: Report, body: Buffer): string {
if (report.image) throw new RoomError('That report has its picture.', 409);
if (Date.now() - Date.parse(report.at) > IMAGE_WINDOW_MS) throw new RoomError('Too late for a picture.', 410);
if (body.length > IMAGE_MAX_BYTES) throw new RoomError('A picture of 2.5 MB at most.', 413);
const ext = body.subarray(0, 4).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47]))
? 'png'
: body.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff]))
? 'jpg'
: body.subarray(0, 4).toString('ascii') === 'RIFF' && body.subarray(8, 12).toString('ascii') === 'WEBP'
? 'webp'
: null;
if (!ext) throw new RoomError('A PNG, JPEG or WebP.', 415);
mkdirSync(this.imageDir, { recursive: true });
const name = `${report.id}.${ext}`;
writeFileSync(join(this.imageDir, name), body);
this.append({ reportId: report.id, image: name, at: new Date().toISOString() });
return name;
}
/** Reports filed from the seats a browser can prove it holds. */
mine(seats: { roomId: string; seat: SeatId }[]): Report[] {
return this.read().filter((r) => seats.some((s) => s.roomId === r.roomId && s.seat === r.seat));
}
}
+318
View File
@@ -0,0 +1,318 @@
import { appendFileSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { game, type Input, type State } from '../../src/lib/game';
import type { GameSpec } from '../../src/lib/game/spec';
import { Rooms } from './rooms';
import { Store } from './store';
import { SPECTATOR } from '../../src/lib/game/spec';
let dir: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'rooms-'));
});
afterEach(() => {
rmSync(dir, { recursive: true, force: true });
});
/** A table of the demo game: Ann, who opened it, Bo, and Cy when asked for, the game begun. */
function table(spec: GameSpec<State, Input> = game, withCy = false) {
const rooms = new Rooms(spec, new Store(dir));
const host = rooms.create('Ann', 3);
const guest = rooms.join(host.room, 'Bo');
const third = withCy ? rooms.join(host.room, 'Cy') : null;
rooms.begin(host.room, host.token);
return { rooms, room: host.room, ann: host.token, bo: guest.token, cy: third?.token };
}
describe('rooms', () => {
it('resolves a round once every seat has moved, and refuses a move for a round already played', () => {
const { rooms, room, ann, bo } = table();
rooms.submit(room, ann, { pick: 5 }, 0);
expect(rooms.waitingOn(room)).toEqual(['B']);
rooms.submit(room, bo, { pick: 2 }, 0);
expect(room.resolved).toBe(1);
expect(() => rooms.submit(room, ann, { pick: 4 }, 0)).toThrow(/already been played/);
});
it("puts the keeper's word in the table's talk though the gallery may not talk, and a restart keeps it", () => {
const { rooms, room } = table();
expect(room.galleryTalk).toBe(false);
rooms.keeperSays(room, 'I came too late for the seat; call me again.');
const said = { id: SPECTATOR, name: 'the keeper', keeper: true, text: 'I came too late for the seat; call me again.' };
expect(room.chat.at(-1)).toMatchObject(said);
expect(new Rooms(game, new Store(dir)).get(room.id).chat.at(-1)).toMatchObject(said);
});
it('gives a seat a new token at the keeper\'s word: the old one opens nothing, and a restart keeps the change', () => {
const { rooms, room, bo } = table();
const phrase = rooms.transfer(room, bo).phrase;
const { seat, token } = rooms.reseat(room, 'B');
expect(seat.name).toBe('Bo');
expect(rooms.seatOf(room, token).id).toBe('B');
expect(() => rooms.seatOf(room, bo)).toThrow(/opens no seat/);
// A phrase minted with the old token carries nothing now.
expect(() => rooms.claim(phrase)).toThrow(/unknown or has expired/);
const reopened = new Rooms(game, new Store(dir)).get(room.id);
expect(rooms.seatOf(reopened, token).id).toBe('B');
expect(() => rooms.seatOf(reopened, bo)).toThrow(/opens no seat/);
});
it('re-seats only a person, and says when each person last acted', () => {
const { rooms, room, ann } = table();
expect(() => rooms.reseat(room, 'Z')).toThrow(/No person sits/);
rooms.submit(room, ann, { pick: 5 }, 0);
const seats = rooms.seatsForKeeper(room);
expect(seats.map((s) => [s.id, s.name])).toEqual([['A', 'Ann'], ['B', 'Bo']]);
expect(seats[0].lastActed).toBeGreaterThan(0);
expect(seats[1].lastActed).toBeNull();
});
it('leaves a room with an unreadable ledger unloaded and opens the rest', () => {
const { room } = table();
appendFileSync(join(dir, 'ZZZZ.jsonl'), '{"t":"room","id":"ZZZZ","seats":2,"createdAt":1,"options":{}}\n{"t":"seat", torn');
const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
const reopened = new Rooms(game, new Store(dir));
expect(errors).toHaveBeenCalledWith(expect.stringMatching(/ZZZZ: ledger unreadable/));
expect(reopened.get(room.id).state).not.toBeNull();
errors.mockRestore();
});
it('holds a draft until it is settled, and lets it be replaced until then', () => {
type Draft = Input & { final?: boolean };
const drafts: GameSpec<State, Input> = {
...game,
cleanInput: (raw) => ({ ...game.cleanInput(raw), final: (raw as Draft)?.final === true }) as Draft,
settled: (input) => (input as Draft).final === true
};
const { rooms, room, ann, bo } = table(drafts);
rooms.submit(room, ann, { pick: 5 }, 0);
rooms.submit(room, bo, { pick: 2, final: true }, 0);
expect(rooms.waitingOn(room)).toEqual(['A']);
rooms.submit(room, ann, { pick: 4 }, 0);
expect(room.resolved).toBe(0);
rooms.submit(room, ann, { pick: 3, final: true }, 0);
expect(room.resolved).toBe(1);
expect(room.state!.rounds[0].picks).toEqual({ A: 3, B: 2 });
rooms.submit(room, bo, { pick: 1, final: true }, 1);
expect(() => rooms.submit(room, bo, { pick: 2, final: true }, 1)).toThrow(/already in/);
rooms.submit(room, bo, { pick: 2 }, 1);
expect(rooms.waitingOn(room)).toEqual(['A', 'B']);
});
it("shows a seat its own move in waiting and its last move played, and nobody else's", () => {
const { rooms, room, ann, bo } = table();
rooms.submit(room, ann, { pick: 5 }, 0);
expect(rooms.view(room, 'A').yourInput).toEqual({ pick: 5 });
expect(rooms.view(room, 'B').yourInput).toBeNull();
expect(rooms.view(room, '').yourInput).toBeNull();
rooms.submit(room, bo, { pick: 2 }, 0);
expect(rooms.view(room, 'A').yourInput).toBeNull();
expect(rooms.view(room, 'A').yourLastInput).toEqual({ pick: 5 });
expect(rooms.view(room, 'B').yourLastInput).toEqual({ pick: 2 });
expect(rooms.view(room, '').yourLastInput).toBeNull();
});
it('shows a private line to its sender and the seats it names, never to anyone else or the gallery', () => {
const { rooms, room, ann, bo } = table(game, true);
rooms.say(room, ann, 'Everyone, hello.');
rooms.say(room, ann, 'Bo, lay a five.', ['B']);
const heard = (seat: string) => rooms.view(room, seat).chat.map((l) => l.text);
expect(heard('A')).toEqual(['Everyone, hello.', 'Bo, lay a five.']);
expect(heard('B')).toEqual(['Everyone, hello.', 'Bo, lay a five.']);
expect(heard('C')).toEqual(['Everyone, hello.']);
expect(heard('')).toEqual(['Everyone, hello.']);
expect(rooms.view(room, 'B').chat[1]).toMatchObject({ id: 'A', to: ['B'], turn: 1 });
expect(() => rooms.say(room, bo, 'Anyone?', ['Q'])).toThrow(/Nobody at this table/);
});
it('keeps each ranking secret until the deal, which reads them all from the start line', () => {
const dealt: Record<string, string[]>[] = [];
const ranked: GameSpec<State, Input> = {
...game,
rankable: () => [
{ value: 'red', label: 'Red' },
{ value: 'blue', label: 'Blue' }
],
create: (names, seed, rules, options, rankings) => {
dealt.push(rankings ?? {});
return game.create(names, seed, rules, options);
}
};
const rooms = new Rooms(ranked, new Store(dir));
const host = rooms.create('Ann', 2);
const guest = rooms.join(host.room, 'Bo');
const room = host.room;
expect(() => rooms.rank(room, host.token, ['red'])).toThrow(/every choice once/);
rooms.rank(room, host.token, ['blue', 'red']);
expect(rooms.view(room, 'A').yourRanking).toEqual(['blue', 'red']);
expect(rooms.view(room, 'B')).toMatchObject({ yourRanking: null, ranked: 1 });
rooms.begin(room, host.token);
expect(dealt).toEqual([{ A: ['blue', 'red'] }]);
expect(() => rooms.rank(room, guest.token, ['red', 'blue'])).toThrow(/ranking is closed/);
new Rooms(ranked, new Store(dir));
expect(dealt[1]).toEqual({ A: ['blue', 'red'] });
});
it('refuses a ranking at a table that asks for none', () => {
const rooms = new Rooms(game, new Store(dir));
const host = rooms.create('Ann', 2);
expect(() => rooms.rank(host.room, host.token, ['A'])).toThrow(/asks for no ranking/);
});
it('lets a game give its bots words: when a round opens and when spoken to, with notes kept from every view', () => {
const heard: string[][] = [];
const talking: GameSpec<State, Input> = {
...game,
botInput: (state, seat, press) => {
heard.push((press ?? []).map((l) => l.text));
return game.botInput(state, seat);
},
botPress: (state, seat, press, people, trigger) =>
trigger === 'phase' ? [{ to: people, text: `Round ${game.turn(state)}.`, note: 'secret' }] : [{ to: [press[press.length - 1].id], text: 'I hear you.' }],
parting: (_press, viewer) => [{ id: 'B', text: `Farewell, ${viewer}.` }]
};
const rooms = new Rooms(talking, new Store(dir));
const host = rooms.create('Ann', 3);
rooms.addBot(host.room, host.token);
const cy = rooms.join(host.room, 'Cy');
const room = host.room;
rooms.begin(room, host.token);
rooms.say(room, host.token, 'Psst.', ['B']);
rooms.say(room, cy.token, 'Hello, all.');
const annSees = rooms.view(room, 'A').chat;
expect(annSees.map((l) => l.text)).toEqual(['Round 1.', 'Psst.', 'I hear you.', 'Hello, all.']);
expect(annSees.some((l) => 'note' in l)).toBe(false);
expect(rooms.view(room, 'C').chat.map((l) => l.text)).toEqual(['Round 1.', 'Hello, all.', 'I hear you.']);
expect(rooms.view(room, '').chat.map((l) => l.text)).toEqual(['Hello, all.']);
rooms.submit(room, host.token, { pick: 1 }, 0);
rooms.submit(room, cy.token, { pick: 2 }, 0);
expect(heard[0]).toEqual(['Round 1.', 'Psst.', 'I hear you.', 'Hello, all.', 'I hear you.']);
expect(room.chat.filter((l) => l.note === 'secret').map((l) => l.text)).toEqual(['Round 1.', 'Round 2.']);
expect(rooms.view(room, 'A').parting).toEqual([]);
});
it('refuses private talk to a bot when the game gives bots no words', () => {
const rooms = new Rooms(game, new Store(dir));
const host = rooms.create('Ann', 2);
rooms.addBot(host.room, host.token);
rooms.begin(host.room, host.token);
expect(() => rooms.say(host.room, host.token, 'Psst.', ['B'])).toThrow(/read no private talk/);
});
describe('a table the bots play on alone', () => {
/** A count to ten that only the bots play: the host is never owed a move. */
type Count = { n: number; over: { winner: null; reason: string } | null };
const count: GameSpec<Count, null> = {
seatIds: ['A', 'B'],
minSeats: 2,
botNames: ['Aldric'],
currentRules: 1,
create: () => ({ n: 0, over: null }),
resolve: (s) => ({ n: s.n + 1, over: s.n + 1 >= 10 ? { winner: null, reason: 'Ten.' } : null }),
needsInput: (s, seat) => seat === 'B' && !s.over,
over: (s) => s.over,
turn: (s) => s.n + 1,
view: (s) => s,
botInput: () => null,
cleanInput: () => null,
nameOf: (_s, seat) => seat
};
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
it('plays a few rounds at once, then one at a pace to watch, and the rest at once when hurried', () => {
const rooms = new Rooms(count, new Store(dir));
const host = rooms.create('Ann', 2);
rooms.addBot(host.room, host.token);
rooms.begin(host.room, host.token);
const room = host.room;
expect(room.state!.n).toBe(4);
expect(rooms.view(room, 'A').playingOn).toBe(true);
vi.advanceTimersByTime(2000);
expect(room.state!.n).toBe(5);
rooms.hurry(room, host.token);
vi.runAllTimers();
expect(room.state!.n).toBe(10);
expect(room.over).toBe(true);
expect(rooms.view(room, 'A').playingOn).toBe(false);
});
});
});
describe('the host and the other seats', () => {
it("gives a person's seat to a bot, which plays it at once, and the person's token opens nothing", () => {
const { rooms, room, ann, bo } = table();
rooms.submit(room, ann, { pick: 5 }, 0);
rooms.standIn(room, ann, 'B');
// The round waited on Bo alone; the bot played it.
expect(room.resolved).toBe(1);
expect(rooms.waitingOn(room)).toEqual(['A']);
expect(() => rooms.seatOf(room, bo)).toThrow(/gave your seat to a bot/);
expect(rooms.view(room, 'A').seats[1]).toEqual({ id: 'B', name: 'Bo', bot: true, standIn: true });
rooms.submit(room, ann, { pick: 3 }, 1);
expect(room.resolved).toBe(2);
});
it('keeps a move the person made before the bot stood in', () => {
const { rooms, room, ann, bo } = table();
rooms.submit(room, bo, { pick: 2 }, 0);
rooms.standIn(room, ann, 'B');
rooms.submit(room, ann, { pick: 5 }, 0);
expect(room.state!.rounds[0].picks).toEqual({ A: 5, B: 2 });
});
it('is the host\'s call alone, in a game under way, for a person other than the host', () => {
const { rooms, room, ann, bo } = table();
expect(() => rooms.standIn(room, bo, 'A')).toThrow(/Only the player who opened/);
expect(() => rooms.standIn(room, ann, 'A')).toThrow(/keeps their own seat/);
expect(() => rooms.standIn(room, ann, 'Z')).toThrow(/No person sits/);
const lobby = rooms.create('Ann', 2);
rooms.join(lobby.room, 'Bo');
expect(() => rooms.standIn(lobby.room, lobby.token, 'B')).toThrow(/under way/);
});
it('gives the seat back by the host\'s phrase, with a new token, and a restart keeps both changes', () => {
const { rooms, room, ann, bo } = table();
rooms.standIn(room, ann, 'B');
expect(new Rooms(game, new Store(dir)).get(room.id).seats[1]).toMatchObject({ bot: true, standIn: true });
const claimed = rooms.claim(rooms.hostPhrase(room, ann, 'B').phrase);
expect(claimed.seat).toBe('B');
expect(rooms.seatOf(room, claimed.token).name).toBe('Bo');
expect(() => rooms.seatOf(room, bo)).toThrow(/opens no seat/);
expect(rooms.waitingOn(room)).toContain('B');
const reopened = new Rooms(game, new Store(dir)).get(room.id);
expect(reopened.seats[1]).toEqual({ id: 'B', name: 'Bo', tokenHash: room.seats[1].tokenHash, bot: false });
});
it("re-seats a person whose browser lost the seat, by the host's phrase, once", () => {
const { rooms, room, ann, bo } = table();
const { phrase } = rooms.hostPhrase(room, ann, 'B');
const claimed = rooms.claim(phrase);
expect(claimed.token).not.toBe(bo);
expect(() => rooms.seatOf(room, bo)).toThrow(/opens no seat/);
expect(() => rooms.claim(phrase)).toThrow(/unknown or has expired/);
});
it("makes a phrase only for the host, and only for another person's seat", () => {
const { rooms, room, ann, bo } = table();
expect(() => rooms.hostPhrase(room, bo, 'A')).toThrow(/Only the player who opened/);
expect(() => rooms.hostPhrase(room, ann, 'A')).toThrow(/No other person/);
const withBot = rooms.create('Ann', 2);
const bot = rooms.addBot(withBot.room, withBot.token);
expect(() => rooms.hostPhrase(withBot.room, withBot.token, bot.id)).toThrow(/No other person/);
});
it('voids a phrase for the seat once a bot stands in, and holds the person\'s seat at a rematch without the stand-in', () => {
const { rooms, room, ann } = table();
const { phrase } = rooms.hostPhrase(room, ann, 'B');
rooms.standIn(room, ann, 'B');
expect(() => rooms.claim(phrase)).toThrow(/unknown or has expired/);
while (!game.over(room.state!)) rooms.submit(room, ann, { pick: 5 }, room.resolved);
const next = rooms.get(rooms.rematch(room, ann).roomId);
expect(next.expected).toEqual(['Bo']);
expect(next.seats.map((s) => s.name)).toEqual(['Ann']);
});
});
+766
View File
@@ -0,0 +1,766 @@
// Rooms: who sits where, whose move it is, and the game itself. Every change
// goes to the ledger first and is then applied, so a restart replays to the
// same place. Inputs wait in memory until every seat that must move has moved;
// then the round resolves at once, bots included. Nothing here knows the
// game beyond the GameSpec it is given.
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
import { cleanOptions, SPECTATOR, tableSize, type GameSpec, type SeatId, type TableOptions } from '../../src/lib/game/spec';
import type { ChatLine, RoomView } from '../../src/lib/net/view';
import type { LedgerLine, Store } from './store';
/** The longest line of talk. A game of long negotiation raises this, and the talk box's maxlength with it. */
const CHAT_MAX_LENGTH = 300;
/** Lines of talk kept and sent; the ledger keeps them all. A game that runs for weeks of talk raises this. */
const CHAT_KEEP = 200;
/** Bots' rounds played in one go, when nobody else owes a move, before the rest are paced. */
const PLAYED_AT_ONCE = 4;
/** Between paced bots' rounds: long enough to watch the table move. */
const PACE_MS = 2000;
/** Bots' rounds played between answers to everyone else, once hurried. */
const HURRIED_STEP = 3;
export { SPECTATOR };
export interface Seat {
id: SeatId;
name: string;
/** SHA-256 of the seat's token, hex; empty for a bot. A seat a bot stands in for keeps the person's, which opens nothing while it does. */
tokenHash: string;
/** A bot plays this seat: one seated as a bot, or one standing in for a person. */
bot: boolean;
/** The host gave this person's seat to a bot; a phrase from the host, or the keeper, gives it back. */
standIn?: true;
}
function hashToken(token: string): string {
return createHash('sha256').update(token).digest('hex');
}
export interface Room<State> {
id: string;
size: number;
createdAt: number;
seats: Seat[];
/** The host lets the Peanut Gallery talk at this table. */
galleryTalk: boolean;
/** The keeper of the site was called to a seat, and by whom. */
challenge: { by: SeatId; at: number } | null;
/** Names with a seat held for them: the players of the last table, or the keeper. */
expected: string[];
/** A finished table that called for a rematch: where it went, and who called. */
rematch: { to: string; by: SeatId } | null;
/** The table this one is the rematch of. */
rematchOf: string | null;
/** The host's choices for this table, every declared option filled. */
options: TableOptions;
/** The over line has been written. */
over: boolean;
state: State | null;
/** Inputs received for the round in progress, by seat. */
pending: Record<SeatId, unknown>;
/** Each seat's ranking of the table's choices, where the table asks for one; secret before the deal and after. */
rankings: Record<SeatId, string[]>;
/** Each seat's input in the last round it played, kept through rounds it had no part in; each seat is shown only its own. */
played: Record<SeatId, unknown>;
chat: ChatLine[];
/** Rounds played so far; a move names the count it was made against. */
resolved: number;
/** Bumped on every change a client might want to see. */
seq: number;
updatedAt: number;
}
export class RoomError extends Error {
constructor(
message: string,
public status = 400
) {
super(message);
}
}
function newId(bytes: number): string {
return randomBytes(bytes).toString('base64url');
}
/** Room codes: four letters or digits, none that read alike, easy to say aloud. */
const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
function newCode(): string {
const bytes = randomBytes(4);
return [...bytes].map((b) => CODE_ALPHABET[b % CODE_ALPHABET.length]).join('');
}
function newSeed(): number {
return (Date.now() ^ (Math.random() * 0xffffffff)) >>> 0;
}
/** Phrases that carry a seat between devices: four plain words, ten minutes, one use. */
const TRANSFER_WORDS = [
'ember', 'raven', 'flagon', 'wand', 'rune', 'moss', 'torch', 'frost', 'amber', 'wisp', 'cellar', 'gable',
'onyx', 'briar', 'tome', 'cinder', 'gloom', 'spiral', 'mirror', 'lantern', 'thistle', 'harbor', 'quill', 'saddle',
'willow', 'copper', 'meadow', 'anvil', 'beacon', 'orchard', 'pebble', 'cloister', 'walnut', 'tallow', 'heron', 'marble',
'ivy', 'kestrel', 'fennel', 'velvet', 'canyon', 'lattice', 'ledger', 'bramble', 'sable', 'tundra', 'juniper', 'compass'
];
const TRANSFER_TTL_MS = 10 * 60 * 1000;
const TRANSFER_FAIL_LIMIT = 20;
function normalizeCode(raw: string): string {
return raw.trim().toUpperCase();
}
function cleanName(raw: unknown): string {
const name = String(raw ?? '')
.replace(/\s+/g, ' ')
.trim()
.slice(0, 24);
if (!name) throw new RoomError('A player needs a name.');
return name;
}
export class Rooms<State, Input> {
private rooms = new Map<string, Room<State>>();
private listeners = new Map<string, Set<(room: Room<State>) => void>>();
/** Sockets watching from the gallery, by room. */
private gallery = new Map<string, number>();
/** Phrases waiting to be claimed, with the seat and the token they carry; the host's carry none, and re-seat on claim. */
private transfers = new Map<string, { roomId: string; seatId: SeatId; token: string | null; expiresAt: number }>();
private failedClaims = 0;
private failWindowStart = 0;
/** Tables whose bots are playing on, paced: the next round's timer. */
private pacing = new Map<string, ReturnType<typeof setTimeout>>();
/** Tables asked to play the rest at once. */
private hurried = new Set<string>();
constructor(
private game: GameSpec<State, Input>,
private store: Store,
/** The keeper of the site: the name a table may call to a seat, and where they live. */
private keeper: { name: string; zone: string } = { name: 'the keeper', zone: 'UTC' }
) {
for (const id of store.roomIds()) {
let room: Room<State> | null;
try {
room = this.replay(id, store.read(id));
} catch (e) {
// One unreadable ledger (a torn last line) keeps its room closed, not the server down.
console.error(`room ${id}: ledger unreadable, left unloaded: ${e instanceof Error ? e.message : String(e)}`);
continue;
}
if (!room) continue;
this.rooms.set(id, room);
// A table that stopped with a bot's move owed picks up where it left off.
if (room.state) this.driveBots(room);
}
}
get maxSeats(): number {
return this.game.seatIds.length;
}
get(id: string): Room<State> {
const room = this.rooms.get(id) ?? this.rooms.get(normalizeCode(id)) ?? this.load(normalizeCode(id));
if (!room) throw new RoomError('No game answers to that code.', 404);
return room;
}
/** A room evicted from memory comes back from its ledger on the next visit. */
private load(id: string): Room<State> | undefined {
if (!/^[A-Z0-9]{4}$/.test(id)) return undefined;
const room = this.replay(id, this.store.read(id));
if (!room) return undefined;
this.rooms.set(id, room);
if (room.state) this.driveBots(room);
return room;
}
/** Forget rooms nobody has touched or watched for a while; their ledgers stay on disk. */
evictIdle(olderThanMs: number, now = Date.now()): number {
let n = 0;
for (const [id, room] of this.rooms) {
if (now - room.updatedAt < olderThanMs) continue;
if ((this.listeners.get(id)?.size ?? 0) > 0) continue;
this.rooms.delete(id);
n += 1;
}
return n;
}
get loaded(): number {
return this.rooms.size;
}
/** The seat a token unlocks, compared by hash in constant time. */
seatOf(room: Room<State>, token: string | undefined): Seat {
if (!token) throw new RoomError('That token opens no seat at this game.', 403);
const given = Buffer.from(hashToken(token), 'hex');
const seat = room.seats.find((s) => s.tokenHash.length === given.length * 2 && timingSafeEqual(Buffer.from(s.tokenHash, 'hex'), given));
if (seat?.standIn) throw new RoomError('The host gave your seat to a bot, which plays on in your place. Ask them for a transfer phrase to take it back.', 403);
if (!seat) throw new RoomError('That token opens no seat at this game.', 403);
return seat;
}
create(name: string, size: number, rawOptions?: unknown): { room: Room<State>; seat: Seat; token: string } {
const { minSeats } = this.game;
const options = cleanOptions(this.game, rawOptions);
const most = tableSize(this.game, options);
if (!Number.isInteger(size) || size < minSeats || size > most) {
throw new RoomError(`A table seats ${minSeats} to ${most} players.`);
}
return this.open(name, size, options);
}
/** A table with nobody seated yet. */
private blank(id: string, size: number, createdAt: number, rematchOf: string | null, expected: string[], options: TableOptions, seq = 0): Room<State> {
return { id, size, createdAt, seats: [], galleryTalk: false, challenge: null, expected, rematch: null, rematchOf, options, over: false, state: null, pending: {}, played: {}, rankings: {}, chat: [], resolved: 0, seq, updatedAt: createdAt };
}
/** Open a table with its first seat taken; a rematch names the table it follows and holds seats for its players. */
private open(name: string, size: number, options: TableOptions, follows?: { rematchOf: string; expected: string[] }): { room: Room<State>; seat: Seat; token: string } {
let id = newCode();
while (this.rooms.has(id) || this.store.exists(id)) id = newCode();
const room = this.blank(id, size, Date.now(), follows?.rematchOf ?? null, follows?.expected ?? [], options);
this.rooms.set(id, room);
this.commit(room, { t: 'room', id, seats: size, createdAt: room.createdAt, options, ...(follows ? { rematchOf: follows.rematchOf, expected: follows.expected } : {}) });
return { room, ...this.sit(room, name, false) };
}
join(room: Room<State>, name: string): { seat: Seat; token: string } {
if (room.state) throw new RoomError('The game has begun; no more seats are taken.', 409);
return this.sit(room, name, false);
}
/** Names with a seat held who have not yet sat. */
private awaited(room: Room<State>): string[] {
return room.expected.filter((n) => !room.seats.some((s) => s.name.toLowerCase() === n.toLowerCase()));
}
/** Host only: let the Peanut Gallery talk at this table, or hush it. Written to the ledger. */
setGalleryTalk(room: Room<State>, token: string | undefined, on: boolean): void {
const seat = this.seatOf(room, token);
if (seat.id !== room.seats[0]?.id) throw new RoomError('Only the player who opened the table decides whether the gallery may talk.', 403);
if (room.galleryTalk === on) return;
this.commit(room, { t: 'galleryTalk', at: Date.now(), on, by: seat.id });
}
/** The keeper of the site says a word at a table from the keeper's door, whether or not the gallery may talk: the answer to a call they could not take up. */
keeperSays(room: Room<State>, raw: unknown): void {
this.commit(room, { t: 'chat', at: Date.now(), id: SPECTATOR, name: this.keeper.name, text: this.cleanTalk(raw), keeper: true });
}
/** A word from the Peanut Gallery, when the host allows it: signed with a name no seat holds. */
sayFromGallery(room: Room<State>, rawName: unknown, raw: unknown): void {
if (!room.galleryTalk) throw new RoomError('The gallery listens at this table; the host has not let it talk.', 403);
const name = cleanName(rawName);
if (room.seats.some((s) => s.name.toLowerCase() === name.toLowerCase())) throw new RoomError('A player at the table has that name.', 409);
this.commit(room, { t: 'chat', at: Date.now(), id: SPECTATOR, name, text: this.cleanTalk(raw) });
}
/**
* A seated player calls the keeper of the site to the table: a seat is
* held under the keeper's name and the call goes on the ledger. Once per
* table, before the game begins. The caller rings the keeper's bell.
*/
callKeeper(room: Room<State>, token: string | undefined, keeper: string): void {
const seat = this.seatOf(room, token);
if (room.state) throw new RoomError('The game has begun.', 409);
if (room.challenge) throw new RoomError(`${keeper} has already been called to this table.`, 409);
if (room.seats.some((s) => s.name.toLowerCase() === keeper.toLowerCase())) throw new RoomError(`${keeper} is already here.`, 409);
if (room.seats.length + this.awaited(room).length >= room.size) throw new RoomError('Every seat at this table is taken or held.', 409);
this.commit(room, { t: 'challenge', at: Date.now(), by: seat.id, keeper });
}
/**
* A finished table calls for a rematch: a new table of the same size with
* the same bots, seats held for the same people, the caller seated as its
* host. Anyone at the old table may call; a second call finds the table
* already open.
*/
rematch(room: Room<State>, token: string | undefined): { roomId: string; seat: Seat | null; token: string | null; created: boolean } {
const caller = this.seatOf(room, token);
if (!room.state || !this.game.over(room.state)) throw new RoomError('The game is not over yet.', 409);
if (room.rematch) return { roomId: room.rematch.to, seat: null, token: null, created: false };
// A person a bot stood in for is still one of the company; the stand-in does not follow.
const others = room.seats.filter((s) => (!s.bot || s.standIn) && s.id !== caller.id).map((s) => s.name);
const next = this.open(caller.name, room.size, room.options, { rematchOf: room.id, expected: others });
for (const bot of room.seats.filter((s) => s.bot && !s.standIn)) this.sit(next.room, bot.name, true);
this.commit(room, { t: 'rematch', at: Date.now(), to: next.room.id, by: caller.id });
return { roomId: next.room.id, seat: next.seat, token: next.token, created: true };
}
/** Mint a phrase that brings this seat to another device: four words, ten minutes, one use. */
transfer(room: Room<State>, token: string | undefined): { phrase: string; expiresAt: number } {
const seat = this.seatOf(room, token);
return this.mint(room.id, seat.id, token!);
}
/**
* The host mints a phrase for another person's seat: for a player whose browser lost it, or to take it back
* from a bot standing in. Claimed, it gives the seat a new token, so the old one opens nothing after.
*/
hostPhrase(room: Room<State>, token: string | undefined, seatId: unknown): { phrase: string; expiresAt: number } {
const host = this.seatOf(room, token);
if (host.id !== room.seats[0]?.id) throw new RoomError('Only the player who opened the table may make a phrase for another seat.', 403);
const seat = room.seats.find((s) => s.id === seatId && s.id !== host.id && (!s.bot || s.standIn));
if (!seat) throw new RoomError('No other person sits in that seat.', 404);
return this.mint(room.id, seat.id, null);
}
private mint(roomId: string, seatId: SeatId, token: string | null): { phrase: string; expiresAt: number } {
const now = Date.now();
for (const [phrase, t] of this.transfers) if (t.expiresAt < now) this.transfers.delete(phrase);
if (this.transfers.size >= 200) throw new RoomError('Too many transfers are pending; try again in a few minutes.', 429);
let phrase: string;
do {
phrase = Array.from({ length: 4 }, () => TRANSFER_WORDS[randomBytes(1)[0] % TRANSFER_WORDS.length]).join('-');
} while (this.transfers.has(phrase));
const expiresAt = now + TRANSFER_TTL_MS;
this.transfers.set(phrase, { roomId, seatId, token, expiresAt });
return { phrase, expiresAt };
}
/** Claim a phrase: the seat and its token, once. Too many misses void every pending phrase. */
claim(raw: unknown): { roomId: string; seat: SeatId; token: string } {
const now = Date.now();
if (now - this.failWindowStart > TRANSFER_TTL_MS) {
this.failWindowStart = now;
this.failedClaims = 0;
}
if (this.failedClaims >= TRANSFER_FAIL_LIMIT) throw new RoomError('Too many failed claims; transfers are cooling off. Mint a fresh phrase.', 429);
const phrase = String(raw ?? '').trim().toLowerCase().replace(/\s+/g, '-');
const t = this.transfers.get(phrase);
if (!t || t.expiresAt < now) {
this.failedClaims += 1;
if (this.failedClaims >= TRANSFER_FAIL_LIMIT) this.transfers.clear();
throw new RoomError('That phrase is unknown or has expired.', 404);
}
this.transfers.delete(phrase);
const room = this.get(t.roomId);
if (t.token === null) {
const { seat, token } = this.reseat(room, t.seatId);
return { roomId: room.id, seat: seat.id, token };
}
const seat = this.seatOf(room, t.token);
return { roomId: room.id, seat: seat.id, token: t.token };
}
/** The host, who opened the table, begins once enough are seated, however full the table. */
begin(room: Room<State>, token: string | undefined): void {
const seat = this.seatOf(room, token);
if (seat.id !== room.seats[0]?.id) throw new RoomError('Only the player who opened the table may begin.', 403);
if (room.state) throw new RoomError('The game has already begun.', 409);
if (room.seats.length < this.game.minSeats) throw new RoomError(`The game needs at least ${this.game.minSeats} players.`, 409);
this.commit(room, { t: 'start', seed: newSeed(), rules: this.game.currentRules, ...(Object.keys(room.rankings).length ? { rankings: { ...room.rankings } } : {}) });
// A game whose first move belongs to a bot must not wait for a human who is not owed a move.
this.driveBots(room);
this.botsSpeak(room, 'phase');
}
/**
* Rounds only bots owe (an opening move, an extra turn, a table the
* people are out of) resolve without waiting; a human's waits for them.
* A few are played at once; past that, the bots play on one round at a
* time, so the table can be watched and the server answers everyone else
* between rounds. Hurried, they play in larger steps.
*/
private driveBots(room: Room<State>, burst = PLAYED_AT_ONCE): void {
if (this.pacing.has(room.id)) return;
const bots = (state: State) => room.seats.filter((s) => s.bot && this.game.needsInput(state, s.id));
let played = 0;
while (room.state && !this.game.over(room.state) && this.waitingOn(room).length === 0 && bots(room.state).length > 0) {
if (played === burst) return this.playOnLater(room);
const inputs: Record<SeatId, unknown> = {};
for (const seat of bots(room.state)) inputs[seat.id] = this.game.botInput(room.state, seat.id, this.heardBy(room, seat.id));
this.commit(room, { t: 'turn', at: Date.now(), inputs });
played += 1;
}
this.hurried.delete(room.id);
const outcome = room.state && this.game.over(room.state);
if (outcome && !room.over) this.commit(room, { t: 'over', at: Date.now(), winner: outcome.winner, reason: outcome.reason });
}
/** The bots' next round, after a pause to watch it by, or at once when hurried. */
private playOnLater(room: Room<State>): void {
const hurried = this.hurried.has(room.id);
const next = setTimeout(() => {
this.pacing.delete(room.id);
// A room forgotten and loaded again drives itself; this one is no longer the table.
if (this.rooms.get(room.id) !== room) return;
this.driveBots(room, hurried ? HURRIED_STEP : 1);
// Played out: the bots have their say once, as after any round, which ends a game with parting words.
if (!this.pacing.has(room.id)) this.botsSpeak(room, 'phase');
}, hurried ? 0 : PACE_MS);
next.unref();
this.pacing.set(room.id, next);
}
/** A seat at a table the bots are playing on asks for the rest at once. */
hurry(room: Room<State>, token: string | undefined): void {
this.seatOf(room, token);
this.hurried.add(room.id);
const waiting = this.pacing.get(room.id);
if (!waiting) return;
clearTimeout(waiting);
this.pacing.delete(room.id);
this.playOnLater(room);
}
/** Whether the bots are playing on by themselves at this table, one paced round at a time. */
playingOn(room: Room<State>): boolean {
return this.pacing.has(room.id);
}
/** The host seats a bot in an empty chair. */
addBot(room: Room<State>, token: string | undefined): Seat {
const host = this.seatOf(room, token);
if (host.id !== room.seats[0]?.id) throw new RoomError('Only the player who opened the table may seat a bot.', 403);
if (room.state) throw new RoomError('The game has begun; no more seats are taken.', 409);
const taken = new Set(room.seats.map((s) => s.name.toLowerCase()));
const pool = this.game.botNames.filter((n) => !taken.has(n.toLowerCase()));
const name = pool[Math.floor(Math.random() * pool.length)] ?? 'The Construct';
return this.sit(room, name, true).seat;
}
/** Take the next free seat. The token is returned once and never stored; the ledger keeps its hash. */
private sit(room: Room<State>, rawName: string, bot: boolean): { seat: Seat; token: string } {
if (room.seats.length >= room.size) throw new RoomError('Every seat at this table is taken.', 409);
const name = cleanName(rawName);
const awaited = this.awaited(room);
if (!awaited.some((n) => n.toLowerCase() === name.toLowerCase()) && room.seats.length + awaited.length >= room.size) {
throw new RoomError('The seats left are held for players expected at this table.', 409);
}
if (room.seats.some((s) => s.name.toLowerCase() === name.toLowerCase())) throw new RoomError('Another player here already has that name.', 409);
const id = this.game.seatIds.find((s) => !room.seats.some((taken) => taken.id === s))!;
const token = bot ? '' : newId(18);
const seat: Seat = { id, name, tokenHash: bot ? '' : hashToken(token), bot };
this.commit(room, { t: 'seat', id: seat.id, name, tokenHash: seat.tokenHash, bot });
return { seat, token };
}
/**
* A person's seat gets a new token, for a player whose browser lost the old one, or one taking it back from a
* bot standing in. Whether the one asking holds the seat is the keeper's judgment, or the host's in the phrase
* they made; this carries it out. The old token opens nothing after.
*/
reseat(room: Room<State>, seatId: unknown): { seat: Seat; token: string } {
const seat = room.seats.find((s) => s.id === seatId && (!s.bot || s.standIn));
if (!seat) throw new RoomError('No person sits in that seat.', 404);
const token = newId(18);
this.commit(room, { t: 'reseat', at: Date.now(), id: seat.id, tokenHash: hashToken(token) });
this.voidPhrases(room, seat.id);
return { seat, token };
}
/**
* The host gives a person's seat to a bot, for a player who cannot go on: the bot plays it from the next move
* the seat owes, and the person's token opens nothing until a phrase from the host gives it back.
*/
standIn(room: Room<State>, token: string | undefined, seatId: unknown): void {
const host = this.seatOf(room, token);
if (host.id !== room.seats[0]?.id) throw new RoomError('Only the player who opened the table may give a seat to a bot.', 403);
if (!room.state || this.game.over(room.state)) throw new RoomError('Only a game under way needs a stand-in.', 409);
if (seatId === host.id) throw new RoomError('The host keeps their own seat.', 409);
const seat = room.seats.find((s) => s.id === seatId && !s.bot);
if (!seat) throw new RoomError('No person sits in that seat.', 404);
this.commit(room, { t: 'standIn', at: Date.now(), id: seat.id, by: host.id });
this.voidPhrases(room, seat.id);
// The round may have been waiting on this seat alone. Bots already playing on take the new one in their stride.
if (!this.pacing.has(room.id) && this.waitingOn(room).length === 0) this.resolve(room);
}
/** A phrase minted for a seat whose token has changed hands would carry a seat that no longer answers to it. */
private voidPhrases(room: Room<State>, seatId: SeatId): void {
for (const [phrase, t] of this.transfers) if (t.roomId === room.id && t.seatId === seatId) this.transfers.delete(phrase);
}
/** The table as the keeper sees it before re-seating: who sits where, and when each person last moved or spoke. */
seatsForKeeper(room: Room<State>): { id: SeatId; name: string; bot: boolean; standIn: boolean; lastActed: number | null }[] {
const last = new Map<SeatId, number>();
for (const line of this.store.read(room.id)) {
if (line.t === 'input' || line.t === 'chat') last.set(line.id, line.at);
else if (line.t === 'turn') for (const id of Object.keys(line.inputs)) last.set(id, line.at);
}
return room.seats.map((s) => ({ id: s.id, name: s.name, bot: s.bot && !s.standIn, standIn: !!s.standIn, lastActed: s.bot && !s.standIn ? null : (last.get(s.id) ?? null) }));
}
/** The host sends a bot away before the game begins. People leave by not coming back. */
unseat(room: Room<State>, token: string | undefined, seatId: unknown): void {
const host = this.seatOf(room, token);
if (host.id !== room.seats[0]?.id) throw new RoomError('Only the player who opened the table may send a bot away.', 403);
if (room.state) throw new RoomError('The game has begun; the table is set.', 409);
const seat = room.seats.find((s) => s.id === seatId);
if (!seat || !seat.bot) throw new RoomError('Only a bot can be sent away.', 400);
this.commit(room, { t: 'unseat', id: seat.id });
}
/** A seat's ranking of the choices the table asks for, best first, before the game begins. */
rank(room: Room<State>, token: string | undefined, raw: unknown): void {
const seat = this.seatOf(room, token);
if (room.state) throw new RoomError('The game has begun; the ranking is closed.', 409);
const choices = this.game.rankable?.(room.options);
if (!choices) throw new RoomError('This table asks for no ranking.', 409);
const ranking = Array.isArray(raw) ? raw.map(String) : [];
const values = choices.map((c) => c.value);
if (ranking.length !== values.length || new Set(ranking).size !== values.length || !ranking.every((r) => values.includes(r))) throw new RoomError('Rank every choice once.');
this.commit(room, { t: 'rank', id: seat.id, ranking });
}
/**
* Record a seat's move on the ledger, so a restart keeps it; resolve the round once nobody else is awaited.
* A draft (an input the game does not call settled) may be replaced, and a settled move taken back
* as a draft, until the round resolves.
* `resolved` is how many rounds the page had seen played when the move was made: a move that
* arrives after its round was played (a slow connection, a second click, a stale tab) is refused
* rather than taken as the move for the next round.
*/
submit(room: Room<State>, token: string | undefined, raw: unknown, resolved: unknown): void {
const seat = this.seatOf(room, token);
if (!room.state) throw new RoomError('The game has not begun: seats are still empty.', 409);
if (this.game.over(room.state)) throw new RoomError('The game is over.', 409);
if (typeof resolved !== 'number') throw new RoomError('This page is out of date. Reload it to see the table as it stands.', 409);
if (resolved !== room.resolved) throw new RoomError('That move was made for a turn that has already been played. Your page will catch up.', 409);
if (!this.game.needsInput(room.state, seat.id)) throw new RoomError('It is not your move.', 409);
const input = this.game.cleanInput(raw);
// A settled move is final; a draft may replace it while the round still waits on others.
if (seat.id in room.pending && this.settled(room.pending[seat.id]) && this.settled(input)) throw new RoomError('Your move is already in.', 409);
const why = this.game.validate?.(room.state, seat.id, input);
if (why) throw new RoomError(why);
this.commit(room, { t: 'input', at: Date.now(), id: seat.id, input });
if (this.waitingOn(room).length === 0) this.resolve(room);
}
private resolve(room: Room<State>): void {
const inputs: Record<SeatId, unknown> = { ...room.pending };
// A move a person settled before a bot stood in for them stands.
for (const seat of room.seats) {
if (seat.bot && this.game.needsInput(room.state!, seat.id) && !(seat.id in inputs && this.settled(inputs[seat.id]))) {
inputs[seat.id] = this.game.botInput(room.state!, seat.id, this.heardBy(room, seat.id));
}
}
this.commit(room, { t: 'turn', at: Date.now(), inputs });
this.driveBots(room);
this.botsSpeak(room, 'phase');
}
/**
* Bots' talk, for a game that gives them words: when a round opens, and to
* a person who has just written to them. Their lines go on the ledger like
* anyone's, so a replay repeats them rather than asking again.
*/
private botsSpeak(room: Room<State>, trigger: 'phase' | 'spoken', only?: SeatId[]): void {
if (!this.game.botPress || !room.state) return;
const people = room.seats.filter((s) => !s.bot).map((s) => s.id);
for (const seat of room.seats) {
// A stand-in plays a person's seat; it does not speak in their name.
if (!seat.bot || seat.standIn || (only && !only.includes(seat.id))) continue;
for (const line of this.game.botPress(room.state, seat.id, this.heardBy(room, seat.id), people, trigger)) {
const to = line.to.filter((id) => people.includes(id));
if (!to.length || !line.text.trim()) continue;
this.commit(room, { t: 'chat', at: Date.now(), id: seat.id, text: this.cleanTalk(line.text), to, ...(line.note !== undefined ? { note: line.note } : {}) });
}
}
}
/** The talk a seat has heard: the table's, and private lines to it or from it. */
private heardBy(room: Room<State>, seatId: SeatId): ChatLine[] {
return room.chat.filter((line) => !line.to || line.id === seatId || line.to.includes(seatId));
}
/** Whether an input is final; a game without drafts makes every input final. */
private settled(input: unknown): boolean {
return this.game.settled ? this.game.settled(input as Input) : true;
}
/**
* Table talk, from a seat: to everyone at the table and in the gallery,
* or, naming seats, privately to them alone. A private line is never
* shown to anyone else, the gallery included.
*/
say(room: Room<State>, token: string | undefined, raw: unknown, rawTo?: unknown): void {
const seat = this.seatOf(room, token);
const to = Array.isArray(rawTo)
? [...new Set(rawTo.filter((id): id is SeatId => typeof id === 'string' && id !== seat.id && room.seats.some((s) => s.id === id)))]
: [];
if (Array.isArray(rawTo) && rawTo.length && !to.length) throw new RoomError('Nobody at this table answers to that.');
// A private line to a seat a bot stands in for waits for the person; the stand-in reads none.
const botsTo = to.filter((id) => room.seats.find((s) => s.id === id && s.bot && !s.standIn));
if (botsTo.length && !this.game.botPress) throw new RoomError('The bots at this table read no private talk.');
// A person's first word of the game, said to everyone, is heard by the bots too: the game chooses who answers.
const first = !to.length && !room.chat.some((l) => l.id === seat.id);
this.commit(room, { t: 'chat', at: Date.now(), id: seat.id, text: this.cleanTalk(raw), ...(to.length ? { to } : {}) });
if (botsTo.length) this.botsSpeak(room, 'spoken', botsTo);
else if (first) this.botsSpeak(room, 'spoken', room.seats.filter((s) => s.bot && !s.standIn).map((s) => s.id));
}
private cleanTalk(raw: unknown): string {
const text = String(raw ?? '')
.replace(/[\u0000-\u001f\u007f]/g, ' ')
.replace(/\s+/g, ' ')
.trim()
.slice(0, CHAT_MAX_LENGTH);
if (!text) throw new RoomError('Nothing to say.');
return text;
}
/** Seats whose input the next resolution needs and has not yet received settled; a draft still waits. */
waitingOn(room: Room<State>): SeatId[] {
if (!room.state || this.game.over(room.state)) return [];
return room.seats
.filter((s) => !s.bot && this.game.needsInput(room.state!, s.id) && !(s.id in room.pending && this.settled(room.pending[s.id])))
.map((s) => s.id);
}
/** The view for a seat, or for the gallery when the seat is SPECTATOR. */
view(room: Room<State>, seatId: SeatId): RoomView<State> {
const seated = seatId !== SPECTATOR;
return {
roomId: room.id,
seq: room.seq,
size: room.size,
me: seatId,
host: room.seats[0]?.id ?? seatId,
seats: room.seats.map((s) => ({ id: s.id, name: s.name, bot: s.bot, ...(s.standIn ? { standIn: true as const } : {}) })),
waitingOn: this.waitingOn(room),
turn: room.state ? this.game.turn(room.state) : null,
resolved: room.resolved,
over: room.state ? this.game.over(room.state) : null,
state: room.state ? this.game.view(room.state, seatId) : null,
yourRanking: seated ? (room.rankings[seatId] ?? null) : null,
ranked: Object.keys(room.rankings).length,
yourInput: seated && seatId in room.pending ? room.pending[seatId] : null,
yourLastInput: seated && seatId in room.played ? room.played[seatId] : null,
// Private lines only to their sender and the seats they name; a note is a bot's own memory, never sent.
chat: this.heardBy(room, seatId).map(({ note: _, ...line }) => line),
parting: room.state && seated && this.game.parting && this.game.over(room.state) ? this.game.parting(room.chat, seatId) : [],
playingOn: this.playingOn(room),
audience: this.gallery.get(room.id) ?? 0,
galleryTalk: room.galleryTalk,
challenge: room.challenge,
expected: this.awaited(room),
rematch: room.rematch,
rematchOf: room.rematchOf,
options: room.options,
keeper: this.keeper.name,
keeperZone: this.keeper.zone
};
}
subscribe(roomId: string, fn: (room: Room<State>) => void): () => void {
if (!this.listeners.has(roomId)) this.listeners.set(roomId, new Set());
this.listeners.get(roomId)!.add(fn);
return () => this.listeners.get(roomId)?.delete(fn);
}
/** Subscribe from the gallery; the table is told when its audience changes. */
watch(room: Room<State>, fn: (room: Room<State>) => void): () => void {
const unsubscribe = this.subscribe(room.id, fn);
this.gallery.set(room.id, (this.gallery.get(room.id) ?? 0) + 1);
room.seq += 1;
this.notify(room);
return () => {
unsubscribe();
this.gallery.set(room.id, Math.max(0, (this.gallery.get(room.id) ?? 1) - 1));
room.seq += 1;
this.notify(room);
};
}
audience(room: Room<State>): number {
return this.gallery.get(room.id) ?? 0;
}
/** Write to the ledger, then apply; the file is the truth a restart returns to. */
private commit(room: Room<State>, line: LedgerLine): void {
this.store.append(room.id, line);
this.apply(room, line);
room.seq += 1;
room.updatedAt = Date.now();
this.notify(room);
}
private notify(room: Room<State>): void {
for (const fn of this.listeners.get(room.id) ?? []) fn(room);
}
private apply(room: Room<State>, line: LedgerLine): void {
switch (line.t) {
case 'room':
break;
case 'over':
room.over = true;
break;
case 'seat':
room.seats.push({ id: line.id, name: line.name, tokenHash: line.tokenHash, bot: line.bot });
break;
case 'reseat': {
const seat = room.seats.find((s) => s.id === line.id);
if (!seat) break;
seat.tokenHash = line.tokenHash;
seat.bot = false;
delete seat.standIn;
break;
}
case 'standIn': {
const seat = room.seats.find((s) => s.id === line.id);
if (!seat) break;
seat.bot = true;
seat.standIn = true;
break;
}
case 'galleryTalk':
room.galleryTalk = line.on;
break;
case 'challenge':
room.challenge = { by: line.by, at: line.at };
if (!room.expected.some((n) => n.toLowerCase() === line.keeper.toLowerCase())) room.expected = [...room.expected, line.keeper];
break;
case 'rematch':
room.rematch = { to: line.to, by: line.by };
break;
case 'input':
room.pending[line.id] = this.game.cleanInput(line.input);
break;
case 'rank':
room.rankings[line.id] = line.ranking;
break;
case 'unseat':
room.seats = room.seats.filter((s) => s.id !== line.id);
delete room.rankings[line.id];
break;
case 'start':
room.state = this.game.create(Object.fromEntries(room.seats.map((s) => [s.id, s.name])), line.seed, line.rules, room.options, line.rankings);
break;
case 'turn':
if (!room.state) return;
room.state = this.game.resolve(room.state, line.inputs as Record<SeatId, Input>);
room.played = { ...room.played, ...(line.inputs as Record<SeatId, unknown>) };
room.pending = {};
room.resolved += 1;
break;
case 'chat':
room.chat.push({
id: line.id,
text: line.text,
at: line.at,
...(room.state ? { turn: this.game.turn(room.state) } : {}),
...(line.name ? { name: line.name } : {}),
...(line.keeper ? { keeper: true as const } : {}),
...(line.to ? { to: line.to } : {}),
...(line.note !== undefined ? { note: line.note } : {})
});
if (room.chat.length > CHAT_KEEP) room.chat.splice(0, room.chat.length - CHAT_KEEP);
break;
}
}
private replay(id: string, lines: LedgerLine[]): Room<State> | null {
const first = lines[0];
if (!first || first.t !== 'room') return null;
const room = this.blank(id, first.seats, first.createdAt, first.rematchOf ?? null, first.expected ?? [], cleanOptions(this.game, first.options), lines.length);
for (const line of lines) {
this.apply(room, line);
if (line.t === 'turn' || line.t === 'input') room.updatedAt = line.at;
}
return room;
}
}
+80
View File
@@ -0,0 +1,80 @@
// One append-only JSONL file per room. A room is its ledger replayed from the
// top: the engine is deterministic given the seed and the recorded inputs, so
// nothing else needs saving.
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import type { SeatId, TableOptions } from '../../src/lib/game/spec';
export type LedgerLine =
/** `rematchOf` and `expected` mark a table opened for a rematch: whose it follows, and whose seats are held. */
| { t: 'room'; id: string; seats: number; createdAt: number; rematchOf?: string; expected?: string[]; options: TableOptions }
/** A seat holds only the hash of its token; the token itself goes once to the browser that earned it. A bot's hash is empty. */
| { t: 'seat'; id: SeatId; name: string; tokenHash: string; bot: boolean }
/**
* A person's seat got a new token, from the keeper or a phrase the host made, for a player whose browser lost the
* old one; the old one opens nothing after. A seat a bot was standing in for is the person's again.
*/
| { t: 'reseat'; at: number; id: SeatId; tokenHash: string }
/** The host gave a person's seat to a bot, which plays it from here on; a reseat gives it back. */
| { t: 'standIn'; at: number; id: SeatId; by: SeatId }
/** One seat's move for the round in progress, so a restart keeps it. The turn line that follows carries every input again. */
| { t: 'input'; at: number; id: SeatId; input: unknown }
/** A bot sent away by the host before the game began; its seat id is free again. */
| { t: 'unseat'; id: SeatId }
/** A seat's ranking of the table's choices, best first, before the game begins; the latest for a seat stands. */
| { t: 'rank'; id: SeatId; ranking: string[] }
/**
* The seed and the rules revision the game began under (a later fix keeps
* this revision's path for it), and at a table that asks for rankings,
* the seats' rankings as the deal read them.
*/
| { t: 'start'; seed: number; rules: number; rankings?: Record<SeatId, string[]> }
| { t: 'turn'; at: number; inputs: Record<SeatId, unknown> }
/** Written after the turn that ends the game, for anything that reads ledgers without the engine. */
| { t: 'over'; at: number; winner: SeatId | null; reason: string }
/**
* A line of table talk: from a seat, or, with `name`, from the Peanut Gallery (id SPECTATOR).
* `to` names the seats a private line was said to; `note` is a bot's memory of what it said, never shown.
*/
| { t: 'chat'; at: number; id: SeatId; text: string; name?: string; keeper?: true; to?: SeatId[]; note?: unknown }
/** The host let the gallery talk, or hushed it. */
| { t: 'galleryTalk'; at: number; on: boolean; by: SeatId }
/** A seat is held for the keeper of the site, called to the table. */
| { t: 'challenge'; at: number; by: SeatId; keeper: string }
/** A finished table called for a rematch: where it went, and who called. */
| { t: 'rematch'; at: number; to: string; by: SeatId };
export class Store {
constructor(private dir: string) {
mkdirSync(dir, { recursive: true });
}
private path(roomId: string): string {
return join(this.dir, `${roomId}.jsonl`);
}
append(roomId: string, line: LedgerLine): void {
appendFileSync(this.path(roomId), JSON.stringify(line) + '\n');
}
read(roomId: string): LedgerLine[] {
const path = this.path(roomId);
if (!existsSync(path)) return [];
return readFileSync(path, 'utf8')
.split('\n')
.filter((l) => l.trim())
.map((l) => JSON.parse(l) as LedgerLine);
}
/** Whether a ledger exists on disk, loaded or not; a code must not be reissued over one. */
exists(roomId: string): boolean {
return existsSync(this.path(roomId));
}
roomIds(): string[] {
return readdirSync(this.dir)
.filter((f) => f.endsWith('.jsonl'))
.map((f) => f.slice(0, -'.jsonl'.length));
}
}
+33
View File
@@ -0,0 +1,33 @@
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { game, type Input, type State } from '../../src/lib/game';
import type { GameSpec } from '../../src/lib/game/spec';
import { Rooms } from './rooms';
import { Store } from './store';
import { Tallies } from './tally';
let dir: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'tally-'));
});
afterEach(() => {
rmSync(dir, { recursive: true, force: true });
});
describe('the tally', () => {
it("adds a game's own lines from every game begun, finished or not", () => {
const counted: GameSpec<State, Input> = { ...game, tallyBegun: () => ({ 'games of High Card begun': 1 }) };
const rooms = new Rooms(counted, new Store(dir));
for (let i = 0; i < 2; i++) {
const host = rooms.create('Ann', 2);
rooms.addBot(host.room, host.token);
rooms.begin(host.room, host.token);
}
rooms.create('Bo', 2);
const t = new Tallies(counted, new Store(dir)).get();
expect(t).toMatchObject({ tablesOpened: 3, gamesBegun: 2, gamesFinished: 0 });
expect(t.byGame).toEqual({ 'games of High Card begun': 2 });
});
});
+97
View File
@@ -0,0 +1,97 @@
// The tally: what the ledgers add up to, for the hall's about panel. Read
// from the files on demand and cached for a minute, so a curious visitor
// costs nothing and a busy hall costs one scan a minute. The counts are
// the kit's; a game may add its own lines through GameSpec.tally (from a
// finished game) and GameSpec.tallyBegun (from any game begun).
import { cleanOptions, type GameSpec, type SeatId } from '../../src/lib/game/spec';
import type { Tally } from '../../src/lib/net/view';
import type { LedgerLine, Store } from './store';
const GAP_LIMIT_MS = 10 * 60 * 1000;
const CACHE_MS = 60 * 1000;
export class Tallies<State, Input> {
private cached: { at: number; tally: Tally } | null = null;
constructor(
private game: GameSpec<State, Input>,
private store: Store
) {}
get(): Tally {
if (this.cached && Date.now() - this.cached.at < CACHE_MS) return this.cached.tally;
const tally = this.count();
this.cached = { at: Date.now(), tally };
return tally;
}
private count(): Tally {
const t: Tally = { tablesOpened: 0, gamesBegun: 0, gamesFinished: 0, namesSeated: 0, turnsPlayed: 0, minutesAtTable: 0, longestGameTurns: 0, gamesWithBot: 0, talkLines: 0, firstGameAt: null, byGame: {} };
const names = new Set<string>();
let firstStart = Infinity;
for (const id of this.store.roomIds()) {
let lines: LedgerLine[];
try {
lines = this.store.read(id);
} catch {
continue; // an unreadable ledger is left out of the count, as its room is left unloaded
}
if (lines[0]?.t !== 'room') continue;
t.tablesOpened += 1;
const seats: { id: SeatId; name: string; bot: boolean }[] = [];
let state: State | null = null;
let turns = 0;
let lastMoveAt = 0;
let hasBot = false;
let over: LedgerLine | null = null;
for (const line of lines) {
if (line.t === 'seat') {
seats.push(line);
if (line.bot) hasBot = true;
else names.add(line.name.toLowerCase());
} else if (line.t === 'unseat') {
const i = seats.findIndex((s) => s.id === line.id);
if (i >= 0) seats.splice(i, 1);
} else if (line.t === 'start') {
t.gamesBegun += 1;
if (hasBot) t.gamesWithBot += 1;
if (lines[0].createdAt < firstStart) firstStart = lines[0].createdAt;
for (const [k, v] of Object.entries(this.game.tallyBegun?.(cleanOptions(this.game, lines[0].options)) ?? {})) t.byGame[k] = (t.byGame[k] ?? 0) + v;
try {
state = this.game.create(Object.fromEntries(seats.map((s) => [s.id, s.name])), line.seed, line.rules, cleanOptions(this.game, lines[0].options), line.rankings);
} catch {
state = null;
}
} else if (line.t === 'input') {
if (lastMoveAt && line.at - lastMoveAt < GAP_LIMIT_MS) t.minutesAtTable += (line.at - lastMoveAt) / 60000;
lastMoveAt = line.at;
} else if (line.t === 'turn') {
turns += 1;
if (lastMoveAt && line.at - lastMoveAt < GAP_LIMIT_MS) t.minutesAtTable += (line.at - lastMoveAt) / 60000;
lastMoveAt = line.at;
if (state) {
try {
state = this.game.resolve(state, line.inputs as Record<SeatId, Input>);
} catch {
state = null;
}
}
} else if (line.t === 'chat') t.talkLines += 1;
else if (line.t === 'over') over = line;
}
t.turnsPlayed += turns;
if (turns > t.longestGameTurns) t.longestGameTurns = turns;
if (over) {
t.gamesFinished += 1;
if (state && this.game.tally) {
for (const [k, v] of Object.entries(this.game.tally(state))) t.byGame[k] = (t.byGame[k] ?? 0) + v;
}
}
}
t.namesSeated = names.size;
t.minutesAtTable = Math.round(t.minutesAtTable);
t.firstGameAt = Number.isFinite(firstStart) ? new Date(firstStart).toISOString() : null;
return t;
}
}