Archilyzer · Source

archilyzer

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

commit 5878590441d8294169e900a14891f47c1b41a83a
parent 6197affb74821d5581f4192b503dad163385126d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 10 Oct 2026 13:50:40 -0400

common: a channel that leaves a site's pool ships tombstones (release 24 H1)

A channel removed from a site's `channels`, or moved to `citedChannels`, is
withdrawn like a withheld X channel: every transcripts/subs/posts/digests
tree the site's last bundle (`<exportBuildsDir>/<site>/out`) served that the
new compose does not ship is written as a tombstone, path for path, and
served no-store. A bundle's tombstones are carried while the channel stays
out. The hub carries its last bundle's tombstones while a non-private site's
pool holds the channel. A site's deploy now probes its tombstones (the trees
its _headers declares withdrawn). builtCitedOnlyProblem accepts a tombstone
of any channel tree (isTombstoneChannelDir, which also refuses tracks and
page hashes).

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

Diffstat:
MPUBLISH.md | 14++++++++++++++
Mcommon/bin/compose-hub.test.ts | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/bin/compose-hub.ts | 56++++++++++++++++++++++++++++++++++++++++++++++----------
Acommon/bin/compose-site.departed.test.ts | 276+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/bin/compose-site.ts | 36++++++++++++++++++++++++++++++++++--
Mcommon/lib/builtExport.test.ts | 22++++++++++++++++++++--
Mcommon/lib/builtExport.ts | 23++++++++++++++++-------
Mcommon/publish/deployStage.test.ts | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcommon/publish/deployStage.ts | 27++++++++++++++++++++++++++-
Mcommon/publish/liveCheck.ts | 4+++-
Mcommon/publish/tombstones.test.ts | 140+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/publish/tombstones.ts | 205+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
12 files changed, 917 insertions(+), 35 deletions(-)

diff --git a/PUBLISH.md b/PUBLISH.md @@ -449,6 +449,20 @@ manifest — a channel only private sites carry is never named on the hub. `_hea serves them `Cache-Control: no-store`. **The hub's deploy reads each tombstone back**, plain and busted, into its live check. +**Tombstones for a channel that leaves a site.** A channel removed from a site's +`channels`, or moved to its `citedChannels`, is withdrawn the same way. The record of +what the site published is its last bundle, `export/.export-builds/<site>/out`, read by +compose before the build replaces it: every `transcripts/`, `subs/`, `posts/` or +`digests/<slug>/` tree it served that the new compose does not ship is written as a +tombstone, path for path — the tree's manifest at `pageCount: 0` and `[]` for each page +the bundle held — and served no-store. A bundle's tombstones are served paths too, so +they are carried build to build while the channel stays out; a channel back in the pool +gets its real trees again. A cited-only channel's moment pages and clips still publish +and are never tombstoned. A site's deploy probes its tombstones like the hub's (each +tree its `_headers` declares withdrawn). The hub carries the tombstones its own last +bundle shipped while a non-private site's pool still holds the channel, and names no +other. A docker-runner build sees no last bundle in its container, so it writes none. + ## The source mirror (homepage) The homepage carries the project's own source, read-only, as static files: diff --git a/common/bin/compose-hub.test.ts b/common/bin/compose-hub.test.ts @@ -46,6 +46,9 @@ function fixturePaths(root: string): Paths { // The hub's tombstones read the shared posts tree (release 18): this // fixture's own, never the checkout's. exportSharedPostsDir: path.join(root, ".export-index", "shared", "posts"), + // The hub's last bundle (release 24 H1 carries its tombstones): this + // fixture's own, never the checkout's. + exportBuildsDir: path.join(root, ".export-builds"), }; } @@ -376,3 +379,94 @@ test("while X posts are private, the hub ships tombstones for every X channel, s rmSync(root, { recursive: true, force: true }); } }); + +// Release 24 H1: a channel the hub's LAST BUNDLE tombstoned keeps its +// tombstone once it is no longer withdrawn — while the hub may still name it +// (a non-private site's pool holds it). One that left every such pool (moved +// to a public site's cited scope, kept only by a private site, or on no site) +// is never named, carried or not; nor is a tree that is not posts. +test("the hub carries its last bundle's tombstones while it may name the channel, and never names one it may not", async () => { + const root = mkdtempSync(path.join(tmpdir(), "compose-hub-")); + const log = console.log; + try { + const paths = fixturePaths(root); + const pub = paths.exportPublicDir; + const writeJson = (file: string, value: unknown) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify(value)); + }; + const STILL = "still-pooled-x"; + const CITED = "now-cited-x"; + const PRIV = "now-private-x"; + const NONE = "now-nowhere-x"; + for (const slug of [STILL, CITED, PRIV, NONE]) { + writeJson(path.join(paths.channelsDir, slug, "config.json"), { + handling: "youtube", + url: `https://x.com/${slug}`, + sourceKind: "social", + platform: "twitter", + }); + } + const site = (siteId: string, slugs: string[], extra: Record<string, unknown> = {}) => + writeJson(path.join(paths.sitesDir, siteId, "site.json"), { + siteId, + siteTitle: siteId, + channels: slugs.map((slug) => ({ slug, groupId: "default" })), + ...extra, + }); + site("pub", [STILL], { citedChannels: [{ slug: CITED }] }); + site("mine", [PRIV], { audience: "private" }); + // The hub's last bundle: the four channels' posts tombstones (all were on + // a public site's pool then), and a stray transcripts tree. + const bundle = path.join(paths.exportBuildsDir, "_hub", "out"); + writeJson(path.join(bundle, "hub-sites.json"), []); + writeJson(path.join(bundle, "posts", "manifest.json"), { channels: [], totalCount: 0 }); + for (const slug of [STILL, CITED, PRIV, NONE]) { + writeJson(path.join(bundle, "posts", slug, "manifest.json"), { pageCount: 0, slugToPage: {} }); + writeJson(path.join(bundle, "posts", slug, "page-0000.json"), []); + writeJson(path.join(bundle, "posts", slug, "page-0001.json"), []); + } + writeJson(path.join(bundle, "transcripts", STILL, "manifest.json"), { pageCount: 0, slugToPage: {} }); + + // X posts public: nothing is withdrawn, and only STILL is carried. + console.log = () => {}; + await main({ paths, settings: {} }); + console.log = log; + assert.deepEqual(readdirSync(path.join(pub, "posts")).sort(), ["manifest.json", STILL]); + assert.deepEqual(readdirSync(path.join(pub, "posts", STILL)).sort(), [ + "manifest.json", + "page-0000.json", + "page-0001.json", + ]); + assert.deepEqual(JSON.parse(readFileSync(path.join(pub, "posts", "manifest.json"), "utf8")).channels, []); + assert.ok(!existsSync(path.join(pub, "transcripts")), "the hub carries posts tombstones only"); + for (const hidden of [CITED, PRIV, NONE]) { + const named = readdirSync(pub, { recursive: true, withFileTypes: true }) + .filter((e) => e.isFile()) + .filter( + (e) => + e.name.includes(hidden) || + e.parentPath.includes(hidden) || + readFileSync(path.join(e.parentPath, e.name), "utf8").includes(hidden), + ); + assert.deepEqual(named.map((e) => e.name), [], `${hidden} is named in the hub's public/`); + } + assert.ok( + readFileSync(path.join(pub, "_headers"), "utf8").endsWith( + "# Withdrawn content (tombstones): never stored at the edge.\n" + + "/posts/*\n Cache-Control: no-store\n Access-Control-Allow-Origin: *\n", + ), + ); + assert.equal(builtHubProblem(pub), null); + + // No last bundle, X public: no posts/ at all, as before. + rmSync(bundle, { recursive: true, force: true }); + console.log = () => {}; + await main({ paths, settings: {} }); + console.log = log; + assert.ok(!existsSync(path.join(pub, "posts"))); + } finally { + console.log = log; + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/common/bin/compose-hub.ts b/common/bin/compose-hub.ts @@ -18,7 +18,10 @@ // channel with a shared posts tree that a // non-private site carries, its manifest at // pageCount 0 and `[]` pages -// (publish/tombstones.ts), served no-store +// (publish/tombstones.ts), served no-store — +// and each one the last hub bundle shipped, +// while a non-private site's pool holds it +// (release 24 H1) // // and REMOVES every per-site entry a site's compose left in public/ // (SITE_ONLY_PUBLIC_ENTRIES below): the hub holds no site's data. @@ -47,11 +50,17 @@ import { readGlobalAliases } from "../lib/aliasesStore"; import { getSettings } from "../lib/settings"; import { emptyPostsManifest, + hubNameableChannels, + lastBundleDir, + servedChannelTrees, tombstoneNoStoreForHub, withdrawnXChannels, + writeDepartedTombstones, writePostsTombstones, + type ChannelTreeTombstone, type PostsTombstone, } from "../publish/tombstones"; +import { HUB_TARGET } from "../publish/stamps"; import { runIfEntryPoint } from "./_cli"; import { writePublicFile } from "./_publicFile"; @@ -134,24 +143,38 @@ export const SITE_ONLY_PUBLIC_ENTRIES: readonly string[] = [ // now — all served no-store. A channel only private sites (or no site) carry is // never named here: private data is never named on the hub. With X // posts public, or no X channel, the hub ships no posts/ at all, as before. +// +// RELEASE 24 H1: a channel the hub's LAST BUNDLE served (its tombstones are +// the only channel paths a hub bundle holds — builtHubProblem) keeps its +// tombstone after it stops being withdrawn (X posts public again, or no +// longer an X channel), for as long as the hub may name it: a member of a +// non-private site's pool (hubNameableChannels). A channel that left every +// such pool — moved to a site's cited scope, kept only by private sites, or +// on no site — is never named here, carried or not. async function composeHubTombstones( paths: Paths, publicDir: string, settings: { social?: { x?: { visibility?: unknown } } }, -): Promise<PostsTombstone[]> { - const slugs = await withdrawnXChannels(paths, settings, listSites(paths)); - if (slugs.length === 0) return []; +): Promise<{ withdrawn: PostsTombstone[]; carried: ChannelTreeTombstone[] }> { + const sites = listSites(paths); + const slugs = await withdrawnXChannels(paths, settings, sites); + const nameable = hubNameableChannels(sites); + const served = (await servedChannelTrees(lastBundleDir(paths, HUB_TARGET))).filter( + (t) => t.tree === "posts" && nameable.has(t.slug) && !slugs.includes(t.slug), + ); + if (slugs.length === 0 && served.length === 0) return { withdrawn: [], carried: [] }; const postsDir = path.join(publicDir, "posts"); - const tombstones = await writePostsTombstones({ + const withdrawn = await writePostsTombstones({ postsDir, sharedPostsDir: paths.exportSharedPostsDir, slugs, }); + const carried = await writeDepartedTombstones({ publicDir, served }); await writePublicFile( path.join(postsDir, "manifest.json"), JSON.stringify(emptyPostsManifest(new Date().toISOString())), ); - return tombstones; + return { withdrawn, carried }; } export async function main( @@ -163,7 +186,17 @@ export async function main( for (const entry of SITE_ONLY_PUBLIC_ENTRIES) { await rm(path.join(publicDir, entry), { recursive: true, force: true }); } - const tombstones = await composeHubTombstones(paths, publicDir, opts.settings ?? getSettings()); + const { withdrawn, carried } = await composeHubTombstones( + paths, + publicDir, + opts.settings ?? getSettings(), + ); + // tombstoneNoStoreForHub asks only whether there is any: the hub's whole + // posts tree is served no-store. + const tombstones: PostsTombstone[] = [ + ...withdrawn, + ...carried.map((t) => ({ slug: t.slug, pages: t.pages })), + ]; // The hub's own alias dictionary is the global one (no site's overrides): // what a hub reader loads for hub-wide search (lib/archive/reader-hub.ts), // where it used to get whichever site had composed last. @@ -246,9 +279,12 @@ export async function main( const summaryNote = await composeHubSummary(paths, publicDir); const tombstoneNote = - tombstones.length > 0 - ? `; ${tombstones.length} withdrawn X channel(s) shipped as tombstones, served no-store` - : ""; + (withdrawn.length > 0 + ? `; ${withdrawn.length} withdrawn X channel(s) shipped as tombstones, served no-store` + : "") + + (carried.length > 0 + ? `; ${carried.length} channel(s) the last hub bundle tombstoned kept as tombstones, served no-store` + : ""); console.log( `compose-hub: ${builtins.length} built-in pool site(s) into ${publicDir}; ${summaryNote}${tombstoneNote}.`, ); diff --git a/common/bin/compose-site.departed.test.ts b/common/bin/compose-site.departed.test.ts @@ -0,0 +1,276 @@ +// Integration (release 24 H1): a channel that leaves a site's published pool — +// removed from `channels`, or moved to `citedChannels` — ships TOMBSTONES for +// every per-channel path the site's last bundle served for it, through the +// REAL index build and the REAL site compose over a temp corpus. +// +// The record of what the site published before is its last bundle, +// `<exportBuildsDir>/<siteId>/out`; each test stands one in by copying the +// composed public/ there, as the build stage's install does. +// +// Run with: node_modules/.bin/tsx --test common/bin/compose-site.departed.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { + cpSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +// Every path getPaths() can resolve to a place this file's code may write is +// pinned under ROOT before anything calls it (buildIndex.test.ts's list). +const ROOT = mkdtempSync(path.join(tmpdir(), "departed-")); +const PINNED: Record<string, string> = { + TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"), + SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"), + SITES_DIR: path.join(ROOT, "transcripts", "sites"), + SETTINGS_FILE: path.join(ROOT, "settings.json"), + EXPORT_PUBLIC_DIR: path.join(ROOT, "public"), + EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"), + EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"), + EDITOR_CHANGELOG_FILE: path.join(ROOT, "editor-CHANGELOG.md"), + EXPORT_CHANGELOG_FILE: path.join(ROOT, "export-CHANGELOG.md"), + CHARTS_CONFIG_FILE: path.join(ROOT, "chart-templates.json"), + SEARCH_ALIASES_FILE: path.join(ROOT, "transcripts", "search-aliases.json"), + CURATED_TAGS_FILE: path.join(ROOT, "transcripts", "tags.json"), + ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"), + ARCHILYZER_SOURCE_SCRATCH: path.join(ROOT, "source-scratch"), +}; +Object.assign(process.env, PINNED); +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { buildIndex } = await import("../controller/buildIndex"); +const { main: composeSite } = await import("./compose-site"); +const { builtCitedOnlyProblem, isTombstoneChannelDir } = await import("../lib/builtExport"); +const { lastBundleDir } = await import("../publish/tombstones"); + +const paths = getPaths(); +const KEEP = "keeper"; +const GONE = "departs"; +const FRESH = "fresh-critic"; + +const writeJson = (file: string, value: unknown) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify(value, null, 2)); +}; +const readJson = <T>(file: string): T => JSON.parse(readFileSync(file, "utf8")) as T; + +// YouTube's rolling-caption shape (parseVtt keeps lines with inline timing). +const VTT = + "WEBVTT\nKind: captions\nLanguage: en\n\n" + + "00:00:00.000 --> 00:00:05.000 align:start position:0%\n" + + "First<00:00:01.000><c> caption</c><00:00:02.000><c> line.</c>\n"; + +function videoChannel(slug: string, videos: number) { + writeJson(path.join(paths.channelsDir, slug, "config.json"), { + handling: "youtube", + name: slug, + url: `https://www.youtube.com/@${slug}/videos`, + }); + for (let i = 1; i <= videos; i++) { + const id = `${slug}-v${i}`; + const dir = path.join(paths.channelsDir, slug, "data", id); + writeJson(path.join(dir, "metadata.info.json"), { + id, + title: `${slug} video ${i}`, + channel: slug, + upload_date: `2026060${i}`, + duration: 120, + webpage_url: `https://www.youtube.com/watch?v=${id}`, + extractor_key: "Youtube", + }); + writeFileSync(path.join(dir, "transcript.en.vtt"), VTT); + } +} + +function site(pool: string[], cited: string[] = []) { + writeJson(path.join(paths.sitesDir, "pub", "site.json"), { + siteId: "pub", + siteTitle: "pub", + siteDescription: "fixture", + headerTitle: "pub", + homeTagline: "", + socialLinks: [], + groups: [{ id: "default", name: "All channels", selectedByDefault: true }], + defaultGroupId: "default", + channels: pool.map((slug) => ({ slug, groupId: "default" })), + ...(cited.length > 0 ? { citedChannels: cited.map((slug) => ({ slug })) } : {}), + siteUrl: "https://pub.example.test", + archives: false, + }); +} + +const quiet = () => {}; +async function indexAndCompose(): Promise<void> { + const log = console.log; + console.log = quiet; + try { + await buildIndex({ paths, onLog: quiet }); + await composeSite({ siteId: "pub", paths }); + } finally { + console.log = log; + } +} + +// The build stage's install, as far as compose can see it: public/ becomes +// the site's bundle. +function install(): string { + const bundle = lastBundleDir(paths, "pub"); + rmSync(bundle, { recursive: true, force: true }); + mkdirSync(path.dirname(bundle), { recursive: true }); + cpSync(paths.exportPublicDir, bundle, { recursive: true, dereference: true }); + return bundle; +} + +const pub = (...rel: string[]) => path.join(paths.exportPublicDir, ...rel); +const TREES = ["transcripts", "subs", "posts", "digests"] as const; +// The trees public/ holds for `slug`. +const treesOf = (slug: string) => TREES.filter((t) => existsSync(pub(t, slug))); +const pageFiles = (dir: string) => readdirSync(dir).filter((f) => f.startsWith("page-")).sort(); + +test("a channel removed from the pool ships a tombstone for every tree its last bundle served", async () => { + videoChannel(KEEP, 1); + videoChannel(GONE, 2); + videoChannel(FRESH, 1); + writeJson(paths.settingsFile, {}); + site([KEEP, GONE]); + await indexAndCompose(); + // This fixture's index writes the channel's transcripts; its subs and + // digests trees (two pages each) stand in for what a richer build served. + assert.deepEqual(treesOf(GONE), ["transcripts"]); + const bundle = install(); + for (const tree of ["subs", "digests"]) { + writeJson(path.join(bundle, tree, GONE, "manifest.json"), { + version: 1, + channelSlug: GONE, + pageCount: 2, + maxPageBytes: 4096, + generatedAt: "2026-10-01T00:00:00.000Z", + slugToPage: { [`${GONE}-v1`]: 0, [`${GONE}-v2`]: 1 }, + ...(tree === "subs" ? { tracks: ["en"] } : { pageHashes: ["a", "b"] }), + }); + for (const page of ["page-0000.json", "page-0001.json"]) { + writeJson(path.join(bundle, tree, GONE, page), [{ id: `${GONE}-v1`, text: "served" }]); + } + } + const servedTrees = ["transcripts", "subs", "digests"]; + const servedPages = Object.fromEntries( + servedTrees.map((t) => [t, pageFiles(path.join(bundle, t, GONE))]), + ); + assert.deepEqual(servedPages.subs, ["page-0000.json", "page-0001.json"]); + + site([KEEP]); + await indexAndCompose(); + // Path for path: the same trees, the same page files, each empty. + assert.deepEqual(treesOf(GONE), servedTrees); + for (const tree of servedTrees) { + const dir = pub(tree, GONE); + assert.ok(isTombstoneChannelDir(dir), `${tree}/${GONE} is a tombstone`); + assert.deepEqual(pageFiles(dir), servedPages[tree], tree); + for (const page of pageFiles(dir)) assert.deepEqual(readJson(path.join(dir, page)), []); + const m = readJson<Record<string, unknown>>(path.join(dir, "manifest.json")); + assert.equal(m.channelSlug, GONE); + if (tree === "subs") assert.deepEqual(m.tracks, []); + assert.equal(m.pageHashes, undefined); + assert.equal(m.pageCount, 0); + assert.equal(m.maxPageBytes, 0); + assert.deepEqual(m.slugToPage, {}); + assert.ok(!readFileSync(path.join(dir, "manifest.json"), "utf8").includes(`${GONE}-v1`)); + } + // The member's trees are real; the departed channel is listed nowhere. + assert.ok(!isTombstoneChannelDir(pub("transcripts", KEEP))); + for (const file of ["corpus.json", "site.json", "summaries/manifest.json", "subs/manifest.json"]) { + assert.ok(!readFileSync(pub(file), "utf8").includes(GONE), `${file} names ${GONE}`); + } + // …served no-store, each tree by its own rule, under the trees' CORS lines. + const headers = readFileSync(pub("_headers"), "utf8"); + assert.ok( + headers.endsWith( + "# Withdrawn content (tombstones): never stored at the edge.\n" + + servedTrees.map((t) => `/${t}/${GONE}/*\n Cache-Control: no-store\n`).join(""), + ), + headers, + ); + // The bundle compose read is untouched by it. + assert.ok(!isTombstoneChannelDir(path.join(bundle, "transcripts", GONE))); + + // Carried: a build over a bundle that holds the tombstones (never deployed, + // say) ships them again. + install(); + await indexAndCompose(); + assert.deepEqual(treesOf(GONE), servedTrees); + for (const tree of servedTrees) assert.ok(isTombstoneChannelDir(pub(tree, GONE))); + + // Back in the pool: its real transcripts replace the tombstone and leave the + // no-store block. The subs and digests it has no tree for now stay + // tombstones — a path served once is never left to the edge's cache. + install(); + site([KEEP, GONE]); + await indexAndCompose(); + assert.ok(!isTombstoneChannelDir(pub("transcripts", GONE))); + assert.ok(isTombstoneChannelDir(pub("subs", GONE))); + assert.ok(readFileSync(pub("corpus.json"), "utf8").includes(GONE)); + const back = readFileSync(pub("_headers"), "utf8"); + assert.ok(!back.includes(`/transcripts/${GONE}/*`), back); + assert.ok(back.includes(`/subs/${GONE}/*`), back); +}); + +test("a channel moved to the cited scope is tombstoned; one never published is not; the guard passes", async () => { + site([KEEP, GONE]); + await indexAndCompose(); + const servedTrees = treesOf(GONE); + install(); + + // GONE moves to the cited scope; FRESH is cited too, and was never in the + // pool, so no bundle served anything for it. + site([KEEP], [GONE, FRESH]); + await indexAndCompose(); + assert.deepEqual(treesOf(GONE), servedTrees); + for (const tree of servedTrees) assert.ok(isTombstoneChannelDir(pub(tree, GONE)), tree); + assert.deepEqual(treesOf(FRESH), [], "a channel the site never published gets nothing"); + const headers = readFileSync(pub("_headers"), "utf8"); + assert.ok(!headers.includes(FRESH)); + for (const file of ["corpus.json", "site.json"]) { + assert.ok(!readFileSync(pub(file), "utf8").includes(GONE), `${file} names ${GONE}`); + } + // A tombstone is not a leak: the cited-only guard passes over the + // tombstoned bundle… + const cited = { + siteId: "pub", + channels: [{ slug: KEEP }], + citedChannels: [{ slug: GONE }, { slug: FRESH }], + }; + assert.equal(builtCitedOnlyProblem(cited, paths.exportPublicDir), null); + // …and still refuses the corpus itself. + assert.match( + builtCitedOnlyProblem(cited, lastBundleDir(paths, "pub")) ?? "", + /cites "departs", "fresh-critic" only \(citedChannels\), but .* publishes its corpus: transcripts\/departs\//, + ); +}); + +test("no bundle, or another site's, is no record: nothing is tombstoned", async () => { + site([KEEP, GONE]); + await indexAndCompose(); + const bundle = install(); + // A bundle that names another site is not this site's record. + writeJson(path.join(bundle, "site.json"), { siteId: "elsewhere" }); + site([KEEP]); + await indexAndCompose(); + assert.deepEqual(treesOf(GONE), []); + assert.ok(!readFileSync(pub("_headers"), "utf8").includes("no-store")); + + rmSync(path.dirname(bundle), { recursive: true, force: true }); + site([KEEP, GONE]); + await indexAndCompose(); + site([KEEP]); + await indexAndCompose(); + assert.deepEqual(treesOf(GONE), []); +}); diff --git a/common/bin/compose-site.ts b/common/bin/compose-site.ts @@ -80,8 +80,12 @@ import { } from "../publish/composeReports"; import { emptyPostsManifest, + lastBundleDir, + servedChannelTrees, tombstoneNoStoreForSite, + writeDepartedTombstones, writePostsTombstones, + type ChannelTreeTombstone, } from "../publish/tombstones"; import { runIfEntryPoint } from "./_cli"; import { copyPublicFile, ownDir, writePublicFile } from "./_publicFile"; @@ -769,6 +773,21 @@ export async function reconcileChannelTree( return next; } +// The channel trees `siteId`'s last bundle served that public/ no longer holds, +// written as tombstones into public/ (release 24 H1). Nothing when there is no +// bundle, or it is not this site's (its site.json names another). +async function departedChannelTombstones( + paths: Paths, + siteId: string, +): Promise<ChannelTreeTombstone[]> { + const bundle = lastBundleDir(paths, siteId); + if (builtSiteIdIn(bundle) !== siteId) return []; + return writeDepartedTombstones({ + publicDir: paths.exportPublicDir, + served: await servedChannelTrees(bundle), + }); +} + // `archilyzer compose site <id>` passes the id; the bare bin (export's // compose:site script) reads SITE_ID, as it always has. export async function main( @@ -974,7 +993,20 @@ export async function main( sharedPostsDir: paths.exportSharedPostsDir, slugs: site.channels.map((c) => c.slug).filter((slug) => !memberSet.has(slug)), }); - if (tombstones.length > 0) { + // --- tombstones for the channels that left this site's pool (release 24 H1) --- + // Every per-channel tree the site's last bundle served that this compose does + // not ship — a channel removed from `channels` or moved to `citedChannels` — + // is replaced, path for path, by a tombstone (publish/tombstones.ts). The + // record is the bundle itself, read before this build replaces it; one that + // names another site is not this site's record. + const departed = await departedChannelTombstones(paths, siteId); + if (departed.length > 0) { + console.log( + `[compose] ${departed.length} channel tree(s) this site served before and no longer publishes ` + + `shipped as tombstones (${[...new Set(departed.map((t) => t.slug))].join(", ")}), served no-store.`, + ); + } + if (tombstones.length > 0 || departed.some((t) => t.tree === "posts")) { if (!(await exists(postsManifestSrc))) { await writePublicFile( path.join(paths.exportPostsDir, "manifest.json"), @@ -1155,7 +1187,7 @@ export async function main( const composed = await composeReports({ paths, site, allowMissingMedia, log: console.log }); // --- federation contract: /site.json descriptor + CORS _headers --- - await emitFederationFiles(site, paths, { noStore: tombstoneNoStoreForSite(tombstones) }); + await emitFederationFiles(site, paths, { noStore: tombstoneNoStoreForSite(tombstones, departed) }); // A site's bundle is not a hub's. export/public is shared with the hub build, // whose compose writes hub-sites.json; left in place it ships in this site's // out/ and makes the bundle ambiguous to builtHubProblem (and to a site's diff --git a/common/lib/builtExport.test.ts b/common/lib/builtExport.test.ts @@ -20,7 +20,7 @@ import { publishFileSizeProblem, reportHistoryProblem, isTombstonePostsTree, - isTombstoneChannelPostsDir, + isTombstoneChannelDir, hubReportDataIn, } from "./builtExport"; @@ -567,7 +567,25 @@ test("a build that publishes a cited-only channel's corpus is refused; its momen // A tombstone of its posts is not its posts. put("posts/critic/manifest.json", JSON.stringify({ pageCount: 0, slugToPage: {} })); put("posts/critic/page-0000.json", "[]"); - assert.equal(isTombstoneChannelPostsDir(path.join(t.dir, "posts", "critic")), true); + assert.equal(isTombstoneChannelDir(path.join(t.dir, "posts", "critic")), true); + assert.equal(builtCitedOnlyProblem(site, t.dir), null); + // Release 24 H1: nor is a tombstone of its transcripts, subs or digests (a + // build before it moved to the cited scope served them). + const tomb = { pageCount: 0, maxPageBytes: 0, slugToPage: {} }; + put("transcripts/critic/manifest.json", JSON.stringify(tomb)); + put("transcripts/critic/page-0000.json", "[]"); + put("subs/critic/manifest.json", JSON.stringify({ ...tomb, tracks: [] })); + put("digests/critic/manifest.json", JSON.stringify(tomb)); + assert.equal(builtCitedOnlyProblem(site, t.dir), null); + // A tombstone names no track and no page hash. + put("subs/critic/manifest.json", JSON.stringify({ ...tomb, tracks: ["en"] })); + assert.equal(isTombstoneChannelDir(path.join(t.dir, "subs", "critic")), false); + assert.match(builtCitedOnlyProblem(site, t.dir) ?? "", /subs\/critic\//); + put("subs/critic/manifest.json", JSON.stringify({ ...tomb, pageHashes: ["h"] })); + assert.equal(isTombstoneChannelDir(path.join(t.dir, "subs", "critic")), false); + rmSync(path.join(t.dir, "subs", "critic"), { recursive: true }); + rmSync(path.join(t.dir, "transcripts", "critic"), { recursive: true }); + rmSync(path.join(t.dir, "digests", "critic"), { recursive: true }); assert.equal(builtCitedOnlyProblem(site, t.dir), null); // Its trees, each named. diff --git a/common/lib/builtExport.ts b/common/lib/builtExport.ts @@ -438,7 +438,9 @@ function listedChannelSlugsIn(outDir: string, file: string): Set<string> { * CITED-ONLY channel's corpus, as one sentence — or null. A cited-only channel * (`citedChannels`) publishes its cited moments and clips (`m/`, `media/`) and * nothing else: no transcripts, subs, posts, digests, stats or archives tree - * named for it (a posts tree of tombstones only aside), and no entry in + * named for it (a tree that is a tombstone aside — release 18's posts ones, + * and since release 24 H1 any of its four channel trees a build before it + * moved to the cited scope served), and no entry in * corpus.json's or site.json's `channels`. Compose never writes those for it; * this is the second line, chained beside builtScopeProblem by the build * (publish/build.ts), the deploy stage and deployAudienceProblem. @@ -458,7 +460,9 @@ export function builtCitedOnlyProblem(site: CitedOnlySite, outDir: string): stri for (const tree of CHANNEL_TREES) { const dir = path.join(outDir, tree, slug); if (!existsSync(dir)) continue; - if (tree === "posts" && isTombstoneChannelPostsDir(dir)) continue; + // A tombstone publishes nothing (release 24 H1: the channel's trees a + // build before it moved to the cited scope served are replaced by them). + if (tree !== "stats" && tree !== "archives" && isTombstoneChannelDir(dir)) continue; found.push(`${tree}/${slug}/`); } for (const [file, slugs] of Object.entries(listedIn)) { @@ -555,16 +559,18 @@ export function isTombstonePostsTree(postsDir: string): boolean { for (const e of entries) { if (e.name === "manifest.json" && e.isFile()) continue; if (!e.isDirectory()) return false; - if (!isTombstoneChannelPostsDir(path.join(postsDir, e.name))) return false; + if (!isTombstoneChannelDir(path.join(postsDir, e.name))) return false; } return true; } /** - * Whether one channel's posts dir (`posts/<slug>/`) is a TOMBSTONE: a posts - * manifest at pageCount 0 with no `slugToPage` entries, and only `[]` pages. + * Whether one channel's dir in a channel tree (`posts/<slug>/`, and since + * release 24 H1 `transcripts/`, `subs/` or `digests/<slug>/`) is a TOMBSTONE: + * a channel manifest at pageCount 0 with no `slugToPage` entries, no `tracks` + * and no `pageHashes`, and only `[]` pages — it publishes nothing. */ -export function isTombstoneChannelPostsDir(dir: string): boolean { +export function isTombstoneChannelDir(dir: string): boolean { const readJson = (file: string): unknown => { try { return JSON.parse(readFileSync(file, "utf8")); @@ -573,10 +579,13 @@ export function isTombstoneChannelPostsDir(dir: string): boolean { } }; const channel = readJson(path.join(dir, "manifest.json")) as - | { pageCount?: unknown; slugToPage?: unknown } + | { pageCount?: unknown; slugToPage?: unknown; tracks?: unknown; pageHashes?: unknown } | undefined; if (!channel || channel.pageCount !== 0) return false; if (channel.slugToPage && Object.keys(channel.slugToPage as object).length > 0) return false; + for (const list of [channel.tracks, channel.pageHashes]) { + if (list !== undefined && !(Array.isArray(list) && list.length === 0)) return false; + } let files: Dirent[]; try { files = readdirSync(dir, { withFileTypes: true }); diff --git a/common/publish/deployStage.test.ts b/common/publish/deployStage.test.ts @@ -139,12 +139,13 @@ function built( } // A live check that finds the build live: every URL answers this build's -// corpus.json (or a tombstone body for a posts path), and records each URL. +// corpus.json (or a tombstone body for a channel tree's path), and records +// each URL. function liveFetch(asked: string[], generatedAt = GENERATED): typeof fetch { return (async (input: string | URL | Request) => { const url = String(input); asked.push(url); - const body = url.includes("/posts/") + const body = /\/(posts|transcripts|subs|digests)\//.test(url) ? url.includes("page-") ? [] : url.includes("/posts/manifest.json") @@ -669,6 +670,56 @@ test("the hub: its project, its bundle, and every tombstone probed plain and bus } }); +// Release 24 H1: a site's deploy probes the tombstones its bundle's _headers +// declares withdrawn — a departed channel's trees and a withheld X channel's +// posts — plain and busted, as the hub's. +test("a site: every tree its _headers declares withdrawn is probed plain and busted", async () => { + const fx = fixture(); + try { + site(fx, "anilyzer"); + built(fx, "anilyzer"); + const out = path.join(fx.paths.exportBuildsDir, "anilyzer", "out"); + writeFileSync( + path.join(out, "_headers"), + "/transcripts/*\n Access-Control-Allow-Origin: *\n" + + "# Withdrawn content (tombstones): never stored at the edge.\n" + + "/posts/manifest.json\n Cache-Control: no-store\n" + + "/posts/jer-x/*\n Cache-Control: no-store\n" + + "/transcripts/gone/*\n Cache-Control: no-store\n" + + "/digests/gone/*\n Cache-Control: no-store\n", + ); + writeJson(path.join(out, "posts", "jer-x", "manifest.json"), { pageCount: 0, slugToPage: {} }); + writeJson(path.join(out, "posts", "jer-x", "page-0000.json"), []); + writeJson(path.join(out, "transcripts", "gone", "manifest.json"), { pageCount: 0, slugToPage: {} }); + writeJson(path.join(out, "transcripts", "gone", "page-0000.json"), []); + writeJson(path.join(out, "transcripts", "gone", "page-0001.json"), []); + writeJson(path.join(out, "digests", "gone", "manifest.json"), { pageCount: 0, slugToPage: {} }); + // A real member's tree is not probed. + writeJson(path.join(out, "transcripts", "kept", "manifest.json"), { pageCount: 1, slugToPage: { a: 0 } }); + const c = ctx(fx, TOKEN); + const res = await runDeployStage(c, { kind: "deploy-site", target: "anilyzer" }); + assert.equal(res.status, "ran"); + const probed = [ + "posts/jer-x/manifest.json", + "posts/jer-x/page-0000.json", + "transcripts/gone/manifest.json", + "transcripts/gone/page-0000.json", + "digests/gone/manifest.json", + ]; + for (const rel of probed) { + assert.ok(c.asked.includes(`https://anilyzer.example.test/${rel}`), rel); + assert.ok(c.asked.includes(`https://anilyzer.example.test/${rel}?cb=built-anilyzer-1`), `${rel} busted`); + } + assert.ok(!c.asked.some((u) => u.includes("/kept/") || u.includes("page-0001")), c.asked.join("\n")); + const rec = await deployedOf(fx, "anilyzer"); + assert.equal(rec.production?.liveCheck?.verdict, "ok"); + assert.deepEqual(rec.production?.liveCheck?.tombstones?.map((t) => t.path), probed); + assert.ok(c.lines.some((l) => /5 withdrawn path\(s\) read as tombstones/.test(l)), c.lines.join("")); + } finally { + fx.cleanup(); + } +}); + test("a stale edge is a WARNING: the deploy is recorded with its verdict and the stage succeeds", async () => { const fx = fixture(); try { diff --git a/common/publish/deployStage.ts b/common/publish/deployStage.ts @@ -61,6 +61,7 @@ import { siteDeployProblem, } from "../lib/builtExport"; import { getHomepageConfig } from "../lib/homepage"; +import { tombstonedTreesInHeaders } from "./tombstones"; import { CLOUDFLARE_AUTH_REFUSED, PRODUCTION_BRANCH, @@ -199,6 +200,25 @@ function hubTombstoneProbes(outDir: string): string[] { return out; } +// A site bundle's tombstone paths worth probing (release 24 H1): per tree its +// `_headers` declares withdrawn — a withheld X channel's posts, a departed +// channel's transcripts/subs/posts/digests — its manifest and first page. +function siteTombstoneProbes(outDir: string): string[] { + let headers: string; + try { + headers = readFileSync(path.join(outDir, "_headers"), "utf8"); + } catch { + return []; + } + const out: string[] = []; + for (const { tree, slug } of tombstonedTreesInHeaders(headers)) { + if (!existsSync(path.join(outDir, tree, slug, "manifest.json"))) continue; + out.push(`${tree}/${slug}/manifest.json`); + if (existsSync(path.join(outDir, tree, slug, "page-0000.json"))) out.push(`${tree}/${slug}/page-0000.json`); + } + return out; +} + function readdirSyncDirs(dir: string): string[] { return readdirSync(dir, { withFileTypes: true }) .filter((e) => e.isDirectory()) @@ -538,7 +558,12 @@ export async function runDeployStage( builtStampId: b.stampId, expected: req.kind === "deploy-homepage" ? null : (b.corpusGeneratedAt ?? bundleGeneratedAt(outDir)), path: req.kind === "deploy-homepage" ? "" : "corpus.json", - tombstones: req.kind === "deploy-hub" ? hubTombstoneProbes(outDir) : undefined, + tombstones: + req.kind === "deploy-hub" + ? hubTombstoneProbes(outDir) + : req.kind === "deploy-site" + ? siteTombstoneProbes(outDir) + : undefined, }, { env, signal, ...ctx.liveCheck }, ); diff --git a/common/publish/liveCheck.ts b/common/publish/liveCheck.ts @@ -29,7 +29,9 @@ // // The hub's deploy also probes its TOMBSTONES (publish/tombstones.ts): each // path must answer, plain and busted, with the empty object that replaced the -// withdrawn content. +// withdrawn content. A site's deploy probes its own since release 24 H1 (each +// tree its `_headers` declares withdrawn: a withheld X channel's posts, a +// departed channel's trees). // // Everything that touches the network or the clock is injected: `fetch`, // `sleep`, `now`, `env`. diff --git a/common/publish/tombstones.test.ts b/common/publish/tombstones.test.ts @@ -13,8 +13,16 @@ import { import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; +import { renderHeadersFile, SITE_CORS_PATHS } from "../lib/archive/headers"; +import { isTombstoneChannelDir } from "../lib/builtExport"; import { emptyPostsManifest, + hubNameableChannels, + lastBundleDir, + servedChannelTrees, + tombstonedTreesInHeaders, + tombstoneTreeManifest, + writeDepartedTombstones, tombstoneChannelManifest, tombstoneNoStoreForHub, tombstoneNoStoreForSite, @@ -174,3 +182,135 @@ test("withdrawnXChannels: the X channels with a shared posts tree that a non-pri rmSync(root, { recursive: true, force: true }); } }); + +// --- release 24 H1: channels that leave a site's published pool ------------- + +test("servedChannelTrees: every channel tree a bundle serves, with its page count; none without a bundle", async () => { + const root = mkdtempSync(path.join(tmpdir(), "tombstones-")); + try { + const out = path.join(root, "out"); + sharedTree(path.join(out, "transcripts"), "b-chan", 2); + sharedTree(path.join(out, "transcripts"), "a-chan", 1); + // A manifest-only tree (a social channel's transcripts) is served too. + writeJson(path.join(out, "transcripts", "social", "manifest.json"), { pageCount: 0, slugToPage: {} }); + // Pages are counted by the highest index, not by how many there are. + writeJson(path.join(out, "subs", "b-chan", "page-0003.json"), []); + sharedTree(path.join(out, "digests"), "a-chan", 1); + writeJson(path.join(out, "posts", "x", "manifest.json"), tombstoneChannelManifest("x", "T")); + // Not a served tree: an empty dir, a stray file, a site manifest. + mkdirSync(path.join(out, "digests", "empty"), { recursive: true }); + writeJson(path.join(out, "transcripts", "manifest.json"), {}); + writeJson(path.join(out, "stats", "a-chan", "page-0000.json"), []); + assert.deepEqual(await servedChannelTrees(out), [ + { tree: "transcripts", slug: "a-chan", pages: 1 }, + { tree: "transcripts", slug: "b-chan", pages: 2 }, + { tree: "transcripts", slug: "social", pages: 0 }, + { tree: "subs", slug: "b-chan", pages: 4 }, + { tree: "posts", slug: "x", pages: 0 }, + { tree: "digests", slug: "a-chan", pages: 1 }, + ]); + assert.deepEqual(await servedChannelTrees(path.join(root, "absent")), []); + assert.equal( + lastBundleDir({ exportBuildsDir: "/b" } as Paths, "pub"), + path.join("/b", "pub", "out"), + ); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("tombstoneTreeManifest: each tree's manifest shape at pageCount 0, with no size and no tracks", () => { + for (const tree of ["transcripts", "subs", "digests"] as const) { + const m = tombstoneTreeManifest(tree, "gone", "T"); + assert.equal(m.channelSlug, "gone"); + assert.equal(m.pageCount, 0); + assert.equal(m.maxPageBytes, 0); + assert.deepEqual(m.slugToPage, {}); + assert.equal(m.generatedAt, "T"); + assert.equal(typeof m.version, "number"); + assert.equal("pageHashes" in m, false); + } + assert.deepEqual(tombstoneTreeManifest("subs", "gone", "T").tracks, []); + assert.equal("tracks" in tombstoneTreeManifest("transcripts", "gone", "T"), false); + assert.deepEqual(tombstoneTreeManifest("posts", "gone", "T"), tombstoneChannelManifest("gone", "T")); +}); + +test("writeDepartedTombstones: a tombstone for each served tree public/ no longer holds, path for path", async () => { + const root = mkdtempSync(path.join(tmpdir(), "tombstones-")); + try { + const pub = path.join(root, "public"); + // Held now: a member's real tree, and a tombstone written earlier in this + // compose (a withheld X channel's) — both left alone. + sharedTree(path.join(pub, "transcripts"), "member", 1); + writeJson(path.join(pub, "posts", "x", "manifest.json"), tombstoneChannelManifest("x", "earlier")); + // A worktree's linked tree root: replaced by public/'s own, its target untouched. + const primary = path.join(root, "primary", "subs"); + writeJson(path.join(primary, "other", "page-0000.json"), [{ id: "keep" }]); + symlinkSync(primary, path.join(pub, "subs")); + const served = [ + { tree: "transcripts" as const, slug: "member", pages: 1 }, + { tree: "transcripts" as const, slug: "gone", pages: 3 }, + { tree: "subs" as const, slug: "gone", pages: 1 }, + { tree: "posts" as const, slug: "x", pages: 2 }, + { tree: "digests" as const, slug: "gone", pages: 0 }, + ]; + const written = await writeDepartedTombstones({ publicDir: pub, served, generatedAt: "T" }); + assert.deepEqual(written, served.filter((t) => t.slug === "gone")); + assert.deepEqual(readdirSync(path.join(pub, "transcripts", "gone")).sort(), [ + "manifest.json", + "page-0000.json", + "page-0001.json", + "page-0002.json", + ]); + for (const t of written) assert.ok(isTombstoneChannelDir(path.join(pub, t.tree, t.slug)), t.tree); + assert.deepEqual(readdirSync(path.join(pub, "digests", "gone")), ["manifest.json"]); + assert.deepEqual(readJson(path.join(pub, "subs", "gone", "manifest.json")).tracks, []); + assert.deepEqual(readJson(path.join(pub, "transcripts", "member", "page-0000.json")), [{ id: "p0" }]); + assert.equal(readJson(path.join(pub, "posts", "x", "manifest.json")).generatedAt, "earlier"); + assert.deepEqual(readJson(path.join(primary, "other", "page-0000.json")), [{ id: "keep" }]); + assert.equal(existsSync(path.join(primary, "gone")), false, "never written through the link"); + // Nothing served, nothing written. + assert.deepEqual(await writeDepartedTombstones({ publicDir: path.join(root, "none"), served: [] }), []); + assert.equal(existsSync(path.join(root, "none")), false); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("a site's no-store paths name each departed tree; its _headers says which trees a deploy probes", () => { + const departed = [ + { tree: "transcripts" as const, slug: "gone", pages: 1 }, + { tree: "subs" as const, slug: "gone", pages: 1 }, + ]; + // No posts tombstone: the posts manifest is not named. + assert.deepEqual(tombstoneNoStoreForSite([], departed), ["/transcripts/gone/*", "/subs/gone/*"]); + assert.deepEqual( + tombstoneNoStoreForSite([{ slug: "a-x", pages: 1 }], [{ tree: "posts", slug: "gone", pages: 0 }, ...departed]), + ["/posts/manifest.json", "/posts/a-x/*", "/posts/gone/*", "/transcripts/gone/*", "/subs/gone/*"], + ); + const headers = renderHeadersFile("compose-site.ts", SITE_CORS_PATHS, { + noStore: tombstoneNoStoreForSite([{ slug: "a-x", pages: 1 }], departed), + }); + // The CORS block's `/transcripts/*` is not a tombstone; the manifest rule is no tree. + assert.deepEqual(tombstonedTreesInHeaders(headers), [ + { tree: "posts", slug: "a-x" }, + { tree: "transcripts", slug: "gone" }, + { tree: "subs", slug: "gone" }, + ]); + assert.deepEqual(tombstonedTreesInHeaders(renderHeadersFile("compose-site.ts", SITE_CORS_PATHS)), []); + assert.deepEqual(tombstonedTreesInHeaders(""), []); +}); + +test("hubNameableChannels: the pools of the sites that are not private, never a cited-only slug", () => { + const members = (...slugs: string[]) => slugs.map((slug) => ({ slug, groupId: "default" })); + assert.deepEqual( + [ + ...hubNameableChannels([ + { channels: members("a", "b") }, + { audience: "public", channels: members("c"), citedChannels: [{ slug: "cited" }] } as never, + { audience: "private", channels: members("mine", "a") }, + ]), + ].sort(), + ["a", "b", "c"], + ); +}); diff --git a/common/publish/tombstones.ts b/common/publish/tombstones.ts @@ -23,10 +23,25 @@ // // The writers go through bin/_publicFile.ts: in a worktree, public/'s entries // are links into the primary checkout, and nothing here writes through one. +// +// RELEASE 24 H1 — A CHANNEL THAT LEAVES A SITE'S PUBLISHED POOL (removed from +// `channels`, or moved to `citedChannels`) is withdrawn the same way: every +// per-channel path the site's LAST BUNDLE served for it — `transcripts/`, +// `subs/`, `posts/` and `digests/<slug>/`, manifest and pages — ships as a +// tombstone of the same shape, served no-store. "What the site published +// before" is that bundle, `<exportBuildsDir>/<siteId>/out` (servedChannelTrees), +// read before the build replaces it: it is the one record of the exact paths +// (and page counts) a deploy of that build shipped; no stamp lists them. A +// bundle's own tombstones are served paths too, so they are carried into the +// next build for as long as the channel stays out — a build that is never +// deployed cannot drop them before one that is. A cited-only channel's moment +// pages and clips (`m/`, `media/`) still publish and are never tombstoned. import path from "node:path"; -import { readdir, readFile, rm } from "node:fs/promises"; +import { lstat, readdir, readFile, rm } from "node:fs/promises"; import type { Paths } from "../lib/paths"; +import { SUBS_CHANNEL_MANIFEST_VERSION, TRANSCRIPTS_MANIFEST_VERSION } from "../lib/manifest"; +import { DIGESTS_MANIFEST_VERSION } from "../lib/digests"; import { POSTS_MANIFEST_VERSION, SITE_POSTS_MANIFEST_VERSION, @@ -38,6 +53,7 @@ import { isXPostsChannel, xPostsVisibility } from "../lib/postsVisibility"; import { isPrivateSite, type Site } from "../lib/siteSchema"; import { readChannelConfig } from "../controller/channels"; import { ownDir, writePublicFile } from "../bin/_publicFile"; +import { targetDir } from "./stamps"; // One channel's tombstone: its slug and how many empty pages stand in for it. export type PostsTombstone = { slug: string; pages: number }; @@ -133,10 +149,22 @@ export function tombstonePaths( return out; } -/** A site's no-store paths: its posts manifest and each tombstoned tree. */ -export function tombstoneNoStoreForSite(tombstones: readonly PostsTombstone[]): string[] { - if (tombstones.length === 0) return []; - return ["/posts/manifest.json", ...tombstones.map((t) => `/posts/${t.slug}/*`)]; +/** + * A site's no-store paths: its posts manifest (when any posts tree is a + * tombstone) and each tombstoned tree — the withheld X channels' posts, then + * each departed channel's trees (release 24 H1). + */ +export function tombstoneNoStoreForSite( + tombstones: readonly PostsTombstone[], + departed: readonly ChannelTreeTombstone[] = [], +): string[] { + if (tombstones.length === 0 && departed.length === 0) return []; + const posts = tombstones.length > 0 || departed.some((t) => t.tree === "posts"); + return [ + ...(posts ? ["/posts/manifest.json"] : []), + ...tombstones.map((t) => `/posts/${t.slug}/*`), + ...departed.map((t) => `/${t.tree}/${t.slug}/*`), + ]; } /** The hub's no-store paths: its whole posts tree, which holds only tombstones. */ @@ -160,11 +188,7 @@ export async function withdrawnXChannels( sites: readonly Pick<Site, "audience" | "channels">[], ): Promise<string[]> { if (xPostsVisibility(settings) !== "private") return []; - const onPublicSite = new Set<string>(); - for (const site of sites) { - if (isPrivateSite(site)) continue; - for (const c of site.channels) onPublicSite.add(c.slug); - } + const onPublicSite = hubNameableChannels(sites); let entries: string[]; try { entries = (await readdir(paths.exportSharedPostsDir, { withFileTypes: true })) @@ -181,3 +205,164 @@ export async function withdrawnXChannels( } return out; } + +/** + * The channels the hub may NAME: every member (`channels`, the pool) of a site + * whose audience is not private — the release 18 rule (review H1): private + * data is never named on the hub. A channel only private sites carry, one only + * cited (`citedChannels`), or one no site carries is not here. + */ +export function hubNameableChannels( + sites: readonly Pick<Site, "audience" | "channels">[], +): Set<string> { + const out = new Set<string>(); + for (const site of sites) { + if (isPrivateSite(site)) continue; + for (const c of site.channels) out.add(c.slug); + } + return out; +} + +// --- release 24 H1: channels that leave a site's published pool ------------- + +/** The per-channel trees a bundle publishes a channel's corpus in. */ +export const CHANNEL_TOMBSTONE_TREES = ["transcripts", "subs", "posts", "digests"] as const; +export type ChannelTree = (typeof CHANNEL_TOMBSTONE_TREES)[number]; + +/** One served (or tombstoned) channel tree: its tree, slug and page count. */ +export type ChannelTreeTombstone = { tree: ChannelTree; slug: string; pages: number }; + +/** `<exportBuildsDir>/<target>/out`: the bundle the target's last build left. */ +export function lastBundleDir(paths: Pick<Paths, "exportBuildsDir">, target: string): string { + return path.join(targetDir(paths, target), "out"); +} + +const PAGE_FILE = /^page-(\d+)\.json$/; + +/** + * Every per-channel tree `outDir` (a built bundle) serves — `<tree>/<slug>/` + * under the four channel trees, real or tombstone — with its page count (the + * highest `page-NNNN.json` + 1). A dir with neither a manifest nor a page is + * not a served tree. None when the bundle is absent. Sorted by tree, then slug. + */ +export async function servedChannelTrees(outDir: string): Promise<ChannelTreeTombstone[]> { + const out: ChannelTreeTombstone[] = []; + for (const tree of CHANNEL_TOMBSTONE_TREES) { + let entries; + try { + entries = await readdir(path.join(outDir, tree), { withFileTypes: true }); + } catch { + continue; + } + const slugs = entries + .filter((e) => e.isDirectory()) + .map((e) => e.name) + .sort(); + for (const slug of slugs) { + let files: string[]; + try { + files = await readdir(path.join(outDir, tree, slug)); + } catch { + continue; + } + let pages = 0; + for (const f of files) { + const m = PAGE_FILE.exec(f); + if (m) pages = Math.max(pages, Number(m[1]) + 1); + } + if (pages === 0 && !files.includes("manifest.json")) continue; + out.push({ tree, slug, pages }); + } + } + return out; +} + +/** + * The channel manifest a tree tombstone ships: the tree's own manifest shape + * at pageCount 0, with no pages, no size and (subs) no tracks. + */ +export function tombstoneTreeManifest( + tree: ChannelTree, + slug: string, + generatedAt: string, +): Record<string, unknown> { + if (tree === "posts") return tombstoneChannelManifest(slug, generatedAt); + const version = + tree === "transcripts" + ? TRANSCRIPTS_MANIFEST_VERSION + : tree === "subs" + ? SUBS_CHANNEL_MANIFEST_VERSION + : DIGESTS_MANIFEST_VERSION; + return { + version, + channelSlug: slug, + pageCount: 0, + maxPageBytes: 0, + generatedAt, + ...(tree === "subs" ? { tracks: [] } : {}), + slugToPage: {}, + }; +} + +async function present(p: string): Promise<boolean> { + try { + await lstat(p); + return true; + } catch { + return false; + } +} + +/** + * Write a tombstone under `publicDir` for every tree in `served` (what the last + * bundle served) that `publicDir` does not serve now — a channel that left the + * pool, or a tree a member no longer has: its manifest at pageCount 0 and `[]` + * for each page the bundle held. A tree `publicDir` holds (a member's, or a + * tombstone written earlier in this compose) is left alone. Returns what was + * written, in `served` order. + */ +export async function writeDepartedTombstones(opts: { + publicDir: string; + served: readonly ChannelTreeTombstone[]; + generatedAt?: string; +}): Promise<ChannelTreeTombstone[]> { + const generatedAt = opts.generatedAt ?? new Date().toISOString(); + const written: ChannelTreeTombstone[] = []; + for (const t of opts.served) { + const treeDir = path.join(opts.publicDir, t.tree); + const dir = path.join(treeDir, t.slug); + if (await present(dir)) continue; + await ownDir(treeDir); + await ownDir(dir); + await writePublicFile( + path.join(dir, "manifest.json"), + JSON.stringify(tombstoneTreeManifest(t.tree, t.slug, generatedAt)), + ); + for (let i = 0; i < t.pages; i++) { + await writePublicFile(path.join(dir, postsPageFileName(i)), "[]"); + } + written.push({ ...t }); + } + return written; +} + +/** + * The tombstoned channel trees a bundle's `_headers` declares no-store + * (`/<tree>/<slug>/*` in its "Withdrawn content" block): what a deploy's live + * check probes on a site. The bundle's own word — a real manifest-only tree + * (a social channel's transcripts, pageCount 0) reads like a tombstone on + * disk, but is never in that block. + */ +export function tombstonedTreesInHeaders(headers: string): { tree: ChannelTree; slug: string }[] { + const out: { tree: ChannelTree; slug: string }[] = []; + const lines = headers.split("\n"); + const start = lines.findIndex((l) => l.startsWith("# Withdrawn content")); + if (start < 0) return out; + const rule = new RegExp(`^/(${CHANNEL_TOMBSTONE_TREES.join("|")})/([^/*]+)/\\*$`); + for (const line of lines.slice(start + 1)) { + if (line.startsWith("#")) break; + const m = rule.exec(line.trim()); + if (m) out.push({ tree: m[1] as ChannelTree, slug: m[2] }); + } + return out; +}