/** * Server-side match registry for Ordnance Disposal (internal key `bomperator`). * * Holds live match records in a module-level Map anchored on `globalThis` (same * pattern as src/lib/minigames/blackjack/tables.ts), so Next.js dev module * duplication does not fork the store. SINGLE-INSTANCE ONLY: match state lives * in process memory, so this will not work across multiple server instances, * and a server restart or redeploy ends any live match. * * The pure engine (./engine, ./views) never touches timers or I/O. This wrapper * owns the fixed ~10 Hz tick loop, lobby membership, the disconnect/reconnect * window, completion rewards, and the idle-expiry sweep. Clients POST inputs and * poll snapshots; the in-memory SSE bus is used only for the profile-update nudge * after awards (it is unreliable across dev module copies, same as blackjack). */ import { getPayload } from "payload"; import type { Payload } from "payload"; import { generateTableName } from "@/lib/minigames/tableNames"; import { BOMP_MATCH_EXPIRY_MS, BOMP_MAX_MATCHES, BOMP_SWEEP_INTERVAL_MS, DEFAULT_ROUND_TARGET, INPUT_RATE_LIMIT_PER_S, MAX_SEATS, MIN_TO_START, RECONNECT_WINDOW_MS, ROUND_TARGET_OPTIONS, TICK_MS, } from "./constants"; import { applyInput, createMatchState, dissolveMatch, eliminateSeat, startRound, tick, type BomperatorInput, } from "./engine"; import { awardBomperatorResult, type BomperatorMatchResult } from "./stats"; import type { BomperatorMatchSummary, BomperatorState, BomperatorView } from "./types"; import { buildBomperatorView } from "./views"; import { broadcastToUser } from "@/lib/realtime/bus"; interface RosterEntry { readonly userId: number; readonly name: string; } interface BomperatorMatchRecord { id: string; name: string | null; version: number; hostUserId: number; roster: RosterEntry[]; /** Seats whose occupant left permanently (window expired or lobby leave). */ leftSeats: Set; roundTarget: number; seed: number; state: BomperatorState; awarded: boolean; tickTimer: ReturnType | null; createdAt: string; lastActivityAt: number; /** Per-seat input rate limiting: rolling one-second window. */ inputWindow: Map; /** Per-seat highest client input seq applied (rejects out-of-order POSTs). */ lastInputSeq: Map; /** userId -> last time they polled/watched, so we can push snapshots to * seated players AND active spectators over the SSE bus. */ viewers: Map; } type MatchesStore = Map; interface GlobalRegistry { __bomperatorMatches?: MatchesStore; } const globalRegistry = globalThis as typeof globalThis & GlobalRegistry; const matches: MatchesStore = (globalRegistry.__bomperatorMatches ??= new Map()); /* --------------------------------------------------------------- helpers */ function seatOf(record: BomperatorMatchRecord, userId: number): number | null { const index = record.roster.findIndex((entry) => entry.userId === userId); return index === -1 ? null : index; } /** Seats still in the match (roster minus those who left permanently). */ function activeSeatCount(record: BomperatorMatchRecord): number { return record.roster.length - record.leftSeats.size; } function rosterDescriptors(record: BomperatorMatchRecord) { return record.roster.map((entry, seat) => ({ seat, userId: entry.userId, name: entry.name })); } async function getPayloadOrNull(): Promise { try { const config = (await import("@payload-config")).default; return await getPayload({ config }); } catch { return null; } } function buildViewFor(record: BomperatorMatchRecord, userId: number | null): BomperatorView { const yourSeat = userId === null ? null : seatOf(record, userId); const view = buildBomperatorView(record.state, { matchId: record.id, name: record.name, version: record.version, yourSeat, }); // Echo each seat's last applied input seq so the owning client can reconcile // its local prediction against what the server has actually consumed. const players = view.players.map((p) => ({ ...p, lastInputSeq: record.lastInputSeq.get(p.seat) ?? 0, })); return { ...view, players }; } /** * Push a fresh per-user snapshot to every seated technician and active spectator * over the SSE bus. This is the low-latency path; the client keeps a slow guarded * poll as a correctness fallback (the bus is single-instance and can drop on dev * module reloads). Recipients are deduped; stale spectators are pruned. */ function pushSnapshots(record: BomperatorMatchRecord): void { const now = Date.now(); const recipients = new Set(); for (const entry of record.roster) recipients.add(entry.userId); for (const [userId, seen] of record.viewers) { if (now - seen > 30_000) record.viewers.delete(userId); else recipients.add(userId); } for (const userId of recipients) { broadcastToUser("bomperator-state", userId, { matchId: record.id, snapshot: buildViewFor(record, userId), }); } } /** Rebuild the inert lobby state after a membership change (contiguous seats). */ function rebuildLobbyState(record: BomperatorMatchRecord): void { record.state = createMatchState(rosterDescriptors(record), record.roundTarget, record.seed); } function listSummaries(viewerId?: number): BomperatorMatchSummary[] { return [...matches.values()].map((record) => ({ matchId: record.id, name: record.name, hostName: record.roster[0]?.name ?? "Unknown", seatedCount: record.roster.length, maxSeats: MAX_SEATS, phase: record.roster.length < MIN_TO_START && record.state.phase === "lobby" ? "waiting" : record.state.phase, roundTarget: record.roundTarget, createdAt: record.createdAt, joined: viewerId !== undefined && seatOf(record, viewerId) !== null, })); } /* ----------------------------------------------------------------- awards */ function matchResults(state: BomperatorState): BomperatorMatchResult[] { return state.players.map((player) => ({ userId: player.userId, won: state.matchWinnerSeat !== null && state.players[state.matchWinnerSeat]?.userId === player.userId, kills: player.kills, roundsWon: player.roundsWon, })); } /** Fire-and-forget reward for a completed match; idempotent per record. */ function awardCompleted(record: BomperatorMatchRecord): void { if (record.awarded || record.state.phase !== "complete") return; record.awarded = true; const results = matchResults(record.state); if (results.length === 0) return; void (async () => { const payload = await getPayloadOrNull(); if (!payload) return; await awardBomperatorResult(payload, record.id, results); })(); } /* -------------------------------------------------------------- tick loop */ /** * When false, `startTickLoop` does not spawn a wall-clock interval. Integration * tests disable this and drive the sim deterministically via `advanceForTests`. */ let autoTickEnabled = true; function startTickLoop(record: BomperatorMatchRecord): void { if (!autoTickEnabled || record.tickTimer) return; record.tickTimer = setInterval(() => step(record), TICK_MS); record.tickTimer.unref?.(); } function stopTickLoop(record: BomperatorMatchRecord): void { if (record.tickTimer) clearInterval(record.tickTimer); record.tickTimer = null; } /** Patch a seat's presence flags without disturbing engine rules. */ function withPresence( state: BomperatorState, seat: number, connected: boolean, disconnectedAt: number | null, ): BomperatorState { const players = [...state.players]; if (!players[seat]) return state; players[seat] = { ...players[seat], connected, disconnectedAt }; return { ...state, players }; } /** One simulation step: expire disconnects, advance the engine, resolve ends. */ function step(record: BomperatorMatchRecord, now: number = Date.now()): void { let state = record.state; // Expire seats whose reconnect window has elapsed: eliminate + mark left. for (let seat = 0; seat < record.roster.length; seat += 1) { if (record.leftSeats.has(seat)) continue; const player = state.players[seat]; if (player && !player.connected && player.disconnectedAt !== null) { if (now - player.disconnectedAt > RECONNECT_WINDOW_MS) { state = eliminateSeat(state, seat); record.leftSeats.add(seat); } } } const prevRound = state.roundIndex; state = tick(state); record.version += 1; // A technician still disconnected when a fresh round opens has left the match. if (state.roundIndex > prevRound) { for (let seat = 0; seat < record.roster.length; seat += 1) { if (record.leftSeats.has(seat)) continue; const player = state.players[seat]; if (player && !player.connected) { state = eliminateSeat(state, seat); record.leftSeats.add(seat); } } } // Dissolve once fewer than two technicians remain in the match. if (activeSeatCount(record) < MIN_TO_START && state.phase !== "complete") { state = dissolveMatch(state); } record.state = state; // Push the fresh snapshot to seated players + spectators (low-latency path). pushSnapshots(record); if (state.phase === "complete") { stopTickLoop(record); awardCompleted(record); } } /* ------------------------------------------------------------------ public */ export function createMatch( userId: number, displayName: string, roundTarget: number = DEFAULT_ROUND_TARGET, ): string { if (matches.size >= BOMP_MAX_MATCHES) { throw new Error("The maximum number of live matches exists. Try again later."); } for (const existing of matches.values()) { // A finished match never blocks starting a new one (it clears on its own). if (seatOf(existing, userId) !== null && existing.state.phase !== "complete") { throw new Error("You are already in a match. Leave it first."); } } const target = (ROUND_TARGET_OPTIONS as readonly number[]).includes(roundTarget) ? roundTarget : DEFAULT_ROUND_TARGET; const seed = (Date.now() ^ Math.floor(Math.random() * 0xffffffff)) >>> 0; const record: BomperatorMatchRecord = { id: crypto.randomUUID(), name: generateTableName(), version: 1, hostUserId: userId, roster: [{ userId, name: displayName }], leftSeats: new Set(), roundTarget: target, seed, state: createMatchState([{ seat: 0, userId, name: displayName }], target, seed), awarded: false, tickTimer: null, createdAt: new Date().toISOString(), lastActivityAt: Date.now(), inputWindow: new Map(), lastInputSeq: new Map(), viewers: new Map(), }; matches.set(record.id, record); return record.id; } export function listMatchSummaries(viewerId?: number): BomperatorMatchSummary[] { return listSummaries(viewerId); } export function joinMatch(matchId: string, userId: number, displayName: string): BomperatorView { const record = matches.get(matchId); if (!record) throw new Error("Match not found."); const existing = seatOf(record, userId); if (existing !== null) { // Rejoin: restore a held seat within the reconnect window. if (!record.state.players[existing]?.connected) { record.state = withPresence(record.state, existing, true, null); record.version += 1; } record.lastActivityAt = Date.now(); record.viewers.set(userId, Date.now()); pushSnapshots(record); return buildViewFor(record, userId); } for (const other of matches.values()) { if ( other.id !== record.id && seatOf(other, userId) !== null && other.state.phase !== "complete" ) { throw new Error("You are already in another match. Leave it first."); } } if (record.roster.length >= MAX_SEATS) throw new Error("This match is full."); if (record.state.phase !== "lobby") throw new Error("This match has already started."); record.roster.push({ userId, name: displayName }); rebuildLobbyState(record); record.lastActivityAt = Date.now(); record.version += 1; record.viewers.set(userId, Date.now()); pushSnapshots(record); return buildViewFor(record, userId); } /** Snapshot for a poller. Non-seated users get a read-only spectator view. */ export function getSnapshotFor(matchId: string, userId: number): BomperatorView { const record = matches.get(matchId); if (!record) throw new Error("Match not found."); record.lastActivityAt = Date.now(); // Register as a viewer so subsequent ticks push snapshots to us too (players // are always recipients; this is how spectators opt in). record.viewers.set(userId, Date.now()); return buildViewFor(record, userId); } export function startMatch(matchId: string, userId: number): BomperatorView { const record = matches.get(matchId); if (!record) throw new Error("Match not found."); if (seatOf(record, userId) === null) throw new Error("You are not in this match."); if (record.state.phase !== "lobby") throw new Error("This match has already started."); if (record.roster.length < MIN_TO_START) { throw new Error(`Need at least ${MIN_TO_START} technicians to start.`); } rebuildLobbyState(record); record.state = startRound(record.state); record.lastActivityAt = Date.now(); record.version += 1; startTickLoop(record); pushSnapshots(record); return buildViewFor(record, userId); } export function submitInput( matchId: string, userId: number, input: BomperatorInput, ): void { const record = matches.get(matchId); if (!record) throw new Error("Match not found."); const seat = seatOf(record, userId); if (seat === null) throw new Error("You are not in this match."); if (!record.state.players[seat]?.connected) throw new Error("Your seat is not active."); // Rate limit: reject more than INPUT_RATE_LIMIT_PER_S inputs in a second. const now = Date.now(); const window = record.inputWindow.get(seat) ?? { count: 0, windowStart: now }; if (now - window.windowStart >= 1000) { window.count = 0; window.windowStart = now; } window.count += 1; if (window.count > INPUT_RATE_LIMIT_PER_S) { record.inputWindow.set(seat, window); throw new Error("Too many inputs. Slow down."); } record.inputWindow.set(seat, window); // Sequence guard: the client fires direction changes immediately, so action // POSTs can arrive out of order. Only the newest intent may win; anything at // or below the last applied seq is a stale echo and is dropped silently. if (typeof input.seq === "number") { const last = record.lastInputSeq.get(seat) ?? -1; if (input.seq <= last) return; record.lastInputSeq.set(seat, input.seq); } record.state = applyInput(record.state, seat, input); record.lastActivityAt = now; } export function leaveMatch(matchId: string, userId: number): void { const record = matches.get(matchId); if (!record) return; const seat = seatOf(record, userId); if (seat === null) return; // A finished drill has nothing to reconnect to: remove it outright so nobody // stays "joined" and blocked from starting a new one until the idle sweep. if (record.state.phase === "complete") { disposeMatch(record); return; } if (record.state.phase === "lobby") { record.roster.splice(seat, 1); rebuildLobbyState(record); record.version += 1; if (record.roster.length === 0) { disposeMatch(record); return; } record.lastActivityAt = Date.now(); pushSnapshots(record); return; } // Mid-match: hold the seat for a reconnect rather than dropping it outright. record.state = withPresence(record.state, seat, false, Date.now()); record.version += 1; record.lastActivityAt = Date.now(); pushSnapshots(record); // If that was the last connected technician, end the match now instead of // leaving a zombie board that only clears after the reconnect window lapses // (and never clears at all if the tick loop died on a server restart). if (!record.state.players.some((player) => player.connected)) { record.state = dissolveMatch(record.state); disposeMatch(record); } } /** * Hard stop: dissolve and remove the match immediately so nobody is stranded in * a drill that cannot finish. Any seated technician may call it (a forfeit beats * being stuck); spectators may not. Awards whatever has been earned. */ export function endMatch(matchId: string, userId: number): void { const record = matches.get(matchId); if (!record) return; // already gone if (seatOf(record, userId) === null && record.hostUserId !== userId) { throw new Error("Only a technician in the drill can end it."); } notifyTerminated(record, userId); if (record.state.phase !== "complete") { record.state = dissolveMatch(record.state); } disposeMatch(record); } /** * Tell every seated technician and active spectator (except the one who ended it) * that the drill was ended by its host, over the SSE bus. Mirrors blackjack's * terminated event; the client also falls back to a neutral toast when its poll * later finds the match gone, so a dropped push still surfaces an explanation. */ function notifyTerminated(record: BomperatorMatchRecord, actorUserId: number): void { const hostName = record.roster.find((entry) => entry.userId === actorUserId)?.name ?? record.roster.find((entry) => entry.userId === record.hostUserId)?.name ?? null; const recipients = new Set(); for (const entry of record.roster) recipients.add(entry.userId); for (const viewerId of record.viewers.keys()) recipients.add(viewerId); recipients.delete(actorUserId); // the host initiated it; no need to tell them for (const recipient of recipients) { broadcastToUser("bomperator-terminated", recipient, { matchId: record.id, reason: "host-ended", hostName, }); } } export function forceExpireMatch(matchId: string): void { const record = matches.get(matchId); if (!record) throw new Error("Match not found."); disposeMatch(record); } function disposeMatch(record: BomperatorMatchRecord): void { stopTickLoop(record); awardCompleted(record); matches.delete(record.id); } function sweepExpiredMatches(): void { const now = Date.now(); for (const record of [...matches.values()]) { if (now - record.lastActivityAt <= BOMP_MATCH_EXPIRY_MS) continue; disposeMatch(record); } } const sweepInterval = setInterval(sweepExpiredMatches, BOMP_SWEEP_INTERVAL_MS); sweepInterval.unref?.(); /** Test-only helper: drop every match and timer without awards. */ export function clearMatchesForTests(): void { for (const record of matches.values()) stopTickLoop(record); matches.clear(); } /** Test-only: disable wall-clock ticking so tests can drive steps manually. */ export function setAutoTickForTests(enabled: boolean): void { autoTickEnabled = enabled; } /** Test-only: run N simulation steps for a match, optionally at a fixed clock. */ export function advanceForTests(matchId: string, ticks = 1, now?: number): void { const record = matches.get(matchId); if (!record) throw new Error("Match not found."); for (let i = 0; i < ticks; i += 1) step(record, now ?? Date.now()); } export { MAX_SEATS, MIN_TO_START }; export type { BomperatorView, BomperatorMatchSummary, BomperatorInput };