78 lines
4.1 KiB
TypeScript
78 lines
4.1 KiB
TypeScript
/**
|
|
* Entry point for the game-modes API. server/testnet/http.ts mounts it with one line:
|
|
* app.use('/api/game', await (await import('../game/index.ts')).gameRouter({ dataDir, enrichment: wikipediaEnrichment }));
|
|
*/
|
|
import { join } from 'node:path';
|
|
import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
import type express from 'express';
|
|
import { loadModes, hostIdentity, gamePeers } from './config.ts';
|
|
import { ModeDiscovery } from './discovery.ts';
|
|
import { ModeHost } from './host.ts';
|
|
import { createGameRouter } from './router.ts';
|
|
import { MatchStore } from './store.ts';
|
|
import type { EnginePort } from './engine-port.ts';
|
|
import { TrendCache } from './trends.ts';
|
|
|
|
type Enrichment = { get(pageId: number): Promise<{ pageviews: { trendPercent: number | null } }> };
|
|
|
|
export async function gameRouter(options: { dataDir: string | null; enrichment?: Enrichment;
|
|
engine?: EnginePort<any, any, any, any>; env?: NodeJS.ProcessEnv; warmTrends?: boolean; handleSignals?: boolean }): Promise<express.Router> {
|
|
const env = options.env ?? process.env;
|
|
const engine = options.engine ?? (await import('./engine-binding.ts')).engineBinding;
|
|
const modes = loadModes(env);
|
|
// Trends come from a slowly warmed, cache-only store: never a Wikipedia call per match.
|
|
let trends: TrendCache | undefined;
|
|
if (options.enrichment && modes.some(m => m.cards.preset === 'trending')) {
|
|
const enrichment = options.enrichment;
|
|
// Wikipedia egress is shared and rate-limited: default one page per 20 s (≥ 15 s enforced).
|
|
const interval = Number(env.WIKIDECK_GAME_TREND_INTERVAL_MS ?? 20_000);
|
|
if (!Number.isSafeInteger(interval) || interval < 15_000 || interval > 3_600_000) throw new Error('WIKIDECK_GAME_TREND_INTERVAL_MS must be 15000..3600000');
|
|
trends = new TrendCache(pageId => enrichment.get(pageId), { intervalMs: interval });
|
|
for (const card of engine.starterDeck(engine.defaultRuleset, 'trend-warmup')) {
|
|
const id = engine.cardPageId(card); if (id !== null) trends.enqueue(id);
|
|
}
|
|
for (const card of engine.previewPool(engine.defaultRuleset, 'trend-warmup', 64)) {
|
|
const id = engine.cardPageId(card); if (id !== null) trends.enqueue(id);
|
|
}
|
|
if (options.warmTrends !== false) trends.start();
|
|
}
|
|
const host = new ModeHost({ identity: hostIdentity(env), modes, engine,
|
|
store: new MatchStore(options.dataDir ? join(options.dataDir, 'game') : null),
|
|
liveData: trends ? async pageId => trends!.get(pageId) : undefined });
|
|
const discovery = new ModeDiscovery({ peers: gamePeers(env) });
|
|
if (options.dataDir) persistLive(host, join(options.dataDir, 'game'), options.handleSignals !== false);
|
|
const timer = setInterval(() => host.sweep(), 5_000);
|
|
timer.unref();
|
|
return createGameRouter(host, discovery);
|
|
}
|
|
|
|
const MAX_LIVE_BYTES = 32 * 1024 * 1024;
|
|
|
|
/**
|
|
* Keep live lobbies and matches across restarts: restore `live.json` on start, save it every
|
|
* 15 s and synchronously on SIGTERM/SIGINT. These listeners are registered when the router is
|
|
* mounted, before the node's own shutdown handler, so the save finishes before it exits.
|
|
*/
|
|
export function persistLive(host: ModeHost, directory: string, handleSignals: boolean): { save(): void } {
|
|
const file = join(directory, 'live.json');
|
|
if (existsSync(file)) {
|
|
try {
|
|
const text = readFileSync(file, 'utf8');
|
|
if (text.length <= MAX_LIVE_BYTES) console.log(`Game modes: restored ${host.restore(text)} live lobbies`);
|
|
} catch (e) { console.error(`Game modes: could not restore live lobbies: ${(e as Error).message.slice(0, 200)}`); }
|
|
// Keep the file we restored from for inspection; the next save writes a fresh one.
|
|
try { renameSync(file, `${file}.restored`); } catch { /* ignore */ }
|
|
}
|
|
const save = () => {
|
|
try {
|
|
const tmp = `${file}.tmp`;
|
|
writeFileSync(tmp, host.snapshot(), { mode: 0o600 });
|
|
renameSync(tmp, file);
|
|
} catch (e) { console.error(`Game modes: could not save live lobbies: ${(e as Error).message.slice(0, 200)}`); }
|
|
};
|
|
const timer = setInterval(save, 15_000);
|
|
timer.unref();
|
|
if (handleSignals) for (const signal of ['SIGTERM', 'SIGINT'] as const) process.once(signal, save);
|
|
return { save };
|
|
}
|