import { stat } from "node:fs/promises"; import path from "node:path"; import { jobView, runningJob, startJob } from "@/lib/jobs"; import { MEDIA_ROOT, MEDIA_TIERED } from "@/lib/paths"; import { indexPrunePlan, invalidateProjects, projectRef, projectRefs, pruneIndex } from "@/lib/projects"; import { MANIFEST_NAME } from "@/lib/projects/report.mjs"; import { pipelineProcessesFor } from "@/lib/report/busy.mjs"; import { UMTOOL_DIR, moveDeliverablesSteps } from "@/lib/report/driver.mjs"; import { moveDeliverables, moveDirToLocal, moveDirToMedia } from "@/lib/report/storage.mjs"; import type { Step } from "@/lib/trim"; import type { ActionPlanView, PlanRow } from "./plan-types"; // --------------------------------------------------------------------------- // SETTINGS · SYSTEM's actions (plans/umtool-redesign.md, P5): thin APIs over // what `umtool` already does from a terminal -- `umtool index --rebuild | // --prune` and `umtool storage move-out | move-back | deliverables`. Every one // that changes or moves anything is PLAN, THEN CONFIRM (the DeletePlan // pattern): the plan is a dry run that measures and refuses and writes // nothing; the confirm reads the plan again, refuses if it now refuses, and // only then acts. A long one runs as a umtool job (lib/jobs.ts: one at a time, // cancellable, in the rail's Running list) through the same CLI a terminal // would run, so the app and the terminal can never disagree about a move. // // index rebuild re-read every project, write its record back (a job) // index prune drop the records of projects that are gone (in process: // a few hundred deletes) // storage move-out | all out/ to the media root, a link left // storage move-back | all out/ back into the project // storage deliverables media|local clips/ and share-*/, then the switch // // Never against the real reports root in a test: every path here is // REPORTS_ROOT's, which the e2e suite points at its fixture. // --------------------------------------------------------------------------- export class ActionError extends Error { constructor( message: string, readonly status = 400, readonly plan: ActionPlanView | null = null, ) { super(message); } } const CLI = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"); const mb = (n: number) => `${(n / 1024 ** 2).toFixed(1)} MB`; function cliStep(label: string, args: string[], timeoutMs: number): Step { return { cwd: UMTOOL_DIR, env: {}, label, argv: ["node", CLI(), ...args], timeoutMs }; } /** Start a job, or say which one is in the way. */ function runJob(kind: string, steps: Step[], project: string | null) { const running = runningJob(); if (running) throw new ActionError(`a job is already running (${running.kind}) — run this when it has finished`, 409); try { return jobView(startJob(kind, steps, { project })); } catch (e) { throw new ActionError(e instanceof Error ? e.message : String(e), 409); } } // ── the index ─────────────────────────────────────────────────────────────── export type IndexAction = "rebuild" | "prune"; export const isIndexAction = (v: unknown): v is IndexAction => v === "rebuild" || v === "prune"; export async function planIndex(action: IndexAction): Promise { const ix = await indexPrunePlan(); const refusals = ix.ok ? [] : ["There is no index (the lmdb store did not open) — nothing to do; everything works without it."]; if (action === "prune") { return { action: "index prune", title: "Prune the index", summary: ix.stale.length ? `Drop ${ix.stale.length} of ${ix.records} records: projects the walk no longer finds. Their folders are gone already; nothing on disk changes.` : `Nothing to drop: all ${ix.records} records are projects that exist.`, rows: ix.stale.map((r) => ({ label: r.id, what: r.title ?? "a record with no title", state: "drop" })), refusals, warnings: [], confirm: ix.stale.length ? `Drop ${ix.stale.length} ${ix.stale.length === 1 ? "record" : "records"}` : "Nothing to drop", job: false, blocked: !ix.ok || ix.stale.length === 0, }; } invalidateProjects(); const n = (await projectRefs()).length; return { action: "index rebuild", title: "Rebuild the index", summary: `Re-read ${n} ${n === 1 ? "project" : "projects"} and write each record back (${ix.records} now). Never needed for correctness — every read checks its own signature — but the first load after a big change is fast instead of merely correct. Runs as a job.`, rows: ix.path ? [{ label: "store", what: ix.path }] : [], refusals, warnings: runningJob() ? [`a job is running (${runningJob()!.kind}): the rebuild cannot start until it has finished`] : [], confirm: "Rebuild the index", job: true, blocked: !ix.ok, }; } export async function applyIndex(action: IndexAction): Promise<{ message: string; job?: ReturnType }> { const plan = await planIndex(action); if (plan.blocked) throw new ActionError(plan.refusals[0] ?? plan.summary, 409, plan); if (action === "prune") { invalidateProjects(); const dropped = await pruneIndex(); return { message: `Dropped ${dropped} ${dropped === 1 ? "record" : "records"}` }; } // The kind reads as "Index rebuild" in the rail's Running list (lib/running.mjs ownJobLabel). const job = runJob("index-rebuild", [cliStep("rebuild the project index", ["index", "--rebuild"], 30 * 60_000)], null); return { message: "The index rebuild is running", job }; } // ── storage ───────────────────────────────────────────────────────────────── export type StorageAction = "move-out" | "move-back" | "deliverables"; export type StorageInput = { action: StorageAction; project: string | null; all: boolean; to: "media" | "local" | null }; export function parseStorage(body: Record): StorageInput { const action = body.action; if (action !== "move-out" && action !== "move-back" && action !== "deliverables") { throw new ActionError('action is "move-out", "move-back" or "deliverables"'); } const all = body.all === true; const project = typeof body.project === "string" && body.project.trim() ? body.project.trim() : null; if (!all && !project) throw new ActionError("which project? name one, or all: true"); if (all && action === "deliverables") throw new ActionError("deliverables move one project at a time"); const to = body.to === "media" || body.to === "local" ? body.to : null; if (action === "deliverables" && !to) throw new ActionError('to is "media" or "local"'); return { action, project: all ? null : project, all, to }; } const hasManifest = (dir: string) => stat(path.join(/* turbopackIgnore: true */ dir, MANIFEST_NAME)).then((s) => s.isFile(), () => false); const WORD: Record = { "would-move": "moves", "would-finish": "finishes a cut move", already: "already there", absent: "nothing to move", busy: "busy — skipped", failed: "refused", }; export async function planStorage(input: StorageInput): Promise { const refusals: string[] = []; const warnings: string[] = []; const rows: PlanRow[] = []; const refs = input.all ? await projectRefs() : [await projectRef(input.project as string)]; if (refs.some((r) => !r)) throw new ActionError(`no such project: ${input.project}`, 404); const projects = refs as NonNullable<(typeof refs)[number]>[]; if (input.action === "deliverables") { const p = projects[0]; const to = input.to as "media" | "local"; if (!(await hasManifest(p.dir))) refusals.push(`${p.id} has no ${MANIFEST_NAME} — deliverables are a report video's`); const busy = pipelineProcessesFor(p); if (busy.length) refusals.push(`a pipeline process is working in ${p.id} (pid ${busy.join(", ")}) — run this when it has finished`); if (!refusals.length) { try { const r = await moveDeliverables(p.dir, to, { dryRun: true, writeMode: async () => {} }); for (const x of r.results as { name: string; state: string; bytes?: number; files?: number; error?: string }[]) { rows.push({ label: `${x.name}/`, what: x.error ?? WORD[x.state] ?? x.state, state: x.state, bytes: x.bytes, files: x.files }); if (x.state === "failed") refusals.push(`${x.name}/: ${x.error}`); } if (!r.results.length) rows.push({ label: "—", what: "no clips/ and no share-*/ yet; only the switch is set" }); rows.push({ label: "storage.deliverables", what: r.before === to ? `${to} already` : `${r.before ?? "unset (reads as local)"} → ${to}`, state: r.before === to ? "already" : "would-move", }); } catch (e) { refusals.push(e instanceof Error ? e.message : String(e)); } } const bytes = rows.reduce((n, r) => n + (r.state === "would-move" ? (r.bytes ?? 0) : 0), 0); return { action: `storage deliverables ${p.id} ${to}`, title: `Move ${p.id}'s deliverables to ${to === "media" ? "the media root" : "the project"}`, summary: `clips/ and every share-*/ ${to === "media" ? `to ${MEDIA_ROOT}` : "back into the project"}, ${mb(bytes)}; then storage.deliverables: ${to}. Copied, mirrored and verified before the original goes. Runs as a job.`, rows, refusals, warnings, confirm: `Move to ${to}`, job: true, blocked: refusals.length > 0, }; } const toMedia = input.action === "move-out"; if (toMedia && !MEDIA_TIERED) { refusals.push("UMTOOL_MEDIA_DIR is not set: there is no media root to move out/ to. Set it to a directory on the media drive (outside the reports root), then restart umtool."); } let moving = 0; let bytes = 0; if (!refusals.length) { for (const p of projects) { const busy = pipelineProcessesFor(p); if (busy.length) { rows.push({ label: p.id, what: `a pipeline process is writing it (pid ${busy.join(", ")})`, state: "busy" }); (input.all ? warnings : refusals).push(`${p.id} is busy (pid ${busy.join(", ")}) — ${input.all ? "it is skipped" : "run this when it has finished"}`); continue; } try { const r = (await (toMedia ? moveDirToMedia : moveDirToLocal)(p.dir, "out", { dryRun: true })) as { state: string; bytes?: number; files?: number }; if (input.all && (r.state === "absent" || r.state === "already")) continue; if (r.state === "would-move" || r.state === "would-finish") { moving += 1; bytes += r.bytes ?? 0; } rows.push({ label: p.id, what: WORD[r.state] ?? r.state, state: r.state, bytes: r.bytes, files: r.files }); } catch (e) { const m = e instanceof Error ? e.message : String(e); rows.push({ label: p.id, what: m, state: "failed" }); (input.all ? warnings : refusals).push(`${p.id}: ${m}`); } } } const subject = input.all ? "every project's out/" : `${projects[0].id}'s out/`; return { action: `storage ${input.action} ${input.all ? "--all" : projects[0].id}`, title: toMedia ? `Move ${subject} to the media root` : `Move ${subject} back into the project`, summary: refusals.length ? "Nothing can move." : moving ? `${moving} ${moving === 1 ? "project" : "projects"}, ${mb(bytes)}: copied, mirrored and verified ${toMedia ? `under ${MEDIA_ROOT}, then a link left in its place` : "into the project, then the link removed"}. Runs as a job.` : "Nothing to move: every out/ is already where it should be.", rows, refusals, warnings, confirm: toMedia ? "Move out" : "Move back", job: true, blocked: refusals.length > 0 || moving === 0, }; } export async function applyStorage(input: StorageInput): Promise<{ message: string; job: ReturnType }> { const plan = await planStorage(input); if (plan.blocked) throw new ActionError(plan.refusals[0] ?? plan.summary, 409, plan); if (input.action === "deliverables") { const p = (await projectRef(input.project as string))!; const job = runJob(`move deliverables ${p.id} to ${input.to}`, moveDeliverablesSteps(p, input.to as "media" | "local"), p.id); return { message: `Moving ${p.id}'s deliverables to ${input.to}`, job }; } const target = input.all ? "--all" : (input.project as string); // "Move out reports/x", "Move back every project" in the Running list. const job = runJob( `${input.action} ${input.all ? "every project" : target}`, [cliStep(`${input.action} ${input.all ? "every project" : target}`, ["storage", input.action, target], 60 * 60_000)], input.all ? null : target, ); return { message: `${input.action === "move-out" ? "Moving out" : "Moving back"} ${input.all ? "every project" : target}`, job }; }