/** * Server-side match registry for the Call for Fire versus mode. * * 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; the SSE pipeline it pushes through has the same limitation. * * The pure engine (./engine, ./views) never touches timers or I/O. This wrapper * owns turn timeouts, lobby broadcasts, per-user snapshot pushes, match * completion rewards, and the expiry sweep. */ import { getPayload } from "payload"; import type { Payload } from "payload"; import { broadcast, broadcastToUser } from "@/lib/realtime/bus"; import { generateTableName } from "@/lib/minigames/tableNames"; import { VERSUS_MAX_MATCHES, VERSUS_MAX_NAME_LENGTH, VERSUS_MATCH_EXPIRY_MS, VERSUS_SWEEP_INTERVAL_MS, VERSUS_TURN_TIMEOUT_MS, VERSUS_WAITING_USER_ID, type FobPlacement, } from "./constants"; import { createVersusState, fireShot, placeFleet, resign, seatPlayer, skipTurn, type VersusShotInput, } from "./engine"; import { awardVersusResult, type VersusMatchResult } from "./stats"; import type { VersusMatchSummary, VersusMatchView, VersusState } from "./types"; import { buildVersusView } from "./views"; const MAX_SEATS = 2; interface VersusMatchRecord { id: string; name: string | null; version: number; hostUserId: number; seatMap: [number | null, number | null]; state: VersusState; userNames: Map; awarded: boolean; turnTimer: ReturnType | null; turnTimerVersion: number | null; turnDeadlineAt: string | null; createdAt: string; lastActivityAt: number; } type VersusMatchesStore = Map; interface VersusGlobalRegistry { __cffVersusMatches?: VersusMatchesStore; } const globalRegistry = globalThis as typeof globalThis & VersusGlobalRegistry; const matches: VersusMatchesStore = (globalRegistry.__cffVersusMatches ??= new Map()); function indexOfUser(record: VersusMatchRecord, userId: number): 0 | 1 | null { if (record.seatMap[0] === userId) return 0; if (record.seatMap[1] === userId) return 1; return null; } function seatedCountOf(record: VersusMatchRecord): number { return record.seatMap.filter((id) => id !== null).length; } async function getPayloadOrNull(): Promise { try { const config = (await import("@payload-config")).default; return await getPayload({ config }); } catch { return null; } } function clearTurnTimer(record: VersusMatchRecord): void { if (record.turnTimer) clearTimeout(record.turnTimer); record.turnTimer = null; record.turnTimerVersion = null; record.turnDeadlineAt = null; } function scheduleTurnTimer(record: VersusMatchRecord): void { clearTurnTimer(record); if (record.state.phase !== "battle" || record.state.turn === null) return; record.turnTimerVersion = record.version; record.turnDeadlineAt = new Date(Date.now() + VERSUS_TURN_TIMEOUT_MS).toISOString(); record.turnTimer = setTimeout(() => onTurnTimeout(record), VERSUS_TURN_TIMEOUT_MS); } function onTurnTimeout(record: VersusMatchRecord): void { const scheduledVersion = record.turnTimerVersion; record.turnTimer = null; record.turnTimerVersion = null; record.turnDeadlineAt = null; if (scheduledVersion === null || scheduledVersion !== record.version) return; record.state = skipTurn(record.state); record.version += 1; afterMutation(record); } function matchResults(state: VersusState): VersusMatchResult[] { return state.players .filter((player) => player.userId !== VERSUS_WAITING_USER_ID) .map((player) => ({ userId: player.userId, won: state.winner !== null && state.players[state.winner].userId === player.userId, fobsDestroyed: player.fobsDestroyed, cellsHit: player.cellsHit, })); } /** Fire-and-forget reward for a completed match; idempotent per record. */ function awardCompleted(record: VersusMatchRecord): 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 awardVersusResult(payload, record.id, results); })(); } function afterMutation(record: VersusMatchRecord): void { if (record.state.phase === "battle") { scheduleTurnTimer(record); } else { clearTurnTimer(record); } if (record.state.phase === "complete") awardCompleted(record); push(record); } function buildView(record: VersusMatchRecord, index: 0 | 1): VersusMatchView { return { matchId: record.id, name: record.name, version: record.version, turnDeadline: record.turnDeadlineAt, ...buildVersusView(record.state, index), }; } function listSummaries(viewerId?: number): VersusMatchSummary[] { return [...matches.values()].map((record) => ({ matchId: record.id, name: record.name, hostName: record.userNames.get(record.hostUserId) ?? "Unknown", guestName: record.seatMap[1] !== null ? (record.userNames.get(record.seatMap[1]) ?? null) : null, seatedCount: seatedCountOf(record), maxSeats: MAX_SEATS, phase: seatedCountOf(record) < 2 ? "waiting" : record.state.phase, createdAt: record.createdAt, joined: viewerId !== undefined && indexOfUser(record, viewerId) !== null, })); } function push(record: VersusMatchRecord): void { for (const userId of record.seatMap) { if (userId === null || userId === VERSUS_WAITING_USER_ID) continue; const index = indexOfUser(record, userId); if (index === null) continue; broadcastToUser("cff-versus-match", userId, { matchId: record.id, view: buildView(record, index), }); } broadcast("cff-versus-matches", { matches: listSummaries() }); } function disposeMatch(record: VersusMatchRecord): void { clearTurnTimer(record); awardCompleted(record); matches.delete(record.id); broadcast("cff-versus-matches", { matches: listSummaries() }); } /* ------------------------------------------------------------------ public */ export function createMatch(userId: number, displayName: string): string { if (matches.size >= VERSUS_MAX_MATCHES) { throw new Error("The maximum number of live matches exists. Try again later."); } for (const existing of matches.values()) { if (indexOfUser(existing, userId) !== null) { throw new Error("You are already in a match. Leave it first."); } } const record: VersusMatchRecord = { id: crypto.randomUUID(), name: generateTableName(), version: 1, hostUserId: userId, seatMap: [userId, null], state: createVersusState( { userId, name: displayName }, { userId: VERSUS_WAITING_USER_ID, name: "Waiting for an opponent" }, ), userNames: new Map([[userId, displayName]]), awarded: false, turnTimer: null, turnTimerVersion: null, turnDeadlineAt: null, createdAt: new Date().toISOString(), lastActivityAt: Date.now(), }; matches.set(record.id, record); push(record); return record.id; } export function listMatchSummaries(viewerId?: number): VersusMatchSummary[] { return listSummaries(viewerId); } export function joinMatch(matchId: string, userId: number, displayName: string): VersusMatchView { const record = matches.get(matchId); if (!record) throw new Error("Match not found."); const existing = indexOfUser(record, userId); if (existing !== null) return buildView(record, existing); for (const other of matches.values()) { if (other.id !== record.id && indexOfUser(other, userId) !== null) { throw new Error("You are already in another match. Leave it first."); } } if (record.seatMap[1] !== null) throw new Error("This match is already full."); if (record.state.phase !== "placing") throw new Error("This match has already started."); record.seatMap[1] = userId; record.userNames.set(userId, displayName); record.state = seatPlayer(record.state, 1, { userId, name: displayName }); record.lastActivityAt = Date.now(); record.version += 1; push(record); return buildView(record, 1); } export function getSnapshotFor(matchId: string, userId: number): VersusMatchView { const record = matches.get(matchId); if (!record) throw new Error("Match not found."); const index = indexOfUser(record, userId); if (index === null) throw new Error("You are not in this match."); record.lastActivityAt = Date.now(); return buildView(record, index); } export function placeFleetFor( matchId: string, userId: number, placements: readonly FobPlacement[], ): VersusMatchView { const record = matches.get(matchId); if (!record) throw new Error("Match not found."); const index = indexOfUser(record, userId); if (index === null) throw new Error("You are not in this match."); const result = placeFleet(record.state, index, placements); if ("error" in result) throw new Error(result.error); record.state = result.state; record.lastActivityAt = Date.now(); record.version += 1; afterMutation(record); return buildView(record, index); } export function fireShotFor( matchId: string, userId: number, input: VersusShotInput, ): VersusMatchView { const record = matches.get(matchId); if (!record) throw new Error("Match not found."); const index = indexOfUser(record, userId); if (index === null) throw new Error("You are not in this match."); const result = fireShot(record.state, index, input); if ("error" in result) throw new Error(result.error); record.state = result.state; record.lastActivityAt = Date.now(); record.version += 1; afterMutation(record); return buildView(record, index); } export function leaveMatch(matchId: string, userId: number): void { const record = matches.get(matchId); if (!record) return; const index = indexOfUser(record, userId); if (index === null) return; if (record.state.phase === "battle") { const resigned = resign(record.state, index); if (!("error" in resigned)) { record.state = resigned.state; record.version += 1; } } record.seatMap[index] = null; record.userNames.delete(userId); record.lastActivityAt = Date.now(); record.version += 1; if (seatedCountOf(record) === 0) { disposeMatch(record); return; } afterMutation(record); } export function forceExpireMatch(matchId: string): void { const record = matches.get(matchId); if (!record) throw new Error("Match not found."); disposeMatch(record); } function sweepExpiredMatches(): void { const now = Date.now(); let expired = false; for (const record of [...matches.values()]) { if (now - record.lastActivityAt <= VERSUS_MATCH_EXPIRY_MS) continue; disposeMatch(record); expired = true; } if (expired) broadcast("cff-versus-matches", { matches: listSummaries() }); } const sweepInterval = setInterval(sweepExpiredMatches, VERSUS_SWEEP_INTERVAL_MS); sweepInterval.unref?.(); /** Test-only helper: drop every match without awards. */ export function clearMatchesForTests(): void { for (const record of matches.values()) clearTurnTimer(record); matches.clear(); } export { VERSUS_MAX_NAME_LENGTH }; export type { VersusMatchView, VersusMatchSummary };