RotNot / src /lib /coding /store.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
1.92 kB
import { PROBLEM_BANK } from "./bank";
import type { CodingProblem } from "./types";
// ---------------------------------------------------------------------------
// Problem resolver — maps a problem id back to its full definition (including
// the answer key) on the server, so submit routes can grade without the
// hidden tests / issues / rubric ever leaving the server.
//
// The curated bank is pre-seeded. LLM-generated problems are registered at
// generate time and resolve within the same process (this app is single-user
// and local-first, running as one Node process). Bank ids always resolve.
// ---------------------------------------------------------------------------
const store = new Map<string, CodingProblem>();
for (const p of PROBLEM_BANK) store.set(p.id, p);
/** Cap on dynamically-registered problems to bound memory in a long session. */
const MAX_DYNAMIC = 500;
const dynamicIds: string[] = [];
export function resolveProblem(id: string): CodingProblem | null {
// Exact match first (covers bank ids and instances registered on THIS
// process). On multi-instance serverless (e.g. Vercel) a submit request may
// land on a fresh lambda that never saw the generate, so fall back to the
// bank by the canonical id encoded in the instance id (`${bankId}::${uuid}`).
// Bank ids are seeded into every process at import, so this is stateless.
const exact = store.get(id);
if (exact) return exact;
const sep = id.indexOf("::");
if (sep > 0) {
return store.get(id.slice(0, sep)) ?? null;
}
return null;
}
export function registerProblem(problem: CodingProblem): void {
if (!store.has(problem.id)) {
dynamicIds.push(problem.id);
if (dynamicIds.length > MAX_DYNAMIC) {
const evict = dynamicIds.shift();
if (evict && !PROBLEM_BANK.some((p) => p.id === evict)) {
store.delete(evict);
}
}
}
store.set(problem.id, problem);
}