File size: 1,920 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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);
}