// DELETE A SITE — a plan, then the delete (release 28 H5; `pnpm ops // delete-site`, and since M9 the editor's Danger → Delete on /sites: // `planSiteDeleteAction`, then `deleteSiteAction`). It says first what goes, // what stays and what refuses. // // WHAT A SITE IS ON DISK (the survey, 2026-10-13): // sites// site.json (the pool: `channels`, // `citedChannels`), tags.json, charts, // its reports/ (each with history-git/) // export/.export-builds// built.json, deployed.json (the publish // state), out/ (the last bundle), // public/ and .r2-staging/ (docker builds) // export/.export-index/sites// 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--` (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; 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, 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 { 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 { 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>; 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; }