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(); 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, 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); }); // demo epic D1 review follow-up: no archive document past 32 MB is read or kept. test("a document over the bound is refused: by its Content-Length, or as it streams; nothing is kept", async () => { const { MAX_ARCHIVE_DOCUMENT_BYTES, OversizeError, readBounded, probeArchive } = await import("./remoteArchives-server"); const declared = new Response("{}", { headers: { "content-length": String(MAX_ARCHIVE_DOCUMENT_BYTES + 1) } }); await assert.rejects(readBounded(declared, "https://stub.test/a.json"), (e: unknown) => e instanceof OversizeError && /is over 32 MB/.test((e as Error).message)); // No length said: counted as it streams, refused at the bound (a small one here). const streamed = new Response(new ReadableStream({ start(c) { for (let i = 0; i < 10; i++) c.enqueue(new Uint8Array(100)); c.close(); } })); await assert.rejects(readBounded(streamed, "https://stub.test/b.json", 500), OversizeError); assert.equal(await readBounded(new Response('{"ok":1}'), "https://stub.test/c.json"), '{"ok":1}'); // The probe says so, and the cache keeps nothing. const big: FetchLike = async () => new Response("{}", { status: 200, headers: { "content-length": String(MAX_ARCHIVE_DOCUMENT_BYTES + 1) } }); await assert.rejects(probeArchive("https://stub.test", { fetch: big }), /is over 32 MB/); const dir = mkdtempSync(path.join(tmpdir(), "archive-cache-")); try { const cache = new ArchiveDiskCache({ dir, fetch: big, sleep: async () => {} }); await assert.rejects(cache.fetch("https://stub.test/corpus.json"), OversizeError); await assert.rejects(cache.fetch("https://stub.test/corpus.json"), OversizeError, "nothing was kept to answer from"); } finally { rmSync(dir, { recursive: true, force: true }); } }); test("the cache's cap is 512 MB unless ARCHIVE_CACHE_MAX_MB says otherwise", async () => { const { ARCHIVE_CACHE_DEFAULT_MB } = await import("./archiveCache-server"); assert.equal(ARCHIVE_CACHE_DEFAULT_MB, 512); const saved = process.env.ARCHIVE_CACHE_MAX_MB; delete process.env.ARCHIVE_CACHE_MAX_MB; try { assert.equal(new ArchiveDiskCache({ dir: "/nonexistent" }).maxBytes, 512 * 1024 * 1024); process.env.ARCHIVE_CACHE_MAX_MB = "64"; assert.equal(new ArchiveDiskCache({ dir: "/nonexistent" }).maxBytes, 64 * 1024 * 1024); } finally { if (saved === undefined) delete process.env.ARCHIVE_CACHE_MAX_MB; else process.env.ARCHIVE_CACHE_MAX_MB = saved; } });