// DELETING AN ARTICLE OR ONE OF ITS ITERATIONS (release 27 follow-up, lane I). // // Each is a PLAN and an APPLY: // // planArticleDelete / planIterationDelete READ ONLY: what would go (every // path, with its size), what is // kept and why, and what refuses // deleteArticle / deleteIteration the same plan made again under // the article store's lock, then // done // // WHAT AN ARTICLE IS, on disk (the survey, plans/release-27.md "Follow-up: // delete, as shipped"): // transcripts/reports// report.json, video.mp4, // poster.jpg, stills/, sources/, // history-git/, notes.json, // iterations/ — removed whole // transcripts/reports/index.json the published list: a published // article is refused, unless // `force` (then unpublished first, // through the registry) // //i/ each iteration's video project // (D1) — removed; the article's // folder too once it is empty // .export-index/articles/report-exports// its staged exports — removed // sites//site.json `pages` a site's pages are the SITE's // reports (sites//reports//), // a different document: one of the // same id is kept and named. A page // naming the id with no report of // its own (a leftover of the // release 26 move) is refused, // unless `force` (then dropped, // through patchSite) // KEPT, always: the generation usage ledger (spend history); the shared // prepared-media cache (`report-media/`, pruned by the next prepare); the git // history of transcripts/ (the corpus repo's own business); a published // build until it is rebuilt and deployed. // // AN ITERATION: `iterations//` and its project `projectOf(projectsRoot, // id, n)` (and a recorded `projectDir` inside the projects root). Refused: // the current article or video, the iteration the article's report.json came // from, one that is queued or running (or a step of it is), and one another // iteration names as `parent` or `copyOf` (delete those first). Its NUMBER is // retired (`current.json` `highest`): the ledger and job logs name it. // // NEVER OUTSIDE THE KNOWN ROOTS. Every path removed is inside the articles // directory, the projects root, the export staging or — for a project's // `out/`, `clips/` or `share-*` that umtool's move-out made a link to the // media root — exactly that link's mirror under the media root // (`/`, umtool/lib/paths.mjs // mediaMirror), when the caller names the media root. Any other link is // removed as a link and its target kept and named. Nothing follows a link. // // THE LOCK IS HELD FOR THE STORE'S WRITES ONLY: unpublishing, the site // pages, and one rename that parks the directory as `.deleting-…` (no reader // sees it from then on). The bulk — gigabytes of renders — is removed after // the lock is let go, so a long delete never makes the lock look stale. A // delete cut in the middle leaves a `.deleting-…` directory, which the next // plan of the same article lists and removes. // // SERVER-ONLY (node:fs). import type { Dirent } from "node:fs"; import { lstat, readdir, readlink, realpath, rm, rmdir, stat } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { getPaths, type Paths } from "../paths"; import { getSite, listSiteIds, patchSite } from "../site"; import { isCitedSite, parseSiteReports } from "../siteSchema"; import { liveVerdictsJob, readVerdictProposals } from "./verdictProposals"; import { ARTICLE_DELETING_PREFIX, ArticleRegistryError, assertArticleId, articleDir, parkArticleDirHoldingLock, readArticlesIndex, unpublishHoldingLock, withArticleStoreLock, } from "./registry"; import { DELETING_PREFIX, iterationDir, iterationDirNumbers, iterationLabel, iterationsDir, projectOf, readIterations, retireIterationHoldingLock, type Iteration, } from "./iterations"; import { articleReportStore } from "./store"; // The paths a delete reads and writes. A full Paths satisfies it; a test // names its own three directories. export type DeletePaths = Pick; // Where umtool keeps a tiered project's bulk (umtool/lib/paths.mjs // REPORTS_ROOT and MEDIA_ROOT). Given, a project link that is exactly its // mirror there has its target removed too. export type DeleteMedia = { reportsRoot: string; mediaRoot: string }; export type DeleteOptions = { // settings.generation.projectsRoot, resolved (`~` expanded; blank = // ~/reports/articles) — the caller's, as every generation path is. projectsRoot: string; media?: DeleteMedia | null; paths?: DeletePaths; // An article: unpublish it and drop its leftover site pages first. force?: boolean; // Sizes: on by default. Off for the re-plan under the lock. measure?: boolean; }; // One thing that would go: a directory, a file or a link. export type DeleteEntry = { path: string; // How a person reads it: `reports//`, `projects//i3/`, …. label: string; what: string; kind: "dir" | "file" | "link" | "absent"; bytes: number; files: number; // A directory's top-level entries, biggest first (an article dir's // report.json, video.mp4, iterations/, …). parts?: { name: string; bytes: number }[]; }; export type DeleteKept = { what: string; path?: string; why: string }; export type DeleteRefusal = { reason: string; forceable: boolean }; export type DeletePlan = { article: string; // The iteration, for an iteration's plan. n?: number; // An article: whether report.json is there (false: in the making). hasReport?: boolean; published?: boolean; refusals: DeleteRefusal[]; // Store writes made before anything is removed (with `force`). steps: string[]; remove: DeleteEntry[]; kept: DeleteKept[]; bytes: number; files: number; }; // Refused: nothing was written. The plan says why. export class DeleteRefusedError extends ArticleRegistryError { constructor( message: string, readonly plan: DeletePlan, ) { super(message, plan.refusals.map((r) => r.reason)); this.name = "DeleteRefusedError"; } } export type DeleteResult = { plan: DeletePlan; // What was removed, and what could not be (the rest was still tried). removed: string[]; failed: { path: string; error: string }[]; }; // Whether a plan stops a delete: any refusal, or — with `force` — any that // force does not answer. export function deleteBlocked(plan: Pick, force = false): boolean { return plan.refusals.some((r) => !force || !r.forceable); } // umtool's reports and media roots from this process's environment, as // umtool/lib/paths.mjs reads them (REPORTS_DIR, else dirname of // SONG_REPORTS_DIR, else ~/reports; UMTOOL_MEDIA_DIR); null when no media root // of its own is set. export function deleteMediaFromEnv(env: NodeJS.ProcessEnv = process.env): DeleteMedia | null { const mediaRoot = env.UMTOOL_MEDIA_DIR; if (!mediaRoot) return null; const reportsRoot = env.REPORTS_DIR ?? (env.SONG_REPORTS_DIR ? path.dirname(path.resolve(env.SONG_REPORTS_DIR)) : path.join(os.homedir(), "reports")); const r = path.resolve(reportsRoot); const m = path.resolve(mediaRoot); return r === m ? null : { reportsRoot: r, mediaRoot: m }; } // ─── Paths ─── const inside = (root: string, p: string) => p === root || p.startsWith(root + path.sep); const strictlyInside = (root: string, p: string) => p !== root && inside(root, p); // `p` is under `root` lexically, and its parent's real path is under the // root's real path (a link on the way out of the root is refused). async function assertUnder(root: string, p: string, what: string): Promise { const r = path.resolve(root); const abs = path.resolve(p); if (!strictlyInside(r, abs)) throw new ArticleRegistryError(`${what} (${abs}) is not inside ${r}: refused`); const [realRoot, realParent] = await Promise.all([realpath(r).catch(() => null), realpath(path.dirname(abs)).catch(() => null)]); if (realRoot && realParent && !inside(realRoot, realParent)) { throw new ArticleRegistryError(`${what} (${abs}) resolves outside ${r} (${realParent}): refused`); } } type Measured = { kind: DeleteEntry["kind"]; bytes: number; files: number; parts: { name: string; bytes: number }[]; // Links met inside a directory, with their targets (resolved, not followed). links: { path: string; target: string }[]; }; async function linkTarget(p: string): Promise { return path.resolve(path.dirname(p), await readlink(p)); } // Sizes, never following a link. `measure: false` answers the kind only. async function measure(p: string, sizes: boolean): Promise { const st = await lstat(p).catch(() => null); if (!st) return { kind: "absent", bytes: 0, files: 0, parts: [], links: [] }; if (st.isSymbolicLink()) return { kind: "link", bytes: 0, files: 0, parts: [], links: [{ path: p, target: await linkTarget(p) }] }; if (!st.isDirectory()) return { kind: "file", bytes: st.size, files: 1, parts: [], links: [] }; const out: Measured = { kind: "dir", bytes: 0, files: 0, parts: [], links: [] }; const walk = async (dir: string, top: { name: string; bytes: number } | null): Promise => { let entries: Dirent[]; try { entries = await readdir(dir, { withFileTypes: true }); } catch { return; } for (const e of entries) { const child = path.join(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 linkTarget(child).catch(() => "?") }); if (!top) part.name = `${e.name} (link)`; } else if (e.isDirectory()) { if (sizes) await walk(child, part); } else if (sizes) { const s = await lstat(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; } async function entryOf(p: string, label: string, what: string, sizes: boolean): Promise<{ entry: DeleteEntry; links: Measured["links"] }> { const m = await measure(p, sizes); 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, }; } const LINK_KEPT_WHY = "a link: it is removed, and what it points at is kept (not this project's own media copy)"; // The links met in what is removed: a project link that is exactly its // umtool media mirror is removed with its target; any other link's target is // kept, and named. async function linkEntries( links: Measured["links"], removing: readonly string[], media: DeleteMedia | null | undefined, sizes: boolean, ): Promise<{ remove: DeleteEntry[]; kept: DeleteKept[] }> { const out = { remove: [] as DeleteEntry[], kept: [] as DeleteKept[] }; for (const l of links) { if (removing.some((r) => inside(r, l.target))) continue; // goes with the tree const mirror = media && strictlyInside(path.resolve(media.reportsRoot), l.path) ? path.join(path.resolve(media.mediaRoot), path.relative(path.resolve(media.reportsRoot), l.path)) : null; if (media && mirror && l.target === mirror && strictlyInside(path.resolve(media.mediaRoot), l.target)) { const { entry } = await entryOf(l.target, l.target, `the media copy ${path.basename(l.path)}/ links to`, sizes); if (entry.kind !== "absent") out.remove.push(entry); continue; } out.kept.push({ what: `${l.path} → ${l.target}`, path: l.target, why: LINK_KEPT_WHY }); } return out; } const ITERATION_PROJECT_RE = /^i[1-9]\d{0,8}$/; const ledgerKept = (): DeleteKept => ({ what: "the generation usage ledger's rows", why: "spend history: kept whatever is deleted", }); const busyReason = (it: Iteration): string | null => { if (it.status === "queued" || it.status === "running") { return `${iterationLabel(it.n)} is ${it.status}${it.jobId ? ` (job ${it.jobId})` : ""}: cancel it, or wait for it to end`; } const step = it.steps.find((s) => s.status === "running"); return step ? `${iterationLabel(it.n)}'s ${step.task} step is running${step.jobId ? ` (job ${step.jobId})` : ""}: wait for it to end` : null; }; function totals(plan: Omit): DeletePlan { return { ...plan, bytes: plan.remove.reduce((s, e) => s + e.bytes, 0), files: plan.remove.reduce((s, e) => s + e.files, 0), }; } // ─── An article ─── type SitePage = { site: string; ownReport: boolean }; async function sitePagesNaming(paths: DeletePaths, id: string): Promise { const out: SitePage[] = []; for (const site of listSiteIds(paths as Paths)) { const pages = parseSiteReports(getSite(site, paths as Paths).pages); if (!pages.includes(id)) continue; const own = await stat(path.join(paths.sitesDir, site, "reports", id)).then((s) => s.isDirectory(), () => false); out.push({ site, ownReport: own }); } return out; } // The export staging of the article store: `/report-exports//` // (publish/reportExportFiles.ts REPORT_EXPORTS_DIRNAME; lib may not import // publish). const ARTICLE_EXPORTS_DIRNAME = "report-exports"; export function articleExportsDir(paths: Pick, id: string): string { return path.join(articleReportStore(paths).stagingDir, ARTICLE_EXPORTS_DIRNAME, id); } async function leftoverParks(dir: string, prefix: string): Promise { const names = await readdir(dir).catch(() => [] as string[]); return names.filter((n) => n.startsWith(prefix)).sort().map((n) => path.join(dir, n)); } // WHAT DELETING ARTICLE `id` WOULD DO. Reads only. Throws for an id that is // not one, and for an article that is nowhere (no directory, not published, // no projects, nothing staged). export async function planArticleDelete(id: string, opts: DeleteOptions): Promise { assertArticleId(id); const paths = opts.paths ?? getPaths(); const sizes = opts.measure !== false; const projectsRoot = path.resolve(opts.projectsRoot); const refusals: DeleteRefusal[] = []; const steps: string[] = []; const remove: DeleteEntry[] = []; const kept: DeleteKept[] = []; const links: Measured["links"] = []; const add = async (p: string, label: string, what: string) => { const e = await entryOf(p, label, what, sizes); if (e.entry.kind === "absent") return false; remove.push(e.entry); links.push(...e.links); return true; }; const dir = articleDir(paths, id); const dirSt = await lstat(dir).catch(() => null); const index = await readArticlesIndex(paths); const published = index.published.includes(id); const hasReport = !!(await stat(path.join(dir, "report.json")).catch(() => null))?.isFile(); if (dirSt?.isSymbolicLink()) { refusals.push({ reason: `reports/${id} is a link (to ${await linkTarget(dir)}), not an article directory: remove it by hand`, forceable: false }); } else if (dirSt && !dirSt.isDirectory()) { refusals.push({ reason: `reports/${id} is not a directory: remove it by hand`, forceable: false }); } // Its iterations: any busy one refuses; each one's project goes. const recorded = new Set(); if (dirSt?.isDirectory()) { const read = await readIterations(id, paths); for (const it of read.iterations) { const busy = busyReason(it); if (busy) refusals.push({ reason: busy, forceable: false }); if (it.projectDir) recorded.add(path.resolve(it.projectDir)); } for (const p of read.problems) { kept.push({ what: `${iterationLabel(p.n)}'s iteration.json`, why: `unsound (${p.problems.join("; ")}): its directory goes with the article all the same` }); } // A verdicts job proposing for it (release 29 M8): it makes no iteration, // so its mark on the sidecar says so (a mark whose process is gone is not // a job). A sidecar that does not read goes with the article. const job = liveVerdictsJob(await readVerdictProposals(id, paths).catch(() => null)); if (job) refusals.push({ reason: `a verdicts job (job ${job.jobId}) is proposing verdicts for it: cancel it, or wait for it to end`, forceable: false }); } if (published) { refusals.push({ reason: `"${id}" is published (reports/index.json, position ${index.published.indexOf(id)}): unpublish it first, or delete with force`, forceable: true, }); if (opts.force) steps.push(`unpublish "${id}" (reports/index.json)`); } for (const page of await sitePagesNaming(paths, id)) { if (page.ownReport) { kept.push({ what: `site ${page.site}'s page "${id}"`, path: path.join(paths.sitesDir, page.site, "reports", id), why: "the site's own report (sites//reports/), a different document from the article: untouched", }); continue; } refusals.push({ reason: `site ${page.site} lists a page "${id}" with no report of its own (sites/${page.site}/reports/${id}/ is not there): drop it from the site's pages, or delete with force`, forceable: true, }); if (opts.force) steps.push(`drop the page "${id}" from site ${page.site} (site.json pages)`); } if (dirSt?.isDirectory()) await add(dir, `reports/${id}/`, hasReport ? "the article directory" : "the article in the making (iterations, no report.json)"); for (const p of await leftoverParks(paths.articlesDir, `${ARTICLE_DELETING_PREFIX}${id}-`)) { await add(p, `reports/${path.basename(p)}/`, "what a cut delete of this article left"); } // The video projects: //i/, and any recorded elsewhere // under the root. const projectsDir = path.join(projectsRoot, id); const projectsSt = await lstat(projectsDir).catch(() => null); let projectsFolderEmptied = false; if (projectsSt?.isSymbolicLink()) { kept.push({ what: projectsDir, path: await linkTarget(projectsDir), why: "the article's projects folder is a link: nothing under it is removed" }); } else if (projectsSt?.isDirectory()) { await assertUnder(projectsRoot, projectsDir, "the article's projects folder"); const names = await readdir(projectsDir).catch(() => [] as string[]); let others = 0; for (const name of names.sort()) { const p = path.join(projectsDir, name); if (ITERATION_PROJECT_RE.test(name)) { await add(p, `${path.basename(projectsRoot)}/${id}/${name}/`, `${name}'s video project`); recorded.delete(path.resolve(p)); } else { others += 1; kept.push({ what: p, path: p, why: "not an iteration's project (i): kept, and the folder with it" }); } } projectsFolderEmptied = others === 0; } for (const p of recorded) { if (inside(projectsDir, p)) continue; if (strictlyInside(projectsRoot, p)) { await assertUnder(projectsRoot, p, "an iteration's recorded project"); await add(p, p, "an iteration's video project (as recorded)"); } else { kept.push({ what: p, path: p, why: "an iteration's recorded project outside the projects root: never removed from here" }); } } await add(articleExportsDir(paths, id), `.export-index/articles/${ARTICLE_EXPORTS_DIRNAME}/${id}/`, "its staged exports"); if (remove.length === 0 && !published && refusals.length === 0) { throw new ArticleRegistryError(`no article "${id}" (no reports/${id}/, not published, no projects or staged exports)`); } const removing = remove.map((e) => e.path); const l = await linkEntries(links, removing, opts.media, sizes); remove.push(...l.remove); kept.push(...l.kept); if (projectsFolderEmptied && projectsSt?.isDirectory()) steps.push(`remove ${projectsDir} once it is empty`); kept.push( ledgerKept(), { what: "the prepared media cache (.export-index/articles/report-media/)", why: "shared by every article: the next `reports prepare --articles` prunes what no published article cites" }, { what: "the git history of transcripts/", why: "the corpus repo's own business: never rewritten" }, ); if (published) kept.push({ what: "the published homepage", why: "carries the article until the homepage is rebuilt and deployed" }); return totals({ article: id, hasReport, published, refusals, steps, remove, kept }); } // Remove what a plan lists, after the store's writes: every path checked // against its root again, a link removed as a link. async function removeEntries( entries: readonly DeleteEntry[], roots: readonly string[], ): Promise> { const out: Pick = { removed: [], failed: [] }; for (const e of entries) { try { const root = roots.map((r) => path.resolve(r)).find((r) => strictlyInside(r, path.resolve(e.path))); if (!root) throw new Error(`not inside a known root (${roots.join(", ")}): refused`); await assertUnder(root, e.path, e.label); await rm(e.path, { recursive: true, force: true }); out.removed.push(e.path); } catch (err) { out.failed.push({ path: e.path, error: (err as Error).message }); } } return out; } const uniqueByPath = (entries: readonly DeleteEntry[]): DeleteEntry[] => [...new Map(entries.map((e) => [e.path, e])).values()]; const stampOf = (now: Date) => `${now.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z")}-${process.pid}`; // DELETE ARTICLE `id`. Refused (DeleteRefusedError, nothing written) while // the plan has a refusal `force` does not answer. Under the store's lock: the // plan made again, the site pages (force), the unpublish (force), and the // directory parked; then the bulk removed. export async function deleteArticle(id: string, opts: DeleteOptions, now: Date = new Date()): Promise { const paths = opts.paths ?? getPaths(); const first = await planArticleDelete(id, opts); if (deleteBlocked(first, opts.force)) throw new DeleteRefusedError(`"${id}" is not deleted`, first); const stamp = stampOf(now); const locked = await withArticleStoreLock(async () => { const plan = await planArticleDelete(id, { ...opts, measure: false }); if (deleteBlocked(plan, opts.force)) throw new DeleteRefusedError(`"${id}" is not deleted`, plan); if (opts.force) { for (const page of await sitePagesNaming(paths, id)) { if (page.ownReport) continue; await patchSite( page.site, (cur) => { const pages = (cur.pages ?? []).filter((x) => x !== id); // Its last page gone, a search-off site would be refused on save // (siteSearchProblem): it is retired as move-to-articles retires one. return pages.length === 0 && isCitedSite(cur) ? { pages, search: true } : { pages }; }, paths as Paths, ); } await unpublishHoldingLock(id, paths); } const parked = await parkArticleDirHoldingLock(id, paths, stamp); return { plan, parked }; }, paths); const projectsRoot = path.resolve(opts.projectsRoot); // What either plan lists — the one made under the lock is what is there now; // the first walked every link (a media copy) — the article directory as it // was parked. const entries = uniqueByPath([...locked.plan.remove, ...first.remove]).map((e) => locked.parked && e.path === articleDir(paths, id) ? { ...e, path: locked.parked } : e, ); const roots = [paths.articlesDir, projectsRoot, paths.exportIndexDir, ...(opts.media ? [opts.media.mediaRoot] : [])]; const done = await removeEntries(entries, roots); const projectsDir = path.join(projectsRoot, id); if (first.steps.some((s) => s.startsWith(`remove ${projectsDir}`))) { await rmdir(projectsDir).then( () => done.removed.push(projectsDir), () => {}, ); } return { plan: first, ...done }; } // ─── An iteration ─── // WHAT DELETING ITERATION `n` OF `id` WOULD DO. Reads only. Throws for an // iteration that is not there. export async function planIterationDelete(id: string, n: number, opts: DeleteOptions): Promise { assertArticleId(id); if (!Number.isInteger(n) || n < 1) throw new ArticleRegistryError(`${String(n)} is not an iteration number (1, 2, …)`); const paths = opts.paths ?? getPaths(); const sizes = opts.measure !== false; const projectsRoot = path.resolve(opts.projectsRoot); const label = iterationLabel(n); if (!(await iterationDirNumbers(id, paths)).includes(n)) throw new ArticleRegistryError(`"${id}" has no iteration ${label}`); const read = await readIterations(id, paths); const it = read.iterations.find((x) => x.n === n) ?? null; const refusals: DeleteRefusal[] = []; const refuse = (reason: string) => refusals.push({ reason, forceable: false }); const cur = read.current; if (cur.report === n) refuse(`${label} is the current article: use another iteration first`); else if (cur.reportFrom === n) refuse(`the article's report.json is ${label}'s (current: ${iterationLabel(cur.report ?? n)}): use another iteration first`); if (cur.video === n) refuse(`${label} is the article's current video: attach another iteration's video first`); if (it) { const busy = busyReason(it); if (busy) refuse(busy); } const children = read.iterations.filter((x) => x.n !== n && (x.parent === n || x.copyOf === n)); if (children.length) { refuse( `${children.map((c) => `${iterationLabel(c.n)} ${c.parent === n ? "revises" : "is a copy of"} it`).join("; ")}: delete ${children.length === 1 ? "it" : "those"} first`, ); } const remove: DeleteEntry[] = []; const kept: DeleteKept[] = []; const links: Measured["links"] = []; const add = async (p: string, l: string, what: string) => { const e = await entryOf(p, l, what, sizes); if (e.entry.kind === "absent") return; remove.push(e.entry); links.push(...e.links); }; await add(iterationDir(paths, id, n), `reports/${id}/iterations/${n}/`, `${label}: its iteration.json, report, sweep and turns`); for (const p of await leftoverParks(iterationsDir(paths, id), `${DELETING_PREFIX}${n}-`)) { await add(p, `reports/${id}/iterations/${path.basename(p)}/`, `what a cut delete of ${label} left`); } const projects = new Set([path.resolve(projectOf(projectsRoot, id, n))]); if (it?.projectDir) projects.add(path.resolve(it.projectDir)); for (const p of projects) { if (!strictlyInside(projectsRoot, p)) { kept.push({ what: p, path: p, why: "a recorded project outside the projects root: never removed from here" }); continue; } const st = await lstat(p).catch(() => null); if (!st) continue; await assertUnder(projectsRoot, p, `${label}'s video project`); await add(p, path.relative(path.dirname(projectsRoot), p) + "/", `${label}'s video project`); } const l = await linkEntries(links, remove.map((e) => e.path), opts.media, sizes); remove.push(...l.remove); kept.push(...l.kept, ledgerKept(), { what: `the number ${label}`, why: "retired: the next iteration is never numbered n again (current.json highest)" }); const steps = [`retire ${label}'s number (iterations/current.json)`]; const projectsDir = path.join(projectsRoot, id); if (remove.some((e) => strictlyInside(projectsDir, e.path))) steps.push(`remove ${projectsDir} if nothing else is left in it`); return totals({ article: id, n, refusals, steps, remove, kept }); } // DELETE ITERATION `n` OF `id`. Refused (DeleteRefusedError, nothing written) // while its plan has any refusal. Under the store's lock: the plan made // again, the number retired and the directory parked; then the bulk removed. export async function deleteIteration(id: string, n: number, opts: DeleteOptions, now: Date = new Date()): Promise { const paths = opts.paths ?? getPaths(); const first = await planIterationDelete(id, n, opts); if (deleteBlocked(first)) throw new DeleteRefusedError(`"${id}" ${iterationLabel(n)} is not deleted`, first); const stamp = stampOf(now); const locked = await withArticleStoreLock(async () => { const plan = await planIterationDelete(id, n, { ...opts, measure: false }); if (deleteBlocked(plan)) throw new DeleteRefusedError(`"${id}" ${iterationLabel(n)} is not deleted`, plan); return { plan, parked: await retireIterationHoldingLock(id, n, paths, stamp) }; }, paths); const projectsRoot = path.resolve(opts.projectsRoot); const own = iterationDir(paths, id, n); const entries = uniqueByPath([...locked.plan.remove, ...first.remove]).map((e) => (e.path === own ? { ...e, path: locked.parked } : e)); const roots = [paths.articlesDir, projectsRoot, ...(opts.media ? [opts.media.mediaRoot] : [])]; const done = await removeEntries(entries, roots); const projectsDir = path.join(projectsRoot, id); if (strictlyInside(projectsRoot, projectsDir) && (await readdir(projectsDir).catch(() => null))?.length === 0) { await rmdir(projectsDir).then( () => done.removed.push(projectsDir), () => {}, ); } return { plan: first, ...done }; } // ─── Saying it ─── export function formatBytes(n: number): string { if (n < 1024) return `${n} B`; const units = ["KiB", "MiB", "GiB", "TiB"]; let v = n / 1024; let u = 0; while (v >= 1024 && u < units.length - 1) { v /= 1024; u += 1; } return `${v.toFixed(v >= 100 ? 0 : 1)} ${units[u]}`; } // A plan as lines, for a terminal or a job log. export function formatDeletePlan(plan: DeletePlan, opts: { force?: boolean } = {}): string[] { const what = plan.n !== undefined ? `"${plan.article}" ${iterationLabel(plan.n)}` : `"${plan.article}"`; const out: string[] = []; const blocked = deleteBlocked(plan, opts.force); out.push( `delete ${what}: ${plan.remove.length} path(s), ${formatBytes(plan.bytes)} in ${plan.files} file(s)${blocked ? " — REFUSED" : ""}`, ); for (const r of plan.refusals) { out.push(` refused${r.forceable ? (opts.force ? " (force answers it)" : " (unless --force)") : ""}: ${r.reason}`); } for (const s of plan.steps) out.push(` then: ${s}`); for (const e of plan.remove) { out.push(` remove ${e.label} ${e.what}, ${e.kind === "link" ? "a link" : `${formatBytes(e.bytes)} in ${e.files} file(s)`}${e.label === e.path ? "" : ` (${e.path})`}`); for (const p of (e.parts ?? []).slice(0, 12)) out.push(` ${p.name} ${formatBytes(p.bytes)}`); if ((e.parts?.length ?? 0) > 12) out.push(` … ${e.parts!.length - 12} more`); } for (const k of plan.kept) out.push(` keep ${k.what}: ${k.why}`); return out; }