// The Wayback pages scan end to end over a temp corpus and the fake Wayback // (common/testing/web/fakeWayback.mjs, its scan listing): paged with the // resume key across two runs, the row cap, collapse by digest, the filters, // a second pass that asks only from before the first began and marks what it // added, a refusal that keeps the resume key, the dry run that asks nothing, // and the refusals before any job. No real archive.org. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/waybackScan.test.ts import { test, after } from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; const ROOT = await mkdtemp(path.join(os.tmpdir(), "wayback-scan-")); process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); const { getPaths } = await import("../lib/paths"); const { WaybackClient } = await import("../lib/waybackClient"); const { startFakeWayback, SCAN_CAPTURES } = await import("../testing/web/fakeWayback.mjs"); const { runWaybackScan, startWaybackScanJob, parseWaybackScanBody, WAYBACK_QUEUE } = await import("./waybackScan"); const { readWaybackScan } = await import("../lib/waybackPages/scanFile-server"); const { isNewRow } = await import("../lib/waybackPages/scanFile"); const { getRegistry } = await import("../jobs/registry"); const wb = await startFakeWayback({ captures: SCAN_CAPTURES }); // A job's end still writes after its status reads done (its log and sidecar, // and the report regeneration it arms in the channel dir): waited for before // the corpus is removed (testing/jobs/quiesce.ts). const { quiesceJobs } = await import("../testing/jobs/quiesce"); after(async () => { await quiesceJobs(); await wb.close(); await rm(ROOT, { recursive: true, force: true }); }); const client = () => new WaybackClient({ fetch: wb.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 1 }); async function channel(slug: string, wayback: unknown) { const dir = path.join(getPaths().channelsDir, slug); await mkdir(dir, { recursive: true }); await writeFile( path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", name: slug, url: "https://web.archive.org/web/*/blog.example*", wayback }), ); } const scanRequests = () => wb.requests.filter((r: { path: string }) => r.path.includes("showResumeKey=true")); test("paged with the resume key across two runs under a row cap; collapsed by digest; assets, 404s and images left out", async () => { await channel("blog", { targets: [{ url: "blog.example", match: "host" }] }); const paths = getPaths(); const wayback = { targets: [{ url: "blog.example", match: "host" as const }], collapse: "digest" as const, auto: false }; const before = scanRequests().length; const first = await runWaybackScan({ paths, slug: "blog", wayback, maxRows: 4, client: client() }); assert.equal(first.ok, true); assert.equal(first.complete, false); assert.equal(first.stopped, "row cap"); assert.equal(first.rowsRead, 4); assert.equal(first.requests, 1); const file1 = (await readWaybackScan(paths.channelsDir, "blog"))!; assert.equal(file1.targets[0].resumeKey, "fake-4"); assert.equal(file1.targets[0].complete, false); const second = await runWaybackScan({ paths, slug: "blog", wayback, maxRows: 100, client: client() }); assert.equal(second.complete, true); assert.equal(second.newPass, false, "the same pass, continued"); const asked = scanRequests().slice(before).map((r: { path: string }) => new URL(r.path, "http://x").searchParams); assert.equal(asked.length, 2); assert.equal(asked[0].get("resumeKey"), null); assert.equal(asked[0].get("limit"), "4"); assert.equal(asked[1].get("resumeKey"), "fake-4"); assert.equal(asked[1].get("matchType"), "host"); const file = (await readWaybackScan(paths.channelsDir, "blog"))!; const keys = file.rows.map((r) => `${r.originalUrl} ${r.digest}`); assert.deepEqual(keys, [ "https://blog.example/ HOMEA", "https://blog.example/ HOMEB", "https://blog.example/post/101/first-post P101A", "https://blog.example/post/101/first-post P101B", "https://blog.example/post/102/second-post P102A", "https://blog.example/post/103/third-post P103A", "https://blog.example/tagged/bread TAGA", ], "the css (served as text/html) dropped by extension, the png by mime, the 404 by status, about. by host"); const home = file.rows.find((r) => r.digest === "HOMEA")!; assert.deepEqual([home.firstTs, home.lastTs, home.count], ["20140102030405", "20140102030405", 1], "the June capture of the same content collapsed away"); assert.equal(file.summary.pages, 5); assert.deepEqual(file.summary.byYear, { "2014": 3, "2015": 4 }); assert.equal(file.targets[0].complete, true); assert.equal(file.targets[0].resumeKey, undefined); assert.ok(file.lastScanAt); assert.equal(file.rows.some((r) => isNewRow(file, r)), false, "nothing is new on the first pass"); }); test("a later pass asks from 30 days before the last began, merges, and marks only what it added", async () => { const paths = getPaths(); const wayback = { targets: [{ url: "blog.example", match: "host" as const }], collapse: "digest" as const, auto: false }; const firstPassStart = (await readWaybackScan(paths.channelsDir, "blog"))!.passStartedAt; // A new capture of a new post appears. SCAN_CAPTURES.push({ original: "https://blog.example/post/104/fourth", timestamp: "20991231000000", statuscode: "200", mimetype: "text/html", digest: "P104A" }); try { const before = scanRequests().length; const run = await runWaybackScan({ paths, slug: "blog", wayback, client: client(), now: () => new Date(Date.parse(firstPassStart) + 86_400_000) }); assert.equal(run.newPass, true); assert.equal(run.pass, 2); assert.equal(run.added, 1); const asked = new URL(scanRequests().slice(before)[0].path, "http://x").searchParams; const from = asked.get("from")!; assert.match(from, /^\d{14}$/); assert.ok(Date.parse(firstPassStart) - Date.UTC(+from.slice(0, 4), +from.slice(4, 6) - 1, +from.slice(6, 8)) >= 29 * 86_400_000); const file = (await readWaybackScan(paths.channelsDir, "blog"))!; assert.equal(file.previousPassStartedAt, firstPassStart); const fresh = file.rows.filter((r) => isNewRow(file, r)).map((r) => r.digest); assert.deepEqual(fresh, ["P104A"]); assert.equal(file.rows.length, 8); } finally { SCAN_CAPTURES.pop(); } }); test("include/exclude per target; a domain target; several targets in one run", async () => { const paths = getPaths(); const targets = [ { url: "blog.example", match: "domain" as const, include: "/post/|about\\.", exclude: "/post/102/" }, { url: "https://blog.example/tagged/", match: "prefix" as const }, ]; await channel("blog-two", { targets }); const run = await runWaybackScan({ paths, slug: "blog-two", wayback: { targets, collapse: "digest", auto: false }, client: client() }); assert.equal(run.complete, true); assert.equal(run.targets.length, 2); const file = (await readWaybackScan(paths.channelsDir, "blog-two"))!; assert.deepEqual( file.rows.map((r) => r.digest).sort(), ["ABOUTA", "P101A", "P101B", "P103A", "TAGA"], ); }); test("a refusal stops the run, keeps the resume key and what it had; the next run continues", async () => { const paths = getPaths(); const targets = [{ url: "blog.example", match: "host" as const }]; const wayback = { targets, collapse: "digest" as const, auto: false }; await channel("blog-refused", { targets }); // Pages of 3 rows, so the listing takes several requests. const paged = (c: InstanceType) => ({ cdxPage: (u: string, o?: { signal?: AbortSignal }) => c.cdxPage(u.replace(/limit=\d+/, "limit=3"), o), }); const refusing = await startFakeWayback({ captures: SCAN_CAPTURES, scanRefuseFrom: 2 }); try { const c = new WaybackClient({ fetch: refusing.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 2 }); const cut = await runWaybackScan({ paths, slug: "blog-refused", wayback, client: paged(c) }); assert.equal(cut.ok, false); assert.match(cut.error ?? "", /did not answer .* after 2 attempts/); assert.equal(cut.stopped, cut.error); assert.equal(cut.rowsRead, 3); const file = (await readWaybackScan(paths.channelsDir, "blog-refused"))!; assert.equal(file.rows.length, 3, "the first page kept"); assert.equal(file.targets[0].resumeKey, "fake-3"); assert.equal(file.targets[0].complete, false); } finally { await refusing.close(); } const before = scanRequests().length; const next = await runWaybackScan({ paths, slug: "blog-refused", wayback, client: paged(client()) }); assert.equal(next.ok, true); assert.equal(next.complete, true); assert.equal(new URL(scanRequests()[before].path, "http://x").searchParams.get("resumeKey"), "fake-3"); assert.equal((await readWaybackScan(paths.channelsDir, "blog-refused"))!.rows.length, 7); }); test("a dry run asks nothing and writes nothing, and says what the next run would ask", async () => { const paths = getPaths(); const targets = [{ url: "dry.example", match: "prefix" as const, from: "2014" }]; await channel("dry", { targets }); const before = wb.requests.length; const run = await runWaybackScan({ paths, slug: "dry", wayback: { targets, collapse: "digest", auto: false }, client: client(), dryRun: true }); assert.equal(wb.requests.length, before); assert.equal(run.dryRun, true); assert.equal(run.requests, 0); assert.match(run.targets[0].next ?? "", /^https:\/\/web\.archive\.org\/cdx\/search\/cdx\?url=dry\.example&matchType=prefix/); assert.equal(await readWaybackScan(paths.channelsDir, "dry"), null); }); test("the body and the job: refused before any job for a channel that is not a Wayback pages channel; the job runs on archive.org's queue", async () => { assert.throws(() => parseWaybackScanBody({}), /slug/); assert.throws(() => parseWaybackScanBody({ slug: "../x" }), /not a channel slug/); assert.throws(() => parseWaybackScanBody({ slug: "x", maxRows: 0 }), /maxRows/); assert.throws(() => parseWaybackScanBody({ slug: "x", dryRun: "yes" }), /dryRun/); assert.deepEqual(parseWaybackScanBody({ slug: "x" }), { slug: "x", dryRun: false, maxRows: 50000, full: false }); const paths = getPaths(); const none = await startWaybackScanJob({ slug: "no-such" }, { paths }); assert.equal(none.ok, false); const dir = path.join(paths.channelsDir, "plain"); await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", url: "https://www.youtube.com/@plain" })); const plain = await startWaybackScanJob({ slug: "plain" }, { paths }); assert.equal(plain.ok, false); assert.match(!plain.ok ? plain.error : "", /not a Wayback pages channel/); let done = ""; const job = await startWaybackScanJob({ slug: "blog", full: true }, { paths, client: client(), onDone: (s) => (done = s) }); assert.equal(job.ok, true); if (!job.ok) return; assert.equal(getRegistry().get(job.jobId)?.queueKey, WAYBACK_QUEUE); assert.equal(getRegistry().get(job.jobId)?.kind, "wayback-scan"); const end = await job.done; assert.equal(end.status, "done"); assert.equal(done, "blog"); const log = await readFile(getRegistry().get(job.jobId)!.logPath, "utf8"); const marker = log.split("\n").find((l) => l.startsWith("@@wayback-scan "))!; const result = JSON.parse(marker.slice("@@wayback-scan ".length)); assert.equal(result.pass, 3, "a full pass is a new pass"); assert.equal(result.complete, true); }); test("release 38 lane C: an excluded target is answered, not failed -- marked, and the next target goes on", async () => { const paths = getPaths(); const targets = [ { url: "gone.example", match: "host" as const }, { url: "blog.example", match: "host" as const }, ]; const wayback = { targets, collapse: "digest" as const, auto: false }; await channel("blog-excluded", { targets }); const fake = await startFakeWayback({ captures: SCAN_CAPTURES, excluded: ["gone.example"] }); try { const c = new WaybackClient({ fetch: fake.fetch, sleep: async () => {} }, { minGapMs: 0, maxAttempts: 2 }); const lines: string[] = []; const run = await runWaybackScan({ paths, slug: "blog-excluded", wayback, client: c, onLog: (l) => lines.push(l) }); assert.equal(run.ok, true, run.error); assert.equal(run.stopped, undefined); assert.deepEqual(run.excluded, ["gone.example"]); const [gone, blog] = run.targets; assert.equal(gone.refusal, "excluded"); assert.match(gone.error ?? "", /excluded from the Wayback Machine \(cause unknown\)/); assert.equal(gone.complete, true); assert.equal(gone.rows, 0); assert.equal(blog.refusal, undefined); assert.ok(blog.rows > 0, "the next target was listed"); assert.ok(lines.some((l) => /excluded from the Wayback Machine \(cause unknown\)/.test(l)), "the log says so"); const file = (await readWaybackScan(paths.channelsDir, "blog-excluded"))!; assert.equal(file.targets[0].excluded, "excluded from the Wayback Machine (cause unknown)"); // A new pass asks again: the mark is cleared when the pass starts. const full = await runWaybackScan({ paths, slug: "blog-excluded", wayback, client: c, full: true }); assert.deepEqual(full.excluded, ["gone.example"]); } finally { await fake.close(); } });