// REMOTE ARCHIVE READS, CACHED ON DISK (demo epic D1 item 6). // // A sweep over a published archive reads its shards — transcript pages of up // to 8 MB each — and D0 measured every sweep downloading them again: the // readers kept them in memory only, for the life of one process. This is the // fetch every server-side reader of a remote archive goes through (the MCP's // RemoteSource — so the editor's sweeps and umtool's research — the editor's // remote-only registration and umtool's chain): a GET of an archive's JSON is // answered from disk while the archive's BUILD has not changed. // // WHAT "NOT CHANGED" MEANS. A published archive is a static build; its // `/corpus.json` `generatedAt` names the build. Every document is kept with // the generation it was read under and its ETag (and Last-Modified): // // corpus.json answered from disk for CORPUS_TTL_MS after it was last // checked; then asked again CONDITIONALLY (If-None-Match / // If-Modified-Since) — a 304 is a few hundred bytes. // anything else answered from disk while its generation is the archive's // current one; under a new build it is asked again // conditionally, and a 304 keeps the bytes (a shard that did // not change between two builds is not downloaded twice). // // When the archive does not answer, a document on disk is served as it is // (a cached read beats a failed sweep); only a 200 is ever kept. // // ONE REQUEST AT A TIME, PACED. Every network request this process makes // through the cache waits for the one before it to end, then for GAP_MS more // — a sweep's page reads never burst an archive's host. The disk answers are // not paced. // // WHERE. ARCHIVE_CACHE_DIR, else `.archive-cache` beside the export builds // (EXPORT_BUILDS_DIR's parent: /data/builds in a container — the builds // volume both the editor and umtool mount — export/ on a checkout). Bounded: // past ARCHIVE_CACHE_MAX_MB (default 512: the host's disk is nearly full) the least recently used documents // are dropped. Never transcripts/ (it is the corpus), never /tmp (it is RAM). import { createHash } from "node:crypto"; import { mkdir, readdir, readFile, rm, stat, utimes } from "node:fs/promises"; import path from "node:path"; import { getPaths } from "./paths"; import { writeFileAtomic } from "./atomicFile.mjs"; import { OffOriginError, fetchOnOrigin, plainGetJson, readBounded, type FetchLike, type GetJson } from "./remoteArchives-server"; export const CORPUS_TTL_MS = 10 * 60_000; export const GAP_MS = 250; export const ARCHIVE_CACHE_DEFAULT_MB = 512; const DEFAULT_MAX_BYTES = ARCHIVE_CACHE_DEFAULT_MB * 1024 * 1024; type Meta = { url: string; etag?: string; lastModified?: string; // The archive's corpus generatedAt this copy was read (or revalidated) under. generation?: string | null; // When it was last read or revalidated over the network (ms). checkedAt: number; bytes: number; }; export type ArchiveCacheOpts = { dir?: string; fetch?: FetchLike; now?: () => number; sleep?: (ms: number) => Promise; gapMs?: number; corpusTtlMs?: number; maxBytes?: number; }; export function archiveCacheDir(env: Record = process.env): string { const set = env.ARCHIVE_CACHE_DIR?.trim(); if (set) return path.resolve(/* turbopackIgnore: true */ set); return path.join(path.dirname(getPaths().exportBuildsDir), ".archive-cache"); } const isCorpus = (url: string) => /\/corpus\.json$/.test(new URL(url).pathname); type Init = { signal?: AbortSignal; headers?: Record; method?: string }; export class ArchiveDiskCache { readonly dir: string; private doFetch: FetchLike; private now: () => number; private sleep: (ms: number) => Promise; private gapMs: number; private corpusTtlMs: number; readonly maxBytes: number; // One network request at a time: each waits on this. private line: Promise = Promise.resolve(); private lastEnd = 0; // base (origin[/path]) -> the generation its corpus.json last said. private generations = new Map(); private bases = new Set(); private writes = 0; // Counters, for the tests and a log line. readonly stats = { network: 0, disk: 0, notModified: 0 }; constructor(opts: ArchiveCacheOpts = {}) { this.dir = opts.dir ?? archiveCacheDir(); // The global fetch, looked up per call (a test that stubs it is obeyed). this.doFetch = opts.fetch ?? (((u: string, i?: Init) => fetch(u, i)) as unknown as FetchLike); this.now = opts.now ?? Date.now; this.sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))); this.gapMs = opts.gapMs ?? GAP_MS; this.corpusTtlMs = opts.corpusTtlMs ?? CORPUS_TTL_MS; const mb = Number(process.env.ARCHIVE_CACHE_MAX_MB); this.maxBytes = opts.maxBytes ?? (Number.isFinite(mb) && mb > 0 ? mb * 1024 * 1024 : DEFAULT_MAX_BYTES); } private fileOf(url: string): string { const h = createHash("sha256").update(url).digest("hex"); return path.join(this.dir, h.slice(0, 2), h); } private async readMeta(file: string): Promise { try { return JSON.parse(await readFile(`${file}.meta.json`, "utf8")) as Meta; } catch { return null; } } // The archive base a URL belongs to: a base whose corpus.json was read // (an archive served under a path), else its origin. private baseOf(url: string): string { const u = new URL(url); const s = `${u.protocol}//${u.host}${u.pathname}`; let best = `${u.protocol}//${u.host}`; for (const b of this.bases) if (s.startsWith(`${b}/`) && b.length > best.length) best = b; return best; } /** The archive's current build, by its corpus.json (read through this cache); undefined when it cannot be told. */ private async generationOf(base: string): Promise { if (!this.generations.has(base)) { const res = await this.fetch(`${base}/corpus.json`).catch(() => null); if (!res?.ok) return undefined; } return this.generations.get(base); } /** Run `fn` as the only network request in flight, after the gap. */ private paced(fn: () => Promise): Promise { const run = this.line.then(async () => { const wait = this.lastEnd + this.gapMs - this.now(); if (this.lastEnd > 0 && wait > 0) await this.sleep(wait); try { return await fn(); } finally { this.lastEnd = this.now(); } }); this.line = run.then( () => undefined, () => undefined, ); return run; } private respond(body: string, meta: Meta, from: "disk" | "network"): Response { return new Response(body, { status: 200, headers: { "content-type": "application/json", "x-archive-cache": from, ...(meta.etag ? { etag: meta.etag } : {}) }, }); } private async keep(file: string, body: string, meta: Meta): Promise { await mkdir(path.dirname(file), { recursive: true }); await writeFileAtomic(file, body); await writeFileAtomic(`${file}.meta.json`, JSON.stringify(meta)); if (++this.writes % 20 === 1) await this.prune().catch(() => {}); } /** A fetch: a GET of an http(s) URL goes through the cache; anything else straight on. */ fetch = async (input: string | URL | Request, init?: Init): Promise => { const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; const method = init?.method ?? (input instanceof Request ? input.method : "GET"); if (method !== "GET" || !/^https?:\/\//i.test(url)) return this.doFetch(url, init); const file = this.fileOf(url); const meta = await this.readMeta(file); const corpus = isCorpus(url); const base = corpus ? url.replace(/\/corpus\.json$/, "") : this.baseOf(url); let generation: string | null | undefined; if (meta) { if (corpus) { if (this.now() - meta.checkedAt < this.corpusTtlMs) return this.fromDisk(file, meta, base, true); } else { generation = await this.generationOf(base); if (generation !== undefined && generation !== null && meta.generation === generation) return this.fromDisk(file, meta, base, false); } } const headers: Record = { accept: "application/json" }; if (meta?.etag) headers["if-none-match"] = meta.etag; if (meta?.lastModified) headers["if-modified-since"] = meta.lastModified; let res: Response; try { // On the archive's own origin only: a redirect elsewhere is refused (fetchOnOrigin). res = await this.paced(() => fetchOnOrigin(this.doFetch, url, { ...(init?.signal ? { signal: init.signal } : {}), headers })); } catch (e) { // An off-origin redirect is a refusal, never an outage: nothing on disk answers it. if (e instanceof OffOriginError) throw e; // The archive did not answer: what is on disk is the answer. if (meta) return this.fromDisk(file, meta, base, corpus); throw e; } this.stats.network += 1; if (res.status === 304 && meta) { this.stats.notModified += 1; const g = corpus ? undefined : (generation ?? (await this.generationOf(base))); const next: Meta = { ...meta, checkedAt: this.now(), ...(corpus ? {} : { generation: g ?? meta.generation ?? null }) }; await writeFileAtomic(`${file}.meta.json`, JSON.stringify(next)).catch(() => {}); return this.fromDisk(file, next, base, corpus, true); } if (!res.ok) { if (meta && res.status >= 500) return this.fromDisk(file, meta, base, corpus); return res; } // Bounded: a document past MAX_ARCHIVE_DOCUMENT_BYTES is refused, never kept. const body = await readBounded(res, url); if (corpus) this.noteCorpus(base, body); const next: Meta = { url, ...(res.headers.get("etag") ? { etag: res.headers.get("etag")! } : {}), ...(res.headers.get("last-modified") ? { lastModified: res.headers.get("last-modified")! } : {}), generation: corpus ? (this.generations.get(base) ?? null) : (generation ?? (await this.generationOf(base)) ?? null), checkedAt: this.now(), bytes: body.length, }; await this.keep(file, body, next).catch(() => {}); return this.respond(body, next, "network"); }; private noteCorpus(base: string, body: string): void { this.bases.add(base); try { const gen = (JSON.parse(body) as { generatedAt?: unknown }).generatedAt; this.generations.set(base, typeof gen === "string" && gen ? gen : null); } catch { this.generations.set(base, null); } } private async fromDisk(file: string, meta: Meta, base: string, corpus: boolean, counted = false): Promise { const body = await readFile(file, "utf8"); if (corpus) this.noteCorpus(base, body); if (!counted) this.stats.disk += 1; // Recently used: the prune drops the oldest first. const t = new Date(this.now()); await utimes(file, t, t).catch(() => {}); return this.respond(body, meta, "disk"); } /** Drop the least recently used documents past the size cap. */ async prune(): Promise { const files: { file: string; bytes: number; at: number }[] = []; for (const sub of await readdir(this.dir).catch(() => [] as string[])) { const d = path.join(this.dir, sub); for (const name of await readdir(d).catch(() => [] as string[])) { if (name.endsWith(".meta.json") || name.includes(".tmp-")) continue; const st = await stat(path.join(d, name)).catch(() => null); if (st?.isFile()) files.push({ file: path.join(d, name), bytes: st.size, at: st.mtimeMs }); } } let total = files.reduce((n, f) => n + f.bytes, 0); if (total <= this.maxBytes) return; files.sort((a, b) => a.at - b.at); for (const f of files) { if (total <= this.maxBytes) break; await rm(f.file, { force: true }); await rm(`${f.file}.meta.json`, { force: true }); total -= f.bytes; } } } // One cache per directory per process (every route bundle shares it), so // "one request at a time" holds across every reader in the process. const g = globalThis as { __archiveDiskCaches?: Map }; const caches = (g.__archiveDiskCaches ??= new Map()); /** * Whether the server-side readers use the disk cache: yes, unless * ARCHIVE_CACHE=0 — or the process is a unit test under node's runner * (NODE_TEST_CONTEXT), whose fakes must never meet another test's cached * bytes; such a test builds its own ArchiveDiskCache on a temp dir. */ export function archiveCacheEnabled(env: Record = process.env): boolean { if (env.ARCHIVE_CACHE === "0") return false; if (env.ARCHIVE_CACHE === "1") return true; return !env.NODE_TEST_CONTEXT; } /** This process's disk cache of archive documents (ARCHIVE_CACHE_DIR, else the default). */ export function archiveCache(): ArchiveDiskCache { const dir = archiveCacheDir(); let c = caches.get(dir); if (!c) { c = new ArchiveDiskCache({ dir }); caches.set(dir, c); } return c; } /** The archive documents' reader for the editor's registration and umtool's chain: through the disk cache. */ export function cachedArchiveGetJson(): GetJson { return archiveCacheEnabled() ? plainGetJson(archiveCache().fetch as unknown as FetchLike) : plainGetJson(); }