// DELETING A PROJECT OR A TAKE (release 27 follow-up, lane I): a PLAN that // reads only -- every path that would go, with its size, what is kept and why, // and what refuses -- then the delete. The plan's shape is common's // (common/lib/report/delete.ts DeletePlan), so one page component shows both. // // a PROJECT its directory under REPORTS_ROOT, whatever its kind; and, for // a top-level link umtool's move-out made (`out`, `clips`, // `share-*` -> `//`), that // link's target on the media root. Any other link is removed as // a link and its target kept. Refused: a project reached through // a link, or that is one; a umtool job working in it; the // project of an article's CURRENT video (an iteration project // `current.json` names as the video), or of an iteration that is // queued or running; a project whose manifest names an article // (`"article": "/"`) with a video attached -- // unless `force` (the article keeps its attached copy). // a TAKE `takes//` -- its take.json, preview, manifest and out/. // Refused: a umtool job working in the project; the take the // project's video.manifest.json IS (byte for byte: what its // deliverable is built from) -- unless `force`. Kept: its row in // takes/verdicts.json and the notes on it (the agent that made // the takes reads both; a verdict on a take that is gone is // shown as missing). // // Never outside REPORTS_ROOT and MEDIA_ROOT, and never either root itself. // Plain ESM (node --test runs it; the routes import it). Every path op carries // `turbopackIgnore`: the app's routes import this module (plans/FACTS.md). import { lstat, readFile, readdir, readlink, realpath, rm, rmdir } from "node:fs/promises"; import path from "node:path"; import { MEDIA_ROOT, REPORTS_ROOT, inside } from "../paths.mjs"; import { isTakeId, takesDirOf } from "./takes.mjs"; import { renderHolds } from "./takeHousekeeping.mjs"; const strictlyInside = (root, p) => p !== root && inside(root, p); /** One project's or take's plan: common's DeletePlan shape (`article` is the project id). */ function plan(project, extra) { const remove = extra.remove; return { project, ...extra, bytes: remove.reduce((s, e) => s + e.bytes, 0), files: remove.reduce((s, e) => s + e.files, 0), }; } /** Whether a plan stops a delete: any refusal, or -- with `force` -- one force does not answer. */ export const deleteBlocked = (p, force = false) => p.refusals.some((r) => !force || !r.forceable); /** Sizes and links, never following a link. */ async function measure(p) { const st = await lstat(/* turbopackIgnore: true */ p).catch(() => null); if (!st) return { kind: "absent", bytes: 0, files: 0, parts: [], links: [] }; const target = async (l) => path.resolve(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ l), await readlink(/* turbopackIgnore: true */ l)); if (st.isSymbolicLink()) return { kind: "link", bytes: 0, files: 0, parts: [], links: [{ path: p, target: await target(p) }] }; if (!st.isDirectory()) return { kind: "file", bytes: st.size, files: 1, parts: [], links: [] }; const out = { kind: "dir", bytes: 0, files: 0, parts: [], links: [] }; const walk = async (dir, top) => { const entries = await readdir(/* turbopackIgnore: true */ dir, { withFileTypes: true }).catch(() => []); for (const e of entries) { const child = path.join(/* turbopackIgnore: true */ dir, e.name); const part = top ?? { name: e.isDirectory() ? `${e.name}/` : e.name, bytes: 0 }; if (!top) out.parts.push(part); if (e.isSymbolicLink()) { out.links.push({ path: child, target: await target(child).catch(() => "?") }); if (!top) part.name = `${e.name} (link)`; } else if (e.isDirectory()) { await walk(child, part); } else { const s = await lstat(/* turbopackIgnore: true */ child).catch(() => null); if (s) { out.bytes += s.size; out.files += 1; part.bytes += s.size; } } } }; await walk(p, null); out.parts.sort((a, b) => b.bytes - a.bytes || a.name.localeCompare(b.name)); return out; } /** `{ entry, links }` for one path, or a null entry when it is not there. */ async function entryOf(p, label, what) { const m = await measure(p); if (m.kind === "absent") return { entry: null, links: [] }; return { entry: { path: p, label, what, kind: m.kind, bytes: m.bytes, files: m.files, ...(m.kind === "dir" && m.parts.length ? { parts: m.parts } : {}) }, links: m.links, }; } /** * The links met in what goes: one that is exactly its media mirror goes with * its target; any other's target is kept and named. */ async function linkEntries(links, removing, roots) { const out = { remove: [], kept: [] }; for (const l of links) { if (removing.some((r) => inside(r, l.target))) continue; const rel = path.relative(/* turbopackIgnore: true */ roots.reportsRoot, l.path); const mirror = roots.tiered && rel && !rel.startsWith("..") && !path.isAbsolute(rel) ? path.join(/* turbopackIgnore: true */ roots.mediaRoot, rel) : null; if (mirror && l.target === mirror && strictlyInside(roots.mediaRoot, l.target)) { const e = await entryOf(l.target, l.target, `the media copy ${path.basename(/* turbopackIgnore: true */ l.path)}/ links to`); if (e.entry) out.remove.push(e.entry); continue; } out.kept.push({ what: `${l.path} → ${l.target}`, path: l.target, why: "a link: it is removed, and what it points at is kept (not this project's own media copy)" }); } return out; } function rootsOf(opts = {}) { const reportsRoot = path.resolve(/* turbopackIgnore: true */ opts.reportsRoot ?? REPORTS_ROOT); const mediaRoot = path.resolve(/* turbopackIgnore: true */ opts.mediaRoot ?? MEDIA_ROOT); return { reportsRoot, mediaRoot, tiered: mediaRoot !== reportsRoot }; } /** `dir` is strictly inside the reports root, is not a link, and its real path is inside the root's. */ async function placeProblem(dir, roots, what) { const abs = path.resolve(/* turbopackIgnore: true */ dir); if (!strictlyInside(roots.reportsRoot, abs)) return `${what} ${abs} is not inside the reports root ${roots.reportsRoot}`; const st = await lstat(/* turbopackIgnore: true */ abs).catch(() => null); if (!st) return `${what} ${abs} is not there`; if (st.isSymbolicLink()) return `${what} ${abs} is a link: remove the link by hand`; const [realRoot, real] = await Promise.all([ realpath(/* turbopackIgnore: true */ roots.reportsRoot).catch(() => null), realpath(/* turbopackIgnore: true */ abs).catch(() => null), ]); if (!realRoot || !real || !strictlyInside(realRoot, real)) return `${what} ${abs} is reached through a link (it is ${real}): remove it by hand`; return null; } const readJson = async (file) => { try { return JSON.parse(await readFile(/* turbopackIgnore: true */ file, "utf8")); } catch { return null; } }; /** * What an iteration project is to the article store, when `dir` is * `/
/i` or an iteration records it as its * `projectDir`: `{ article, n, current: "video" | null, status }`, else null. * Read-only reads of `ARTICLES_DIR/
/iterations/`. */ export async function iterationOfProject(dir, { projectsRoot, articlesDir }) { if (!projectsRoot || !articlesDir) return null; const abs = path.resolve(/* turbopackIgnore: true */ dir); const rel = path.relative(/* turbopackIgnore: true */ path.resolve(/* turbopackIgnore: true */ projectsRoot), abs).split(path.sep); if (rel.length !== 2 || rel[0].startsWith(".") || rel[0] === ".." || !/^i[1-9]\d{0,8}$/.test(rel[1])) return null; const [article, label] = rel; const n = Number(label.slice(1)); const its = path.join(/* turbopackIgnore: true */ articlesDir, article, "iterations"); const it = await readJson(path.join(/* turbopackIgnore: true */ its, String(n), "iteration.json")); if (!it || it.article !== article || it.n !== n) return null; const cur = (await readJson(path.join(/* turbopackIgnore: true */ its, "current.json"))) ?? {}; const running = it.status === "queued" || it.status === "running" || (Array.isArray(it.steps) && it.steps.some((s) => s?.status === "running")); return { article, n, current: cur.video === n ? "video" : null, status: running ? "busy" : String(it.status) }; } /** * WHAT DELETING PROJECT `project` WOULD DO. Reads only. * * @param {{ id: string, dir: string }} project * @param {{ reportsRoot?: string, mediaRoot?: string, busyJob?: string | null, * projectsRoot?: string, articlesDir?: string, * articleVideo?: (ref: string) => Promise, force?: boolean }} [opts] * `busyJob`: the umtool job working in it, by name, if one is; `articleVideo`: * whether the article a manifest names (`/`) has a video attached. */ export async function planProjectDelete(project, opts = {}) { const roots = rootsOf(opts); const refusals = []; const kept = []; const steps = []; const remove = []; const place = await placeProblem(project.dir, roots, "the project"); if (place) refusals.push({ reason: place, forceable: false }); if (opts.busyJob) refusals.push({ reason: `${opts.busyJob} is working in it: wait for it, or cancel it`, forceable: false }); const it = await iterationOfProject(project.dir, opts); if (it?.current === "video") { refusals.push({ reason: `it is i${it.n}'s project, and i${it.n} is the article "${it.article}"'s current video: attach another iteration's video, or delete the article`, forceable: false }); } else if (it?.status === "busy") { refusals.push({ reason: `it is i${it.n}'s project, and i${it.n} of "${it.article}" is running`, forceable: false }); } else if (it) { kept.push({ what: `i${it.n}'s iteration record (article "${it.article}")`, why: "kept, without its project: delete the iteration on the article's Iterations tab to remove both" }); } const manifest = await readJson(path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json")); const ref = typeof manifest?.article === "string" ? manifest.article : null; if (ref && opts.articleVideo && (await opts.articleVideo(ref).catch(() => false))) { refusals.push({ reason: `its manifest names the article ${ref}, which has a video attached: delete anyway to remove the project (the article keeps its attached copy)`, forceable: true, }); } else if (ref) { kept.push({ what: `the article ${ref} its manifest names`, why: "untouched (no video attached from it)" }); } if (!place) { const e = await entryOf(project.dir, project.id, "the project directory"); if (e.entry) { remove.push(e.entry); const l = await linkEntries(e.links, [path.resolve(/* turbopackIgnore: true */ project.dir)], roots); remove.push(...l.remove); kept.push(...l.kept); } } if (it) steps.push(`remove ${path.dirname(/* turbopackIgnore: true */ project.dir)} if nothing else is left in it`); kept.push({ what: "notes on it", why: "they live in its notes.json, which goes with the directory" }); return plan(project.id, { refusals, steps, remove, kept }); } /** Remove what a plan lists: each path inside a root and not a root, re-checked. */ async function removeEntries(entries, roots) { const out = { removed: [], failed: [] }; for (const e of entries) { try { const abs = path.resolve(/* turbopackIgnore: true */ e.path); const root = [roots.reportsRoot, ...(roots.tiered ? [roots.mediaRoot] : [])].find((r) => strictlyInside(r, abs)); if (!root) throw new Error("not inside the reports or media root: refused"); const realParent = await realpath(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ abs)).catch(() => null); const realRoot = await realpath(/* turbopackIgnore: true */ root).catch(() => null); if (!realParent || !realRoot || !inside(realRoot, realParent)) throw new Error("resolves outside its root: refused"); await rm(/* turbopackIgnore: true */ abs, { recursive: true, force: true }); out.removed.push(abs); } catch (err) { out.failed.push({ path: e.path, error: err instanceof Error ? err.message : String(err) }); } } return out; } /** A refusal: nothing was removed. `plan` says why. */ export class DeleteRefused extends Error { constructor(message, plan) { super(message); this.name = "DeleteRefused"; this.plan = plan; } } /** DELETE PROJECT `project`: the plan made again, then done. Throws DeleteRefused. */ export async function deleteProject(project, opts = {}) { const roots = rootsOf(opts); const p = await planProjectDelete(project, opts); if (deleteBlocked(p, opts.force)) throw new DeleteRefused(`${project.id} is not deleted: ${p.refusals.map((r) => r.reason).join("; ")}`, p); const done = await removeEntries(p.remove, roots); // An iteration project's article folder (/
/) goes once empty. if (p.steps.length) { const parent = path.dirname(/* turbopackIgnore: true */ path.resolve(/* turbopackIgnore: true */ project.dir)); if (strictlyInside(roots.reportsRoot, parent)) await rmdir(/* turbopackIgnore: true */ parent).then(() => done.removed.push(parent), () => {}); } return { plan: p, ...done }; } /** * WHAT DELETING TAKE `takeId` OF A PROJECT WOULD DO. Reads only. * * @param {{ id: string, dir: string }} project * @param {string} takeId * @param {{ reportsRoot?: string, mediaRoot?: string, busyJob?: string | null }} [opts] */ export async function planTakeDelete(project, takeId, opts = {}) { if (!isTakeId(takeId)) throw new Error("not a take id"); const roots = rootsOf(opts); const refusals = []; const kept = []; const remove = []; const dir = path.join(/* turbopackIgnore: true */ takesDirOf(project.dir), takeId); const st = await lstat(/* turbopackIgnore: true */ dir).catch(() => null); if (!st) throw new Error(`${project.id} has no take ${takeId}`); const place = await placeProblem(project.dir, roots, "the project"); if (place) refusals.push({ reason: place, forceable: false }); if (opts.busyJob) refusals.push({ reason: `${opts.busyJob} is working in ${project.id}: wait for it, or cancel it`, forceable: false }); // What a running render names (a `umtool take` from a terminal is no job of // the app's): the take rendering, or the base a render is made from. for (const why of await renderHolds(project.dir, takeId)) refusals.push({ reason: `take ${takeId}: ${why}`, forceable: false }); const [mine, theirs] = await Promise.all([ readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, "video.manifest.json"), "utf8").catch(() => null), readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"), "utf8").catch(() => null), ]); if (mine !== null && theirs !== null && mine === theirs) { refusals.push({ reason: `the project's video.manifest.json is this take's: the deliverable is built from it — delete anyway to remove the take (the project keeps its manifest)`, forceable: true, }); } if (!place) { const e = await entryOf(dir, `${project.id}/takes/${takeId}/`, st.isSymbolicLink() ? "the take (a link)" : "the take: take.json, its preview, its manifest and renders"); if (e.entry) { remove.push(e.entry); const l = await linkEntries(e.links, [path.resolve(/* turbopackIgnore: true */ dir)], roots); remove.push(...l.remove); kept.push(...l.kept); } } kept.push( { what: `its row in takes/verdicts.json`, why: "kept: the agent that made the takes reads it (a verdict on a take that is gone shows as missing)" }, { what: "notes on it", why: "kept in the project's notes.json (never hand-edited); they say the take is no longer in takes/" }, ); return plan(project.id, { take: takeId, refusals, steps: [], remove, kept }); } /** DELETE TAKE `takeId`: the plan made again, then done. Throws DeleteRefused. */ export async function deleteTake(project, takeId, opts = {}) { const p = await planTakeDelete(project, takeId, opts); if (deleteBlocked(p, opts.force)) throw new DeleteRefused(`take ${takeId} is not deleted: ${p.refusals.map((r) => r.reason).join("; ")}`, p); return { plan: p, ...(await removeEntries(p.remove, rootsOf(opts))) }; }