// THE RAIL'S ACTIONS (lane L5): one click on a stage runs its action through an action that already exists -- // the editor's ops for what touches the corpus, umtool's own for what touches a project. Nothing here downloads, // transcribes or deletes by itself: it builds the editor's body and asks. // // persist Downloaded POST /api/ops/persist-videos {items:[{slug, id}]} the channel's download queue; // a Rumble recording is saved whole // transcribe Transcribed POST /api/ops/transcribe-one {slug, id} the GPU (the editor's worker pool) // fetch Windows POST /api/ops/fetch-windows {items, requestedBy, …} one paced job per platform queue: // the project's own body (projectFetchBody), narrowed to this recording's unfetched clips // evict Windows POST /api/ops/evict-clips {slug, id, windows:[name]} targeted: that one window // quote-check Checked `umtool quote-check --clips …` on the app's job runner (the route starts it) // links Published POST /api/report/links {project, fix?} umtool's own link check // // Two steps, always: `plan` says what the action does, what it costs (network, the GPU, the disk) and which // queue it lands on -- for fetch-windows and persist-videos the editor's own dry run answers -- and the page // asks before it `start`s. An action that costs neither still says what it does. // // Plain ESM; the route (app/api/ingredients/action) is its only caller. import { createHash } from "node:crypto"; import { lstat, readlink, stat } from "node:fs/promises"; import path from "node:path"; import { resolveProject } from "../projects/core.mjs"; import { askEditorOps, postFetchWindows, projectFetchBody, summarizeAnswer } from "../report/fetchWindows.mjs"; import { audioFilesOf, present, readSavedVideoPointer } from "yt-dlp-transcript-common/lib/evidenceClip.mjs"; import { ingredientIdentity, isChannelSlug, isVideoId, listWindows } from "./stages.mjs"; export const ACTIONS = ["persist", "transcribe", "fetch", "evict", "quote-check", "links"]; const CLIP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/; export class ActionError extends Error { constructor(message, status = 400) { super(message); this.status = status; } } const plural = (n, w) => `${n} ${w}${n === 1 ? "" : "s"}`; async function projectOf(id, reportsRoot) { const r = await resolveProject(String(id ?? ""), reportsRoot); if (!r?.project) throw new ActionError(`no project "${id}"`, 404); return r.project; } function clipList(v) { const list = (Array.isArray(v) ? v : String(v ?? "").split(",")).map((s) => String(s).trim()).filter(Boolean); if (!list.length) throw new ActionError("name the clips (clips: [ids])"); for (const c of list) if (!CLIP_ID.test(c)) throw new ActionError(`"${c}" is not a clip id`); return [...new Set(list)]; } /** * A KEY FOR WHAT THE PLAN SHOWED: `start` carries it back, and the action is re-read and refused when it no * longer matches (a fetch body that changed, a window refetched or set aside since the page asked). */ const keyOf = (v) => createHash("sha256").update(JSON.stringify(v)).digest("hex").slice(0, 16); const fetchKey = (body) => keyOf(body.items.map((i) => [String(i.id), i.from, i.to, String(i.clipId ?? "")]).sort()); const evictKey = (w, twins) => keyOf([w.file, w.bytes, w.mtime, ...twins.map((t) => [t.file, t.bytes, t.mtime])]); const plainKey = (action, idn) => keyOf([action, idn.ch, idn.dirId]); /** * AN UNMOUNTED DRIVE IS NOT A MISSING FILE (AGENTS.md, "A channel's media may live on another drive"): a media * link that does not resolve, the channel's media/ linked to a drive not answering, a saved video whose file does * not answer. A plan that read those as "absent" would offer to download again what is only out of reach, so the * plan says which drive, costs nothing and offers no Start, and a start is refused. null when everything answers. * @param {Awaited>} idn * @param {{ saved?: boolean }} [o] also the saved-video store's file (persist) */ export async function unreachableOf(idn, { saved = false } = {}) { const channelMedia = path.join(idn.dir, "..", "..", "media"); if (idn.mediaDrive === "missing") { const to = await readlink(channelMedia).catch(() => null); return `the channel's media drive does not answer (${idn.ch}/media -> ${to ?? "?"}): mount it, or re-point its location on /storage`; } if (!idn.exists) return null; const dangling = []; for (const a of await audioFilesOf(idn.dir)) { const l = await lstat(a.path).catch(() => null); if (l?.isSymbolicLink() && !(await stat(a.path).catch(() => null))) dangling.push(`${a.name} -> ${(await readlink(a.path).catch(() => null)) ?? "?"}`); } if (dangling.length) return `its media does not answer (${dangling.join(", ")}): the drive it lives on is not mounted`; if (saved) { const pointer = await readSavedVideoPointer(idn.dir); if (pointer && !(await present(pointer.path))) return `its saved video does not answer (${pointer.path}): the saved-video store's drive is not mounted`; } return null; } const unreachablePlan = (action, why) => ({ action, what: `Not now: ${why}`, cost: null, queue: "—", unreachable: why, start: null }); /** The fetch-windows bodies for the named clips of one project, narrowed to this recording (one per project). */ async function fetchBodyFor(project, clips, idn) { const { body, skipped } = await projectFetchBody(project, { localIds: true }); const want = new Set(clips); const items = body.items.filter((it) => it.slug === idn.ch && String(it.id) === idn.dirId && want.has(String(it.clipId))); if (!items.length) { const why = skipped.filter((s) => want.has(s.clipId)).map((s) => `${s.clipId}: ${s.why}`); throw new ActionError(`no window of ${idn.ch}/${idn.dirId} to fetch for ${clips.join(", ")}${why.length ? ` (${why.join("; ")})` : ""}`); } return { ...body, requestedBy: `${body.requestedBy} (ingredient rail)`, items }; } /** * What an action will do, before it does it. * * @param {{ action: string, ch: string, id: string, project?: string, clips?: string[] | string, window?: string, fix?: boolean }} req * @param {{ cfg: { url: string, token: string, fetch?: typeof fetch }, reportsRoot: string, channelsDir: string }} ctx * @returns {Promise<{ action: string, what: string, cost: "network" | "gpu" | "disk" | null, queue: string, start: { route: string, body: Record }, plan?: any }>} */ export async function planAction(req, ctx) { const { action } = req; if (!ACTIONS.includes(action)) throw new ActionError(`action is one of ${ACTIONS.join(", ")}`); if (!isChannelSlug(req.ch) || !isVideoId(req.id)) throw new ActionError("ch and id name a recording"); const idn = await ingredientIdentity({ channelsDir: ctx.channelsDir, ch: req.ch, id: req.id }); const self = (extra = {}) => ({ route: "/api/ingredients/action", body: { action, ch: idn.ch, id: idn.dirId, ...extra, step: "start" } }); const rumble = idn.platform === "rumble"; if (action === "persist") { const away = await unreachableOf(idn, { saved: true }); if (away) return unreachablePlan(action, away); const body = { items: [{ slug: idn.ch, id: idn.dirId }] }; const plan = await askEditorOps(ctx.cfg, "/api/ops/persist-videos", { method: "POST", body: { ...body, dryRun: true } }); // The editor's plan buckets each item: { saved: {count, items}, toFetch, noUrl, unknown, willFetch }. const buckets = plan?.plan ?? plan?.buckets ?? {}; const count = (k) => (Array.isArray(buckets?.[k]) ? buckets[k].length : Number(buckets?.[k]?.count ?? 0) || 0); const already = count("saved"); return { action, what: already ? `The source video is already saved: the editor will skip it` : `Download the source video to the saved-video store${rumble ? " -- on Rumble the WHOLE recording, saved once (the editor's whole-recording rule)" : ""}`, cost: already ? null : "network", queue: `the ${idn.ch} channel's download queue (the editor's)`, plan: { saved: already, toFetch: count("toFetch"), noUrl: count("noUrl"), unknown: count("unknown") }, start: self({ key: plainKey(action, idn) }), }; } if (action === "transcribe") { const away = await unreachableOf(idn); if (away) return unreachablePlan(action, away); const audio = idn.exists ? (await Promise.all((await audioFilesOf(idn.dir)).map(async (a) => ((await present(a.path)) ? a.name : null)))).filter(Boolean) : []; return { action, what: audio.length ? `Transcribe ${audio[0]} through the editor's worker pool (an existing transcript is replaced by the new one)` : `Download the audio, then transcribe it (a YouTube video with English captions has those fetched instead)`, cost: "gpu", queue: audio.length ? `transcribe-one:${idn.ch}:${idn.dirId}` : `the ${idn.ch} channel's platform queue for the download, then transcribe-one:${idn.ch}:${idn.dirId}`, start: self({ key: plainKey(action, idn) }), }; } if (action === "fetch") { const project = await projectOf(req.project, ctx.reportsRoot); const clips = clipList(req.clips); const body = await fetchBodyFor(project, clips, idn); const answer = await postFetchWindows(ctx.cfg, body, { dryRun: true }); const groups = Array.isArray(answer?.groups) ? answer.groups : []; const queues = [...new Set(groups.map((g) => g.queueKey).filter(Boolean))]; const cached = Array.isArray(answer?.cached) ? answer.cached.length : Number(answer?.cached ?? 0) || 0; return { action, what: `Fetch ${plural(body.items.length, "window")} for ${project.id} (${clips.join(", ")})${rumble ? " -- Rumble: cut from the whole recording, which the editor saves once" : ""}${cached ? `; ${cached} already on disk` : ""}`, cost: "network", queue: queues.length ? queues.join(", ") : "the editor's paced fetch queue for the platform", plan: { summary: summarizeAnswer(answer) }, start: self({ project: project.id, clips, key: fetchKey(body) }), }; } if (action === "evict") { const { w, twins } = await evictTarget(idn, req.window); const mb = (b) => `${(b / 1e6).toFixed(1)} MB`; return { action, what: `Delete the cached window ${w.file} (${mb(w.bytes)})` + // The editor's targeted evict names the `-` stem, and a set-aside twin of the span goes with it. (twins.length ? `, and with it ${twins.map((t) => `${t.file} (${mb(t.bytes)})`).join(", ")}: the editor evicts a span's set-aside twin with it` : "") + `. A window is a cache: it can be fetched again, and that fetch is the cost. Nothing knows whether a project still cites it`, cost: "disk", queue: "an evict-clips job on the editor", start: self({ window: w.file, key: evictKey(w, twins) }), }; } if (action === "quote-check") { const project = await projectOf(req.project, ctx.reportsRoot); const clips = clipList(req.clips); return { action, what: `Check ${clips.join(", ")} in ${project.id}: each clip's seconds transcribed by the editor, its quote found in them (writes ${project.id}/quote-check.json)`, cost: "gpu", queue: "umtool's job runner (one job at a time); the transcriptions on the editor's transcribe queue", start: self({ project: project.id, clips }), }; } // links const project = await projectOf(req.project, ctx.reportsRoot); return { action, what: req.fix === true ? `Rewrite each dead link of ${project.id} the last check knows the fix for, then check every link again` : `Check that each clip QR of ${project.id} opens on its site (the archive's corpus.json, the channel's manifest, the shard's record)`, cost: "network", queue: "this umtool, one request at a time to the site (cached)", start: { route: "/api/report/links", body: { project: project.id, ...(req.fix === true ? { fix: true } : {}) } }, }; } /** * Do it: the editor-bound actions (persist, transcribe, fetch, evict). quote-check is started by the route on * the app's job runner; links goes to /api/report/links. * @returns {Promise<{ ok: true, action: string, jobIds: string[], message: string, answer?: any }>} */ export async function startAction(req, ctx) { const { action } = req; if (!["persist", "transcribe", "fetch", "evict"].includes(action)) throw new ActionError(`${action} is not started here`); if (!isChannelSlug(req.ch) || !isVideoId(req.id)) throw new ActionError("ch and id name a recording"); const idn = await ingredientIdentity({ channelsDir: ctx.channelsDir, ch: req.ch, id: req.id }); if (typeof req.key !== "string" || !req.key) throw new ActionError("start carries the plan's key: ask for the plan first"); const changed = () => new ActionError("it changed since the plan was shown: ask again", 409); if (action === "persist" || action === "transcribe") { const away = await unreachableOf(idn, { saved: action === "persist" }); if (away) throw new ActionError(`refused: ${away}`, 409); if (req.key !== plainKey(action, idn)) throw changed(); } const ids = (a) => [...new Set([...(Array.isArray(a?.jobIds) ? a.jobIds : []), ...(a?.jobId ? [a.jobId] : [])].map(String))]; if (action === "persist") { const a = await askEditorOps(ctx.cfg, "/api/ops/persist-videos", { method: "POST", body: { items: [{ slug: idn.ch, id: idn.dirId }] } }); return { ok: true, action, jobIds: ids(a), message: ids(a).length ? `persist started (${ids(a).join(", ")})` : "nothing to persist: already saved", answer: a }; } if (action === "transcribe") { const a = await askEditorOps(ctx.cfg, "/api/ops/transcribe-one", { method: "POST", body: { slug: idn.ch, id: idn.dirId } }); return { ok: true, action, jobIds: ids(a), message: a?.instead === "captions" ? String(a.message ?? "captions fetched instead") : `transcription queued (${ids(a).join(", ")})`, answer: a }; } if (action === "fetch") { const project = await projectOf(req.project, ctx.reportsRoot); const body = await fetchBodyFor(project, clipList(req.clips), idn); if (req.key !== fetchKey(body)) throw changed(); const a = await postFetchWindows(ctx.cfg, body); return { ok: true, action, jobIds: ids(a), message: ids(a).length ? `fetch started (${ids(a).join(", ")})` : "nothing to fetch: every window is on disk or in flight", answer: summarizeAnswer(a) }; } const { w, twins } = await evictTarget(idn, req.window); if (req.key !== evictKey(w, twins)) throw changed(); const a = await askEditorOps(ctx.cfg, "/api/ops/evict-clips", { method: "POST", body: { slug: idn.ch, id: idn.dirId, windows: [w.name] } }); return { ok: true, action, jobIds: ids(a), message: `evicting ${w.name} (${ids(a).join(", ")})`, answer: a }; } /** The window a targeted evict names, EXACTLY by its file, and the set-aside twin of its span that goes with it. */ async function evictTarget(idn, file) { const f = String(file ?? ""); const all = idn.exists ? await listWindows(idn.dir) : []; const w = all.find((x) => x.file === f); if (!w) throw new ActionError(`no window file "${f}" in ${idn.ch}/${idn.dirId}/clips/`, 404); return { w, twins: all.filter((x) => x !== w && x.name === w.name) }; } /** The argv of a quote check of some of a project's clips (the route runs it on the app's job runner). */ export function quoteCheckArgv(umtoolDir, project, clips) { return [process.execPath, path.join(umtoolDir, "bin", "umtool.mjs"), "quote-check", project, "--clips", clips.join(",")]; } export { clipList as parseClipList };