// THE ARTICLE REGISTRY — the one writer of the article store // (`transcripts/reports/`, release 26; plans/reports-on-homepage.md, "The // model"). The `patchSite` of articles: every write is LOCKED, VALIDATED and // ATOMIC, and nothing else — not a generator, not a script, not a hand — writes // `index.json` or an article's `audience`. // // transcripts/reports/index.json {"published": [ids]} — the // published, ordered list; an // article directory it does not // name is a draft // transcripts/reports//report.json the article (REPORT.md), with // `audience` "public" | "private" // (absent = private, D2) // transcripts/reports//iterations/ the article's generations // (release 27, ./iterations.ts), // written under the same lock and // never published; a directory with // iterations and no report.json is // an article in the making, not // listed (listPendingArticles) // transcripts/reports/.registry.lock held while a write runs // transcripts/reports/.deleting--… an article a delete has parked // (./delete.ts): not an id, so // never listed; removed after the // lock is let go // // THE LOCK is two locks: withJsonFileLock (in-process: the editor's routes and // server actions) around an O_EXCL lock file (across processes: a generator // in ~/reports/* calling this beside a running editor). A lock file whose // holder is gone — its pid does not answer on this host, or it is older than // LOCK_STALE_MS — is taken over. A write waits for a live holder up to // LOCK_WAIT_MS, then refuses. // // VALIDATED: an index names report ids, once each. Publishing needs a sound // report.json (no problem lib/report/validate.ts names). A patch may not make // a report worse: a patched report.json is written only when it parses and // has no problem the report did not already have. A whole document // (writeArticle) is written only when it has none. // // ATOMIC: each file is replaced whole (writeJsonAtomic). A call that writes // both files (configureArticle) checks everything first and writes nothing // when anything is refused. // // SERVER-ONLY (node:fs). import type { Dirent } from "node:fs"; import { lstat, mkdir, open, readdir, readFile, rename, rm, stat } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { getPaths, type Paths } from "../paths"; import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../jsonFile-server"; import type { Problem } from "../citations/validate"; import { isReportId, REPORT_AUDIENCES, type Report, type ReportAudience } from "./schema"; import { parseReport } from "./validate"; import { articleReportStore, storeReportDir, storeReportFile } from "./store"; export const ARTICLES_INDEX_FILENAME = "index.json"; export const ARTICLES_LOCK_FILENAME = ".registry.lock"; // How long a write waits for another process's write, and when a lock file is // stale whoever holds it (a write takes milliseconds). export const LOCK_WAIT_MS = 10_000; export const LOCK_STALE_MS = 60_000; const LOCK_POLL_MS = 25; export type ArticlesIndex = { published: string[] }; // A refusal: nothing was written. `problems` lists a report's problems as // `: ` lines when that is why. export class ArticleRegistryError extends Error { constructor( message: string, readonly problems: string[] = [], ) { super(problems.length > 0 ? `${message}:\n${problems.map((p) => ` ${p}`).join("\n")}` : message); this.name = "ArticleRegistryError"; } } // ─── Where ─── export function articlesIndexFile(paths: Pick = getPaths()): string { return path.join(paths.articlesDir, ARTICLES_INDEX_FILENAME); } export function articleDir(paths: Pick, id: string): string { return storeReportDir(articleReportStore(paths), id); } export function articleFile(paths: Pick, id: string): string { return storeReportFile(articleReportStore(paths), id); } // ─── Reading ─── // Who may read an article: its `audience`, absent = private. export function articleAudience(report: { audience?: unknown } | null | undefined): ReportAudience { return report?.audience === "public" ? "public" : "private"; } export function isReportAudience(v: unknown): v is ReportAudience { return typeof v === "string" && (REPORT_AUDIENCES as readonly string[]).includes(v); } // index.json's shape: `{"published": [ids]}`, ids once each, nothing else. export function parseArticlesIndex(raw: unknown): { ok: true; index: ArticlesIndex } | { ok: false; problem: string } { if (!raw || typeof raw !== "object" || Array.isArray(raw)) { return { ok: false, problem: 'is not an object {"published": [ids]}' }; } const extra = Object.keys(raw).filter((k) => k !== "published"); if (extra.length > 0) return { ok: false, problem: `has unknown key(s): ${extra.join(", ")}` }; const published = (raw as { published?: unknown }).published ?? []; if (!Array.isArray(published)) return { ok: false, problem: '"published" is not a list of article ids' }; const seen = new Set(); for (const id of published) { if (!isReportId(id)) return { ok: false, problem: `"published" names ${JSON.stringify(id)}, which is not an article id` }; if (seen.has(id)) return { ok: false, problem: `"published" names "${id}" twice` }; seen.add(id); } return { ok: true, index: { published: [...published] as string[] } }; } // The published list. No index.json = none published. An index that cannot be // read is an error, never an empty list: a build must not publish nothing // because a file is torn. export async function readArticlesIndex(paths: Pick = getPaths()): Promise { const file = articlesIndexFile(paths); const read = await readJsonFile(file); if (!read.ok) { if (read.reason === "absent") return { published: [] }; throw new ArticleRegistryError(`reports/${ARTICLES_INDEX_FILENAME} is ${read.reason} (${file})`); } const parsed = parseArticlesIndex(read.value); if (!parsed.ok) throw new ArticleRegistryError(`reports/${ARTICLES_INDEX_FILENAME} ${parsed.problem}`); return parsed.index; } // The directory of an article's iterations (release 27, ./iterations.ts). // Named here because the registry must know one when it lists articles. export const ARTICLE_ITERATIONS_DIRNAME = "iterations"; async function idDirs(dir: string): Promise { let entries: Dirent[]; try { entries = await readdir(dir, { withFileTypes: true }); } catch { return []; } return entries .filter((e) => e.isDirectory() && isReportId(e.name)) .map((e) => e.name) .sort((a, b) => a.localeCompare(b)); } // An article IN THE MAKING (release 27, S4): a directory with `iterations/` // and no report.json — a generation started it, and no iteration has been made // current yet. The registry does not list it as an article (not even a draft): // nothing that reads the registry — compose, the homepage, the editor's // Articles tab, umtool's /articles, `reports check` — sees it until the first // makeCurrent writes its report.json. `listPendingArticles` lists them. async function isPendingArticleDir(dir: string): Promise { if (await stat(path.join(dir, "report.json")).then(() => true, () => false)) return false; return (await stat(path.join(dir, ARTICLE_ITERATIONS_DIRNAME)).catch(() => null))?.isDirectory() ?? false; } // Every article directory, published or draft: a directory under // `transcripts/reports/` whose name is an article id — an article in the // making (iterations and no report.json) excepted. Sorted. export async function listArticleDirs(paths: Pick = getPaths()): Promise { const out: string[] = []; for (const id of await idDirs(paths.articlesDir)) { if (!(await isPendingArticleDir(path.join(paths.articlesDir, id)))) out.push(id); } return out; } // Every article in the making: iterations and no report.json yet. Sorted. export async function listPendingArticles(paths: Pick = getPaths()): Promise { const out: string[] = []; for (const id of await idDirs(paths.articlesDir)) { if (await isPendingArticleDir(path.join(paths.articlesDir, id))) out.push(id); } return out; } // One article as the registry knows it. export type ArticleState = { id: string; // report.json is there (an index may name an article whose directory is gone). exists: boolean; title: string | null; audience: ReportAudience; published: boolean; // Its place in the published list (0 = first), or null for a draft. position: number | null; // What lib/report/validate.ts says about report.json (one entry when it is // not readable JSON). problems: Problem[]; }; type ReadArticle = | { ok: true; raw: Record; problems: Problem[]; report: Report | null } | { ok: false; reason: "absent" | "unreadable" | "unparseable" | "not-an-object" }; async function readArticle(paths: Pick, id: string): Promise { const read = await readJsonFile(articleFile(paths, id)); if (!read.ok) return { ok: false, reason: read.reason }; if (!read.value || typeof read.value !== "object" || Array.isArray(read.value)) return { ok: false, reason: "not-an-object" }; const raw = read.value as Record; const parsed = parseReport(raw, { id }); return { ok: true, raw, problems: parsed.problems, report: parsed.ok ? parsed.value : null }; } function stateOf(id: string, read: ReadArticle, index: ArticlesIndex): ArticleState { const position = index.published.indexOf(id); return { id, exists: read.ok, title: read.ok && typeof read.raw.title === "string" ? read.raw.title : null, audience: articleAudience(read.ok ? read.raw : null), published: position >= 0, position: position >= 0 ? position : null, problems: read.ok ? read.problems : read.reason === "absent" ? [] : [{ path: "", message: `report.json is ${read.reason === "not-an-object" ? "not a JSON object" : read.reason}` }], }; } // One article's state, or null when it has no directory and the index does // not name it. export async function readArticleState( id: string, paths: Pick = getPaths(), ): Promise { if (!isReportId(id)) return null; const index = await readArticlesIndex(paths); const read = await readArticle(paths, id); if (!read.ok && read.reason === "absent" && !index.published.includes(id)) { const dir = await stat(articleDir(paths, id)).catch(() => null); if (!dir?.isDirectory()) return null; // An article in the making is not an article yet. if (await isPendingArticleDir(articleDir(paths, id))) return null; } return stateOf(id, read, index); } // Every article: the published ones in their order, then the drafts by id. // An id the index names whose report.json is gone is listed (`exists` false). export async function listArticles(paths: Pick = getPaths()): Promise { const index = await readArticlesIndex(paths); const dirs = await listArticleDirs(paths); const ids = [...index.published, ...dirs.filter((d) => !index.published.includes(d))]; const out: ArticleState[] = []; for (const id of ids) out.push(stateOf(id, await readArticle(paths, id), index)); return out; } // The published articles a build of `audience` carries, in order: a public // build only those whose report.json says `audience: "public"`; a private build // every published one. An article whose report.json cannot be read is kept // (compose names its problem) by a private build and left out by a public one, // which can never know it is public. export async function publishedArticleIds( audience: ReportAudience, paths: Pick = getPaths(), ): Promise { const index = await readArticlesIndex(paths); if (audience === "private") return index.published; const out: string[] = []; for (const id of index.published) { const read = await readArticle(paths, id); if (read.ok && articleAudience(read.raw) === "public") out.push(id); } return out; } // ─── The lock ─── type LockHolder = { pid: number; host: string; since: number }; const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); export function pidAlive(pid: number): boolean { try { process.kill(pid, 0); return true; } catch (e) { return (e as NodeJS.ErrnoException).code === "EPERM"; } } async function lockIsStale(file: string): Promise { let holder: LockHolder | null = null; try { holder = JSON.parse(await readFile(file, "utf8")) as LockHolder; } catch { holder = null; } if (!holder || typeof holder.since !== "number") { // Torn (a taker died between creating and writing it): stale once old. const st = await stat(file).catch(() => null); return !st || Date.now() - st.mtimeMs > LOCK_STALE_MS; } if (Date.now() - holder.since > LOCK_STALE_MS) return true; return holder.host === os.hostname() && typeof holder.pid === "number" && !pidAlive(holder.pid); } // Run `fn` holding the article store's lock, in this process and across // processes. Exported for a caller that writes several things as one. export function withArticleStoreLock( fn: () => Promise, paths: Pick = getPaths(), ): Promise { const file = path.join(paths.articlesDir, ARTICLES_LOCK_FILENAME); return withJsonFileLock(file, async () => { await mkdir(paths.articlesDir, { recursive: true }); const deadline = Date.now() + LOCK_WAIT_MS; for (;;) { try { const h = await open(file, "wx"); try { await h.writeFile(JSON.stringify({ pid: process.pid, host: os.hostname(), since: Date.now() } satisfies LockHolder)); } finally { await h.close(); } break; } catch (e) { if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e; if (await lockIsStale(file)) { await rm(file, { force: true }); continue; } if (Date.now() > deadline) { throw new ArticleRegistryError(`the article store is busy (${file} is held by another write) — try again`); } await sleep(LOCK_POLL_MS); } } try { return await fn(); } finally { await rm(file, { force: true }); } }); } // ─── Writing ─── const problemLines = (problems: readonly Problem[]) => problems.map((p) => `${p.path || "(root)"}: ${p.message}`); const problemKey = (p: Problem) => `${p.path}\u0000${p.message}`; // Ids an article may not take: umtool's `/articles/new` is a page (release 27 S8). export const RESERVED_ARTICLE_IDS: readonly string[] = ["new"]; export function assertArticleId(id: unknown): asserts id is string { if (!isReportId(id)) { throw new ArticleRegistryError(`"${String(id)}" is not an article id (a lowercase slug: [a-z0-9][a-z0-9-]*, at most 64)`); } if (RESERVED_ARTICLE_IDS.includes(id)) { throw new ArticleRegistryError(`"${id}" is reserved (umtool's /articles/${id} is a page): pick another article id`); } } const assertId: (id: unknown) => asserts id is string = assertArticleId; async function writeIndex(paths: Pick, index: ArticlesIndex): Promise { await writeJsonAtomic(articlesIndexFile(paths), { published: index.published }, { mkdir: true }); } // Where an article goes in a published list: `position` (0 = first), else // where it is, else last. function placed(list: readonly string[], id: string, position: number | undefined): string[] { const without = list.filter((x) => x !== id); const at = position ?? (list.includes(id) ? list.indexOf(id) : without.length); if (!Number.isInteger(at) || at < 0 || at > without.length) { throw new ArticleRegistryError( `position ${String(position)} is out of range: 0 (first) to ${without.length} (last) for "${id}"`, ); } return [...without.slice(0, at), id, ...without.slice(at)]; } // The change configureArticle and the ops action make. export type ArticleConfigChange = { audience?: ReportAudience; // true publishes (at `position`, else where it is, else last); false // unpublishes (it stays on disk, a draft). published?: boolean; // Its place in the published list, 0 = first. Moves a published article; // with `published: true` places it. Refused on a draft or with `published: false`. position?: number; }; // Set an article's audience and its place in the published list, in one // locked call: every refusal before anything is written. Answers the article // as it now is. export async function configureArticle( id: string, change: ArticleConfigChange, paths: Pick = getPaths(), ): Promise { assertId(id); if (change.audience !== undefined && !isReportAudience(change.audience)) { throw new ArticleRegistryError(`audience must be one of ${REPORT_AUDIENCES.join(", ")}`); } if (change.published === false && change.position !== undefined) { throw new ArticleRegistryError(`"${id}": a position places a published article — not one being unpublished`); } return withArticleStoreLock(async () => { const index = await readArticlesIndex(paths); const read = await readArticle(paths, id); if (!read.ok) { // Unpublishing an article whose directory is gone tidies the index. if (change.published === false && change.audience === undefined && index.published.includes(id)) { const next = { published: index.published.filter((x) => x !== id) }; await writeIndex(paths, next); return stateOf(id, read, next); } throw new ArticleRegistryError( read.reason === "absent" ? `no article "${id}" (no reports/${id}/report.json)` : `reports/${id}/report.json is ${read.reason === "not-an-object" ? "not a JSON object" : read.reason}`, ); } const wasPublished = index.published.includes(id); const publish = change.published ?? wasPublished; if (change.position !== undefined && !publish) { throw new ArticleRegistryError(`"${id}" is a draft: give "published": true to place it`); } // Only a sound article is published (compose would refuse it anyway). if (publish && !wasPublished && read.problems.length > 0) { throw new ArticleRegistryError(`"${id}" cannot be published while report.json has problems`, problemLines(read.problems)); } const nextIndex: ArticlesIndex = publish ? { published: placed(index.published, id, change.position) } : { published: index.published.filter((x) => x !== id) }; let raw = read.raw; if (change.audience !== undefined && articleAudience(raw) !== change.audience) { raw = { ...raw, audience: change.audience }; const after = parseReport(raw, { id }); const before = new Set(read.problems.map(problemKey)); const worse = after.problems.filter((p) => !before.has(problemKey(p))); if (!after.ok || worse.length > 0) { throw new ArticleRegistryError(`"${id}": setting its audience would make report.json invalid`, problemLines(worse)); } await writeJsonAtomic(articleFile(paths, id), raw); } if (nextIndex.published.join("\n") !== index.published.join("\n")) await writeIndex(paths, nextIndex); return stateOf(id, { ...read, raw }, nextIndex); }, paths); } // Publish (`true`) or unpublish (`false`) an article; `position` places it // (0 = first; absent = where it is, else last). Answers the published list. export async function setPublished( id: string, published: boolean, opts: { position?: number } = {}, paths: Pick = getPaths(), ): Promise { await configureArticle(id, { published, ...(opts.position !== undefined ? { position: opts.position } : {}) }, paths); return readArticlesIndex(paths); } // Replace the published order whole: `ids` must be the published articles, // each once, in their new order. Answers the published list. export async function setArticlesOrder( ids: readonly string[], paths: Pick = getPaths(), ): Promise { return withArticleStoreLock(async () => { const index = await readArticlesIndex(paths); const want = [...ids].sort().join("\n"); if (new Set(ids).size !== ids.length || want !== [...index.published].sort().join("\n")) { throw new ArticleRegistryError( `an order must name every published article once (published: ${index.published.join(", ") || "none"})`, ); } const next = { published: [...ids] }; await writeIndex(paths, next); return next; }, paths); } // The keys a patch may change: anything but what names the document. export type ArticlePatch = Partial>; // PATCH SOME KEYS OF AN ARTICLE'S report.json — read inside the lock and // patched as it is now, so a patch never writes back keys read earlier. A key // given as `undefined` is removed. A function patch is given the report as it // is now. Written only when the result parses and has no problem the report // did not already have. Null when the article has no report.json: a patch // never creates one (writeArticle does). export async function patchArticle( id: string, patch: ArticlePatch | ((current: Report) => ArticlePatch), paths: Pick = getPaths(), ): Promise { assertId(id); return withArticleStoreLock(() => patchArticleHoldingLock(id, patch, paths), paths); } // patchArticle's body, for a caller that already holds withArticleStoreLock // and checks more than the report before it patches (release 29 M8: a verdict // proposal's review, ./verdictProposals.ts). The lock is not re-entrant: never // call patchArticle there. export async function patchArticleHoldingLock( id: string, patch: ArticlePatch | ((current: Report) => ArticlePatch), paths: Pick = getPaths(), ): Promise { assertId(id); { const read = await readArticle(paths, id); if (!read.ok) { if (read.reason === "absent") return null; throw new ArticleRegistryError(`reports/${id}/report.json is ${read.reason === "not-an-object" ? "not a JSON object" : read.reason}`); } let changes: ArticlePatch; if (typeof patch === "function") { if (!read.report) { throw new ArticleRegistryError(`reports/${id}/report.json does not parse: fix it before a function patch`, problemLines(read.problems)); } changes = patch(read.report); } else { changes = patch; } for (const k of ["format", "version", "id"]) { if (k in (changes as object)) throw new ArticleRegistryError(`"${id}": a patch may not change "${k}"`); } const next: Record = { ...read.raw }; for (const [k, v] of Object.entries(changes)) { if (v === undefined) delete next[k]; else next[k] = v; } const after = parseReport(next, { id }); const before = new Set(read.problems.map(problemKey)); const worse = after.problems.filter((p) => !before.has(problemKey(p))); if (!after.ok || worse.length > 0) { throw new ArticleRegistryError(`"${id}": the patch would make report.json invalid`, problemLines(worse)); } await writeJsonAtomic(articleFile(paths, id), next); return after.value; } } // WRITE A WHOLE ARTICLE — a generator's report.json, created or replaced at // `transcripts/reports//report.json`. Written only when it has no // problem. A document with no `audience` keeps the one on disk (regenerating a // public article does not make it private); `keepAudience: false` writes it as // given. Its place in the index is untouched: publish with setPublished. export type WriteArticleOptions = { paths?: Pick; keepAudience?: boolean; // Keep the attached `video` on disk when the document has none (release 27: // making a report iteration current does not take the article's video away; // the chain's attach step replaces it). Default false. keepVideo?: boolean; }; export async function writeArticle(doc: unknown, opts: WriteArticleOptions = {}): Promise { const paths = opts.paths ?? getPaths(); articleIdOf(doc); // refused before the lock is taken return withArticleStoreLock(() => writeArticleHoldingLock(doc, { ...opts, paths }), paths); } function articleIdOf(doc: unknown): string { if (!doc || typeof doc !== "object" || Array.isArray(doc)) throw new ArticleRegistryError("an article is a JSON object"); const id = (doc as { id?: unknown }).id; assertId(id); return id; } // writeArticle's body, for a caller that already holds withArticleStoreLock // and writes more than the article as one (lib/report/iterations.ts // makeCurrent). The lock is not re-entrant: never call writeArticle there. export async function writeArticleHoldingLock(doc: unknown, opts: WriteArticleOptions = {}): Promise { const paths = opts.paths ?? getPaths(); const id = articleIdOf(doc); let next = doc as Record; if ((opts.keepAudience !== false && next.audience === undefined) || (opts.keepVideo === true && next.video === undefined)) { const read = await readArticle(paths, id); if (read.ok && opts.keepAudience !== false && next.audience === undefined && read.raw.audience !== undefined) { next = { ...next, audience: read.raw.audience }; } if (read.ok && opts.keepVideo === true && next.video === undefined && read.raw.video !== undefined) { next = { ...next, video: read.raw.video }; } } const parsed = parseReport(next, { id }); if (!parsed.ok || parsed.problems.length > 0) { throw new ArticleRegistryError(`"${id}" is not a sound report`, problemLines(parsed.problems)); } await writeJsonAtomic(articleFile(paths, id), next, { mkdir: true }); return parsed.value; } // ─── Deleting (./delete.ts) ─── // // The two writes a delete makes to the store, for a caller HOLDING // withArticleStoreLock (./delete.ts deleteArticle, which plans, refuses and // removes the bulk). Nothing else calls them. // What a delete parks a directory as until it is removed: not an article id, // so no listing sees it from the moment it is renamed. export const ARTICLE_DELETING_PREFIX = ".deleting-"; // Take `id` out of the published list. Answers whether it was in it. export async function unpublishHoldingLock(id: string, paths: Pick): Promise { assertId(id); const index = await readArticlesIndex(paths); if (!index.published.includes(id)) return false; await writeIndex(paths, { published: index.published.filter((x) => x !== id) }); return true; } // Rename `reports//` to `reports/.deleting--/` (one rename: the // article is gone for every reader at once). Answers the parked directory, or // null when there was none. A directory that is a symlink is refused — the // planner refuses it first. export async function parkArticleDirHoldingLock( id: string, paths: Pick, stamp: string, ): Promise { assertId(id); const dir = articleDir(paths, id); const st = await lstat(dir).catch(() => null); if (!st) return null; if (!st.isDirectory()) throw new ArticleRegistryError(`reports/${id} is not a directory (a link?): remove it by hand`); const parked = path.join(paths.articlesDir, `${ARTICLE_DELETING_PREFIX}${id}-${stamp}`); await rename(dir, parked); return parked; }