Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit cbfef853acc4d300408d4ed22132599d06e2d5e3
parent b7d0f3bc866a2d82e0801afd0d324f2ba067ea49
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 21:58:17 -0400

common: the site delete lives in publish/ — controller/ may not import publish/

The architecture test's layering: controller/ never imports publish/; the
delete reads the publish state, the publish lock and the bundle's path, so it
is publish/siteDelete.ts (publish/ may import controller/ and lib/). The
route imports it from there.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Dcommon/controller/siteDelete.test.ts | 152-------------------------------------------------------------------------------
Dcommon/controller/siteDelete.ts | 250-------------------------------------------------------------------------------
Acommon/publish/siteDelete.test.ts | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/publish/siteDelete.ts | 250+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/delete-site/route.ts | 4++--
5 files changed, 404 insertions(+), 404 deletions(-)

diff --git a/common/controller/siteDelete.test.ts b/common/controller/siteDelete.test.ts @@ -1,152 +0,0 @@ -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { existsSync } from "node:fs"; -import { lstat, mkdir, mkdtemp, readdir, readFile, readlink, rm, symlink, writeFile } from "node:fs/promises"; -import os from "node:os"; -import path from "node:path"; -import { acquirePublishLock } from "../publish/stageLock"; -import { deleteSiteByPlan, formatSiteDeletePlan, planSiteDelete, siteDeleteBlocked, SiteDeleteRefusedError } from "./siteDelete"; - -// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/siteDelete.test.ts -// -// Release 28 H5: a site's delete over a temp transcripts/ and export/ — never -// the real ones. - -async function tree() { - const dir = await mkdtemp(path.join(os.tmpdir(), "site-delete-")); - const paths = { - sitesDir: path.join(dir, "transcripts", "sites"), - channelsDir: path.join(dir, "transcripts", "channels"), - exportDir: path.join(dir, "export"), - exportBuildsDir: path.join(dir, "export", ".export-builds"), - exportSitesIndexDir: path.join(dir, "export", ".export-index", "sites"), - }; - const site = async (id: string, json: Record<string, unknown> = {}, o: { reports?: string[]; builds?: boolean; deployed?: unknown } = {}) => { - const d = path.join(paths.sitesDir, id); - await mkdir(d, { recursive: true }); - await writeFile(path.join(d, "site.json"), JSON.stringify({ siteId: id, siteTitle: id, channels: ["demo-channel"], audience: "private", ...json })); - await writeFile(path.join(d, "tags.json"), "{}"); - for (const r of o.reports ?? []) { - await mkdir(path.join(d, "reports", r), { recursive: true }); - await writeFile(path.join(d, "reports", r, "report.json"), "{}"); - } - if (o.builds !== false) { - const b = path.join(paths.exportBuildsDir, id); - await mkdir(path.join(b, "out"), { recursive: true }); - await writeFile(path.join(b, "built.json"), "{}"); - await writeFile(path.join(b, "out", "index.html"), "<html></html>"); - if (o.deployed) await writeFile(path.join(b, "deployed.json"), JSON.stringify(o.deployed)); - await mkdir(path.join(paths.exportSitesIndexDir, id, "report-media"), { recursive: true }); - await writeFile(path.join(paths.exportSitesIndexDir, id, "summary.json"), "{}"); - } - }; - // A channel the site's pool names: never touched. - await mkdir(path.join(paths.channelsDir, "demo-channel", "data", "v1"), { recursive: true }); - await writeFile(path.join(paths.channelsDir, "demo-channel", "config.json"), "{}"); - await writeFile(path.join(paths.channelsDir, "demo-channel", "data", "v1", "transcript.json"), "{}"); - return { dir, paths, site, done: () => rm(dir, { recursive: true, force: true }) }; -} - -test("a private site with nothing deployed: the plan, then its three directories go, and nothing else", async () => { - const t = await tree(); - try { - await t.site("doomed"); - await t.site("keeper"); - const plan = await planSiteDelete("doomed", t.paths); - assert.equal(plan.exists, true); - assert.deepEqual(plan.refusals, []); - assert.deepEqual(plan.remove.map((e) => e.label), ["sites/doomed/", "export/.export-builds/doomed/", "export/.export-index/sites/doomed/"]); - assert.equal(plan.files, 5); - assert.ok(plan.kept.some((k) => k.what === "every channel's data")); - assert.match(formatSiteDeletePlan(plan)[0]!, /^delete site "doomed": 3 path\(s\)/); - const r = await deleteSiteByPlan("doomed", t.paths); - assert.equal(r.removed.length, 3); - assert.deepEqual(r.failed, []); - for (const e of plan.remove) assert.equal(existsSync(e.path), false, e.label); - // No park left behind; the other site and the channel untouched. - assert.deepEqual(await readdir(t.paths.sitesDir), ["keeper"]); - assert.deepEqual((await readdir(t.paths.exportBuildsDir)).filter((n) => !n.startsWith(".publish")), ["keeper"]); - assert.ok(existsSync(path.join(t.paths.exportSitesIndexDir, "keeper", "summary.json"))); - assert.equal(await readFile(path.join(t.paths.channelsDir, "demo-channel", "data", "v1", "transcript.json"), "utf8"), "{}"); - // Gone means gone: a second delete has no site to delete. - await assert.rejects(deleteSiteByPlan("doomed", t.paths), (e: unknown) => e instanceof SiteDeleteRefusedError && /no site "doomed"/.test(e.message)); - } finally { - await t.done(); - } -}); - -test("a deploy target, a recorded deploy or reports of its own refuse unless force; force deletes and keeps the remote", async () => { - const t = await tree(); - try { - await t.site("public-one", { audience: "public", cloudflareProject: "demo-pages", siteUrl: "https://demo.example" }, { - reports: ["a-report"], - deployed: { v: 1, target: "public-one", previews: {}, production: { builtStampId: "x", builtAt: 1, kind: "production", url: "https://demo.example", at: 2, liveCheck: null } }, - }); - const plan = await planSiteDelete("public-one", t.paths); - assert.deepEqual( - plan.refusals.map((r) => [r.reason, r.forceable]), - [ - ['it deploys to the Cloudflare Pages project "demo-pages"', true], - ["it holds 1 report (a-report), which go with it", true], - ["the publish state records a deploy: production (https://demo.example)", true], - ], - ); - assert.equal(siteDeleteBlocked(plan), true); - assert.equal(siteDeleteBlocked(plan, true), false); - await assert.rejects(deleteSiteByPlan("public-one", t.paths), SiteDeleteRefusedError); - assert.ok(existsSync(path.join(t.paths.sitesDir, "public-one", "site.json")), "a refusal writes nothing"); - assert.ok(plan.kept.some((k) => k.what === 'the Pages project "demo-pages"')); - const r = await deleteSiteByPlan("public-one", t.paths, { force: true }); - assert.equal(r.removed.length, 3); - assert.equal(existsSync(path.join(t.paths.sitesDir, "public-one")), false); - } finally { - await t.done(); - } -}); - -test("never forceable: no such site, a site dir that is a link, a publish stage running", async () => { - const t = await tree(); - try { - const none = await planSiteDelete("ghost", t.paths); - assert.equal(none.exists, false); - assert.deepEqual(none.refusals, [{ reason: 'no site "ghost" (sites/ghost/site.json)', forceable: false }]); - // A link: refused, never followed. - await t.site("real", {}, { builds: false }); - await symlink(path.join(t.paths.sitesDir, "real"), path.join(t.paths.sitesDir, "alias")); - const link = await planSiteDelete("alias", t.paths); - assert.equal(siteDeleteBlocked(link, true), true); - assert.match(link.refusals[0]!.reason, /sites\/alias is a link/); - // A publish stage holds the lock (this process, alive): refused, force or not. - await t.site("busy"); - const lock = await acquirePublishLock(t.paths, { kind: "build-site", target: "other" }); - try { - const busy = await planSiteDelete("busy", t.paths); - assert.deepEqual(busy.refusals.map((r) => r.forceable), [false]); - assert.match(busy.refusals[0]!.reason, /a publish stage is running: build-site other/); - await assert.rejects(deleteSiteByPlan("busy", t.paths, { force: true }), SiteDeleteRefusedError); - } finally { - await lock.release(); - } - assert.ok(existsSync(path.join(t.paths.sitesDir, "busy", "site.json"))); - assert.equal((await deleteSiteByPlan("busy", t.paths)).removed.length, 3); - assert.ok((await lstat(path.join(t.paths.sitesDir, "real"))).isDirectory(), "the link's target is kept"); - } finally { - await t.done(); - } -}); - -test("export/out linking into the site's bundle is named and kept", async () => { - const t = await tree(); - try { - await t.site("linked"); - await mkdir(t.paths.exportDir, { recursive: true }); - const out = path.join(t.paths.exportDir, "out"); - await symlink(path.join(t.paths.exportBuildsDir, "linked", "out"), out); - const plan = await planSiteDelete("linked", t.paths); - assert.ok(plan.kept.some((k) => k.what === "export/out" && /next build makes it again/.test(k.why))); - await deleteSiteByPlan("linked", t.paths); - assert.equal(await readlink(out), path.join(t.paths.exportBuildsDir, "linked", "out")); - } finally { - await t.done(); - } -}); diff --git a/common/controller/siteDelete.ts b/common/controller/siteDelete.ts @@ -1,250 +0,0 @@ -// DELETE A SITE — a plan, then the delete (release 28 H5; `pnpm ops -// delete-site`). The editor's Danger → Delete (`deleteSiteAction` → -// lib/site.ts `deleteSite`) removes `sites/<id>/` and nothing else; this is -// the scripted path, and it says first what goes, what stays and what refuses. -// -// WHAT A SITE IS ON DISK (the survey, 2026-10-13): -// sites/<id>/ site.json (the pool: `channels`, -// `citedChannels`), tags.json, charts, -// its reports/ (each with history-git/) -// export/.export-builds/<id>/ built.json, deployed.json (the publish -// state), out/ (the last bundle), -// public/ and .r2-staging/ (docker builds) -// export/.export-index/sites/<id>/ compose's staging: report-media/, -// report-exports/, summaries, stats -// Nothing else names a site by id on disk: channel membership is site.json's -// own pool (a channel's config holds no site list), the hub lists the sites -// that are on disk with a siteUrl (its next build drops this one), and curated -// tags' site scoping is read against the sites that exist. -// -// REMOVED: the three directories. KEPT, always: every channel's data (never -// touched), the Cloudflare Pages project and anything already deployed to it -// or to R2 (remote: a deploy, not a delete, takes a site off the edge), a -// deployed hub until it is rebuilt, `export/out` when it links into this -// site's bundle (the next build makes it again). -// -// REFUSED — forceable: a deploy target (`cloudflareProject`), a deploy the -// publish state records (production, preview or local), a site that holds -// reports (they go with it). Never forceable: no such site; its directory is a -// link; a publish stage running (the publish lock held by a live holder). -// -// THE DELETE: under the site.json lock and the publish lock (taken without -// waiting: a stage running refuses), the plan is made again, then each -// directory is renamed aside to `.deleting-<id>-<stamp>` (not a site id, so no -// reader lists it); the bulk is removed after the locks are let go. - -import type { Dirent } from "node:fs"; -import { lstat, readdir, readlink, rename, rm } from "node:fs/promises"; -import path from "node:path"; -import { withJsonFileLock } from "../lib/jsonFile-server"; -import type { Paths } from "../lib/paths"; -import { getSite, siteConfigFile, siteDir } from "../lib/site"; -import { isValidSiteId } from "../lib/siteSchema"; -import { exportOutPath } from "../publish/build"; -import { holderIsGone, LockWaitCancelled, acquirePublishLock, describeHolder, readLockHolder, type LockHolder } from "../publish/stageLock"; -import { readDeployedFile, targetDir } from "../publish/stamps"; - -export type SiteDeletePaths = Pick<Paths, "sitesDir" | "exportBuildsDir" | "exportSitesIndexDir" | "exportDir">; - -export type SiteDeleteEntry = { path: string; label: string; what: string; kind: "dir" | "link" | "file"; bytes: number; files: number }; -export type SiteDeleteKept = { what: string; why: string }; -export type SiteDeleteRefusal = { reason: string; forceable: boolean }; - -export type SiteDeletePlan = { - siteId: string; - exists: boolean; - refusals: SiteDeleteRefusal[]; - remove: SiteDeleteEntry[]; - kept: SiteDeleteKept[]; - bytes: number; - files: number; -}; - -export type SiteDeleteResult = { plan: SiteDeletePlan; removed: string[]; failed: { path: string; error: string }[] }; - -export class SiteDeleteRefusedError extends Error { - constructor( - message: string, - readonly plan: SiteDeletePlan, - ) { - super(message); - this.name = "SiteDeleteRefusedError"; - } -} - -export function siteDeleteBlocked(plan: Pick<SiteDeletePlan, "refusals">, force = false): boolean { - return plan.refusals.some((r) => !force || !r.forceable); -} - -async function measure(p: string): Promise<{ bytes: number; files: number }> { - let bytes = 0; - let files = 0; - const walk = async (dir: string) => { - let entries: Dirent[]; - try { - entries = await readdir(dir, { withFileTypes: true }); - } catch { - return; - } - for (const e of entries) { - const child = path.join(dir, e.name); - if (e.isDirectory()) await walk(child); - else { - const s = await lstat(child).catch(() => null); - if (s) { - bytes += s.isSymbolicLink() ? 0 : s.size; - files += 1; - } - } - } - }; - await walk(p); - return { bytes, files }; -} - -async function lstatOrNull(p: string) { - return lstat(p).catch(() => null); -} - -export async function planSiteDelete( - siteId: string, - paths: SiteDeletePaths, - o: { measure?: boolean; ownLock?: LockHolder } = {}, -): Promise<SiteDeletePlan> { - if (!isValidSiteId(siteId)) throw new Error(`Invalid site id: ${String(siteId)}`); - const sizes = o.measure !== false; - const refusals: SiteDeleteRefusal[] = []; - const remove: SiteDeleteEntry[] = []; - const kept: SiteDeleteKept[] = [{ what: "every channel's data", why: "a site's delete never touches a channel" }]; - const dir = siteDir(paths as Paths, siteId); - const st = await lstatOrNull(dir); - const exists = !!st && (st.isSymbolicLink() || (st.isDirectory() && !!(await lstatOrNull(siteConfigFile(paths as Paths, siteId))))); - if (!exists) refusals.push({ reason: `no site "${siteId}" (sites/${siteId}/site.json)`, forceable: false }); - else if (st!.isSymbolicLink()) refusals.push({ reason: `sites/${siteId} is a link (to ${await readlink(dir).catch(() => "?")}): refused, never followed`, forceable: false }); - - const add = async (p: string, label: string, what: string) => { - const s = await lstatOrNull(p); - if (!s) return; - if (s.isSymbolicLink()) { - remove.push({ path: p, label, what, kind: "link", bytes: 0, files: 0 }); - return; - } - const m = sizes && s.isDirectory() ? await measure(p) : { bytes: s.isDirectory() ? 0 : s.size, files: s.isDirectory() ? 0 : 1 }; - remove.push({ path: p, label, what, kind: s.isDirectory() ? "dir" : "file", ...m }); - }; - - if (exists && !st!.isSymbolicLink()) { - const site = getSite(siteId, paths as Paths); - await add(dir, `sites/${siteId}/`, "the site: site.json, its pool and pages, tags, charts, reports"); - if (site.cloudflareProject?.trim()) { - refusals.push({ reason: `it deploys to the Cloudflare Pages project "${site.cloudflareProject.trim()}"`, forceable: true }); - kept.push({ what: `the Pages project "${site.cloudflareProject.trim()}"`, why: "remote: what it serves stays until the project is changed there" }); - } - const reports = (await readdir(path.join(dir, "reports"), { withFileTypes: true }).catch(() => [] as Dirent[])).filter((e) => e.isDirectory()).map((e) => e.name); - if (reports.length) { - refusals.push({ reason: `it holds ${reports.length} report${reports.length === 1 ? "" : "s"} (${reports.slice(0, 5).join(", ")}${reports.length > 5 ? ", …" : ""}), which go with it`, forceable: true }); - } - } - // The publish state and the last bundle. - const builds = targetDir(paths, siteId); - const deployed = await readDeployedFile(paths, siteId).catch(() => null); - if (deployed) { - const kinds = [ - ...(deployed.production ? [`production (${deployed.production.url ?? "no url"})`] : []), - ...Object.keys(deployed.previews ?? {}).map((b) => `preview ${b}`), - ...(deployed.local ? ["local"] : []), - ]; - if (kinds.length) { - refusals.push({ reason: `the publish state records a deploy: ${kinds.join(", ")}`, forceable: true }); - kept.push({ what: "what was deployed", why: "remote (or the local site volume): a delete does not undeploy" }); - } - } - await add(builds, `export/.export-builds/${siteId}/`, "its publish state (built.json, deployed.json) and last bundle"); - await add(path.join(paths.exportSitesIndexDir, siteId), `export/.export-index/sites/${siteId}/`, "compose's staging for it (report media and exports, summaries, stats)"); - // export/out linking into this site's bundle: named, kept. - const out = exportOutPath(paths); - const outLink = await readlink(out).catch(() => null); - if (outLink) { - const target = path.resolve(path.dirname(out), outLink); - if (target === builds || target.startsWith(builds + path.sep)) { - kept.push({ what: "export/out", why: `it links to this site's bundle (${target}); the next build makes it again` }); - } - } - kept.push({ what: "a deployed hub", why: "it lists the site until it is rebuilt (the next hub build drops it)" }); - // A publish stage running: never forceable. - const holder = await readLockHolder(paths); - const mine = o.ownLock && holder && holder.pid === o.ownLock.pid && holder.since === o.ownLock.since && holder.host === o.ownLock.host; - if (holder && !mine && !holderIsGone(holder)) refusals.push({ reason: `a publish stage is running: ${describeHolder(holder)}`, forceable: false }); - - return { - siteId, - exists, - refusals, - remove, - kept, - bytes: remove.reduce((s, e) => s + e.bytes, 0), - files: remove.reduce((s, e) => s + e.files, 0), - }; -} - -export async function deleteSiteByPlan(siteId: string, paths: SiteDeletePaths, o: { force?: boolean; now?: Date } = {}): Promise<SiteDeleteResult> { - const first = await planSiteDelete(siteId, paths); - if (siteDeleteBlocked(first, o.force)) { - throw new SiteDeleteRefusedError(`delete site "${siteId}" refused: ${first.refusals.map((r) => r.reason).join("; ")}`, first); - } - const stamp = (o.now ?? new Date()).toISOString().replace(/[-:.]/g, ""); - const parked: string[] = []; - // The publish lock, without waiting: a stage that started since the plan refuses. - let lock: Awaited<ReturnType<typeof acquirePublishLock>>; - try { - lock = await acquirePublishLock(paths, { kind: "delete-site", target: siteId }, { signal: AbortSignal.timeout(1500), pollMs: 250 }); - } catch (e) { - if (e instanceof LockWaitCancelled) { - const again = await planSiteDelete(siteId, paths, { measure: false }); - throw new SiteDeleteRefusedError(`delete site "${siteId}" refused: a publish stage is running`, again); - } - throw e; - } - try { - await withJsonFileLock(siteConfigFile(paths as Paths, siteId), async () => { - const plan = await planSiteDelete(siteId, paths, { measure: false, ownLock: lock.holder }); - if (siteDeleteBlocked(plan, o.force)) { - throw new SiteDeleteRefusedError(`delete site "${siteId}" refused: ${plan.refusals.map((r) => r.reason).join("; ")}`, plan); - } - for (const e of plan.remove) { - if (e.kind === "link") { - await rm(e.path, { force: true }); - parked.push(e.path); - continue; - } - const aside = path.join(path.dirname(e.path), `.deleting-${siteId}-${stamp}`); - await rename(e.path, aside); - parked.push(aside); - } - }); - } finally { - await lock.release(); - } - const removed: string[] = []; - const failed: { path: string; error: string }[] = []; - for (const p of parked) { - try { - await rm(p, { recursive: true, force: true }); - removed.push(p); - } catch (e) { - failed.push({ path: p, error: (e as Error).message }); - } - } - return { plan: first, removed, failed }; -} - -const fmt = (n: number) => (n < 1024 ? `${n} B` : n < 1024 ** 2 ? `${(n / 1024).toFixed(1)} KiB` : n < 1024 ** 3 ? `${(n / 1024 ** 2).toFixed(1)} MiB` : `${(n / 1024 ** 3).toFixed(1)} GiB`); - -export function formatSiteDeletePlan(plan: SiteDeletePlan, o: { force?: boolean } = {}): string[] { - const blocked = siteDeleteBlocked(plan, o.force); - const out = [`delete site "${plan.siteId}": ${plan.remove.length} path(s), ${fmt(plan.bytes)} in ${plan.files} file(s)${blocked ? " — REFUSED" : ""}`]; - for (const r of plan.refusals) out.push(` refused${r.forceable ? (o.force ? " (force answers it)" : " (unless force)") : ""}: ${r.reason}`); - for (const e of plan.remove) out.push(` remove ${e.label} ${e.what}, ${e.kind === "link" ? "a link" : `${fmt(e.bytes)} in ${e.files} file(s)`}`); - for (const k of plan.kept) out.push(` keep ${k.what}: ${k.why}`); - return out; -} diff --git a/common/publish/siteDelete.test.ts b/common/publish/siteDelete.test.ts @@ -0,0 +1,152 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { lstat, mkdir, mkdtemp, readdir, readFile, readlink, rm, symlink, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { acquirePublishLock } from "./stageLock"; +import { deleteSiteByPlan, formatSiteDeletePlan, planSiteDelete, siteDeleteBlocked, SiteDeleteRefusedError } from "./siteDelete"; + +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test publish/siteDelete.test.ts +// +// Release 28 H5: a site's delete over a temp transcripts/ and export/ — never +// the real ones. + +async function tree() { + const dir = await mkdtemp(path.join(os.tmpdir(), "site-delete-")); + const paths = { + sitesDir: path.join(dir, "transcripts", "sites"), + channelsDir: path.join(dir, "transcripts", "channels"), + exportDir: path.join(dir, "export"), + exportBuildsDir: path.join(dir, "export", ".export-builds"), + exportSitesIndexDir: path.join(dir, "export", ".export-index", "sites"), + }; + const site = async (id: string, json: Record<string, unknown> = {}, o: { reports?: string[]; builds?: boolean; deployed?: unknown } = {}) => { + const d = path.join(paths.sitesDir, id); + await mkdir(d, { recursive: true }); + await writeFile(path.join(d, "site.json"), JSON.stringify({ siteId: id, siteTitle: id, channels: ["demo-channel"], audience: "private", ...json })); + await writeFile(path.join(d, "tags.json"), "{}"); + for (const r of o.reports ?? []) { + await mkdir(path.join(d, "reports", r), { recursive: true }); + await writeFile(path.join(d, "reports", r, "report.json"), "{}"); + } + if (o.builds !== false) { + const b = path.join(paths.exportBuildsDir, id); + await mkdir(path.join(b, "out"), { recursive: true }); + await writeFile(path.join(b, "built.json"), "{}"); + await writeFile(path.join(b, "out", "index.html"), "<html></html>"); + if (o.deployed) await writeFile(path.join(b, "deployed.json"), JSON.stringify(o.deployed)); + await mkdir(path.join(paths.exportSitesIndexDir, id, "report-media"), { recursive: true }); + await writeFile(path.join(paths.exportSitesIndexDir, id, "summary.json"), "{}"); + } + }; + // A channel the site's pool names: never touched. + await mkdir(path.join(paths.channelsDir, "demo-channel", "data", "v1"), { recursive: true }); + await writeFile(path.join(paths.channelsDir, "demo-channel", "config.json"), "{}"); + await writeFile(path.join(paths.channelsDir, "demo-channel", "data", "v1", "transcript.json"), "{}"); + return { dir, paths, site, done: () => rm(dir, { recursive: true, force: true }) }; +} + +test("a private site with nothing deployed: the plan, then its three directories go, and nothing else", async () => { + const t = await tree(); + try { + await t.site("doomed"); + await t.site("keeper"); + const plan = await planSiteDelete("doomed", t.paths); + assert.equal(plan.exists, true); + assert.deepEqual(plan.refusals, []); + assert.deepEqual(plan.remove.map((e) => e.label), ["sites/doomed/", "export/.export-builds/doomed/", "export/.export-index/sites/doomed/"]); + assert.equal(plan.files, 5); + assert.ok(plan.kept.some((k) => k.what === "every channel's data")); + assert.match(formatSiteDeletePlan(plan)[0]!, /^delete site "doomed": 3 path\(s\)/); + const r = await deleteSiteByPlan("doomed", t.paths); + assert.equal(r.removed.length, 3); + assert.deepEqual(r.failed, []); + for (const e of plan.remove) assert.equal(existsSync(e.path), false, e.label); + // No park left behind; the other site and the channel untouched. + assert.deepEqual(await readdir(t.paths.sitesDir), ["keeper"]); + assert.deepEqual((await readdir(t.paths.exportBuildsDir)).filter((n) => !n.startsWith(".publish")), ["keeper"]); + assert.ok(existsSync(path.join(t.paths.exportSitesIndexDir, "keeper", "summary.json"))); + assert.equal(await readFile(path.join(t.paths.channelsDir, "demo-channel", "data", "v1", "transcript.json"), "utf8"), "{}"); + // Gone means gone: a second delete has no site to delete. + await assert.rejects(deleteSiteByPlan("doomed", t.paths), (e: unknown) => e instanceof SiteDeleteRefusedError && /no site "doomed"/.test(e.message)); + } finally { + await t.done(); + } +}); + +test("a deploy target, a recorded deploy or reports of its own refuse unless force; force deletes and keeps the remote", async () => { + const t = await tree(); + try { + await t.site("public-one", { audience: "public", cloudflareProject: "demo-pages", siteUrl: "https://demo.example" }, { + reports: ["a-report"], + deployed: { v: 1, target: "public-one", previews: {}, production: { builtStampId: "x", builtAt: 1, kind: "production", url: "https://demo.example", at: 2, liveCheck: null } }, + }); + const plan = await planSiteDelete("public-one", t.paths); + assert.deepEqual( + plan.refusals.map((r) => [r.reason, r.forceable]), + [ + ['it deploys to the Cloudflare Pages project "demo-pages"', true], + ["it holds 1 report (a-report), which go with it", true], + ["the publish state records a deploy: production (https://demo.example)", true], + ], + ); + assert.equal(siteDeleteBlocked(plan), true); + assert.equal(siteDeleteBlocked(plan, true), false); + await assert.rejects(deleteSiteByPlan("public-one", t.paths), SiteDeleteRefusedError); + assert.ok(existsSync(path.join(t.paths.sitesDir, "public-one", "site.json")), "a refusal writes nothing"); + assert.ok(plan.kept.some((k) => k.what === 'the Pages project "demo-pages"')); + const r = await deleteSiteByPlan("public-one", t.paths, { force: true }); + assert.equal(r.removed.length, 3); + assert.equal(existsSync(path.join(t.paths.sitesDir, "public-one")), false); + } finally { + await t.done(); + } +}); + +test("never forceable: no such site, a site dir that is a link, a publish stage running", async () => { + const t = await tree(); + try { + const none = await planSiteDelete("ghost", t.paths); + assert.equal(none.exists, false); + assert.deepEqual(none.refusals, [{ reason: 'no site "ghost" (sites/ghost/site.json)', forceable: false }]); + // A link: refused, never followed. + await t.site("real", {}, { builds: false }); + await symlink(path.join(t.paths.sitesDir, "real"), path.join(t.paths.sitesDir, "alias")); + const link = await planSiteDelete("alias", t.paths); + assert.equal(siteDeleteBlocked(link, true), true); + assert.match(link.refusals[0]!.reason, /sites\/alias is a link/); + // A publish stage holds the lock (this process, alive): refused, force or not. + await t.site("busy"); + const lock = await acquirePublishLock(t.paths, { kind: "build-site", target: "other" }); + try { + const busy = await planSiteDelete("busy", t.paths); + assert.deepEqual(busy.refusals.map((r) => r.forceable), [false]); + assert.match(busy.refusals[0]!.reason, /a publish stage is running: build-site other/); + await assert.rejects(deleteSiteByPlan("busy", t.paths, { force: true }), SiteDeleteRefusedError); + } finally { + await lock.release(); + } + assert.ok(existsSync(path.join(t.paths.sitesDir, "busy", "site.json"))); + assert.equal((await deleteSiteByPlan("busy", t.paths)).removed.length, 3); + assert.ok((await lstat(path.join(t.paths.sitesDir, "real"))).isDirectory(), "the link's target is kept"); + } finally { + await t.done(); + } +}); + +test("export/out linking into the site's bundle is named and kept", async () => { + const t = await tree(); + try { + await t.site("linked"); + await mkdir(t.paths.exportDir, { recursive: true }); + const out = path.join(t.paths.exportDir, "out"); + await symlink(path.join(t.paths.exportBuildsDir, "linked", "out"), out); + const plan = await planSiteDelete("linked", t.paths); + assert.ok(plan.kept.some((k) => k.what === "export/out" && /next build makes it again/.test(k.why))); + await deleteSiteByPlan("linked", t.paths); + assert.equal(await readlink(out), path.join(t.paths.exportBuildsDir, "linked", "out")); + } finally { + await t.done(); + } +}); diff --git a/common/publish/siteDelete.ts b/common/publish/siteDelete.ts @@ -0,0 +1,250 @@ +// DELETE A SITE — a plan, then the delete (release 28 H5; `pnpm ops +// delete-site`). The editor's Danger → Delete (`deleteSiteAction` → +// lib/site.ts `deleteSite`) removes `sites/<id>/` and nothing else; this is +// the scripted path, and it says first what goes, what stays and what refuses. +// +// WHAT A SITE IS ON DISK (the survey, 2026-10-13): +// sites/<id>/ site.json (the pool: `channels`, +// `citedChannels`), tags.json, charts, +// its reports/ (each with history-git/) +// export/.export-builds/<id>/ built.json, deployed.json (the publish +// state), out/ (the last bundle), +// public/ and .r2-staging/ (docker builds) +// export/.export-index/sites/<id>/ compose's staging: report-media/, +// report-exports/, summaries, stats +// Nothing else names a site by id on disk: channel membership is site.json's +// own pool (a channel's config holds no site list), the hub lists the sites +// that are on disk with a siteUrl (its next build drops this one), and curated +// tags' site scoping is read against the sites that exist. +// +// REMOVED: the three directories. KEPT, always: every channel's data (never +// touched), the Cloudflare Pages project and anything already deployed to it +// or to R2 (remote: a deploy, not a delete, takes a site off the edge), a +// deployed hub until it is rebuilt, `export/out` when it links into this +// site's bundle (the next build makes it again). +// +// REFUSED — forceable: a deploy target (`cloudflareProject`), a deploy the +// publish state records (production, preview or local), a site that holds +// reports (they go with it). Never forceable: no such site; its directory is a +// link; a publish stage running (the publish lock held by a live holder). +// +// THE DELETE: under the site.json lock and the publish lock (taken without +// waiting: a stage running refuses), the plan is made again, then each +// directory is renamed aside to `.deleting-<id>-<stamp>` (not a site id, so no +// reader lists it); the bulk is removed after the locks are let go. + +import type { Dirent } from "node:fs"; +import { lstat, readdir, readlink, rename, rm } from "node:fs/promises"; +import path from "node:path"; +import { withJsonFileLock } from "../lib/jsonFile-server"; +import type { Paths } from "../lib/paths"; +import { getSite, siteConfigFile, siteDir } from "../lib/site"; +import { isValidSiteId } from "../lib/siteSchema"; +import { exportOutPath } from "./build"; +import { holderIsGone, LockWaitCancelled, acquirePublishLock, describeHolder, readLockHolder, type LockHolder } from "./stageLock"; +import { readDeployedFile, targetDir } from "./stamps"; + +export type SiteDeletePaths = Pick<Paths, "sitesDir" | "exportBuildsDir" | "exportSitesIndexDir" | "exportDir">; + +export type SiteDeleteEntry = { path: string; label: string; what: string; kind: "dir" | "link" | "file"; bytes: number; files: number }; +export type SiteDeleteKept = { what: string; why: string }; +export type SiteDeleteRefusal = { reason: string; forceable: boolean }; + +export type SiteDeletePlan = { + siteId: string; + exists: boolean; + refusals: SiteDeleteRefusal[]; + remove: SiteDeleteEntry[]; + kept: SiteDeleteKept[]; + bytes: number; + files: number; +}; + +export type SiteDeleteResult = { plan: SiteDeletePlan; removed: string[]; failed: { path: string; error: string }[] }; + +export class SiteDeleteRefusedError extends Error { + constructor( + message: string, + readonly plan: SiteDeletePlan, + ) { + super(message); + this.name = "SiteDeleteRefusedError"; + } +} + +export function siteDeleteBlocked(plan: Pick<SiteDeletePlan, "refusals">, force = false): boolean { + return plan.refusals.some((r) => !force || !r.forceable); +} + +async function measure(p: string): Promise<{ bytes: number; files: number }> { + let bytes = 0; + let files = 0; + const walk = async (dir: string) => { + let entries: Dirent[]; + try { + entries = await readdir(dir, { withFileTypes: true }); + } catch { + return; + } + for (const e of entries) { + const child = path.join(dir, e.name); + if (e.isDirectory()) await walk(child); + else { + const s = await lstat(child).catch(() => null); + if (s) { + bytes += s.isSymbolicLink() ? 0 : s.size; + files += 1; + } + } + } + }; + await walk(p); + return { bytes, files }; +} + +async function lstatOrNull(p: string) { + return lstat(p).catch(() => null); +} + +export async function planSiteDelete( + siteId: string, + paths: SiteDeletePaths, + o: { measure?: boolean; ownLock?: LockHolder } = {}, +): Promise<SiteDeletePlan> { + if (!isValidSiteId(siteId)) throw new Error(`Invalid site id: ${String(siteId)}`); + const sizes = o.measure !== false; + const refusals: SiteDeleteRefusal[] = []; + const remove: SiteDeleteEntry[] = []; + const kept: SiteDeleteKept[] = [{ what: "every channel's data", why: "a site's delete never touches a channel" }]; + const dir = siteDir(paths as Paths, siteId); + const st = await lstatOrNull(dir); + const exists = !!st && (st.isSymbolicLink() || (st.isDirectory() && !!(await lstatOrNull(siteConfigFile(paths as Paths, siteId))))); + if (!exists) refusals.push({ reason: `no site "${siteId}" (sites/${siteId}/site.json)`, forceable: false }); + else if (st!.isSymbolicLink()) refusals.push({ reason: `sites/${siteId} is a link (to ${await readlink(dir).catch(() => "?")}): refused, never followed`, forceable: false }); + + const add = async (p: string, label: string, what: string) => { + const s = await lstatOrNull(p); + if (!s) return; + if (s.isSymbolicLink()) { + remove.push({ path: p, label, what, kind: "link", bytes: 0, files: 0 }); + return; + } + const m = sizes && s.isDirectory() ? await measure(p) : { bytes: s.isDirectory() ? 0 : s.size, files: s.isDirectory() ? 0 : 1 }; + remove.push({ path: p, label, what, kind: s.isDirectory() ? "dir" : "file", ...m }); + }; + + if (exists && !st!.isSymbolicLink()) { + const site = getSite(siteId, paths as Paths); + await add(dir, `sites/${siteId}/`, "the site: site.json, its pool and pages, tags, charts, reports"); + if (site.cloudflareProject?.trim()) { + refusals.push({ reason: `it deploys to the Cloudflare Pages project "${site.cloudflareProject.trim()}"`, forceable: true }); + kept.push({ what: `the Pages project "${site.cloudflareProject.trim()}"`, why: "remote: what it serves stays until the project is changed there" }); + } + const reports = (await readdir(path.join(dir, "reports"), { withFileTypes: true }).catch(() => [] as Dirent[])).filter((e) => e.isDirectory()).map((e) => e.name); + if (reports.length) { + refusals.push({ reason: `it holds ${reports.length} report${reports.length === 1 ? "" : "s"} (${reports.slice(0, 5).join(", ")}${reports.length > 5 ? ", …" : ""}), which go with it`, forceable: true }); + } + } + // The publish state and the last bundle. + const builds = targetDir(paths, siteId); + const deployed = await readDeployedFile(paths, siteId).catch(() => null); + if (deployed) { + const kinds = [ + ...(deployed.production ? [`production (${deployed.production.url ?? "no url"})`] : []), + ...Object.keys(deployed.previews ?? {}).map((b) => `preview ${b}`), + ...(deployed.local ? ["local"] : []), + ]; + if (kinds.length) { + refusals.push({ reason: `the publish state records a deploy: ${kinds.join(", ")}`, forceable: true }); + kept.push({ what: "what was deployed", why: "remote (or the local site volume): a delete does not undeploy" }); + } + } + await add(builds, `export/.export-builds/${siteId}/`, "its publish state (built.json, deployed.json) and last bundle"); + await add(path.join(paths.exportSitesIndexDir, siteId), `export/.export-index/sites/${siteId}/`, "compose's staging for it (report media and exports, summaries, stats)"); + // export/out linking into this site's bundle: named, kept. + const out = exportOutPath(paths); + const outLink = await readlink(out).catch(() => null); + if (outLink) { + const target = path.resolve(path.dirname(out), outLink); + if (target === builds || target.startsWith(builds + path.sep)) { + kept.push({ what: "export/out", why: `it links to this site's bundle (${target}); the next build makes it again` }); + } + } + kept.push({ what: "a deployed hub", why: "it lists the site until it is rebuilt (the next hub build drops it)" }); + // A publish stage running: never forceable. + const holder = await readLockHolder(paths); + const mine = o.ownLock && holder && holder.pid === o.ownLock.pid && holder.since === o.ownLock.since && holder.host === o.ownLock.host; + if (holder && !mine && !holderIsGone(holder)) refusals.push({ reason: `a publish stage is running: ${describeHolder(holder)}`, forceable: false }); + + return { + siteId, + exists, + refusals, + remove, + kept, + bytes: remove.reduce((s, e) => s + e.bytes, 0), + files: remove.reduce((s, e) => s + e.files, 0), + }; +} + +export async function deleteSiteByPlan(siteId: string, paths: SiteDeletePaths, o: { force?: boolean; now?: Date } = {}): Promise<SiteDeleteResult> { + const first = await planSiteDelete(siteId, paths); + if (siteDeleteBlocked(first, o.force)) { + throw new SiteDeleteRefusedError(`delete site "${siteId}" refused: ${first.refusals.map((r) => r.reason).join("; ")}`, first); + } + const stamp = (o.now ?? new Date()).toISOString().replace(/[-:.]/g, ""); + const parked: string[] = []; + // The publish lock, without waiting: a stage that started since the plan refuses. + let lock: Awaited<ReturnType<typeof acquirePublishLock>>; + try { + lock = await acquirePublishLock(paths, { kind: "delete-site", target: siteId }, { signal: AbortSignal.timeout(1500), pollMs: 250 }); + } catch (e) { + if (e instanceof LockWaitCancelled) { + const again = await planSiteDelete(siteId, paths, { measure: false }); + throw new SiteDeleteRefusedError(`delete site "${siteId}" refused: a publish stage is running`, again); + } + throw e; + } + try { + await withJsonFileLock(siteConfigFile(paths as Paths, siteId), async () => { + const plan = await planSiteDelete(siteId, paths, { measure: false, ownLock: lock.holder }); + if (siteDeleteBlocked(plan, o.force)) { + throw new SiteDeleteRefusedError(`delete site "${siteId}" refused: ${plan.refusals.map((r) => r.reason).join("; ")}`, plan); + } + for (const e of plan.remove) { + if (e.kind === "link") { + await rm(e.path, { force: true }); + parked.push(e.path); + continue; + } + const aside = path.join(path.dirname(e.path), `.deleting-${siteId}-${stamp}`); + await rename(e.path, aside); + parked.push(aside); + } + }); + } finally { + await lock.release(); + } + const removed: string[] = []; + const failed: { path: string; error: string }[] = []; + for (const p of parked) { + try { + await rm(p, { recursive: true, force: true }); + removed.push(p); + } catch (e) { + failed.push({ path: p, error: (e as Error).message }); + } + } + return { plan: first, removed, failed }; +} + +const fmt = (n: number) => (n < 1024 ? `${n} B` : n < 1024 ** 2 ? `${(n / 1024).toFixed(1)} KiB` : n < 1024 ** 3 ? `${(n / 1024 ** 2).toFixed(1)} MiB` : `${(n / 1024 ** 3).toFixed(1)} GiB`); + +export function formatSiteDeletePlan(plan: SiteDeletePlan, o: { force?: boolean } = {}): string[] { + const blocked = siteDeleteBlocked(plan, o.force); + const out = [`delete site "${plan.siteId}": ${plan.remove.length} path(s), ${fmt(plan.bytes)} in ${plan.files} file(s)${blocked ? " — REFUSED" : ""}`]; + for (const r of plan.refusals) out.push(` refused${r.forceable ? (o.force ? " (force answers it)" : " (unless force)") : ""}: ${r.reason}`); + for (const e of plan.remove) out.push(` remove ${e.label} ${e.what}, ${e.kind === "link" ? "a link" : `${fmt(e.bytes)} in ${e.files} file(s)`}`); + for (const k of plan.kept) out.push(` keep ${k.what}: ${k.why}`); + return out; +} diff --git a/editor/app/api/ops/delete-site/route.ts b/editor/app/api/ops/delete-site/route.ts @@ -6,7 +6,7 @@ import { deleteSiteByPlan, planSiteDelete, siteDeleteBlocked, -} from "yt-dlp-transcript-common/controller/siteDelete"; +} from "yt-dlp-transcript-common/publish/siteDelete"; import { OpsInputError, ops, opsFail, optBool, reqString } from "../_lib"; export const dynamic = "force-dynamic"; @@ -17,7 +17,7 @@ export const dynamic = "force-dynamic"; // DELETE A SITE (release 28 H5), plan first: `sites/<id>/` (site.json, its // pool and pages, tags, charts, reports), its publish state and last bundle // (`export/.export-builds/<id>/`) and compose's staging for it -// (`export/.export-index/sites/<id>/`) — through controller/siteDelete.ts, +// (`export/.export-index/sites/<id>/`) — through publish/siteDelete.ts, // under the site.json lock and the publish lock. Channel data is never // touched; the Pages project, what was deployed and a deployed hub are kept // (remote: a delete does not undeploy). `dryRun` answers the plan and writes