Files
wikideck/server/game/index.ts
T

46 lines
2.5 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 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 }): 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) });
const timer = setInterval(() => host.sweep(), 5_000);
timer.unref();
return createGameRouter(host, discovery);
}