// The article registry (release 26 A2): the one writer of // transcripts/reports/index.json and an article's `audience`. Temp stores only. // // Run with: node_modules/.bin/tsx --test lib/report/registry.test.ts import { after, test } from "node:test"; import assert from "node:assert/strict"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import os from "node:os"; import path from "node:path"; import { ARTICLES_LOCK_FILENAME, ArticleRegistryError, articleFile, articlesIndexFile, configureArticle, listArticles, patchArticle, publishedArticleIds, readArticleState, readArticlesIndex, setArticlesOrder, setPublished, writeArticle, } from "./registry"; const ROOTS: string[] = []; after(() => { for (const r of ROOTS) rmSync(r, { recursive: true, force: true }); }); function store() { const root = mkdtempSync(path.join(tmpdir(), "article-registry-")); ROOTS.push(root); return { articlesDir: path.join(root, "transcripts", "reports"), exportIndexDir: path.join(root, ".export-index") }; } const doc = (id: string, over: Record = {}) => ({ format: "archilyzer-report", version: 1, id, kind: "sweep", title: `Article ${id}`, sections: [{ id: "s1", title: "One", body: "Plain words." }], ...over, }); function put(paths: ReturnType, id: string, value: unknown) { const file = articleFile(paths, id); mkdirSync(path.dirname(file), { recursive: true }); writeFileSync(file, typeof value === "string" ? value : JSON.stringify(value, null, 2)); } const read = (file: string) => (existsSync(file) ? readFileSync(file, "utf8") : null); const json = (file: string) => JSON.parse(readFileSync(file, "utf8")) as Record; test("an empty store: nothing published, nothing listed", async () => { const paths = store(); assert.deepEqual(await readArticlesIndex(paths), { published: [] }); assert.deepEqual(await listArticles(paths), []); assert.deepEqual(await publishedArticleIds("private", paths), []); assert.equal(await readArticleState("nothing", paths), null); }); test("publish, place, move and unpublish — index.json in order; drafts listed after", async () => { const paths = store(); for (const id of ["a", "b", "c", "d"]) put(paths, id, doc(id)); await setPublished("a", true, {}, paths); await setPublished("b", true, {}, paths); assert.deepEqual(json(articlesIndexFile(paths)), { published: ["a", "b"] }); await configureArticle("c", { published: true, position: 0 }, paths); assert.deepEqual((await readArticlesIndex(paths)).published, ["c", "a", "b"]); // Moved: a published article's position alone. const moved = await configureArticle("b", { position: 1 }, paths); assert.equal(moved.position, 1); assert.deepEqual((await readArticlesIndex(paths)).published, ["c", "b", "a"]); // Publishing an already-published one with no position keeps its place. await setPublished("b", true, {}, paths); assert.deepEqual((await readArticlesIndex(paths)).published, ["c", "b", "a"]); await setPublished("c", false, {}, paths); assert.deepEqual((await readArticlesIndex(paths)).published, ["b", "a"]); assert.ok(existsSync(articleFile(paths, "c")), "unpublishing keeps the article on disk"); const listed = await listArticles(paths); assert.deepEqual( listed.map((a) => [a.id, a.published, a.position]), [ ["b", true, 0], ["a", true, 1], ["c", false, null], ["d", false, null], ], ); assert.equal(listed[0].title, "Article b"); assert.equal(listed[0].audience, "private", "absent = private"); await setArticlesOrder(["a", "b"], paths); assert.deepEqual((await readArticlesIndex(paths)).published, ["a", "b"]); }); test("audience: written into report.json, absent = private; a public build carries only public articles", async () => { const paths = store(); for (const id of ["pub", "priv", "draft"]) put(paths, id, doc(id)); await configureArticle("pub", { audience: "public", published: true }, paths); await configureArticle("priv", { published: true }, paths); await configureArticle("draft", { audience: "public" }, paths); assert.equal(json(articleFile(paths, "pub")).audience, "public"); assert.equal("audience" in json(articleFile(paths, "priv")), false, "no audience written unasked"); assert.deepEqual(await publishedArticleIds("public", paths), ["pub"]); assert.deepEqual(await publishedArticleIds("private", paths), ["pub", "priv"]); // Back to private. const st = await configureArticle("pub", { audience: "private" }, paths); assert.equal(st.audience, "private"); assert.deepEqual(await publishedArticleIds("public", paths), []); // Unchanged audience: report.json's bytes are not rewritten. const before = read(articleFile(paths, "priv")); await configureArticle("priv", { audience: "private" }, paths); assert.equal(read(articleFile(paths, "priv")), before); }); test("refusals come before anything is written", async () => { const paths = store(); put(paths, "ok", doc("ok")); put(paths, "bad", doc("bad", { sections: [{ id: "s1", title: "x", body: "[a](cite:nope)" }] })); put(paths, "torn", "{ not json"); await setPublished("ok", true, {}, paths); const indexBefore = read(articlesIndexFile(paths)); const okBefore = read(articleFile(paths, "ok")); const cases: [() => Promise, RegExp][] = [ [() => configureArticle("Bad Id", { published: true }, paths), /not an article id/], [() => configureArticle("missing", { published: true }, paths), /no article "missing"/], [() => configureArticle("ok", { audience: "everyone" as never }, paths), /audience must be one of public, private/], [() => configureArticle("bad", { published: true }, paths), /cannot be published while report.json has problems[\s\S]*cite:nope|cannot be published/], [() => configureArticle("torn", { published: true }, paths), /unparseable/], [() => configureArticle("bad", { position: 0 }, paths), /is a draft/], [() => configureArticle("ok", { published: false, position: 0 }, paths), /not one being unpublished/], [() => configureArticle("ok", { position: 5 }, paths), /position 5 is out of range: 0 \(first\) to 0/], [() => configureArticle("ok", { audience: "public", position: -1 }, paths), /out of range/], [() => setArticlesOrder(["ok", "ok"], paths), /every published article once/], [() => setArticlesOrder(["bad"], paths), /every published article once/], ]; for (const [call, re] of cases) { await assert.rejects(call, (e: unknown) => e instanceof ArticleRegistryError && re.test((e as Error).message), String(re)); } assert.equal(read(articlesIndexFile(paths)), indexBefore, "index.json untouched"); assert.equal(read(articleFile(paths, "ok")), okBefore, "report.json untouched (audience + bad position refused whole)"); }); test("an unreadable index.json is an error, never an empty list", async () => { const paths = store(); put(paths, "a", doc("a")); mkdirSync(path.dirname(articlesIndexFile(paths)), { recursive: true }); for (const bad of ['{"published": "a"}', '{"published": ["a", "a"]}', '{"published": [], "extra": 1}', "[]", "{"]) { writeFileSync(articlesIndexFile(paths), bad); await assert.rejects(readArticlesIndex(paths), ArticleRegistryError, bad); await assert.rejects(setPublished("a", true, {}, paths), ArticleRegistryError, bad); assert.equal(read(articlesIndexFile(paths)), bad, "not overwritten"); } }); test("unpublishing an article whose directory is gone tidies the index", async () => { const paths = store(); put(paths, "a", doc("a")); await setPublished("a", true, {}, paths); rmSync(path.dirname(articleFile(paths, "a")), { recursive: true }); const listed = await listArticles(paths); assert.deepEqual(listed.map((a) => [a.id, a.exists]), [["a", false]]); await setPublished("a", false, {}, paths); assert.deepEqual(await readArticlesIndex(paths), { published: [] }); }); test("patchArticle: patched as on disk, a key given as undefined removed, never made worse", async () => { const paths = store(); put(paths, "a", doc("a", { subtitle: "old" })); const r = await patchArticle("a", { title: "New title", subtitle: undefined }, paths); assert.equal(r?.title, "New title"); const onDisk = json(articleFile(paths, "a")); assert.equal(onDisk.title, "New title"); assert.equal("subtitle" in onDisk, false); const fn = await patchArticle("a", (cur) => ({ title: `${cur.title}!` }), paths); assert.equal(fn?.title, "New title!"); assert.equal(await patchArticle("missing", { title: "x" }, paths), null); const before = read(articleFile(paths, "a")); await assert.rejects(patchArticle("a", { kind: "essay" as never }, paths), /would make report.json invalid/); await assert.rejects( patchArticle("a", { summary: "see [x](cite:nobody)" }, paths), /would make report.json invalid[\s\S]*summary/, ); await assert.rejects(patchArticle("a", { id: "b" } as never, paths), /may not change "id"/); assert.equal(read(articleFile(paths, "a")), before); // A report that already has a problem may still be patched elsewhere. put(paths, "b", doc("b", { summary: "see [x](cite:nobody)" })); assert.equal((await patchArticle("b", { title: "Still a draft" }, paths))?.title, "Still a draft"); }); test("writeArticle: only a sound document; a regenerated one keeps its audience", async () => { const paths = store(); await assert.rejects(writeArticle(doc("a", { kind: "essay" }), { paths }), /not a sound report/); await assert.rejects(writeArticle(doc("Bad"), { paths }), /not an article id/); assert.equal(existsSync(articleFile(paths, "a")), false); await writeArticle(doc("a"), { paths }); await configureArticle("a", { audience: "public", published: true }, paths); await writeArticle(doc("a", { title: "Regenerated" }), { paths }); assert.equal(json(articleFile(paths, "a")).audience, "public", "kept"); assert.equal(json(articleFile(paths, "a")).title, "Regenerated"); await writeArticle(doc("a"), { paths, keepAudience: false }); assert.equal("audience" in json(articleFile(paths, "a")), false, "written as given"); assert.deepEqual((await readArticlesIndex(paths)).published, ["a"], "the index is untouched by a write"); }); test("the lock: parallel writes all land; a live holder is waited for; a dead one is taken over", async () => { const paths = store(); const ids = Array.from({ length: 12 }, (_, i) => `a${i}`); for (const id of ids) put(paths, id, doc(id)); await Promise.all(ids.map((id) => setPublished(id, true, {}, paths))); assert.deepEqual([...(await readArticlesIndex(paths)).published].sort(), [...ids].sort()); assert.equal(existsSync(path.join(paths.articlesDir, ARTICLES_LOCK_FILENAME)), false, "released"); // A live holder (this process, fresh): the write waits until it is gone. const lock = path.join(paths.articlesDir, ARTICLES_LOCK_FILENAME); writeFileSync(lock, JSON.stringify({ pid: process.pid, host: os.hostname(), since: Date.now() })); let released = false; setTimeout(() => { released = true; rmSync(lock, { force: true }); }, 300); await setPublished("a0", false, {}, paths); assert.equal(released, true, "it waited for the holder"); // A dead holder on this host: taken over at once. writeFileSync(lock, JSON.stringify({ pid: 2 ** 22 + 12345, host: os.hostname(), since: Date.now() })); const t0 = Date.now(); await setPublished("a0", true, {}, paths); assert.ok(Date.now() - t0 < 2000, "no wait for a dead holder"); assert.equal(existsSync(lock), false); });