88 lines
3.8 KiB
TypeScript
88 lines
3.8 KiB
TypeScript
/**
|
|
* Off-chain match records for this node: an append-only JSON-lines file plus in-memory
|
|
* aggregates (leaderboards, host totals). Nothing here touches the ledger.
|
|
*/
|
|
import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
import { join } from 'node:path';
|
|
import { z } from 'zod';
|
|
|
|
export const MatchRecordSchema = z.object({
|
|
matchId: z.string().regex(/^[a-f0-9]{32}$/),
|
|
modeId: z.string().max(40),
|
|
modeVersion: z.number().int(),
|
|
/** Host-chosen seed. Together with decks and actions it lets anyone replay the match. */
|
|
seed: z.string().max(128),
|
|
/** The resolved ruleset the match ran under (mode overrides already applied). */
|
|
rules: z.unknown(),
|
|
players: z.array(z.object({ id: z.string().regex(/^[a-f0-9]{64}$/), name: z.string().max(24) }).strict()).length(2),
|
|
winner: z.union([z.literal(0), z.literal(1), z.null()]),
|
|
reason: z.string().max(40),
|
|
startedAt: z.number().int(),
|
|
endedAt: z.number().int(),
|
|
decks: z.array(z.array(z.unknown()).max(64)).length(2),
|
|
actions: z.array(z.object({ seat: z.union([z.literal(0), z.literal(1)]), action: z.unknown() }).strict()).max(2000),
|
|
}).strict();
|
|
export type MatchRecord = z.infer<typeof MatchRecordSchema>;
|
|
|
|
export type LeaderboardEntry = { playerId: string; name: string; wins: number; losses: number; draws: number; played: number };
|
|
type ModeAgg = { matches: number; players: Map<string, LeaderboardEntry> };
|
|
|
|
const KEEP_RECENT = 500;
|
|
|
|
export class MatchStore {
|
|
private readonly file: string | null;
|
|
private readonly modes = new Map<string, ModeAgg>();
|
|
private readonly recent = new Map<string, MatchRecord>();
|
|
private readonly allPlayers = new Set<string>();
|
|
total = 0;
|
|
|
|
/** `directory` null keeps records in memory only (tests). */
|
|
constructor(directory: string | null) {
|
|
this.file = directory ? join(directory, 'matches.jsonl') : null;
|
|
if (!directory || !this.file) return;
|
|
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
if (!existsSync(this.file)) return;
|
|
for (const line of readFileSync(this.file, 'utf8').split('\n')) {
|
|
if (!line.trim()) continue;
|
|
const parsed = MatchRecordSchema.safeParse(safeJson(line));
|
|
if (parsed.success) this.index(parsed.data); // A torn last line after a crash is skipped.
|
|
}
|
|
}
|
|
|
|
add(record: MatchRecord): void {
|
|
const valid = MatchRecordSchema.parse(record);
|
|
if (this.file) appendFileSync(this.file, JSON.stringify(valid) + '\n', { mode: 0o600 });
|
|
this.index(valid);
|
|
}
|
|
|
|
get(matchId: string): MatchRecord | undefined { return this.recent.get(matchId); }
|
|
|
|
modeMatches(modeId: string): number { return this.modes.get(modeId)?.matches ?? 0; }
|
|
modePlayers(modeId: string): number { return this.modes.get(modeId)?.players.size ?? 0; }
|
|
distinctPlayers(): number { return this.allPlayers.size; }
|
|
|
|
leaderboard(modeId: string, limit = 20): LeaderboardEntry[] {
|
|
const players = [...(this.modes.get(modeId)?.players.values() ?? [])];
|
|
return players.sort((a, b) => b.wins - a.wins || a.losses - b.losses || b.played - a.played ||
|
|
a.playerId.localeCompare(b.playerId)).slice(0, limit).map(p => ({ ...p }));
|
|
}
|
|
|
|
private index(r: MatchRecord): void {
|
|
this.total++;
|
|
const agg = this.modes.get(r.modeId) ?? { matches: 0, players: new Map() };
|
|
this.modes.set(r.modeId, agg);
|
|
agg.matches++;
|
|
r.players.forEach((p, seat) => {
|
|
this.allPlayers.add(p.id);
|
|
const e = agg.players.get(p.id) ?? { playerId: p.id, name: p.name, wins: 0, losses: 0, draws: 0, played: 0 };
|
|
e.name = p.name; e.played++;
|
|
if (r.winner === null) e.draws++; else if (r.winner === seat) e.wins++; else e.losses++;
|
|
agg.players.set(p.id, e);
|
|
});
|
|
this.recent.set(r.matchId, r);
|
|
if (this.recent.size > KEEP_RECENT) this.recent.delete(this.recent.keys().next().value!);
|
|
}
|
|
}
|
|
|
|
function safeJson(line: string): unknown { try { return JSON.parse(line); } catch { return null; } }
|