// `umtool queue …` and `umtool jobs` (lib/queue/store.mjs is the queue): what // an agent calls instead of writing a shell chain. Queue the steps, then poll: // // umtool queue add [--after |last] [--label T] [--timeout ] [--json] -- // umtool queue ls [--all] [--json] // umtool queue status [--json] exit 0 done · 3 queued/running · 1 failed/blocked/cancelled // umtool queue wait [--timeout ] the same exit, after up to seconds (default 90) // umtool queue log [--tail N] its full log // umtool queue cancel | retry [--json] // umtool jobs [--json] every running and recent render and step, across projects // // Plain ESM: the CLI runs it under bare node. import { readdir, readFile } from "node:fs/promises"; import path from "node:path"; import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { readRenderRecord, recordLines, renderPointerFile } from "../report/renderRecord.mjs"; import { fastKindOf } from "../report/takePreview.mjs"; import { addStep, cancelStep, getStep, isQid, listSteps, logFileOf, logTail, queueDirOf, readLease, resolveStep, retryStep, stepExitCode, TERMINAL, } from "./store.mjs"; export const QUEUE_USAGE = [ "usage: umtool queue add [--after |last] [--label T] [--timeout ] [--json] -- ", " a step: the argv of a umtool command (no shell: one word per argument), run by the umtool app", " (its systemd unit) one at a time, in order. --after waits for that step to be DONE; if it fails", " or is cancelled this one is BLOCKED (`retry` the failed one and both go back). Prints the qid", " (q) on stdout. --timeout: the step's time limit (default 720 minutes)", " umtool queue ls [--all] [--json] the steps (default: not finished, or finished in the last 24 h)", " and whether the app's runner is up", " umtool queue status [--json] one step: state, exit code, error, log path.", " EXIT 0 done · 3 queued or running · 1 failed, blocked or cancelled", " umtool queue wait [--timeout ] wait up to seconds (default 90) for it to finish; the same exits", " umtool queue log [--tail N] its full log (the latest attempt's)", " umtool queue cancel [--json] a queued/blocked step at once; a running one is stopped (its process group)", " umtool queue retry [--json] a failed or cancelled step back in the queue, with the steps blocked behind it", "", "A running step whose app died reads FAILED (\"the step's process is gone\"), its log kept: it is never re-run on its", "own. A take render's own record is `umtool take status --id `.", ].join("\n"); export const JOBS_USAGE = [ "usage: umtool jobs [--json] every running and recent take render (takes//render.json, read through the queue", " dir's renders/ pointers), every queue step not finished or finished in the last 24 h, and the", " umtool app's own jobs (GET /api/jobs at --url / UMTOOL_URL, when it answers)", ].join("\n"); class CliError extends Error {} const DAY_MS = 86_400_000; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); function parse(args, valued) { const dash = args.indexOf("--"); const head = dash === -1 ? args : args.slice(0, dash); const rest = dash === -1 ? null : args.slice(dash + 1); const flags = {}; const positional = []; for (let i = 0; i < head.length; i += 1) { const a = head[i]; if (a.startsWith("--")) { if (valued.has(a)) { if (i + 1 >= head.length) throw new CliError(`${a} needs a value`); flags[a] = head[++i]; } else flags[a] = ""; } else positional.push(a); } return { flags, positional, rest, has: (n) => n in flags, one: (n) => flags[n] }; } /** The umtool app's base URL (buildRun.mjs's rule). */ const appBase = (url, env = process.env) => String(url || env.UMTOOL_URL || "http://localhost:3050").replace(/\/+$/, ""); async function askApp(base, route, fetchImpl, timeoutMs = 1500) { try { const res = await fetchImpl(`${base}${route}`, { signal: AbortSignal.timeout(timeoutMs) }); if (!res.ok) return { ok: false, error: `HTTP ${res.status}` }; return { ok: true, json: await res.json() }; } catch (e) { return { ok: false, error: e instanceof Error ? e.message : String(e) }; } } /** * Which project and take a step works on, when its argv says: `take

--id `, * `takes

[]`, or any command whose first word after it is a project. */ export async function targetOf(argv, root) { const [cmd, ...rest] = argv; // umtool's commands take the project first (`takes` after its subcommand). const word = cmd === "takes" ? rest[1] : rest[0]; let project = null; if (word && !word.startsWith("-")) { const r = await resolveProject(word, root).catch(() => ({})); if (r?.project) project = r.project.id; } let take = null; if (cmd === "take") { const i = rest.indexOf("--id"); take = i >= 0 ? rest[i + 1] ?? null : null; } else if (cmd === "takes" && ["pick", "cancel", "relabel", "delete", "supersede", "fork"].includes(rest[0] ?? "")) take = rest[2] ?? null; return project || take ? { project, take } : null; } const fmtTime = (iso) => (iso ? String(iso).slice(0, 19).replace("T", " ") : "—"); /** One line of a step, for `ls` and `jobs`. */ export function stepLine(s) { const tail = s.state === "blocked" || s.state === "failed" || s.state === "cancelled" ? ` — ${s.error ?? ""}` : s.state === "running" ? ` (since ${fmtTime(s.startedAt).slice(11)}, pid ${s.pid ?? "?"})` : s.state === "done" ? ` (${fmtTime(s.endedAt).slice(11)})` : s.after ? ` (after ${s.after})` : ""; return `${s.qid.padEnd(6)} ${s.state.toUpperCase().padEnd(9)} ${s.label}${tail}`; } function stepDetail(s, dir) { const out = [stepLine(s)]; out.push(` argv: umtool ${s.argv.map((a) => (/[\s"'$]/.test(a) ? JSON.stringify(a) : a)).join(" ")}`); if (s.after) out.push(` after: ${s.after}`); out.push(` queued ${fmtTime(s.createdAt)}${s.startedAt ? ` · started ${fmtTime(s.startedAt)}` : ""}${s.endedAt ? ` · ended ${fmtTime(s.endedAt)}` : ""}${s.exitCode != null ? ` · exit ${s.exitCode}` : ""}${s.attempts > 1 ? ` · attempt ${s.attempts}` : ""}`); if (s.error) out.push(` error: ${s.error}`); if (s.target?.take && s.target?.project) out.push(` its take's record: umtool take status ${s.target.project} --id ${s.target.take}`); out.push(` log: ${logFileOf(dir, s.qid)}`); return out; } /** The runner line: is the app running the queue? */ function runnerLine(lease) { if (lease?.live) return `runner: the umtool app (pid ${lease.pid}${lease.host ? ` on ${lease.host}` : ""}, since ${fmtTime(lease.since)})`; return "runner: NONE — nothing runs until the umtool app is up (archilyzer-umtool.service; `archilyzer service restart --apps umtool`)"; } /** * `umtool queue …` * @param {string[]} args everything after `queue` * @param {{ reportsRoot?: string, commands?: string[], log?: (s: string) => void, err?: (s: string) => void, * fetchImpl?: typeof fetch, cwd?: string, env?: Record, pollMs?: number }} [opts] * @returns {Promise} */ export async function queueCommand(args, { reportsRoot = REPORTS_ROOT, commands = null, log = console.log, err = console.error, fetchImpl = fetch, cwd = process.cwd(), env = process.env, pollMs = 2000 } = {}) { try { const p = parse(args, new Set(["--after", "--label", "--timeout", "--tail", "--url"])); const [sub, qid] = p.positional; const dir = queueDirOf({ reportsRoot, env }); const json = p.has("--json"); if (!sub || p.has("--help")) { log(QUEUE_USAGE); return sub ? 0 : 2; } if (sub === "add") { const argv = p.rest ?? []; if (!argv.length) throw new CliError("umtool queue add [--after ] [--label T] -- (the `--` and then the command)"); if (argv[0] === "umtool") throw new CliError("give the subcommand, not `umtool` itself: `-- take --id …`"); if (argv[0] === "queue") throw new CliError("a queue step cannot queue steps"); if (commands && !commands.includes(argv[0])) throw new CliError(`"${argv[0]}" is not a umtool command (\`umtool help\`)`); const after = p.one("--after") ?? null; if (after !== null && after !== "last" && !isQid(after)) throw new CliError(`--after takes a qid (q) or "last", not "${after}"`); const target = await targetOf(argv, reportsRoot); const step = await addStep(dir, { argv, label: p.one("--label") ?? null, after, cwd, target, by: env.USER ? `umtool queue add (${env.USER})` : "umtool queue add", timeoutMin: p.has("--timeout") ? Number(p.one("--timeout")) : undefined, }); const lease = await readLease(dir); if (json) log(JSON.stringify({ ok: true, step, runner: lease }, null, 2)); else { log(step.qid); err(`${step.qid} queued: ${step.label}${step.after ? ` (after ${step.after})` : ""}`); err(` poll: umtool queue status ${step.qid} (exit 0 done, 3 still going, 1 failed)`); if (!lease?.live) err(` ${runnerLine(lease)}`); } return 0; } if (sub === "ls") { const lease = await readLease(dir); const all = (await listSteps(dir)).map((s) => resolveStep(s)); const cutoff = Date.now() - DAY_MS; const steps = p.has("--all") ? all : all.filter((s) => !TERMINAL.has(s.state) || Date.parse(s.endedAt ?? s.createdAt) > cutoff); if (json) log(JSON.stringify({ dir, runner: lease, steps }, null, 2)); else { log(runnerLine(lease)); if (!steps.length) log(all.length ? "no step finished in the last 24 h (--all lists every one)" : "the queue is empty"); for (const s of steps) log(stepLine(s)); } return 0; } if (sub === "status" || sub === "wait" || sub === "log" || sub === "cancel" || sub === "retry") { if (!isQid(qid)) throw new CliError(`umtool queue ${sub} (q: \`umtool queue ls\`)`); if (sub === "cancel") { const r = await cancelStep(dir, qid); if (json) log(JSON.stringify({ ok: true, ...r }, null, 2)); else log(r.said); return 0; } if (sub === "retry") { const r = await retryStep(dir, qid); if (json) log(JSON.stringify({ ok: true, ...r }, null, 2)); else log(r.said); return 0; } const first = await getStep(dir, qid); if (!first) throw new CliError(`no step ${qid} (\`umtool queue ls --all\`)`); if (sub === "log") { const file = logFileOf(dir, qid); if (p.has("--tail")) { const n = Math.max(1, Number(p.one("--tail")) || 40); for (const l of (await logTail(file, 1024 * 1024)).slice(-n)) log(l); } else { const text = await readFile(file, "utf8").catch(() => null); if (text === null) { err(`${qid} has no log yet (${first.state})`); return 1; } log(text.replace(/\n$/, "")); } return 0; } let step = resolveStep(first); if (sub === "wait") { const limit = Math.max(1, Number(p.one("--timeout") ?? 90) || 90) * 1000; const until = Date.now() + limit; while (stepExitCode(step.state) === 3 && Date.now() < until) { await sleep(Math.min(pollMs, Math.max(50, until - Date.now()))); const s = await getStep(dir, qid); if (s) step = resolveStep(s); } } const code = stepExitCode(step.state); if (json) log(JSON.stringify({ ...step, exit: code, log: logFileOf(dir, qid) }, null, 2)); else for (const l of stepDetail(step, dir)) log(l); return code; } throw new CliError(`unknown: queue ${sub}\n\n${QUEUE_USAGE}`); } catch (e) { err(e instanceof Error ? e.message : String(e)); return e instanceof CliError ? 2 : 1; } } /** * The recent take renders, through the pointers in the queue dir's renders/. * @param {string} dir the queue dir * @param {{ days?: number, limit?: number }} [o] */ export async function recentRenders(dir, { days = 7, limit = 30 } = {}) { const names = await readdir(path.join(dir, "renders")).catch(() => []); const ptrs = []; for (const n of names) { if (!n.endsWith(".json")) continue; const ptr = await readFile(path.join(dir, "renders", n), "utf8").then(JSON.parse, () => null); if (ptr?.projectDir && ptr?.take) ptrs.push(ptr); } const cutoff = Date.now() - days * DAY_MS; const out = []; for (const ptr of ptrs.sort((a, b) => String(b.startedAt).localeCompare(String(a.startedAt))).slice(0, limit * 2)) { const rec = await readRenderRecord(path.join(ptr.projectDir, "takes", ptr.take)); if (!rec) continue; const live = rec.state === "running" || rec.state === "waiting"; if (!live && Date.parse(rec.endedAt ?? rec.startedAt) < cutoff) continue; out.push({ ...rec, project: rec.project ?? ptr.project, projectDir: ptr.projectDir, logPath: path.join(ptr.projectDir, "takes", ptr.take, rec.log ?? "render.log") }); if (out.length >= limit) break; } return out; } /** * `umtool jobs` * @param {string[]} args * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, fetchImpl?: typeof fetch, env?: Record }} [opts] */ export async function jobsCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, fetchImpl = fetch, env = process.env } = {}) { try { const p = parse(args, new Set(["--url"])); if (p.has("--help")) { log(JOBS_USAGE); return 0; } const dir = queueDirOf({ reportsRoot, env }); const [lease, all, renders, app] = await Promise.all([ readLease(dir), listSteps(dir), recentRenders(dir), askApp(appBase(p.one("--url"), env), "/api/jobs?n=20", fetchImpl), ]); const cutoff = Date.now() - DAY_MS; const steps = all.map((s) => resolveStep(s)).filter((s) => !TERMINAL.has(s.state) || Date.parse(s.endedAt ?? s.createdAt) > cutoff); const appJobs = app.ok ? /** @type {any} */ (app.json)?.jobs ?? [] : null; if (p.has("--json")) { log(JSON.stringify({ queue: { dir, runner: lease, steps }, renders, app: app.ok ? { jobs: appJobs } : { error: app.error } }, null, 2)); return 0; } log("QUEUE"); log(` ${runnerLine(lease)}`); if (!steps.length) log(" no step queued, running or finished in the last 24 h"); for (const s of [...steps].reverse()) log(` ${stepLine(s)}`); log("TAKE RENDERS"); if (!renders.length) log(" none recorded in the last 7 days"); for (const r of renders) for (const [i, l] of recordLines(r, { tail: 0 }).entries()) log(` ${i ? " " : ""}${l}`); log("THE APP'S JOBS"); if (!appJobs) log(` the umtool app did not answer (${app.error})`); else if (!appJobs.length) log(" none"); else for (const j of appJobs) log(` ${String(j.state).toUpperCase().padEnd(9)} ${j.label}${j.error ? ` — ${j.error}` : ""}`); return 0; } catch (e) { err(e instanceof Error ? e.message : String(e)); return 1; } } /** * `umtool take status [--id ] [--json] [--log] [--tail N]`: the * take's render record (renderRecord.mjs), or -- when no render of it runs -- * the queue step waiting to render it (`queued`). Without --id: every take of * the project that has a record, newest first, and the exit of the newest. * * @param {{ id: string, dir: string }} project * @param {{ take: string | null, json: boolean, showLog: boolean, tail: number | null, reportsRoot?: string, env?: Record, * log: (s: string) => void, err: (s: string) => void }} o */ export { fastKindOf }; /** * A take's preview and changes renders, for `take status`: each one's record and output (takePreview.mjs * fastRenders), or the queue step still to run it. */ async function fastStatus(project, id, steps) { const { fastRenders } = await import("../report/takePreview.mjs"); const slug = await readFile(path.join(project.dir, "video.manifest.json"), "utf8").then((t) => String(JSON.parse(t).slug ?? ""), () => ""); const got = await fastRenders(path.join(project.dir, "takes", id), slug); /** @type {Record} */ const out = {}; for (const kind of ["preview", "window", "changes"]) { const step = steps.filter((s) => s.target.take === id && fastKindOf(s.argv) === kind).at(-1) ?? null; const rec = got[/** @type {"preview" | "window" | "changes"} */ (kind)]; const live = rec && (rec.state === "running" || rec.state === "waiting"); if (step && !live && (step.state === "queued" || step.state === "blocked" || (step.state === "running" && !(rec?.endedAt === null)))) { out[kind] = { ...(rec ?? {}), state: step.state === "running" ? "running" : step.state, queue: { qid: step.qid, state: step.state, after: step.after, error: step.error } }; } else if (rec) out[kind] = rec; } return out; } export async function takeStatus(project, { take, json, showLog, tail, reportsRoot = REPORTS_ROOT, env = process.env, log, err }) { const { statusExitCode } = await import("../report/renderRecord.mjs"); const takesRoot = path.join(project.dir, "takes"); const dir = queueDirOf({ reportsRoot, env }); const allSteps = (await listSteps(dir)).map((s) => resolveStep(s)).filter((s) => s.target?.project === project.id && s.target?.take); // A preview or a changes reel is not the take's render: its steps are reported beside it (fastStatus). const steps = allSteps.filter((s) => !fastKindOf(s.argv)); const ids = take ? [take] : (await readdir(takesRoot).catch(() => [])).filter((n) => !n.startsWith(".")); const rows = []; for (const id of ids) { const rec = await readRenderRecord(path.join(takesRoot, id)); // The newest queue step that renders this take, and whether the record is of its run or older. const step = steps.filter((s) => s.target.take === id).at(-1) ?? null; const stepAt = step ? Date.parse(step.startedAt ?? step.createdAt) : NaN; const recIsOlder = !rec || Date.parse(rec.startedAt) < stepAt; const recLive = rec && (rec.state === "running" || rec.state === "waiting"); let row; const fromStep = (state, exit, error = null) => ({ project: project.id, take: id, state, queue: { qid: step.qid, state: step.state, after: step.after, error: step.error }, error, previous: rec, exit, }); // A step still to run renders this take again, whatever an earlier run recorded (a render live now speaks for itself). if (step && !recLive && step.state === "queued") row = fromStep("queued", 3); else if (step && !recLive && step.state === "blocked") row = fromStep("blocked", 1, step.error); // Started, its take process not yet writing its own record (a second of setup): running, never the last run's word. else if (step && recIsOlder && step.state === "running") row = { ...fromStep("running", 3), stage: "starting" }; // Ended without a record of its own (refused before the take's directory existed): the step says why. else if (step && recIsOlder && (step.state === "failed" || step.state === "cancelled")) row = fromStep(step.state, 1, step.error); else if (rec) { row = { ...rec, exit: statusExitCode(rec.state) }; } else if (take) { // No record: a take made before records (take.json built, its preview there) reads done from take.json. const doc = await readFile(path.join(takesRoot, id, "take.json"), "utf8").then(JSON.parse, () => null); if (doc?.builtAt && !doc.draft) row = { project: project.id, take: id, state: "done", recorded: false, builtAt: doc.builtAt, seconds: doc.seconds ?? null, mp4: doc.preview ?? "preview.mp4", exit: 0 }; else row = { project: project.id, take: id, state: "none", error: doc?.draft ? "a draft: never rendered" : `no render of take ${id} is recorded`, exit: 1 }; } const fast = await fastStatus(project, id, allSteps); if (row && Object.keys(fast).length) Object.assign(row, fast); else if (!row && Object.keys(fast).length) row = { project: project.id, take: id, state: "none", error: "never rendered at full quality", exit: 1, ...fast }; if (row) rows.push(row); } rows.sort((a, b) => String(b.startedAt ?? b.queue?.qid ?? "").localeCompare(String(a.startedAt ?? a.queue?.qid ?? ""))); if (!rows.length) { if (json) log(JSON.stringify({ project: project.id, takes: [] }, null, 2)); else err(`${project.id}: no take render is recorded`); return 1; } const code = rows[0].exit; if (json) { log(JSON.stringify(take ? { ...rows[0], logPath: path.join(takesRoot, take, "render.log") } : { project: project.id, takes: rows }, null, 2)); return code; } const fastLines = (r) => { for (const kind of ["preview", "window", "changes"]) { const f = r[kind]; if (!f) continue; const what = f.queue ? `${String(f.state).toUpperCase()} in the queue as ${f.queue.qid}` : String(f.state ?? "?").toUpperCase(); // A window preview's own record (out/window/), named by the window it was asked for. log(` ${kind === "window" && f.span ? `window ${f.span}` : kind}: ${what}${f.mp4 ? ` — ${f.mp4}${f.seconds != null ? ` (${f.seconds} s)` : ""}` : ""}${f.items != null ? `, ${f.items} piece(s) against ${f.from}, list ${f.list}` : ""}${f.error ? ` — ${f.error}` : ""}`); } }; for (const r of rows) { if (r.queue) { log(`${project.id} take ${r.take}: ${r.state.toUpperCase()} in the queue as ${r.queue.qid}${r.queue.after ? ` (after ${r.queue.after})` : ""}${r.error ? ` — ${r.error}` : ""}`); log(` poll: umtool queue status ${r.queue.qid}`); fastLines(r); continue; } if (r.recorded === false || r.state === "none") { log(`${project.id} take ${r.take}: ${r.state.toUpperCase()}${r.recorded === false ? ` (made ${fmtTime(r.builtAt)}, before renders recorded themselves)` : ` — ${r.error}`}`); fastLines(r); continue; } for (const l of recordLines(r, { logPath: path.join(takesRoot, r.take, r.log ?? "render.log"), tail: take ? (tail ?? 12) : 0 })) log(l); fastLines(r); } if (showLog && take) { const file = path.join(takesRoot, take, "render.log"); const lines = tail ? (await logTail(file, 1024 * 1024)).slice(-tail) : (await readFile(file, "utf8").catch(() => "")).split("\n"); log("--- render.log"); for (const l of lines) log(l); } return code; } export { renderPointerFile };