import path from "node:path"; import { cancelJob, runningJob, startJob } from "@/lib/jobs"; import { REPORTS_ROOT } from "@/lib/paths.mjs"; import { projectRef } from "@/lib/projects"; import { UMTOOL_DIR } from "@/lib/report/driver.mjs"; import { readRenderRecord } from "@/lib/report/renderRecord.mjs"; import { acquireLease, pruneSteps, queueDirOf, queueTick } from "./store.mjs"; // --------------------------------------------------------------------------- // THE QUEUE'S RUNNER, in the umtool app (lib/queue/store.mjs says what the // queue is). Armed by instrumentation.ts at boot, so the live unit // (archilyzer-umtool.service) runs the steps whoever queued them, and keeps // running them across an AI session's end, an app restart or a ship. // // Every 2 s, one turn (queueTick): take or renew the lease (runner.json -- one // runner per queue dir, machine-wide), mark a running step whose process is // gone failed (the app that ran it died: never re-run), block what waits on a // failure, and start the next ready step as a job on the app's own runner // (lib/jobs.ts). So a step shows in the rail's Running list and /settings/system // like any job, a Takes-page job and a step never run at once (a page job asked // for while a step runs is a 409 naming it; a step waits while a page job runs), // and a step gets the runner's process-group kill and its time limit (the step's // `timeoutMin`, 12 h by default). Its FULL log is the job's Step.logFile. // // On by default only under `next start` (NODE_ENV=production: the live unit, // the e2e suite's own app over its fixture); `next dev` in a worktree runs // nothing unless UMTOOL_QUEUE_RUNNER=1. UMTOOL_QUEUE_RUNNER=0 turns it off. // ARCHILYZER_IDLE_BOOT=1 boots without it (instrumentation.ts). // --------------------------------------------------------------------------- export const QUEUE_TICK_MS = 2000; const PRUNE_EVERY_MS = 60 * 60 * 1000; type Held = { cancelling: boolean; cancel: () => void }; type RunnerState = { dir: string; held: Map; timer: ReturnType | null; ticking: boolean; holding: boolean; lastTickAt: number | null; lastError: string | null; lastPruneAt: number; waiting: string | null; }; const g = globalThis as typeof globalThis & { __umtoolQueueRunner?: RunnerState }; /** Whether this process runs the queue (see the top of the file). */ export function queueRunnerEnabled(env: Record = process.env): boolean { const v = (env.UMTOOL_QUEUE_RUNNER ?? "").trim(); if (v === "0" || v === "false" || v === "off") return false; if (v === "1" || v === "true" || v === "on") return true; return env.NODE_ENV === "production"; } export const queueDir = () => queueDirOf({ reportsRoot: REPORTS_ROOT }); const umtoolCli = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"); type QueueStep = { qid: string; label: string; argv: string[]; cwd: string | null; timeoutMin: number; startedAt: string | null; target?: { project: string | null; take: string | null } | null }; /** A failed take step's error, from the take's own render record when it is this attempt's. */ async function describe(step: QueueStep): Promise { const t = step.target; if (!t?.project || !t.take) return null; const project = await projectRef(t.project); if (!project) return null; const rec = await readRenderRecord(path.join(/* turbopackIgnore: true */ project.dir, "takes", t.take)); if (!rec || (rec.state !== "failed" && rec.state !== "cancelled") || !rec.error) return null; if (step.startedAt && String(rec.startedAt) < step.startedAt) return null; return `take ${t.take}: ${rec.error}`; } const exec = { busy: () => { const j = runningJob(); return j ? `${j.kind} (${j.id})` : null; }, start: (step: QueueStep, { logFile, onEnd }: { logFile: string; onEnd: (end: { exitCode: number | null; signal: string | null; cancelled: boolean; error: string | null }) => void }) => { const job = startJob( `queue ${step.qid}: ${step.label}`, [ { label: step.label, argv: [process.execPath, umtoolCli(), ...step.argv], cwd: step.cwd ?? UMTOOL_DIR, env: {}, timeoutMs: Math.max(1, step.timeoutMin) * 60_000, logFile, }, ], { project: step.target?.project ?? null, onEnd: (j) => onEnd({ exitCode: j.exitCode, signal: j.signal, cancelled: j.cancelling, error: j.error }), }, ); return { pid: job.pids[0] ?? null, jobId: job.id, cancel: () => void cancelJob(job.id) }; }, describe, }; async function tick(st: RunnerState) { if (st.ticking) return; st.ticking = true; try { st.holding = await acquireLease(st.dir); if (!st.holding) return; const r = await queueTick(st.dir, exec, { held: st.held }); st.waiting = r.waiting; if (Date.now() - st.lastPruneAt > PRUNE_EVERY_MS) { st.lastPruneAt = Date.now(); await pruneSteps(st.dir).catch(() => []); } st.lastError = null; } catch (e) { st.lastError = e instanceof Error ? e.message : String(e); } finally { st.lastTickAt = Date.now(); st.ticking = false; } } /** Arm the runner (idempotent: one per process). */ export function startQueueRunner({ intervalMs = QUEUE_TICK_MS }: { intervalMs?: number } = {}): RunnerState { const have = g.__umtoolQueueRunner; if (have?.timer) return have; const st: RunnerState = have ?? { dir: queueDir(), held: new Map(), timer: null, ticking: false, holding: false, lastTickAt: null, lastError: null, lastPruneAt: 0, waiting: null, }; g.__umtoolQueueRunner = st; void tick(st); st.timer = setInterval(() => void tick(st), intervalMs); // No signal handler of its own (one would keep the process from exiting on // SIGTERM): the lease names this pid, and a dead pid's lease is free. st.timer.unref?.(); return st; } /** Ask for a turn now (after an add, a cancel, a retry from the page). */ export function kickQueue() { const st = g.__umtoolQueueRunner; if (st?.timer) void tick(st); } /** What the page and GET /api/queue say about this process's runner. */ export function queueRunnerStatus() { const st = g.__umtoolQueueRunner; return { enabled: queueRunnerEnabled(), armed: !!st?.timer, holding: st?.holding ?? false, running: st ? [...st.held.keys()] : [], lastTickAt: st?.lastTickAt ?? null, lastError: st?.lastError ?? null, waiting: st?.waiting ?? null, }; }