Archilyzer · Source

archilyzer

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

commit 3bdc533cde4dc212f2c4964d434e8dce6ce3f6a3
parent 81be8df333d4f7d58b9250ad47a071165e8f62b0
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 11 Nov 2026 07:32:01 -0500

archives: a remote archive's documents cached on disk by its build, read one at a time, paced (demo epic D1 item 6)

D0: every sweep over jeralyzer.pages.dev downloaded its 8 MB shards again --
the readers kept them in memory only. lib/archiveCache-server.ts is the fetch
every server-side reader of a remote archive now 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 document is kept with the archive's build (corpus.json `generatedAt`) and
its ETag: corpus.json is answered from disk for 10 minutes, then asked again
conditionally; anything else is answered from disk while the build is the
same, and under a new build asked conditionally -- a 304 keeps the bytes.
An archive that does not answer is served from disk; only a 200 is kept.
Every network request waits for the one before it and a 250 ms gap: a
sweep's 8-wide page window is serialized here. Bounded (ARCHIVE_CACHE_MAX_MB,
2048: least recently used dropped). ARCHIVE_CACHE_DIR, else .archive-cache
beside EXPORT_BUILDS_DIR -- the builds volume in a container, which the
editor and umtool both mount; off under node's test runner (a test's fakes
never meet cached bytes) and with ARCHIVE_CACHE=0. RemoteSource takes an
injectable fetch (the global one by default, so a browser and every stubbed
test are as before). ENVIRONMENT.md regenerated; export/.archive-cache/
ignored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Diffstat:
M.gitignore | 2++
MENVIRONMENT.md | 5++++-
Mcommon/lib/archive/reader.ts | 12+++++++++---
Acommon/lib/archiveCache-server.test.ts | 163+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/archiveCache-server.ts | 314+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/lib/envVars.ts | 5++++-
Mmcp/src/sources.ts | 5++++-
7 files changed, 486 insertions(+), 20 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -91,6 +91,8 @@ yarn-error.log* /export/.compose-cache/ # per-site docker build outputs (out/, .next, public/, caches) — one dir per site /export/.export-builds/ +# remote archives' documents cached on disk (common/lib/archiveCache-server.ts) +/export/.archive-cache/ /transcripts/index.mdb/ # homepage (hub) generated public data (regenerate with `pnpm build:homepage`) diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -98,7 +98,10 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | `REPORTS_DIR` | `~/reports` (or the parent of `SONG_REPORTS_DIR`) | umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete. | common/lib/report/delete.ts, common/bin/case.ts, umtool (lib/paths.mjs) | | `SONG_REPORTS_DIR` | unset | umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete and `archilyzer case` read (as umtool does). | common/lib/report/delete.ts, common/bin/case.ts, umtool (song/paths.mjs) | | `UMTOOL_URL` | unset (no link; the MCP's `notes` off) | umtool's front door; when set, the video page links to it, its Find clips hands the recording to umtool's clip finder (the `find-clips` job posts to `/api/report/clips` with WORKER_TOKEN), and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). Unset: Find clips is disabled. | editor/app/channels/[slug]/videos/[id]/page.tsx, common/lib/umtoolUrl.ts, mcp/src/archivalTools.ts | -| `TRANSCRIPT_SITE_URL` | — | MCP server: one published archive to read over HTTP. | mcp/src/sources.ts | +| `TRANSCRIPT_SITE_URL` | — | MCP server: one published archive to read over HTTP. Also the default connected archive (common/lib/remoteArchives.ts): the editor, umtool and the MCP offer it as a source when settings.remoteArchives does not list it, without writing it. | mcp/src/sources.ts | +| `ARCHIVE_CACHE_DIR` | `.archive-cache` beside EXPORT_BUILDS_DIR | Where a remote archive's documents (corpus.json, manifests, shard pages) are kept on disk, by the archive's build: a sweep over a published archive downloads a shard once per build, not once per sweep. In a container it is on the builds volume. | common/lib/archiveCache-server.ts | +| `ARCHIVE_CACHE_MAX_MB` | 2048 | The disk cache of remote archive documents' size cap, MB: past it the least recently used are dropped. | common/lib/archiveCache-server.ts | +| `ARCHIVE_CACHE` | on (off under node's test runner) | `0` reads remote archives without the disk cache (every read over the network, still one at a time); `1` turns it on under node's test runner, where it is off. | common/lib/archiveCache-server.ts | | `TRANSCRIPT_HUB_URL` | — | MCP server: a hub, federating every archive it lists. | mcp/src/sources.ts | | `TRANSCRIPT_LOCAL_DIR` | — | MCP server: a composed public dir on disk. | mcp/src/sources.ts | | `TRANSCRIPT_PLATFORM_LINKS` | off | `1` cites platform watch pages instead of the archive's own pages. | common/lib/archive/reader-fs.ts | diff --git a/common/lib/archive/reader.ts b/common/lib/archive/reader.ts @@ -692,7 +692,13 @@ export class RemoteSource implements ArchiveReader { // `budgetBytes` lets a hub divide one memory ceiling across its members // instead of granting each member the full budget (N members × 48 MB is not a // budget, it's N budgets). - constructor(baseUrl: string, budgetBytes = pageCacheBudgetBytes()) { + // The fetch every read goes through: the global one by default (a browser, + // a test that stubs it), the disk cache on a server (demo epic D1: + // common/lib/archiveCache-server.ts, passed by mcp/src/sources.ts). + private fetchImpl: typeof fetch; + + constructor(baseUrl: string, budgetBytes = pageCacheBudgetBytes(), opts: { fetch?: typeof fetch } = {}) { + this.fetchImpl = opts.fetch ?? ((input, init) => fetch(input, init)); this.base = baseUrl.replace(/\/+$/, ""); this.label = `remote:${this.base}`; this.subsPages = new PageCache<SubsDetail[]>(budgetBytes); @@ -879,7 +885,7 @@ export class RemoteSource implements ArchiveReader { p: string, kind?: string, ): Promise<{ value: T; bytes: number }> { - const res = await fetch(`${this.base}${p}`); + const res = await this.fetchImpl(`${this.base}${p}`); if (!res.ok) { throw new ArchiveHttpError(res.status, `${this.base}${p}`, res.statusText); } @@ -968,7 +974,7 @@ export class RemoteSource implements ArchiveReader { slug: string, ): Promise<ChannelDigestsManifest | null> { const p = manifestUrl("digests", slug); - const res = await fetch(`${this.base}${p}`); + const res = await this.fetchImpl(`${this.base}${p}`); if (res.status === 404) return null; if (!res.ok) { throw new ArchiveHttpError(res.status, `${this.base}${p}`, res.statusText); diff --git a/common/lib/archiveCache-server.test.ts b/common/lib/archiveCache-server.test.ts @@ -0,0 +1,163 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { ArchiveDiskCache, archiveCacheEnabled } from "./archiveCache-server"; +import type { FetchLike } from "./remoteArchives-server"; +import { RemoteSource } from "./archive/reader"; + +// demo epic D1 item 6: a remote archive's documents on disk, by build; one +// request at a time, paced. A fake archive only. + +const ORIGIN = "https://stub.test"; + +function archive() { + const docs = new Map<string, { body: unknown; etag: string }>(); + const put = (p: string, body: unknown, etag: string) => docs.set(`${ORIGIN}${p}`, { body, etag }); + const asked: { url: string; ifNoneMatch?: string }[] = []; + let inFlight = 0; + let maxInFlight = 0; + const fetch: FetchLike = async (url, init) => { + const ifNoneMatch = init?.headers?.["if-none-match"]; + asked.push({ url, ...(ifNoneMatch ? { ifNoneMatch } : {}) }); + inFlight += 1; + maxInFlight = Math.max(maxInFlight, inFlight); + await new Promise((r) => setTimeout(r, 5)); + inFlight -= 1; + const d = docs.get(url); + if (!d) return new Response("nope", { status: 404 }); + if (ifNoneMatch === d.etag) return new Response(null, { status: 304 }); + return new Response(JSON.stringify(d.body), { status: 200, headers: { etag: d.etag } }); + }; + return { put, asked, fetch, maxInFlight: () => maxInFlight }; +} + +function cacheOn(a: ReturnType<typeof archive>, clock: { t: number }, sleeps: number[] = []) { + const dir = mkdtempSync(path.join(tmpdir(), "archive-cache-")); + const cache = new ArchiveDiskCache({ + dir, + fetch: a.fetch, + now: () => clock.t, + sleep: async (ms) => { + sleeps.push(ms); + clock.t += ms; + }, + gapMs: 250, + corpusTtlMs: 60_000, + }); + return { cache, dir }; +} + +test("a shard read twice under one build is read from the network once", async () => { + const a = archive(); + a.put("/corpus.json", { generatedAt: "g1" }, '"c1"'); + a.put("/transcripts/alpha/page-0000.json", [{ id: "a1" }], '"p1"'); + const clock = { t: 1_000_000 }; + const { cache, dir } = cacheOn(a, clock); + try { + const url = `${ORIGIN}/transcripts/alpha/page-0000.json`; + assert.deepEqual(await (await cache.fetch(url)).json(), [{ id: "a1" }]); + assert.deepEqual(a.asked.map((x) => x.url), [url, `${ORIGIN}/corpus.json`]); + // A second process (a new cache on the same dir) reads it from disk too: one corpus check, no shard. + const again = new ArchiveDiskCache({ dir, fetch: a.fetch, now: () => clock.t, sleep: async () => {}, corpusTtlMs: 60_000 }); + const res = await again.fetch(url); + assert.equal(res.headers.get("x-archive-cache"), "disk"); + assert.deepEqual(await res.json(), [{ id: "a1" }]); + assert.deepEqual(a.asked.slice(2).map((x) => x.url), [], "corpus.json within its TTL is the disk's too"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("a new build: the shard is asked conditionally, a 304 keeps the bytes, a change replaces them", async () => { + const a = archive(); + a.put("/corpus.json", { generatedAt: "g1" }, '"c1"'); + a.put("/transcripts/alpha/page-0000.json", [{ id: "a1" }], '"p1"'); + const clock = { t: 1_000_000 }; + const { cache, dir } = cacheOn(a, clock); + try { + const url = `${ORIGIN}/transcripts/alpha/page-0000.json`; + await cache.fetch(url); + // The archive is rebuilt; the corpus check is due. + a.put("/corpus.json", { generatedAt: "g2" }, '"c2"'); + clock.t += 61_000; + const fresh = new ArchiveDiskCache({ dir, fetch: a.fetch, now: () => clock.t, sleep: async () => {}, corpusTtlMs: 60_000 }); + const before = a.asked.length; + assert.deepEqual(await (await fresh.fetch(url)).json(), [{ id: "a1" }]); + const asked = a.asked.slice(before); + assert.deepEqual(asked, [ + { url: `${ORIGIN}/corpus.json`, ifNoneMatch: '"c1"' }, + { url, ifNoneMatch: '"p1"' }, + ]); + assert.equal(fresh.stats.notModified, 1); + // Unchanged since: the disk again, nothing asked. + const n = a.asked.length; + await fresh.fetch(url); + assert.equal(a.asked.length, n); + // The page changed in a third build: replaced. + a.put("/corpus.json", { generatedAt: "g3" }, '"c3"'); + a.put("/transcripts/alpha/page-0000.json", [{ id: "a1" }, { id: "a2" }], '"p2"'); + clock.t += 61_000; + const third = new ArchiveDiskCache({ dir, fetch: a.fetch, now: () => clock.t, sleep: async () => {}, corpusTtlMs: 60_000 }); + assert.deepEqual(await (await third.fetch(url)).json(), [{ id: "a1" }, { id: "a2" }]); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("one request at a time, the gap between them; an archive that does not answer is served from disk", async () => { + const a = archive(); + a.put("/corpus.json", { generatedAt: "g1" }, '"c1"'); + for (let i = 0; i < 4; i++) a.put(`/transcripts/alpha/page-000${i}.json`, [{ id: `a${i}` }], `"p${i}"`); + const clock = { t: 1_000_000 }; + const sleeps: number[] = []; + const { cache, dir } = cacheOn(a, clock, sleeps); + try { + // Through the reader, as a sweep reads: its 8-wide page window is serialized here. + const reader = new RemoteSource(ORIGIN, undefined, { fetch: cache.fetch as unknown as typeof fetch }); + await Promise.all([0, 1, 2, 3].map((i) => reader.transcriptPage({ key: "alpha", slug: "alpha", name: "alpha" }, i))); + assert.equal(a.maxInFlight(), 1, "never two at once"); + assert.ok(sleeps.length >= 4 && sleeps.every((ms) => ms > 0 && ms <= 250), JSON.stringify(sleeps)); + // The host goes away: what is on disk still answers (a new process, past the corpus TTL). + clock.t += 120_000; + const down: FetchLike = async () => { + throw new Error("ECONNREFUSED"); + }; + const offline = new ArchiveDiskCache({ dir, fetch: down, now: () => clock.t, sleep: async () => {} }); + assert.deepEqual(await (await offline.fetch(`${ORIGIN}/transcripts/alpha/page-0002.json`)).json(), [{ id: "a2" }]); + await assert.rejects(offline.fetch(`${ORIGIN}/transcripts/alpha/page-0009.json`), /ECONNREFUSED/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("past the size cap the least recently used documents go", async () => { + const a = archive(); + a.put("/corpus.json", { generatedAt: "g1" }, '"c1"'); + a.put("/a.json", "x".repeat(400), '"a"'); + a.put("/b.json", "y".repeat(400), '"b"'); + const clock = { t: 1_000_000 }; + const dir = mkdtempSync(path.join(tmpdir(), "archive-cache-")); + try { + const cache = new ArchiveDiskCache({ dir, fetch: a.fetch, now: () => clock.t, sleep: async () => {}, maxBytes: 600 }); + await cache.fetch(`${ORIGIN}/a.json`); + clock.t += 1000; + await cache.fetch(`${ORIGIN}/b.json`); + await cache.prune(); + const n = a.asked.length; + await cache.fetch(`${ORIGIN}/b.json`); + assert.equal(a.asked.length, n, "the newest is kept"); + await cache.fetch(`${ORIGIN}/a.json`); + assert.equal(a.asked.length, n + 1, "the oldest was dropped"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("on by default on a server; off under node's test runner and with ARCHIVE_CACHE=0", () => { + assert.equal(archiveCacheEnabled({}), true); + assert.equal(archiveCacheEnabled({ ARCHIVE_CACHE: "0" }), false); + assert.equal(archiveCacheEnabled({ NODE_TEST_CONTEXT: "child-v8" }), false); + assert.equal(archiveCacheEnabled({ NODE_TEST_CONTEXT: "child-v8", ARCHIVE_CACHE: "1" }), true); +}); diff --git a/common/lib/archiveCache-server.ts b/common/lib/archiveCache-server.ts @@ -1,18 +1,304 @@ -// THE ARCHIVE READS the editor makes for a connected archive (demo epic D1): -// corpus.json, a channel's transcripts manifest, a shard page — for a -// remote-only channel's facts and a cited record's page URL. One document at a -// time, never in parallel. Item 6 keeps them on disk. +// 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 2048) the least recently used documents +// are dropped. Never transcripts/ (it is the corpus), never /tmp (it is RAM). -import { plainGetJson, type GetJson } from "./remoteArchives-server"; +import { createHash } from "node:crypto"; +import { mkdir, readdir, readFile, rename, rm, stat, utimes, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { getPaths } from "./paths"; +import { plainGetJson, type FetchLike, type GetJson } from "./remoteArchives-server"; -/** The editor's reader of archive documents. */ -export function cachedArchiveGetJson(): GetJson { - const get = plainGetJson(); - let chain: Promise<unknown> = Promise.resolve(); - // Sequential: each read waits for the one before it. - return (url) => { - const next = chain.then(() => get(url)); - chain = next.catch(() => {}); - return next; +export const CORPUS_TTL_MS = 10 * 60_000; +export const GAP_MS = 250; +const DEFAULT_MAX_BYTES = 2048 * 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<void>; + gapMs?: number; + corpusTtlMs?: number; + maxBytes?: number; +}; + +export function archiveCacheDir(env: Record<string, string | undefined> = 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<string, string>; method?: string }; + +export class ArchiveDiskCache { + readonly dir: string; + private doFetch: FetchLike; + private now: () => number; + private sleep: (ms: number) => Promise<void>; + private gapMs: number; + private corpusTtlMs: number; + private maxBytes: number; + // One network request at a time: each waits on this. + private line: Promise<void> = Promise.resolve(); + private lastEnd = 0; + // base (origin[/path]) -> the generation its corpus.json last said. + private generations = new Map<string, string | null>(); + private bases = new Set<string>(); + 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<Meta | null> { + 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<string | null | undefined> { + 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<T>(fn: () => Promise<T>): Promise<T> { + 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<void> { + await mkdir(path.dirname(file), { recursive: true }); + const tmp = `${file}.${process.pid}.${this.now()}.tmp`; + await writeFile(tmp, body); + await rename(tmp, file); + await writeFile(`${tmp}.meta`, JSON.stringify(meta)); + await rename(`${tmp}.meta`, `${file}.meta.json`); + 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<Response> => { + 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<string, string> = { 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 { + res = await this.paced(() => this.doFetch(url, { ...(init?.signal ? { signal: init.signal } : {}), headers })); + } catch (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 writeFile(`${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; + } + const body = await res.text(); + 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<Response> { + 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<void> { + 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.endsWith(".tmp") || name.endsWith(".meta")) 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<string, ArchiveDiskCache> }; +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<string, string | undefined> = 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(); } diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -134,7 +134,10 @@ const DECLARED: EnvVarDecl[] = [ { name: "REPORTS_DIR", audience: "runtime", default: "`~/reports` (or the parent of `SONG_REPORTS_DIR`)", readBy: "common/lib/report/delete.ts, common/bin/case.ts, umtool (lib/paths.mjs)", doc: "umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete." }, { name: "SONG_REPORTS_DIR", audience: "runtime", default: "unset", readBy: "common/lib/report/delete.ts, common/bin/case.ts, umtool (song/paths.mjs)", doc: "umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete and `archilyzer case` read (as umtool does)." }, { name: "UMTOOL_URL", audience: "runtime", default: "unset (no link; the MCP's `notes` off)", readBy: "editor/app/channels/[slug]/videos/[id]/page.tsx, common/lib/umtoolUrl.ts, mcp/src/archivalTools.ts", doc: "umtool's front door; when set, the video page links to it, its Find clips hands the recording to umtool's clip finder (the `find-clips` job posts to `/api/report/clips` with WORKER_TOKEN), and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). Unset: Find clips is disabled." }, - { name: "TRANSCRIPT_SITE_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: one published archive to read over HTTP." }, + { name: "TRANSCRIPT_SITE_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: one published archive to read over HTTP. Also the default connected archive (common/lib/remoteArchives.ts): the editor, umtool and the MCP offer it as a source when settings.remoteArchives does not list it, without writing it." }, + { name: "ARCHIVE_CACHE_DIR", audience: "runtime", default: "`.archive-cache` beside EXPORT_BUILDS_DIR", readBy: "common/lib/archiveCache-server.ts", doc: "Where a remote archive's documents (corpus.json, manifests, shard pages) are kept on disk, by the archive's build: a sweep over a published archive downloads a shard once per build, not once per sweep. In a container it is on the builds volume." }, + { name: "ARCHIVE_CACHE_MAX_MB", audience: "runtime", default: "2048", readBy: "common/lib/archiveCache-server.ts", doc: "The disk cache of remote archive documents' size cap, MB: past it the least recently used are dropped." }, + { name: "ARCHIVE_CACHE", audience: "runtime", default: "on (off under node's test runner)", readBy: "common/lib/archiveCache-server.ts", doc: "`0` reads remote archives without the disk cache (every read over the network, still one at a time); `1` turns it on under node's test runner, where it is off." }, { name: "TRANSCRIPT_HUB_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: a hub, federating every archive it lists." }, { name: "TRANSCRIPT_LOCAL_DIR", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: a composed public dir on disk." }, { name: "TRANSCRIPT_PLATFORM_LINKS", audience: "runtime", default: "off", readBy: "common/lib/archive/reader-fs.ts", doc: "`1` cites platform watch pages instead of the archive's own pages." }, diff --git a/mcp/src/sources.ts b/mcp/src/sources.ts @@ -1,6 +1,7 @@ import { readFileSync } from "node:fs"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { connectedArchives, type ConnectedArchive } from "yt-dlp-transcript-common/lib/remoteArchives"; +import { archiveCache, archiveCacheEnabled } from "yt-dlp-transcript-common/lib/archiveCache-server"; import { LocalSource, RemoteSource, @@ -57,7 +58,9 @@ export function buildSource(spec: SourceSpec): ShardSource { case "hub": return new HubSource(spec.url, spec.sites); case "remote": - return new RemoteSource(spec.url); + // Its shards cached on disk while the archive's build is unchanged, read + // one at a time, paced (demo epic D1: common/lib/archiveCache-server.ts). + return archiveCacheEnabled() ? new RemoteSource(spec.url, undefined, { fetch: archiveCache().fetch as typeof fetch }) : new RemoteSource(spec.url); case "local": return new LocalSource(spec.dir); }