// `umtool fetch` (release 35 O1): a project's clip windows asked of the editor // as one fetch-windows batch (lib/report/fetchWindows.mjs) — the dry run, the // start, and the wait — the same body the Cut tab's and the clip deck's // "Fetch windows" button sends. // // umtool fetch --body the body, printed; the editor is not asked // umtool fetch --dry-run [--json] the editor's plan: groups per platform, cached, in flight, unresolved // umtool fetch [--wait] [--json] start it: one job per platform queue; --wait follows them to the end // umtool fetch --status [--json] the last run's jobs, followed once (what --wait polls) // … [--reason "…"] the provenance reason (default: " montage", or the title) // … --refetch <clipId>[,<clipId>…] evict those clips' cached windows first (the editor's evict-clips, // --refetch-video <slug>/<id> `covering` their fetch spans), then fetch as usual // … --take <id> a TAKE's clips (its walk's manifest; a draft's too), the run // recorded with `take` in fetch-runs.json import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { EditorError, FETCH_RUNS_FILE, TERMINAL, editorConfig, followRun, jobLog, jobStatus, lastStartedRun, parseEvictLog, postEvictClips, postFetchWindows, projectFetchBody, readFetchRuns, recordFetchRun, markRefetched, refetchEvictions, refetchTiers, summarizeAnswer, } from "./fetchWindows.mjs"; import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs"; export const FETCH_USAGE = [ "usage: umtool fetch <project> --body the editor's fetch-windows body for the manifest, printed", " umtool fetch <project> --dry-run [--json] what the editor would do: groups per platform, cached, unresolved", " umtool fetch <project> [--wait] [--json] start it (one paced job per platform); --wait follows the jobs", " umtool fetch <project> --status [--json] the last run's jobs, and the windows they failed", " … [--reason \"…\"] the provenance reason (default \"<title> montage\" for a montage, else the title)", " … --refetch <clipId>[,<clipId>…] evict the cached windows overlapping those clips' fetch spans first", " … --refetch-video <slug>/<id> the same for every window this project asks of that video", " (the editor's evict-clips; with --dry-run the eviction is a dry run too and nothing is deleted)", " … --take <id> a take's clips instead of the cut's: the take's manifest as its walk reads it (a draft's", " too — nothing rendered), so a clip only the take has is fetched; --status follows its last run", "", `Every run is recorded in <project>/${FETCH_RUNS_FILE}; \`umtool fallback\` reads it for the refused windows.`, "The editor: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN (else the editor's env files).", ].join("\n"); class CliError extends Error {} const POLL_MS = Number(process.env.UMTOOL_FETCH_POLL_MS) > 0 ? Number(process.env.UMTOOL_FETCH_POLL_MS) : 5000; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); /** The answer's summary as lines. */ export function summaryLines(s) { const lines = []; for (const g of s.groups) lines.push(` ${g.platform.padEnd(10)} ${g.items} window(s)${g.storedUrlItems ? ` (${g.storedUrlItems} with a stored media URL)` : ""}`); lines.push(` cached ${s.cached.length}${s.cached.length ? ` ${s.cached.join(" ")}` : ""}`); if (s.inFlight.length) lines.push(` in flight ${s.inFlight.length} ${s.inFlight.map((f) => `${f.clipId} (job ${f.jobId})`).join(" ")}`); for (const u of s.unresolved) lines.push(` unresolved ${u.clipId}: ${u.error}`); for (const r of s.refused) lines.push(` refused ${r.platform}: ${r.items} window(s) — ${r.error}`); for (const j of s.jobs) lines.push(` job ${j.jobId} ${j.platform}, ${j.items} window(s)`); // THE HEIGHT TIER: a clip that stays lower than the project renders from, and why. if (s.clampedFrom !== undefined) lines.push(` height ${s.clampedFrom}p asked; the editor's clips.windowMaxHeight holds windows lower`); for (const l of s.lower ?? []) { lines.push(` lower ${l.clipId}: ${l.height !== null ? `${l.height}p` : "height unknown"} (asked ${l.asked}p) in ${l.file} — ${l.why}`); } // THE RECORDING'S END: the last clip's pad runs past a whole saved recording -- cut from it, to its end. for (const e of s.atRecordingEnd ?? []) { lines.push( ` at end ${e.clipId}: saved-video, clamped at the recording's end (asked to ${e.askedTo.toFixed(2)}, cut to ${e.cutTo.toFixed(2)}) — ${e.why}`, ); } return lines; } const stateLine = (st) => ` ${st.jobId} ${String(st.platform ?? "").padEnd(8)} ${st.status}` + (st.progress && Number.isFinite(Number(st.progress.done)) ? ` ${st.progress.done}/${st.progress.total ?? "?"}` : "") + (st.queue && Number(st.queue.position) > 0 ? ` queued, position ${st.queue.position}` : "") + (st.failed?.length ? ` ${st.failed.length} window(s) failed` : ""); /** * @param {string[]} args the words after `fetch` * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, cfg?: ReturnType<typeof editorConfig> & { fetch?: typeof fetch }, pollMs?: number }} [opts] * @returns {Promise<number>} the exit code */ export async function fetchCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), cfg = editorConfig(), pollMs = POLL_MS } = {}) { const json = args.includes("--json"); const words = []; let reason = null; let take = null; const refetchClips = []; const refetchVideos = []; for (let i = 0; i < args.length; i += 1) { if (args[i] === "--reason") { reason = args[i + 1] ?? ""; i += 1; } else if (args[i] === "--take") { take = args[i + 1] ?? ""; i += 1; if (!take || take.startsWith("--")) { err(`--take needs a take id\n${FETCH_USAGE}`); return 2; } } else if (args[i] === "--refetch" || args[i] === "--refetch-video") { const v = args[i + 1]; if (!v || v.startsWith("--")) { err(`${args[i]} needs a value\n${FETCH_USAGE}`); return 2; } (args[i] === "--refetch" ? refetchClips : refetchVideos).push(...v.split(",").map((x) => x.trim()).filter(Boolean)); i += 1; } else if (!args[i].startsWith("--")) words.push(args[i]); } try { const [projectArg] = words; if (!projectArg || args.includes("--help")) { err(FETCH_USAGE); return 2; } const r = await resolveProject(projectArg, root); if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`); if (!r.project) throw new CliError(`no project matches "${projectArg}"`); const project = r.project; const who = take ? `${project.id} take ${take}` : project.id; if (take) { const { isTakeId } = await import("./takes.mjs"); if (!isTakeId(take)) throw new CliError(`"${take}" is not a take id`); } if (args.includes("--status")) { const run = lastStartedRun(await readFetchRuns(project.dir), { take }); if (!run) throw new CliError(`${who} has no started fetch run in ${FETCH_RUNS_FILE}`); const states = await followRun(cfg, project.dir, run); // A run that has ended landed what it landed: the bench's prep for it. if (states.length && states.every((st) => TERMINAL.has(st.status)) && states.some((st) => st.status === "done")) { benchPrepAfterWrite(project.dir, null, { excerptsOnly: false, take }); } if (json) out(JSON.stringify({ project: project.id, ...(take ? { take } : {}), run: { at: run.at, jobIds: run.jobIds }, jobs: states }, null, 2)); else { out(`${who}: the run of ${run.at}`); for (const st of states) out(stateLine(st)); for (const st of states) for (const f of st.failed ?? []) out(` ✗ ${f.clipId ?? `${f.slug}/${f.id}`}: ${f.class} — ${f.message}`); } return 0; } let fetched; try { fetched = await projectFetchBody(project, { reason, take, localIds: true }); } catch (e) { if (take) throw new CliError(`${project.id}: ${e instanceof Error ? e.message : String(e)}`); throw e; } const { body, skipped } = fetched; if (args.includes("--body")) { out(JSON.stringify(body, null, 1)); return 0; } if (!body.items.length) { out(`${who}: no clip windows to fetch${skipped.length ? ` (${skipped.length} skipped)` : ""}`); return 0; } if (fetched.mapped?.length && !json) { const { mappedLine } = await import("umtool-report-to-video/recording-ids"); out(`${who}: asked by directory id: ${mappedLine(fetched.mapped)}`); } const dryRun = args.includes("--dry-run"); // A REFETCH EVICTS FIRST, and waits: the fetch takes a cache hit before // anything else, so it must not be asked until the eviction has ended. let refetch = null; if (refetchClips.length || refetchVideos.length) { // A video named by its cited id (a Rumble embed id) is the directory the body asks for. const { localVideoId } = await import("umtool-report-to-video/recording-ids"); const videos = []; for (const v of refetchVideos) { const at = String(v).indexOf("/"); videos.push(at > 0 ? `${v.slice(0, at)}/${await localVideoId({ slug: v.slice(0, at), id: v.slice(at + 1) })}` : v); } const plan = refetchEvictions(body, skipped, { clipIds: refetchClips, videos }); if (!plan.ok) throw new CliError(plan.error); // The refetched items say so (`refetch: true`): on a tall project a lower // held window then does not answer them — cut again at their tier, or fetched. markRefetched(body, plan.requests); refetch = []; for (const req of plan.requests) { const { jobId } = await postEvictClips(cfg, { ...req, tiers: refetchTiers(body) }, { dryRun }); let status = "unknown"; for (;;) { status = String((await jobStatus(cfg, jobId))?.job?.status ?? "unknown"); if (TERMINAL.has(status)) break; await sleep(pollMs); } const { windows, summary: said } = parseEvictLog(await jobLog(cfg, jobId).catch(() => "")); refetch.push({ slug: req.slug, id: req.id, clipIds: req.clipIds, covering: req.covering, dryRun, jobId, status, windows }); if (!json) { out(`${project.id}: ${dryRun ? "would evict" : "evicted"} for ${req.clipIds.join(",")} (${req.slug}/${req.id}, job ${jobId}): ${windows.length ? windows.join(" ") : "no cached window"}`); if (said) out(` ${said}`); } if (status !== "done") throw new CliError(`the eviction of ${req.slug}/${req.id} ended ${status} (job ${jobId}) — nothing was fetched`); } if (dryRun && !json) out(" (a dry run evicts nothing, so those windows still read as cached below)"); } const answer = await postFetchWindows(cfg, body, { dryRun }); const run = await recordFetchRun(project.dir, { body, answer, refetch, take }); const summary = summarizeAnswer(answer); if (!dryRun && !args.includes("--wait")) { if (json) out(JSON.stringify({ project: project.id, ...(take ? { take } : {}), items: body.items.length, skipped, ...(refetch ? { refetch } : {}), ...summary }, null, 2)); else { out(`${who}: ${body.items.length} window(s) asked${skipped.length ? `, ${skipped.length} skipped` : ""}`); for (const l of summaryLines(summary)) out(l); } return summary.refused.length && !summary.jobs.length ? 1 : 0; } if (dryRun) { if (json) out(JSON.stringify({ project: project.id, ...(take ? { take } : {}), items: body.items.length, skipped, ...(refetch ? { refetch } : {}), ...summary }, null, 2)); else { out(`${who}: ${body.items.length} window(s) — the dry run${skipped.length ? ` (${skipped.length} skipped: ${skipped.map((s) => `${s.clipId} ${s.why}`).join(", ")})` : ""}`); for (const l of summaryLines(summary)) out(l); } return 0; } // --wait: follow every job to its end. if (!json) { out(`${who}: ${body.items.length} window(s) asked`); for (const l of summaryLines(summary)) out(l); } let states = []; const said = new Map(); for (;;) { states = await followRun(cfg, project.dir, { ...run, jobs: (await readFetchRuns(project.dir)).runs.find((x) => x.at === run.at && x.bodyHash === run.bodyHash)?.jobs }); if (!json) { for (const st of states) { const line = stateLine(st); if (said.get(st.jobId) !== line) out(line); said.set(st.jobId, line); } } if (states.every((st) => TERMINAL.has(st.status))) break; await sleep(pollMs); } // What landed, prepared for the walk (a runner in the background; bin/umtool.mjs waits for the queueing only). if (states.some((st) => st.status === "done")) benchPrepAfterWrite(project.dir, null, { excerptsOnly: false, take }); const failed = states.flatMap((st) => st.failed ?? []); if (json) out(JSON.stringify({ project: project.id, ...(take ? { take } : {}), items: body.items.length, skipped, ...(refetch ? { refetch } : {}), ...summary, jobsEnded: states }, null, 2)); else { for (const f of failed) out(` ✗ ${f.clipId ?? `${f.slug}/${f.id}`}: ${f.class} — ${f.message}`); if (failed.length) out(`${failed.length} window(s) failed — \`umtool fallback ${project.id} --dry-run\` finds a stand-in for each refused one`); } return states.some((st) => st.status !== "done") || summary.refused.length ? 1 : 0; } catch (e) { if (e instanceof CliError || e instanceof EditorError) { err(e.message); return 1; } throw e; } }