import fs from 'node:fs'; import path from 'node:path'; import { randomUUID } from 'node:crypto'; import type { Phase, PlayMode, Role, Seat } from '@two-keys/shared'; import { makeCode } from './codes'; export interface PlayerRec { token: string; seat: Seat | null; ready: boolean; viewing: string | null; } export interface Room { code: string; gameId: string; mode: PlayMode; phase: Phase; players: PlayerRec[]; createdAt: number; lastActivity: number; notepad: string; keys: string[]; startedAt: number | null; finishedAt: number | null; penaltySeconds: number; hintsUsed: number; wrongGuesses: number; /** Engine-specific state, owned by the game's engine. */ engine: unknown; result: { success: boolean; ending: string | null; reveal: string | null; outOfTime?: boolean } | null; } export const ROOM_TTL_MS = 24 * 60 * 60 * 1000; export const SNAPSHOT_INTERVAL_MS = 10_000; export function seatFor(room: Room, role: Role): PlayerRec | undefined { return room.players.find((p) => p.seat === role || p.seat === 'both'); } /** In-memory room store, snapshotted to disk so a restart doesn't kill a game in progress. */ export class RoomStore { readonly rooms = new Map(); private timer: NodeJS.Timeout | null = null; constructor(private readonly file: string | null) {} create(gameId: string, mode: PlayMode, now = Date.now()): { room: Room; player: PlayerRec } { const player: PlayerRec = { token: randomUUID(), seat: mode === 'couch' ? 'both' : null, ready: false, viewing: null, }; const room: Room = { code: makeCode((code) => this.rooms.has(code)), gameId, mode, phase: 'lobby', players: [player], createdAt: now, lastActivity: now, notepad: '', keys: [], startedAt: null, finishedAt: null, penaltySeconds: 0, hintsUsed: 0, wrongGuesses: 0, engine: null, result: null, }; this.rooms.set(room.code, room); return { room, player }; } get(code: string): Room | undefined { return this.rooms.get(code); } /** Drop rooms idle for more than 24h. */ sweep(now = Date.now()): number { let removed = 0; for (const [code, room] of this.rooms) { if (now - room.lastActivity > ROOM_TTL_MS) { this.rooms.delete(code); removed++; } } return removed; } load(isKnownGame: (gameId: string) => boolean): void { if (!this.file || !fs.existsSync(this.file)) return; try { const rooms = JSON.parse(fs.readFileSync(this.file, 'utf8')) as Room[]; for (const room of rooms) { if (room?.code && isKnownGame(room.gameId)) this.rooms.set(room.code, room); } this.sweep(); } catch (err) { console.warn(`Could not restore rooms from ${this.file}:`, err); } } snapshot(): void { if (!this.file) return; try { fs.mkdirSync(path.dirname(this.file), { recursive: true }); const tmp = `${this.file}.tmp`; fs.writeFileSync(tmp, JSON.stringify([...this.rooms.values()])); fs.renameSync(tmp, this.file); } catch (err) { console.warn('Room snapshot failed:', err); } } start(): void { this.timer = setInterval(() => { this.sweep(); this.snapshot(); }, SNAPSHOT_INTERVAL_MS); this.timer.unref(); } stop(): void { if (this.timer) clearInterval(this.timer); this.timer = null; this.snapshot(); } }