// Lane spn-batch: anonymous Save Page Now (no keys) vs SPN2 with keys, the // pacer (one save at a time, the gap, a 429's Retry-After and the doubling // rest), and the batch — skip-archived, saved, failed, resumed after a // restart, evidence JSON + CSV rows. HTTP is stubbed; no network. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/savePageNowBatch.test.ts import test, { after } from "node:test"; import assert from "node:assert/strict"; import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import { parseSpnAnonymous, spnCaptureOf, spnLinkMemento } from "../lib/waybackPages/savePageNow"; import { savePageNow, SpnPacer, SPN_USER_AGENT, type SavePageNowResult } from "./savePageNow"; import { planSpnBatch, runSpnBatch, spnEvidenceCsv, spnEvidenceRow, type SpnBatchDeps } from "./savePageNowBatch"; import type { ArchiveLookup } from "../lib/archives/index"; const ROOT = mkdtempSync(path.join(tmpdir(), "spn-batch-")); after(() => rmSync(ROOT, { recursive: true, force: true })); const paths = { channelsDir: path.join(ROOT, "channels"), transcriptsDir: ROOT, jobsDir: path.join(ROOT, "jobs") } as unknown as Paths; const NO_KEYS = { archiveOrg: { s3KeyFile: path.join(ROOT, "no-such-keys.env") }, social: { x: { visibility: "public" } } }; const KEYS_ENV = { ARCHIVE_ORG_S3_ACCESS: "FAKEACCESS0001", ARCHIVE_ORG_S3_SECRET: "FAKESECRET0001" }; const TS = "20261105120000"; const PAGE = "https://x.com/someone/status/111"; // A virtual clock: sleep advances it. function clock(start = Date.parse("2026-11-05T12:00:00Z")) { let t = start; const sleeps: number[] = []; return { now: () => t, sleep: async (ms: number) => { sleeps.push(ms); t += ms; }, sleeps, }; } type Sent = { url: string; method: string; headers?: Record }; type Answer = { status: number; text?: string; headers?: Record; url?: string }; function stubClient(answers: ((s: Sent) => Answer)[]) { const sent: Sent[] = []; return { sent, send: async (url: string, init: { method: "GET" | "POST"; headers?: Record }) => { const s = { url, method: init.method, ...(init.headers ? { headers: init.headers } : {}) }; sent.push(s); const a: Answer = (answers.shift() ?? ((): Answer => ({ status: 500 })))(s); return { status: a.status, text: a.text ?? "", headers: new Headers(a.headers ?? {}), url: a.url ?? url }; }, }; } test("the anonymous answers read: Content-Location, Link memento, the final URL, a watched job, a runtime error, 429, 5xx", () => { const h = (o: Record) => (n: string) => o[n.toLowerCase()] ?? null; assert.deepEqual(parseSpnAnonymous({ status: 200, header: h({ "content-location": `/web/${TS}/${PAGE}` }), text: "" }), { state: "success", timestamp: TS, originalUrl: PAGE }); assert.equal(spnLinkMemento(`<${PAGE}>; rel="original", ; rel="memento"; datetime="x"`), `https://web.archive.org/web/${TS}/${PAGE}`); assert.equal(parseSpnAnonymous({ status: 200, header: h({ link: `; rel="memento"` }), text: "" }).state, "success"); assert.equal(parseSpnAnonymous({ status: 200, header: h({}), finalUrl: `https://web.archive.org/web/${TS}/${PAGE}`, text: "" }).state, "success"); assert.equal(spnCaptureOf(`https://evil.example/web/${TS}/${PAGE}`), null, "only an archive.org URL names a capture"); assert.deepEqual(parseSpnAnonymous({ status: 200, header: h({}), text: `` }), { state: "pending", jobId: "spn2-abc123" }); const robots = parseSpnAnonymous({ status: 200, header: h({ "x-archive-wayback-runtime-error": "RobotAccessControlException: Blocked By Robots" }), text: "" }); assert.equal(robots.state === "error" && robots.code, "blocked-by-robots"); const busy = parseSpnAnonymous({ status: 429, header: h({}), text: "", retryAfterMs: 90_000 }); assert.deepEqual(busy, { state: "rate-limited", error: "archive.org answered HTTP 429 (too many captures)", retryAfterMs: 90_000 }); assert.equal(parseSpnAnonymous({ status: 503, header: h({}), text: "" }).state, "unavailable"); // A 523 from the save is THIS URL's failure, with the page's sentence (not a rest). const failed = parseSpnAnonymous({ status: 523, header: h({}), text: "Wayback Machine

Save Page Now

Sorry. Job failed: the server returned a 404.

" }); assert.deepEqual(failed, { state: "error", code: "http-523", error: "Save Page Now could not capture the page (HTTP 523): Sorry." }); const session = parseSpnAnonymous({ status: 200, header: h({}), text: JSON.stringify({ status: "error", status_ext: "error:user-session-limit", message: "limit" }) }); assert.equal(session.state, "rate-limited"); const perUrl = parseSpnAnonymous({ status: 200, header: h({}), text: JSON.stringify({ status: "error", status_ext: "error:too-many-daily-captures", message: "This URL has been captured 10 times today." }) }); assert.equal(perUrl.state, "error", "a URL captured too often today is that URL's failure, not a rest"); }); test("anonymous vs keys: no keys → GET /save/ with no Authorization and the honest UA; keys → POST /save with LOW", async () => { const c = clock(); const anon = stubClient([() => ({ status: 200, headers: { "content-location": `/web/${TS}/${PAGE}` } })]); const r = await savePageNow({ paths, url: PAGE, settings: NO_KEYS, env: {}, deps: { client: anon, sleep: c.sleep } }); assert.equal(r.ok, true); assert.equal(r.mode, "anonymous"); assert.equal(r.waybackUrl, `https://web.archive.org/web/${TS}/${PAGE}`); assert.equal(anon.sent[0].method, "GET"); assert.equal(anon.sent[0].url, `https://web.archive.org/save/${PAGE}`); assert.equal(anon.sent[0].headers?.authorization, undefined); assert.equal(anon.sent[0].headers?.["user-agent"], SPN_USER_AGENT); assert.match(SPN_USER_AGENT, /^Mozilla\/5\.0 \(compatible; Archilyzer Save Page Now; \+https:\/\//); const keyed = stubClient([ () => ({ status: 200, text: JSON.stringify({ url: PAGE, job_id: "spn2-k1" }) }), () => ({ status: 200, text: JSON.stringify({ status: "success", timestamp: TS, original_url: PAGE }) }), ]); const k = await savePageNow({ paths, url: PAGE, settings: NO_KEYS, env: KEYS_ENV, pollMs: 1, deps: { client: keyed, sleep: c.sleep } }); assert.equal(k.ok, true); assert.equal(k.mode, "keys"); assert.equal(keyed.sent[0].method, "POST"); assert.equal(keyed.sent[0].url, "https://web.archive.org/save"); assert.match(keyed.sent[0].headers?.authorization ?? "", /^LOW /); assert.ok(!JSON.stringify(k).includes("FAKESECRET0001"), "the keys are in no result"); // An anonymous answer that watches a job: its status is polled, anonymously. const watched = stubClient([ () => ({ status: 200, text: `spn.watchJob("spn2-w1", "/_static/", 6000)` }), () => ({ status: 200, text: JSON.stringify({ status: "pending" }) }), () => ({ status: 200, text: JSON.stringify({ status: "success", timestamp: TS, original_url: PAGE }) }), ]); const w = await savePageNow({ paths, url: PAGE, settings: NO_KEYS, env: {}, pollMs: 1, deps: { client: watched, sleep: c.sleep } }); assert.equal(w.ok && w.spnJobId, "spn2-w1"); assert.equal(watched.sent[1].url, "https://web.archive.org/save/status/spn2-w1"); assert.equal(watched.sent[1].headers?.authorization, undefined); }); test("the pacer: one save at a time, ≥ 60 s apart anonymous (10 s with keys), a 429's Retry-After and the doubling rest", async () => { const c = clock(); const pacer = new SpnPacer({ now: c.now, sleep: c.sleep }); const order: string[] = []; const slow = (name: string) => async () => { order.push(`start ${name}`); await c.sleep(5_000); order.push(`end ${name}`); }; await Promise.all([pacer.turn("anonymous", slow("a")), pacer.turn("anonymous", slow("b"))]); assert.deepEqual(order, ["start a", "end a", "start b", "end b"], "never two at once"); assert.ok(c.sleeps.some((ms) => ms >= 60_000), "the second waited the anonymous gap"); assert.equal(pacer.gapMs("keys"), 10_000); // A 429 with Retry-After 300 s: the result says it rested, and the next save waits it out. const c2 = clock(); const p2 = new SpnPacer({ now: c2.now, sleep: c2.sleep }); const busy = stubClient([() => ({ status: 429, headers: { "retry-after": "300" } })]); const r = await savePageNow({ paths, url: PAGE, settings: NO_KEYS, env: {}, deps: { client: busy, sleep: c2.sleep, pacer: p2 } }); assert.equal(r.ok, false); assert.equal(r.rateLimited, true); assert.equal(r.restMs, 300_000); assert.ok(p2.resting()); const before = c2.now(); const ok = stubClient([() => ({ status: 200, headers: { "content-location": `/web/${TS}/${PAGE}` } })]); const r2 = await savePageNow({ paths, url: PAGE, settings: NO_KEYS, env: {}, deps: { client: ok, sleep: c2.sleep, pacer: p2 } }); assert.equal(r2.ok, true); assert.ok(c2.now() - before >= 299_000, "the next save waited out the Retry-After"); // No Retry-After: 2 min, then doubling. const c3 = clock(); const p3 = new SpnPacer({ now: c3.now, sleep: c3.sleep }); assert.equal(p3.rest(null), 120_000); assert.equal(p3.rest(null), 240_000); p3.saved(); assert.equal(p3.rest(null), 120_000, "a save starts the doubling over"); }); // The batch's world: a lookup table and a save stub. function batchDeps(o: { copies: Record; saves: ((url: string) => SavePageNowResult)[]; c: ReturnType; }): SpnBatchDeps & { looked: string[]; saved: string[] } { const looked: string[] = []; const saved: string[] = []; return { looked, saved, lookup: async (url) => { looked.push(url); return { url, found: 0, sources: o.copies[url] ?? [{ source: "wayback", label: "Wayback Machine", ok: true, captures: [] }] }; }, save: async (url) => { saved.push(url); const f = o.saves.shift(); return f ? f(url) : { ok: false, url, error: "no stub" }; }, pacer: { gapMs: () => 60_000, resting: () => null }, now: o.c.now, sleep: o.c.sleep, }; } const wbRow = (url: string, status: string, ts = "20250101000000") => ({ source: "wayback" as const, captureTs: ts, originalUrl: url, mementoUrl: `https://web.archive.org/web/${ts}/${url}`, status, mimetype: "text/html" }); test("the batch: archived already skipped (copy recorded), saved, failed; evidence JSON + CSV; resumed after a restart", async () => { const U = ["https://x.com/a/status/1", "https://x.com/a/status/2", "https://x.com/a/status/3", "https://x.com/a/status/4"]; const list = path.join(ROOT, "list.json"); writeFileSync(list, JSON.stringify([...U, U[0], "ftp://nope", `https://web.archive.org/web/2020/${U[0]}`])); const evidence = path.join(ROOT, "out", "evidence"); const planned = await planSpnBatch(paths, { file: list, evidence }, { settings: NO_KEYS, env: {} }); assert.ok(planned.ok); const plan = planned.ok ? planned.plan : (null as never); assert.equal(plan.mode, "anonymous"); assert.equal(plan.dailyCap, 150); assert.equal(plan.state.items.length, 4, "deduped; not-http and Wayback URLs left out"); assert.equal(plan.rejected.length, 2); const c = clock(); const copies = { [U[0]]: [ { source: "wayback" as const, label: "Wayback Machine", ok: true, captures: [wbRow(U[0], "302", "20240101000000"), wbRow(U[0], "200", "20250101000000")] }, { source: "archive.today" as const, label: "archive.today", ok: true, captures: [] }, ], // Only a redirect captured: not shown, so saved. [U[1]]: [{ source: "wayback" as const, label: "Wayback Machine", ok: true, captures: [wbRow(U[1], "302")] }], }; // Run 1: U0 archived already; U1 saved; then a "crash" (the save throws) on U2. const d1 = batchDeps({ copies, c, saves: [ (url) => ({ ok: true, url, mode: "anonymous", captureTs: TS, originalUrl: url, waybackUrl: `https://web.archive.org/web/${TS}/${url}` }), () => { throw new Error("process went away"); }, ], }); await assert.rejects(runSpnBatch({ plan, deps: d1 }), /process went away/); assert.deepEqual(d1.saved, [U[1], U[2]]); // Run 2, after the "restart": the state is read back; U0, U1 are not asked again. const replanned = await planSpnBatch(paths, { batch: plan.id }, { settings: NO_KEYS, env: {} }); assert.ok(replanned.ok); const plan2 = replanned.ok ? replanned.plan : (null as never); assert.equal(plan2.resumed, true); assert.equal(plan2.state.evidence.json, `${evidence}.json`, "the evidence path is kept"); const d2 = batchDeps({ copies, c, saves: [ (url) => ({ ok: true, url, mode: "anonymous", captureTs: TS, originalUrl: url, waybackUrl: `https://web.archive.org/web/${TS}/${url}` }), (url) => ({ ok: false, url, mode: "anonymous", code: "error:blocked-url", error: "Save Page Now refused the capture (HTTP 200, error:blocked-url)" }), ], }); const progress: string[] = []; const r = await runSpnBatch({ plan: plan2, deps: d2, onProgress: (p) => progress.push(`${p.done}/${p.total}`) }); assert.deepEqual(d2.saved, [U[2], U[3]], "only the pending URLs"); assert.ok(!d2.looked.includes(U[0]) && !d2.looked.includes(U[1]), "nothing looked up twice"); assert.deepEqual(r.counts, { total: 4, pending: 0, archivedAlready: 1, saved: 2, failed: 1 }); assert.equal(r.stopped, undefined); assert.ok(progress.includes("4/4")); const ev = JSON.parse(readFileSync(`${evidence}.json`, "utf8")) as { rows: ReturnType[] }; const byUrl = Object.fromEntries(ev.rows.map((row) => [row.url, row])); assert.equal(byUrl[U[0]].status, "archived-already"); assert.equal(byUrl[U[0]].waybackUrl, `https://web.archive.org/web/20250101000000/${U[0]}`, "the copy that recorded a 200"); assert.equal(byUrl[U[0]].waybackHttpStatus, "200"); assert.equal(byUrl[U[0]].shows, "yes"); assert.equal(byUrl[U[1]].status, "saved"); assert.equal(byUrl[U[1]].waybackUrl, `https://web.archive.org/web/${TS}/${U[1]}`); assert.equal(byUrl[U[1]].savedMode, "anonymous"); assert.equal(byUrl[U[3]].status, "failed"); assert.match(byUrl[U[3]].reason, /blocked-url/); const csv = readFileSync(`${evidence}.csv`, "utf8").trim().split("\n"); assert.equal(csv[0], "url,status,reason,waybackUrl,waybackCaptureTs,waybackHttpStatus,waybackMimetype,archiveTodayUrl,archiveTodayCaptureTs,shows,savedMode,checkedAt,doneAt"); assert.equal(csv.length, 5); assert.match(csv[4], /"Save Page Now refused the capture \(HTTP 200, error:blocked-url\)"/, "a reason with a comma is quoted"); assert.equal(spnEvidenceCsv([]).trim().split("\n").length, 1); }); test("the batch rests on a 429 and asks the same URL again; stops after too many rests; respects the daily cap", async () => { const U = ["https://x.com/b/status/1", "https://x.com/b/status/2"]; const planned = await planSpnBatch(paths, { urls: U, skipArchived: false, dailyCap: 1 }, { settings: NO_KEYS, env: {} }); assert.ok(planned.ok); const plan = planned.ok ? planned.plan : (null as never); const c = clock(); const rl = (url: string): SavePageNowResult => ({ ok: false, url, rateLimited: true, restMs: 120_000, error: "archive.org answered HTTP 429; resting 2 min" }); const ok = (url: string): SavePageNowResult => ({ ok: true, url, captureTs: TS, originalUrl: url, waybackUrl: `https://web.archive.org/web/${TS}/${url}` }); const d = batchDeps({ copies: {}, c, saves: [rl, ok, ok] }); const r = await runSpnBatch({ plan, deps: d }); assert.deepEqual(d.saved, [U[0], U[0], U[1]], "the rested URL asked again, then the next"); assert.deepEqual(d.looked, [], "skipArchived: false asks no lookup"); assert.equal(r.counts.saved, 2); assert.ok(c.sleeps.some((ms) => ms >= 23 * 60 * 60 * 1000), "the daily cap (1) waited out the 24 h window"); const planned2 = await planSpnBatch(paths, { urls: ["https://x.com/b/status/9"], skipArchived: false }, { settings: NO_KEYS, env: {} }); const plan2 = planned2.ok ? planned2.plan : (null as never); const d2 = batchDeps({ copies: {}, c, saves: Array.from({ length: 10 }, () => rl) }); const r2 = await runSpnBatch({ plan: plan2, deps: d2 }); assert.match(r2.stopped ?? "", /kept asking us to slow down/); assert.equal(r2.counts.pending, 1, "the URL stays pending for the next run"); // Refusals before a job. const bad = await planSpnBatch(paths, { urls: ["ftp://x"] }, { settings: NO_KEYS, env: {} }); assert.match(bad.ok ? "" : bad.error, /no http\(s\) URLs/); const cap = await planSpnBatch(paths, { urls: U, dailyCap: 500 }, { settings: NO_KEYS, env: {} }); assert.match(cap.ok ? "" : cap.error, /at most 200 without keys/); const keyed = await planSpnBatch(paths, { urls: U, dailyCap: 500 }, { settings: NO_KEYS, env: KEYS_ENV }); assert.equal(keyed.ok && keyed.plan.mode, "keys"); const rel = await planSpnBatch(paths, { urls: U, evidence: "relative/path" }, { settings: NO_KEYS, env: {} }); assert.match(rel.ok ? "" : rel.error, /absolute path/); const none = await planSpnBatch(paths, { batch: "spn-000000000000" }, { settings: NO_KEYS, env: {} }); assert.match(none.ok ? "" : none.error, /no batch spn-000000000000/); }); test("a site Save Page Now refuses (the live x.com answer) is asked once; its other URLs are looked up, not saved", async () => { const U = ["https://x.com/d/status/1", "https://x.com/d/status/2", "https://blog.example/p"]; const planned = await planSpnBatch(paths, { urls: U }, { settings: NO_KEYS, env: {} }); const plan = planned.ok ? planned.plan : (null as never); const c = clock(); const page = "Wayback Machine

Sorry We\u2019re currently facing some limitations when it comes to archiving this site.

"; const answer = parseSpnAnonymous({ status: 523, header: () => null, text: page }); assert.equal(answer.state === "error" && answer.code, "host-limited"); const d = batchDeps({ copies: {}, c, saves: [ (url) => ({ ok: false, url, code: "host-limited", error: answer.state === "error" ? answer.error : "" }), (url) => ({ ok: true, url, captureTs: TS, originalUrl: url, waybackUrl: `https://web.archive.org/web/${TS}/${url}` }), ], }); const r = await runSpnBatch({ plan, deps: d }); assert.deepEqual(d.saved, [U[0], U[2]], "x.com asked once; the other host still saved"); assert.deepEqual(d.looked, U, "every URL still looked up"); assert.equal(r.counts.failed, 2); assert.match(plan.state.items[1].reason ?? "", /^not asked: Save Page Now refuses x\.com as a site/); }); test("archive.today refusing a check is left out for the rest of the run, never pressed", async () => { const U = ["https://x.com/c/status/1", "https://x.com/c/status/2"]; const planned = await planSpnBatch(paths, { urls: U }, { settings: NO_KEYS, env: {} }); const plan = planned.ok ? planned.plan : (null as never); const c = clock(); const asked: string[][] = []; const d = batchDeps({ copies: {}, c, saves: [] }); d.lookup = async (url, o) => { asked.push([...o.sources]); return { url, found: 1, sources: [ { source: "wayback", label: "Wayback Machine", ok: true, captures: [wbRow(url, "200")] }, ...(o.sources.includes("archive.today") ? [{ source: "archive.today" as const, label: "archive.today", ok: false, captures: [], refusal: "challenge" as const, error: "a check" }] : []), ], }; }; const r = await runSpnBatch({ plan, deps: d }); assert.deepEqual(asked, [["wayback", "archive.today"], ["wayback"]]); assert.equal(r.counts.archivedAlready, 2); });