Archilyzer · Source

archilyzer

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

commit 6ca8b210cfee5cbe20de6ac4104fb1946b1a008c
parent 2436ad41311b6419487a524cf1cb7f956abb0fc1
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 20 Oct 2026 09:23:01 -0400

wayback pages: the scan — CDX over a channel's targets, paged and resumable, into wayback-scan.json

`wayback-scan` (controller/waybackScan.ts): every target of `config.wayback`
listed through the Wayback client's paced chain (`WaybackClient.cdxPage`),
matchType per target, status 200, the target's mimes, collapse=digest, date
bounds, pages of 5,000 with showResumeKey, at most maxRows (50,000) a run; a
cut run keeps each target's resume key, a later pass asks from 30 days before
the last began. No bodies. `channels/<slug>/wayback-scan.json`
(lib/waybackPages/scanFile.ts): one row per (URL, digest), summaries by year
and path prefix, rows new since the previous pass. Imported state derived
from the channel's webpage records (imported.ts). The fake Wayback's scan
listing in its own block. A job kind on `platform:archive.org`, drainable,
text-guarded.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Acommon/controller/waybackScan.test.ts | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/waybackScan.ts | 380+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobKinds.test.ts | 5++++-
Mcommon/jobs/jobKinds.ts | 15+++++++++++++++
Mcommon/lib/waybackClient.ts | 9+++++++++
Acommon/lib/waybackPages/imported.ts | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/origin.ts | 29+++++++++++++++++++++++++++++
Acommon/lib/waybackPages/scan.test.ts | 198+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/scanCdx.ts | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/scanFile-server.ts | 43+++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/scanFile.ts | 260+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/targets.ts | 157+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/testing/web/fakeWayback.d.mts | 15++++++++++++++-
Mcommon/testing/web/fakeWayback.mjs | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
14 files changed, 1601 insertions(+), 2 deletions(-)

diff --git a/common/controller/waybackScan.test.ts b/common/controller/waybackScan.test.ts @@ -0,0 +1,207 @@ +// 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 }); +after(async () => { + 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<typeof WaybackClient>) => ({ + 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); +}); diff --git a/common/controller/waybackScan.ts b/common/controller/waybackScan.ts @@ -0,0 +1,380 @@ +// THE WAYBACK PAGES SCAN (release 37 S2): which captures the Wayback Machine +// holds of a Wayback pages channel's targets (`config.wayback.targets`), as +// `channels/<slug>/wayback-scan.json` (lib/waybackPages/scanFile.ts) — a +// `wayback-scan` job, `pnpm ops wayback-scan {slug, dryRun?, maxRows?, full?}`, +// `archilyzer wayback scan <slug>`, the channel page's Captures tab. +// +// LISTINGS ONLY. A scan asks the CDX API and never fetches a capture's body; +// `import-page` does that, one capture per job. Every request goes through the +// Wayback client's paced ArchiveOrgClient (one at a time, a 2 s gap, 429/503 +// waited out), on the `platform:archive.org` queue, and a run reads at most +// `maxRows` CDX rows (50,000) in pages of 5,000. A run that stops before a +// target's end (the cap, a refusal, a drain, a cancel) keeps the target's +// resume key, and the next run continues from it. Once every target is complete +// the next run starts a new pass, which asks only from 30 days before the +// previous pass began (scanFile.ts). `full` starts a new pass from each target's +// own start. +// +// A refusal (archive.org kept answering 429/503, or answered an error) stops the +// run with what it had written, and the job fails with the reason. +// +// A dry run asks nothing and writes nothing: it says, per target, what the next +// run would ask for. + +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { readJsonFile } from "../lib/jsonFile-server"; +import { isSafeChannelSegment } from "../lib/citations/moments"; +import { ArchiveOrgRequestError } from "../lib/archiveOrgClient"; +import { waybackClient } from "../lib/waybackClient"; +import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; +import { waybackOrigin } from "../lib/waybackPages/origin"; +import { + keepCaptureUrl, + waybackConfigOf, + waybackTargetKey, + type WaybackChannelConfig, + type WaybackTarget, +} from "../lib/waybackPages/targets"; +import { + CDX_PAGE_ROWS, + DEFAULT_SCAN_MAX_ROWS, + parseScanCdxPage, + SCAN_MAX_ROWS_LIMIT, + scanCdxUrl, +} from "../lib/waybackPages/scanCdx"; +import { + cdxTsBefore, + emptyScanFile, + indexScanRows, + mergeCdxRows, + PASS_OVERLAP_DAYS, + sortScanRows, + summarizeScan, + type WaybackScanFile, + type WaybackScanTarget, +} from "../lib/waybackPages/scanFile"; +import { readWaybackScan, writeWaybackScan } from "../lib/waybackPages/scanFile-server"; +import { channelConfigPath } from "./channels"; + +export const WAYBACK_SCAN_JOB_KIND = "wayback-scan"; +// archive.org's own queue for Wayback work: a scan, and every `import-page`, +// run one at a time on it. +export const WAYBACK_QUEUE = "platform:archive.org"; +export const WAYBACK_SCAN_RESULT_MARKER = "@@wayback-scan "; +export const WAYBACK_SCAN_BODY_KEYS = ["slug", "dryRun", "maxRows", "full"] as const; + +// A run never sends more CDX requests than this, whatever the pages hold (a +// listing that answers resume keys with no rows must not spin). +export const SCAN_MAX_REQUESTS = 100; + +export type CdxPager = { cdxPage(url: string, o?: { signal?: AbortSignal }): Promise<string> }; + +export type WaybackScanBody = { + slug: string; + dryRun: boolean; + maxRows: number; + full: boolean; +}; + +export function parseWaybackScanBody(raw: Record<string, unknown>): WaybackScanBody { + const slug = typeof raw.slug === "string" ? raw.slug.trim() : ""; + if (!slug) throw new Error('"slug" is required: the Wayback pages channel'); + if (!isSafeChannelSegment(slug)) throw new Error(`not a channel slug: ${JSON.stringify(slug)}`); + for (const k of ["dryRun", "full"] as const) { + if (raw[k] !== undefined && typeof raw[k] !== "boolean") throw new Error(`"${k}" must be true or false`); + } + let maxRows = DEFAULT_SCAN_MAX_ROWS; + if (raw.maxRows !== undefined) { + if (typeof raw.maxRows !== "number" || !Number.isInteger(raw.maxRows) || raw.maxRows < 1 || raw.maxRows > SCAN_MAX_ROWS_LIMIT) { + throw new Error(`"maxRows" must be a whole number from 1 to ${SCAN_MAX_ROWS_LIMIT}`); + } + maxRows = raw.maxRows; + } + return { slug, dryRun: raw.dryRun === true, maxRows, full: raw.full === true }; +} + +// The channel's `config.wayback`, read from config.json as it is on disk. +export async function readWaybackChannelConfig(paths: Paths, slug: string): Promise<WaybackChannelConfig | null> { + const read = await readJsonFile(channelConfigPath(paths, slug)); + return read.ok ? waybackConfigOf(read.value) : null; +} + +// Why a channel cannot be scanned, or null. +export async function waybackScanRefusal(paths: Paths, slug: string): Promise<string | null> { + const read = await readJsonFile(channelConfigPath(paths, slug)); + if (!read.ok) return `No channel "${slug}".`; + if (!waybackConfigOf(read.value)) { + return `${slug} is not a Wayback pages channel: its config names no wayback.targets.`; + } + return null; +} + +export type WaybackScanTargetReport = { + url: string; + match: string; + requests: number; + rows: number; + added: number; + complete: boolean; + resumeKey?: string; + // A dry run: what the next request for this target would be. + next?: string; +}; + +export type WaybackScanResult = { + ok: boolean; + slug: string; + dryRun: boolean; + pass: number; + newPass: boolean; + targets: WaybackScanTargetReport[]; + requests: number; + rowsRead: number; + added: number; + totalRows: number; + complete: boolean; + // Why the run stopped before every target's end: "row cap", "drained", + // "cancelled", "request cap", or the refusal. + stopped?: string; + error?: string; + path?: string; +}; + +export type RunWaybackScanOpts = { + paths: Paths; + slug: string; + wayback: WaybackChannelConfig; + dryRun?: boolean; + maxRows?: number; + full?: boolean; + client?: CdxPager; + origin?: string; + now?: () => Date; + jobId?: string; + onLog?: (line: string) => void; + signal?: AbortSignal; + drainSignal?: AbortSignal; +}; + +// Line the file's targets up with the config's: a known target keeps its +// state, a new one starts incomplete, one the config no longer names is +// dropped (its rows stay). +export function reconcileTargets(file: WaybackScanFile, targets: ReadonlyArray<WaybackTarget>): void { + const byKey = new Map(file.targets.map((t) => [t.key, t])); + file.targets = targets.map((t) => { + const key = waybackTargetKey(t); + return ( + byKey.get(key) ?? { + key, + url: t.url, + match: t.match, + ...(t.from ? { from: t.from } : {}), + ...(t.to ? { to: t.to } : {}), + complete: false, + rows: 0, + } + ); + }); +} + +// Start a new pass (mutates): every target from its start — or, `incremental`, +// from PASS_OVERLAP_DAYS before the pass that just ended began. +export function startPass(file: WaybackScanFile, nowIso: string, incremental: boolean): void { + const previous = file.passStartedAt; + const fresh = file.rows.length === 0 && file.targets.every((t) => t.rows === 0 && !t.complete); + if (!fresh) { + file.pass += 1; + file.previousPassStartedAt = previous; + } + file.passStartedAt = nowIso; + const passFrom = incremental && !fresh ? cdxTsBefore(previous, PASS_OVERLAP_DAYS) : undefined; + file.targets = file.targets.map((t): WaybackScanTarget => { + const { resumeKey: _r, completedAt: _c, passFrom: _p, ...rest } = t; + return { ...rest, complete: false, rows: 0, ...(passFrom ? { passFrom } : {}) }; + }); +} + +export async function runWaybackScan(opts: RunWaybackScanOpts): Promise<WaybackScanResult> { + const log = (l: string) => opts.onLog?.(l); + const now = opts.now ?? (() => new Date()); + const client = opts.client ?? waybackClient; + const origin = opts.origin ?? waybackOrigin(); + const maxRows = Math.max(1, Math.min(opts.maxRows ?? DEFAULT_SCAN_MAX_ROWS, SCAN_MAX_ROWS_LIMIT)); + const channelsDir = opts.paths.channelsDir; + + const file = (await readWaybackScan(channelsDir, opts.slug)) ?? emptyScanFile(opts.slug, now().toISOString()); + reconcileTargets(file, opts.wayback.targets); + let newPass = false; + if (opts.full) { + startPass(file, now().toISOString(), false); + newPass = true; + } else if (file.targets.length > 0 && file.targets.every((t) => t.complete)) { + startPass(file, now().toISOString(), true); + newPass = true; + } + const configByKey = new Map(opts.wayback.targets.map((t) => [waybackTargetKey(t), t])); + const reports = new Map<string, WaybackScanTargetReport>( + file.targets.map((t) => [ + t.key, + { url: t.url, match: t.match, requests: 0, rows: 0, added: 0, complete: t.complete, ...(t.resumeKey ? { resumeKey: t.resumeKey } : {}) }, + ]), + ); + const result = (extra: Partial<WaybackScanResult> = {}): WaybackScanResult => ({ + ok: true, + slug: opts.slug, + dryRun: opts.dryRun === true, + pass: file.pass, + newPass, + targets: [...reports.values()], + requests: [...reports.values()].reduce((n, r) => n + r.requests, 0), + rowsRead: [...reports.values()].reduce((n, r) => n + r.rows, 0), + added: [...reports.values()].reduce((n, r) => n + r.added, 0), + totalRows: file.rows.length, + complete: file.targets.every((t) => t.complete), + ...extra, + }); + + if (opts.dryRun) { + for (const t of file.targets) { + const target = configByKey.get(t.key)!; + const r = reports.get(t.key)!; + if (!t.complete) { + r.next = scanCdxUrl({ target, limit: Math.min(CDX_PAGE_ROWS, maxRows), ...(t.resumeKey ? { resumeKey: t.resumeKey } : {}), ...(t.passFrom ? { from: t.passFrom } : {}) }, origin); + } + log(`${t.match} ${t.url}: ${t.complete ? "complete this pass" : `would ask ${r.next}`}`); + } + return result(); + } + + const index = indexScanRows(file); + let remaining = maxRows; + let requests = 0; + let stopped: string | undefined; + let error: string | undefined; + let written: string | undefined; + const flush = async () => { + const at = now().toISOString(); + file.lastScanAt = at; + if (opts.jobId) file.jobId = opts.jobId; + sortScanRows(file.rows); + file.summary = summarizeScan(file.rows); + written = await writeWaybackScan(channelsDir, file); + }; + + outer: for (const t of file.targets) { + if (t.complete) continue; + const target = configByKey.get(t.key)!; + const r = reports.get(t.key)!; + log(`${t.match} ${t.url}${t.resumeKey ? " (continuing from its resume key)" : ""}${t.passFrom ? ` — captures from ${t.passFrom.slice(0, 8)}` : ""}`); + while (!t.complete) { + if (opts.signal?.aborted) { stopped = "cancelled"; break outer; } + if (opts.drainSignal?.aborted) { stopped = "drained"; break outer; } + if (remaining <= 0) { stopped = "row cap"; break outer; } + if (requests >= SCAN_MAX_REQUESTS) { stopped = "request cap"; break outer; } + const url = scanCdxUrl({ target, limit: Math.min(CDX_PAGE_ROWS, remaining), ...(t.resumeKey ? { resumeKey: t.resumeKey } : {}), ...(t.passFrom ? { from: t.passFrom } : {}) }, origin); + let body: string; + requests++; + r.requests++; + try { + body = await client.cdxPage(url, opts.signal ? { signal: opts.signal } : {}); + } catch (e) { + if (opts.signal?.aborted) { stopped = "cancelled"; break outer; } + error = e instanceof ArchiveOrgRequestError ? e.message : `the CDX request failed: ${(e as Error).message}`; + stopped = error; + break outer; + } + let page; + try { + page = parseScanCdxPage(body); + } catch (e) { + error = `${(e as Error).message} for ${t.url}`; + stopped = error; + break outer; + } + const kept = page.rows.filter((row) => keepCaptureUrl(target, row.originalUrl)); + const added = mergeCdxRows(file, kept, index); + r.rows += page.rows.length; + r.added += added; + t.rows += page.rows.length; + remaining -= page.rows.length; + t.lastScanAt = now().toISOString(); + const stalled = page.rows.length === 0 && page.resumeKey !== undefined && page.resumeKey === t.resumeKey; + if (page.resumeKey && !stalled) { + t.resumeKey = page.resumeKey; + } else { + delete t.resumeKey; + t.complete = true; + t.completedAt = t.lastScanAt; + } + r.complete = t.complete; + if (t.resumeKey) r.resumeKey = t.resumeKey; + else delete r.resumeKey; + log(` ${page.rows.length} rows, ${kept.length} kept, ${added} new${t.complete ? " — complete" : " — continues"}`); + await flush(); + } + } + if (!written) await flush(); + const out = result({ ...(stopped ? { stopped } : {}), ...(written ? { path: written } : {}) }); + if (error) return { ...out, ok: false, error }; + return out; +} + +// What the `@@wayback-scan` line says (the targets without dry-run URLs only +// when there are many). +export function waybackScanSummary(r: WaybackScanResult): WaybackScanResult { + const { path: _p, ...rest } = r; + return rest; +} + +// Enqueue a `wayback-scan` job (refused before any job for a channel that is +// not a Wayback pages channel). `onDone` runs after a run that wrote its file +// (the editor revalidates the channel page there). +export async function startWaybackScanJob( + raw: Record<string, unknown>, + deps: { paths: Paths; onDone?: (slug: string) => void; client?: CdxPager; now?: () => Date; background?: boolean }, +): Promise<StreamActionResult> { + let body: WaybackScanBody; + try { + body = parseWaybackScanBody(raw); + } catch (e) { + return { ok: false, error: (e as Error).message }; + } + const refusal = await waybackScanRefusal(deps.paths, body.slug); + if (refusal) return { ok: false, error: refusal }; + return runManagedFunction({ + kind: WAYBACK_SCAN_JOB_KIND, + queueKey: WAYBACK_QUEUE, + paths: deps.paths, + channelSlug: body.slug, + ...(deps.background ? { background: true } : {}), + fn: async (onLog, signal, _setProgress, ctx) => { + const wayback = await readWaybackChannelConfig(deps.paths, body.slug); + if (!wayback) throw new Error(`${body.slug} is not a Wayback pages channel: its config names no wayback.targets.`); + onLog(`Wayback scan of ${body.slug}${body.dryRun ? " (dry run: nothing is asked or written)" : ""}${body.full ? " (a full pass)" : ""}`); + const out = await runWaybackScan({ + paths: deps.paths, + slug: body.slug, + wayback, + dryRun: body.dryRun, + maxRows: body.maxRows, + full: body.full, + jobId: ctx.jobId, + onLog, + signal, + drainSignal: ctx.drainSignal, + ...(deps.client ? { client: deps.client } : {}), + ...(deps.now ? { now: deps.now } : {}), + }); + onLog( + `pass ${out.pass}${out.newPass ? " (new)" : ""}: ${out.requests} request${out.requests === 1 ? "" : "s"}, ` + + `${out.rowsRead} rows read, ${out.added} new, ${out.totalRows} in the scan` + + (out.complete ? " — every target complete" : out.stopped ? ` — stopped: ${out.stopped}` : ""), + ); + if (out.path) onLog(`wrote ${path.relative(deps.paths.transcriptsDir, out.path)}`); + onLog(`${WAYBACK_SCAN_RESULT_MARKER}${JSON.stringify(waybackScanSummary(out))}`); + if (out.path) deps.onDone?.(body.slug); + if (!out.ok) throw new Error(out.error ?? "the Wayback scan stopped"); + }, + }); +} diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts @@ -109,6 +109,8 @@ const ADDED_KINDS: Record<string, { label: string; drainable: boolean }> = { "fetch-copies": { label: "Fetch copies", drainable: true }, // An article's own video (release 32): one remux or encode. "attach-report-video": { label: "Attach article video", drainable: false }, + // A Wayback pages channel's CDX scan (release 37 S2). + "wayback-scan": { label: "Wayback scan", drainable: true }, }; test("added kinds carry their pinned label and drainability", () => { @@ -290,7 +292,8 @@ test("release 18: the kinds no longer created keep their labels (seven of them n test("release 18: every drainable kind but the lane runners and the clip-window batch is an ingest kind", () => { const runners = new Set(["auto-transcribe", "auto-download", "auto-digest", "auto-backfill", "auto-publish"]); // fetch-windows writes only `data/<id>/clips/`, a cache the index never reads. - const notIngest = new Set(["fetch-windows"]); + // wayback-scan writes only `wayback-scan.json`, which the index never reads. + const notIngest = new Set(["fetch-windows", "wayback-scan"]); for (const kind of jobKindIds()) { if (!isDrainableKind(kind) || runners.has(kind) || notIngest.has(kind)) continue; assert.equal(isIngestKind(kind), true, `${kind} is drainable and per channel: an ingest kind`); diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -606,6 +606,21 @@ const JOB_KINDS: Record<string, JobKindMeta> = { replayable: true, queueKeyStrategy: "platform", }, + // A WAYBACK PAGES CHANNEL'S SCAN (release 37 S2, controller/waybackScan.ts): + // the CDX listings of its targets into `wayback-scan.json`, no bodies, on + // archive.org's queue (`platform:archive.org`) beside every `import-page`. + // Drainable (it stops between pages and keeps the resume key); not an + // ingest kind — the index never reads the scan. Reads only the channel's + // own files, so the text guard covers it. + "wayback-scan": { + kind: "wayback-scan", + label: "Wayback scan", + drainable: true, + replayable: false, + queueKeyStrategy: "custom", + needsMedia: false, + needsText: true, + }, // The posts analogue of the video availability check: which archived posts // have since been deleted at the source. "check-post-availability": { diff --git a/common/lib/waybackClient.ts b/common/lib/waybackClient.ts @@ -207,6 +207,15 @@ export class WaybackClient { throw new ArchiveOrgRequestError(`${(e as Error).message} for ${url}`, null, false); } } + + // ONE PAGE OF A CDX LISTING the caller built (release 37 S2, the Wayback + // pages scan — lib/waybackPages/scanCdx.ts builds the URL and parses the + // answer): the body as text, through the same chain, gap and back-off. + // Throws ArchiveOrgRequestError when the API kept refusing or answered an + // error. + async cdxPage(cdxUrl: string, o: { signal?: AbortSignal } = {}): Promise<string> { + return this.http.getText(cdxUrl, "application/json", o.signal); + } } // THE process's Wayback client: one chain, one gap. diff --git a/common/lib/waybackPages/imported.ts b/common/lib/waybackPages/imported.ts @@ -0,0 +1,69 @@ +// WHICH SCAN ROWS ARE ALREADY IMPORTED (release 37 S2). Derived, never stored +// twice: a row of wayback-scan.json is imported when the channel holds a +// webpage record (a Post with `page`) of the same original URL whose capture is +// that content — the same digest, or, for a record that names no digest, a +// capture time inside the row's first..last seen. Pure, client-safe. + +import { normalHost, type WaybackScanRow } from "./scanFile"; + +// The `page` facts this needs (PagePostInfo's provenance half + digest). +export type ImportedPageFacts = { + originalUrl: string; + captureTs: string; + digest?: string; + waybackUrl?: string; +}; + +export type ImportedRecordRef = { + id: string; + captureTs: string; + waybackUrl?: string; +}; + +export type ImportedIndex = Map<string, Array<ImportedRecordRef & { digest?: string }>>; + +// One spelling per page the Wayback Machine treats as one: no scheme, the host +// lowercased without www. or a default port, path and query as captured. +export function pageUrlKey(url: string): string { + try { + const u = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(url) ? url : `http://${url}`); + return `${normalHost(u.host)}${u.pathname}${u.search}`; + } catch { + return url; + } +} + +export function buildImportedIndex( + posts: ReadonlyArray<{ id: string; page?: ImportedPageFacts | null }>, +): ImportedIndex { + const index: ImportedIndex = new Map(); + for (const p of posts) { + const page = p.page; + if (!page || typeof page.originalUrl !== "string" || typeof page.captureTs !== "string") continue; + const key = pageUrlKey(page.originalUrl); + const list = index.get(key) ?? []; + list.push({ + id: p.id, + captureTs: page.captureTs, + ...(page.digest ? { digest: page.digest } : {}), + ...(page.waybackUrl ? { waybackUrl: page.waybackUrl } : {}), + }); + index.set(key, list); + } + for (const list of index.values()) list.sort((a, b) => a.captureTs.localeCompare(b.captureTs) || a.id.localeCompare(b.id)); + return index; +} + +// The first record that holds this row's content, or null. +export function importedRecordOf( + row: Pick<WaybackScanRow, "originalUrl" | "digest" | "firstTs" | "lastTs">, + index: ImportedIndex, +): ImportedRecordRef | null { + const list = index.get(pageUrlKey(row.originalUrl)); + if (!list) return null; + for (const r of list) { + const hit = r.digest ? r.digest === row.digest : r.captureTs >= row.firstTs && r.captureTs <= row.lastTs; + if (hit) return { id: r.id, captureTs: r.captureTs, ...(r.waybackUrl ? { waybackUrl: r.waybackUrl } : {}) }; + } + return null; +} diff --git a/common/lib/waybackPages/origin.ts b/common/lib/waybackPages/origin.ts @@ -0,0 +1,29 @@ +// Where the Wayback Machine is, for the requests a Wayback pages job sends +// (release 37 S2). One place, so the editor's e2e server can put it on a fake. +// +// TEST-ONLY: E2E_WAYBACK_ORIGIN_FILE names a file holding ONE loopback origin +// (`http://127.0.0.1:<port>`). While that file exists, web.archive.org is that +// origin — the fake Wayback (common/testing/web/fakeWayback.mjs) a spec starts +// and names in the file. Read per call, so a spec can start its fake after the +// server booted. Anything but a loopback origin in it is ignored. Unset +// everywhere but the editor's e2e server; unit tests pass a fetch directly. +// SERVER-ONLY (node:fs). + +import { readFileSync } from "node:fs"; +import { WAYBACK_ORIGIN } from "../waybackClient"; + +const LOOPBACK_ORIGIN = /^http:\/\/(?:127\.0\.0\.1|localhost)(?::\d{1,5})?$/; + +export function waybackOrigin(env: Readonly<Record<string, string | undefined>> = process.env): string { + const file = env.E2E_WAYBACK_ORIGIN_FILE; + if (file) { + let origin = ""; + try { + origin = readFileSync(file, "utf8").trim().replace(/\/$/, ""); + } catch { + origin = ""; + } + if (LOOPBACK_ORIGIN.test(origin)) return origin; + } + return WAYBACK_ORIGIN; +} diff --git a/common/lib/waybackPages/scan.test.ts b/common/lib/waybackPages/scan.test.ts @@ -0,0 +1,198 @@ +// The Wayback pages scan's pure half (release 37 S2): the targets reader, the +// CDX URL per match type, the page parse with its resume key, the merge by +// (URL, digest), the asset/include/exclude filters, the summaries, and which +// rows are already imported. Synthetic URLs only. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackPages/scan.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + cdxUrlParam, + isAssetUrl, + keepCaptureUrl, + waybackConfigOf, + waybackTargetKey, + type WaybackTarget, +} from "./targets"; +import { parseScanCdxPage, scanCdxUrl } from "./scanCdx"; +import { + cdxTsBefore, + displayPathOf, + emptyScanFile, + isNewRow, + mergeCdxRows, + pathPrefixOf, + summarizeScan, +} from "./scanFile"; +import { buildImportedIndex, importedRecordOf, pageUrlKey } from "./imported"; + +test("the targets reader is tolerant: unknown keys ignored, bad targets dropped, defaults filled", () => { + assert.equal(waybackConfigOf({}), null); + assert.equal(waybackConfigOf({ wayback: { targets: [] } }), null); + assert.equal(waybackConfigOf({ wayback: { targets: [{ match: "host" }] } }), null); + const w = waybackConfigOf({ + handling: "transcribe", + wayback: { + targets: [ + { url: " blog.example ", match: "host", from: "2014", to: "20151231", mime: ["text/html", "image/png"], include: "/post/", exclude: "(" , other: 1 }, + { url: "https://example.org/a", match: "sideways", from: "14" }, + ], + collapse: "none", + auto: "yes", + extra: true, + }, + }); + assert.deepEqual(w, { + targets: [ + { url: "blog.example", match: "host", from: "2014", to: "20151231", mime: ["text/html"], include: "/post/" }, + { url: "https://example.org/a", match: "exact" }, + ], + collapse: "digest", + auto: false, + }); + assert.equal(waybackConfigOf({ wayback: { targets: [{ url: "x.example" }], auto: true } })?.auto, true); +}); + +test("a target's key changes with what it asks, not with its filters", () => { + const a: WaybackTarget = { url: "blog.example", match: "host" }; + assert.equal(waybackTargetKey(a), waybackTargetKey({ ...a, include: "/post/" })); + assert.notEqual(waybackTargetKey(a), waybackTargetKey({ ...a, from: "2014" })); + assert.notEqual(waybackTargetKey(a), waybackTargetKey({ ...a, match: "domain" })); +}); + +test("the CDX URL per match type: url, matchType, the 200 and mime filters, collapse, bounds, paging", () => { + const params = (t: WaybackTarget, extra: Partial<Parameters<typeof scanCdxUrl>[0]> = {}) => + new URL(scanCdxUrl({ target: t, limit: 5000, ...extra })).searchParams; + for (const match of ["exact", "prefix", "host", "domain"] as const) { + const url = match === "host" || match === "domain" ? "https://www.blog.example/whatever" : "https://blog.example/post/"; + const p = params({ url, match }); + assert.equal(p.get("matchType"), match); + assert.equal(p.get("url"), match === "host" || match === "domain" ? "www.blog.example" : url); + assert.deepEqual(p.getAll("filter"), ["statuscode:200", "mimetype:text\\/html"]); + assert.equal(p.get("collapse"), "digest"); + assert.equal(p.get("showResumeKey"), "true"); + assert.equal(p.get("output"), "json"); + assert.equal(p.get("limit"), "5000"); + assert.equal(p.get("resumeKey"), null); + } + assert.equal(cdxUrlParam({ url: "blog.example", match: "domain" }), "blog.example"); + const p = params( + { url: "blog.example", match: "host", from: "2014", to: "2015", mime: ["text/html", "text/plain", "application/json"] }, + { resumeKey: "abc 123", from: "20140601000000" }, + ); + assert.equal(p.getAll("filter")[1], "mimetype:text\\/html|text\\/plain|application\\/json"); + assert.equal(p.get("from"), "20140601000000", "the later of the target's from and the pass's"); + assert.equal(p.get("to"), "2015"); + assert.equal(p.get("resumeKey"), "abc 123"); + assert.equal(params({ url: "blog.example", match: "host", from: "2016" }, { from: "20140601000000" }).get("from"), "2016"); + assert.ok(scanCdxUrl({ target: { url: "a.example", match: "host" }, limit: 1 }).startsWith("https://web.archive.org/cdx/search/cdx?")); +}); + +test("a CDX page: rows by the header's columns, the resume key after an empty row, [] as none", () => { + assert.deepEqual(parseScanCdxPage(""), { rows: [] }); + assert.deepEqual(parseScanCdxPage("[]"), { rows: [] }); + const page = parseScanCdxPage( + JSON.stringify([ + ["original", "timestamp", "digest", "mimetype", "statuscode"], + ["https://blog.example/", "20140102030405", "HOMEA", "text/html", "200"], + ["https://blog.example/x", "bad", "X", "text/html", "200"], + ["https://blog.example/y", "20140102030406", "", "text/html", "200"], + [], + ["key-2"], + ]), + ); + assert.equal(page.resumeKey, "key-2"); + assert.deepEqual(page.rows, [ + { originalUrl: "https://blog.example/", timestamp: "20140102030405", digest: "HOMEA", mimetype: "text/html", status: 200 }, + { originalUrl: "https://blog.example/y", timestamp: "20140102030406", digest: "ts-20140102030406", mimetype: "text/html", status: 200 }, + ]); + assert.equal(parseScanCdxPage(JSON.stringify([["original", "timestamp"], ["https://a.example/", "20140102030405"]])).resumeKey, undefined); + assert.throws(() => parseScanCdxPage("<html>"), /did not answer JSON/); + assert.throws(() => parseScanCdxPage("{}"), /not a list/); +}); + +test("assets are dropped by extension unless include names them; exclude always wins", () => { + for (const u of ["https://blog.example/style.css", "https://blog.example/a/logo.PNG?v=2", "https://blog.example/f.woff2", "https://blog.example/app.js"]) { + assert.equal(isAssetUrl(u), true, u); + } + for (const u of ["https://blog.example/", "https://blog.example/post/1", "https://blog.example/page.html", "https://blog.example/x?f=a.css"]) { + assert.equal(isAssetUrl(u), false, u); + } + const t: WaybackTarget = { url: "blog.example", match: "host" }; + assert.equal(keepCaptureUrl(t, "https://blog.example/post/1"), true); + assert.equal(keepCaptureUrl(t, "https://blog.example/style.css"), false); + assert.equal(keepCaptureUrl({ ...t, include: "\\.css$" }, "https://blog.example/style.css"), true); + assert.equal(keepCaptureUrl({ ...t, include: "/post/" }, "https://blog.example/tagged/x"), false); + assert.equal(keepCaptureUrl({ ...t, exclude: "/post/1$" }, "https://blog.example/post/1"), false); + assert.equal(keepCaptureUrl({ ...t, include: "/post/", exclude: "/post/1$" }, "https://blog.example/post/1"), false); +}); + +const row = (originalUrl: string, timestamp: string, digest: string) => ({ originalUrl, timestamp, digest, mimetype: "text/html", status: 200 }); + +test("the merge: one row per (URL, digest); a later sighting widens first/last and counts; a second pass marks what it added", () => { + const file = emptyScanFile("blog", "2026-01-01T00:00:00.000Z"); + const added = mergeCdxRows(file, [ + row("https://blog.example/", "20140601000000", "HOMEA"), + row("https://blog.example/", "20150101000000", "HOMEB"), + row("https://blog.example/", "20160101000000", "HOMEA"), + row("https://blog.example/post/1", "20140203000000", "P1A"), + ]); + assert.equal(added, 3); + const home = file.rows.find((r) => r.digest === "HOMEA")!; + assert.deepEqual([home.firstTs, home.lastTs, home.count], ["20140601000000", "20160101000000", 2]); + // The same capture again (an overlapping later pass) is not counted twice. + file.pass = 2; + assert.equal(mergeCdxRows(file, [row("https://blog.example/", "20160101000000", "HOMEA"), row("https://blog.example/", "20140102000000", "HOMEA")]), 0); + assert.deepEqual([home.firstTs, home.lastTs, home.count], ["20140102000000", "20160101000000", 3]); + assert.equal(mergeCdxRows(file, [row("https://blog.example/post/2", "20170101000000", "P2A")]), 1); + const p2 = file.rows.find((r) => r.digest === "P2A")!; + assert.equal(isNewRow(file, p2), true); + assert.equal(isNewRow(file, home), false); + assert.equal(isNewRow({ pass: 1 }, { pass: 1 }), false, "nothing is new on the first pass"); +}); + +test("summaries: pages, versions, rows by first-seen year and by one- and two-segment prefix", () => { + const file = emptyScanFile("blog", "2026-01-01T00:00:00.000Z"); + mergeCdxRows(file, [ + row("https://blog.example/", "20140601000000", "H"), + row("https://www.blog.example/post/1/first", "20140203000000", "P1A"), + row("https://blog.example/post/1/first", "20150203000000", "P1B"), + row("https://blog.example/post/2/second", "20150203000000", "P2A"), + row("https://blog.example/tagged/bread", "20150203000000", "T"), + ]); + const s = summarizeScan(file.rows); + assert.equal(s.versions, 5); + assert.equal(s.pages, 5, "www. and bare are two original URLs"); + assert.deepEqual(s.byYear, { "2014": 2, "2015": 3 }); + assert.deepEqual(s.byPrefix, { + "blog.example/": 1, + "blog.example/post/": 3, + "blog.example/post/1/": 2, + "blog.example/tagged/": 1, + }); + assert.equal(pathPrefixOf("https://blog.example/post/1/first", 1), "blog.example/post/"); + assert.equal(pathPrefixOf("https://blog.example/post/1/", 2), "blog.example/post/1/"); + assert.equal(displayPathOf("https://blog.example/post/1?x=2", false), "/post/1?x=2"); + assert.equal(displayPathOf("https://www.blog.example/post/1", true), "blog.example/post/1"); + assert.equal(cdxTsBefore("2026-02-01T12:00:00.000Z", 31), "20260101120000"); +}); + +test("imported: a record of the same page with the row's digest, or with no digest a capture inside its range", () => { + const index = buildImportedIndex([ + { id: "20140203000000-aaa", page: { originalUrl: "http://www.blog.example/post/1", captureTs: "20140203000000", digest: "P1A", waybackUrl: "https://web.archive.org/web/20140203000000/http://www.blog.example/post/1" } }, + { id: "20150301000000-bbb", page: { originalUrl: "https://blog.example/", captureTs: "20150301000000" } }, + { id: "a-post-with-no-page" }, + ]); + assert.equal(pageUrlKey("http://www.Blog.example:80/post/1"), "blog.example/post/1"); + const r = (originalUrl: string, digest: string, firstTs: string, lastTs: string) => ({ originalUrl, digest, firstTs, lastTs }); + assert.deepEqual(importedRecordOf(r("https://blog.example/post/1", "P1A", "20140203000000", "20140304000000"), index), { + id: "20140203000000-aaa", + captureTs: "20140203000000", + waybackUrl: "https://web.archive.org/web/20140203000000/http://www.blog.example/post/1", + }); + assert.equal(importedRecordOf(r("https://blog.example/post/1", "P1B", "20150405000000", "20150405000000"), index), null, "another version is not imported"); + assert.equal(importedRecordOf(r("https://blog.example/", "HOMEB", "20150101000000", "20150601000000"), index)?.id, "20150301000000-bbb"); + assert.equal(importedRecordOf(r("https://blog.example/", "HOMEA", "20140101000000", "20140601000000"), index), null); + assert.equal(importedRecordOf(r("https://blog.example/post/9", "X", "2014", "2015"), index), null); +}); diff --git a/common/lib/waybackPages/scanCdx.ts b/common/lib/waybackPages/scanCdx.ts @@ -0,0 +1,117 @@ +// THE CDX LISTING A WAYBACK PAGES SCAN ASKS FOR (release 37 S2): one target's +// captures, paged with the API's resume key, one row per distinct content +// (`collapse=digest`), only those that recorded a 200, only the target's +// mimetypes, inside its date bounds. Pure: the URL and the parse; the request +// is the Wayback client's (lib/waybackClient.ts `cdxPage`), paced. +// +// The CDX server's JSON answer with `showResumeKey=true`: a header row, the +// rows, and — when more remain — an empty row then `[<resumeKey>]`. + +import { WAYBACK_ORIGIN } from "../waybackClient"; +import { cdxMimeFilter, cdxUrlParam, type WaybackTarget } from "./targets"; + +// Rows asked for per request. +export const CDX_PAGE_ROWS = 5_000; +// Rows read per run, all targets together, unless the run asks for fewer. +export const DEFAULT_SCAN_MAX_ROWS = 50_000; +// The hard ceiling on a run's `maxRows`. +export const SCAN_MAX_ROWS_LIMIT = 200_000; + +// The columns asked for, in this order. +export const CDX_FIELDS = ["original", "timestamp", "digest", "mimetype", "statuscode"] as const; + +export type CdxQuery = { + target: WaybackTarget; + limit: number; + resumeKey?: string; + // A later pass's lower bound (YYYYMMDDhhmmss), when later than the target's + // own `from`. + from?: string; +}; + +export function scanCdxUrl(q: CdxQuery, origin: string = WAYBACK_ORIGIN): string { + const t = q.target; + const p = new URLSearchParams(); + p.set("url", cdxUrlParam(t)); + p.set("matchType", t.match); + p.set("output", "json"); + p.set("fl", CDX_FIELDS.join(",")); + p.append("filter", "statuscode:200"); + p.append("filter", cdxMimeFilter(t)); + p.set("collapse", "digest"); + const from = laterTs(t.from, q.from); + if (from) p.set("from", from); + if (t.to) p.set("to", t.to); + p.set("limit", String(q.limit)); + p.set("showResumeKey", "true"); + if (q.resumeKey) p.set("resumeKey", q.resumeKey); + return `${origin}/cdx/search/cdx?${p.toString()}`; +} + +// The later of two CDX bounds (prefix timestamps compare by padding). +function laterTs(a: string | undefined, b: string | undefined): string | undefined { + if (!a) return b; + if (!b) return a; + return a.padEnd(14, "0") >= b.padEnd(14, "0") ? a : b; +} + +export type CdxScanRow = { + originalUrl: string; + timestamp: string; + digest: string; + mimetype: string; + status: number; +}; + +export type CdxScanPage = { + rows: CdxScanRow[]; + // Present when the listing continues. + resumeKey?: string; +}; + +// One page of the answer. An empty body or `[]` is no rows; anything that is +// not the JSON list shape is an error (the API changed, or answered a page). +export function parseScanCdxPage(body: string): CdxScanPage { + const text = body.trim(); + if (!text) return { rows: [] }; + let raw: unknown; + try { + raw = JSON.parse(text); + } catch { + throw new Error(`the CDX API did not answer JSON (${text.slice(0, 80)})`); + } + if (!Array.isArray(raw)) throw new Error("the CDX API's answer is not a list"); + if (raw.length === 0) return { rows: [] }; + const list = raw as unknown[]; + let resumeKey: string | undefined; + // The tail: [] then [key]. + const last = list[list.length - 1]; + const beforeLast = list[list.length - 2]; + let end = list.length; + if (Array.isArray(last) && last.length === 1 && typeof last[0] === "string" && Array.isArray(beforeLast) && beforeLast.length === 0) { + resumeKey = last[0] || undefined; + end -= 2; + } + const header = list[0]; + if (!Array.isArray(header)) throw new Error("the CDX API's answer has no header row"); + const col = (name: string) => (header as unknown[]).indexOf(name); + const ci = { original: col("original"), timestamp: col("timestamp"), digest: col("digest"), mimetype: col("mimetype"), statuscode: col("statuscode") }; + if (ci.original < 0 || ci.timestamp < 0) throw new Error("the CDX API's header names no timestamp or original"); + const rows: CdxScanRow[] = []; + for (const row of list.slice(1, end)) { + if (!Array.isArray(row) || row.length === 0) continue; + const timestamp = String(row[ci.timestamp] ?? ""); + const originalUrl = String(row[ci.original] ?? ""); + if (!/^\d{14}$/.test(timestamp) || !originalUrl) continue; + const digest = ci.digest >= 0 ? String(row[ci.digest] ?? "") : ""; + const status = ci.statuscode >= 0 ? Number(row[ci.statuscode]) : 200; + rows.push({ + originalUrl, + timestamp, + digest: digest || `ts-${timestamp}`, + mimetype: ci.mimetype >= 0 ? String(row[ci.mimetype] ?? "") : "", + status: Number.isFinite(status) ? status : 0, + }); + } + return { rows, ...(resumeKey ? { resumeKey } : {}) }; +} diff --git a/common/lib/waybackPages/scanFile-server.ts b/common/lib/waybackPages/scanFile-server.ts @@ -0,0 +1,43 @@ +// The disk half of lib/waybackPages/scanFile.ts: +// `channels/<slug>/wayback-scan.json`, read and written (atomic), and the +// channel's imported-record index read through the posts store's reader. +// SERVER-ONLY (node:fs). + +import path from "node:path"; +import { readFile } from "node:fs/promises"; +import { writeJsonAtomic } from "../jsonFile-server"; +import { readAllPosts } from "../posts-server"; +import { isSafeChannelSegment } from "../citations/moments"; +import { buildImportedIndex, type ImportedIndex, type ImportedPageFacts } from "./imported"; +import { isWaybackScanFile, WAYBACK_SCAN_FILENAME, type WaybackScanFile } from "./scanFile"; + +export function waybackScanPath(channelsDir: string, slug: string): string { + if (!isSafeChannelSegment(slug)) throw new Error(`not a channel slug: ${JSON.stringify(slug)}`); + return path.join(channelsDir, slug, WAYBACK_SCAN_FILENAME); +} + +// The channel's scan, or null (none yet, unreadable, or another format). +export async function readWaybackScan(channelsDir: string, slug: string): Promise<WaybackScanFile | null> { + try { + const v = JSON.parse(await readFile(waybackScanPath(channelsDir, slug), "utf8")) as unknown; + return isWaybackScanFile(v) ? v : null; + } catch { + return null; + } +} + +// Compact: a 50,000-row scan is ~8 MB of JSON as it is. +export async function writeWaybackScan(channelsDir: string, file: WaybackScanFile): Promise<string> { + const p = waybackScanPath(channelsDir, file.slug); + await writeJsonAtomic(p, file, { indent: 0 }); + return p; +} + +// The channel's webpage records, by page (imported.ts). Every record through +// the posts store's own reader; a record without `page` is not a capture. +export async function readImportedIndex(channelsDir: string, slug: string): Promise<ImportedIndex> { + const posts = await readAllPosts(path.join(channelsDir, slug)); + return buildImportedIndex( + posts.map((p) => ({ id: p.id, page: (p as { page?: ImportedPageFacts }).page ?? null })), + ); +} diff --git a/common/lib/waybackPages/scanFile.ts b/common/lib/waybackPages/scanFile.ts @@ -0,0 +1,260 @@ +// `channels/<slug>/wayback-scan.json` — what a Wayback pages channel's scan +// found (release 37 S2; written by controller/waybackScan.ts, read by the +// channel page's Captures tab and the download lane's `wayback.auto` pick). +// Every distinct (original URL, digest) the CDX API listed for the channel's +// targets — no bodies: a scan never fetches one, only `import-page` does. +// +// Shape: `{format: "archilyzer-wayback-scan", version: 1, slug, pass, +// passStartedAt, previousPassStartedAt?, lastScanAt?, jobId?, targets, rows, +// summary}`. +// targets[] per target: {key, url, match, from?, to?, resumeKey?, complete, +// rows (CDX rows read this pass), lastScanAt?, completedAt?, +// passFrom?} +// rows[] {originalUrl, digest, firstTs, lastTs, count, mimetype, status, +// pass (the pass that first listed it)} +// summary {pages, versions, byYear (first seen), byPrefix (first one and +// two path segments, host first)} +// +// A PASS is one walk of every target to its end. A pass that is cut (the row +// cap, a refusal, a drain) keeps each target's resume key and the next run +// continues it; once every target is complete the next run starts a new pass, +// asking only for captures from 30 days before the previous pass started (the +// CDX index lags the crawl). A row is NEW when a pass after the first listed it +// in the current pass. Imported state is NOT stored here — it is derived from +// the channel's posts (imported.ts). +// +// Pure, client-safe (types, merge, summaries). + +import type { WaybackMatchType } from "./targets"; +import type { CdxScanRow } from "./scanCdx"; + +export const WAYBACK_SCAN_FORMAT = "archilyzer-wayback-scan"; +export const WAYBACK_SCAN_VERSION = 1; +export const WAYBACK_SCAN_FILENAME = "wayback-scan.json"; + +// How far before the previous pass's start a later pass asks from. +export const PASS_OVERLAP_DAYS = 30; + +export type WaybackScanTarget = { + key: string; + url: string; + match: WaybackMatchType; + from?: string; + to?: string; + resumeKey?: string; + complete: boolean; + // CDX rows read for this target in the current pass. + rows: number; + lastScanAt?: string; + completedAt?: string; + // The lower bound this pass asks from (a later pass only). + passFrom?: string; +}; + +export type WaybackScanRow = { + originalUrl: string; + digest: string; + // YYYYMMDDhhmmss: the earliest and latest capture of this content listed. + // With collapse=digest a run of identical captures is listed once, at its + // first; `count` counts the listed captures, not every crawl. + firstTs: string; + lastTs: string; + count: number; + mimetype: string; + status: number; + pass: number; +}; + +export type WaybackScanSummary = { + // Distinct original URLs, and distinct (URL, digest). + pages: number; + versions: number; + byYear: Record<string, number>; + byPrefix: Record<string, number>; +}; + +export type WaybackScanFile = { + format: typeof WAYBACK_SCAN_FORMAT; + version: typeof WAYBACK_SCAN_VERSION; + slug: string; + pass: number; + passStartedAt: string; + previousPassStartedAt?: string; + lastScanAt?: string; + jobId?: string; + targets: WaybackScanTarget[]; + rows: WaybackScanRow[]; + summary: WaybackScanSummary; +}; + +export function isWaybackScanFile(v: unknown): v is WaybackScanFile { + const f = v as WaybackScanFile | null; + return ( + !!f && + typeof f === "object" && + f.format === WAYBACK_SCAN_FORMAT && + f.version === WAYBACK_SCAN_VERSION && + typeof f.slug === "string" && + typeof f.pass === "number" && + Array.isArray(f.targets) && + Array.isArray(f.rows) + ); +} + +export function emptyScanFile(slug: string, now: string): WaybackScanFile { + return { + format: WAYBACK_SCAN_FORMAT, + version: WAYBACK_SCAN_VERSION, + slug, + pass: 1, + passStartedAt: now, + targets: [], + rows: [], + summary: { pages: 0, versions: 0, byYear: {}, byPrefix: {} }, + }; +} + +export function scanRowKey(r: Pick<WaybackScanRow, "originalUrl" | "digest">): string { + return `${r.originalUrl}\u0000${r.digest}`; +} + +// Fold one page of CDX rows into `file.rows` (mutated): a new (URL, digest) +// is added under the current pass; a known one widens its first/last seen and +// counts the capture when it lies outside what was already seen. Answers how +// many rows were added. `index` is the caller's key → row map, kept across +// pages so a 50,000-row file is not rescanned per page. +export function mergeCdxRows( + file: WaybackScanFile, + rows: ReadonlyArray<CdxScanRow>, + index: Map<string, WaybackScanRow> = indexScanRows(file), +): number { + let added = 0; + for (const r of rows) { + const key = scanRowKey(r); + const have = index.get(key); + if (!have) { + const row: WaybackScanRow = { + originalUrl: r.originalUrl, + digest: r.digest, + firstTs: r.timestamp, + lastTs: r.timestamp, + count: 1, + mimetype: r.mimetype, + status: r.status, + pass: file.pass, + }; + file.rows.push(row); + index.set(key, row); + added++; + continue; + } + if (r.timestamp < have.firstTs) { + have.firstTs = r.timestamp; + have.count++; + } else if (r.timestamp > have.lastTs) { + have.lastTs = r.timestamp; + have.count++; + } + } + return added; +} + +export function indexScanRows(file: Pick<WaybackScanFile, "rows">): Map<string, WaybackScanRow> { + return new Map(file.rows.map((r) => [scanRowKey(r), r])); +} + +// A row is new when a pass after the first listed it in the current pass. +export function isNewRow(file: Pick<WaybackScanFile, "pass">, row: Pick<WaybackScanRow, "pass">): boolean { + return file.pass > 1 && row.pass === file.pass; +} + +// "example.org" for every www./port spelling of one host. +export function normalHost(host: string): string { + return host.toLowerCase().replace(/^www\./, "").replace(/:(80|443)$/, ""); +} + +function parseUrl(u: string): URL | null { + try { + return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(u) ? u : `http://${u}`); + } catch { + return null; + } +} + +// The first `depth` path segments of a URL, host first: "example.org/blog/", +// "example.org/blog/2014/". A URL with fewer segments is its own path's +// directory ("example.org/"). +export function pathPrefixOf(originalUrl: string, depth: 1 | 2): string { + const u = parseUrl(originalUrl); + if (!u) return originalUrl; + const segs = u.pathname.split("/").filter(Boolean); + // The last segment of a path that does not end in "/" is a page, not a dir. + const dirs = u.pathname.endsWith("/") ? segs : segs.slice(0, -1); + const take = dirs.slice(0, depth); + return `${normalHost(u.host)}/${take.map((s) => `${s}/`).join("")}`; +} + +// What the table shows for a URL: its path and query, with the host first +// when the scan spans hosts. +export function displayPathOf(originalUrl: string, withHost: boolean): string { + const u = parseUrl(originalUrl); + if (!u) return originalUrl; + const p = `${u.pathname}${u.search}`; + return withHost ? `${normalHost(u.host)}${p}` : p; +} + +export function hostsOf(rows: ReadonlyArray<Pick<WaybackScanRow, "originalUrl">>): Set<string> { + const out = new Set<string>(); + for (const r of rows) { + const u = parseUrl(r.originalUrl); + if (u) out.add(normalHost(u.host)); + } + return out; +} + +// Prefixes kept in the summary: every one-segment prefix, and the two-segment +// ones that hold more than one row (a two-segment prefix per post would be a +// copy of the rows), at most this many of each, most rows first. +export const SUMMARY_PREFIXES_MAX = 200; + +export function summarizeScan(rows: ReadonlyArray<WaybackScanRow>): WaybackScanSummary { + const pages = new Set<string>(); + const byYear: Record<string, number> = {}; + const one = new Map<string, number>(); + const two = new Map<string, number>(); + for (const r of rows) { + pages.add(r.originalUrl); + const y = r.firstTs.slice(0, 4); + byYear[y] = (byYear[y] ?? 0) + 1; + const p1 = pathPrefixOf(r.originalUrl, 1); + const p2 = pathPrefixOf(r.originalUrl, 2); + one.set(p1, (one.get(p1) ?? 0) + 1); + if (p2 !== p1) two.set(p2, (two.get(p2) ?? 0) + 1); + } + const top = (m: Map<string, number>, min: number) => + [...m.entries()] + .filter(([, n]) => n >= min) + .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])) + .slice(0, SUMMARY_PREFIXES_MAX); + const byPrefix: Record<string, number> = {}; + for (const [k, n] of [...top(one, 1), ...top(two, 2)].sort((a, b) => a[0].localeCompare(b[0]))) byPrefix[k] = n; + return { pages: pages.size, versions: rows.length, byYear, byPrefix }; +} + +// Rows in table order: by URL, then by first seen. +export function sortScanRows(rows: WaybackScanRow[]): WaybackScanRow[] { + return rows.sort((a, b) => a.originalUrl.localeCompare(b.originalUrl) || a.firstTs.localeCompare(b.firstTs)); +} + +// YYYYMMDDhhmmss of an ISO time, minus `days`. +export function cdxTsBefore(iso: string, days: number): string { + const ms = Date.parse(iso) - days * 86_400_000; + const d = new Date(Number.isFinite(ms) ? ms : 0); + const p = (n: number, w = 2) => String(n).padStart(w, "0"); + return `${p(d.getUTCFullYear(), 4)}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}`; +} + +// "2014-05-06" of a CDX timestamp. +export function cdxTsDate(ts: string): string { + return ts.length >= 8 ? `${ts.slice(0, 4)}-${ts.slice(4, 6)}-${ts.slice(6, 8)}` : ts; +} diff --git a/common/lib/waybackPages/targets.ts b/common/lib/waybackPages/targets.ts @@ -0,0 +1,157 @@ +// A WAYBACK PAGES CHANNEL'S SCOPE (release 37 S2): `config.wayback` — the +// targets whose captures the channel is about, and whether the download lane +// imports new ones by itself. Pure and client-safe: no I/O. +// +// config.wayback = { +// targets: [{url, match: "exact"|"prefix"|"host"|"domain", from?, to?, +// mime?: ["text/html"], include?, exclude?}], +// collapse?: "digest", +// auto?: boolean, +// } +// +// The reader is TOLERANT: unknown keys are ignored, a target without a usable +// `url` is dropped, a bad `match` is "exact", a date that is not 4–14 digits is +// dropped, a regex that does not compile is dropped. A channel with no usable +// target is not a Wayback pages channel. + +export const WAYBACK_MATCH_TYPES = ["exact", "prefix", "host", "domain"] as const; +export type WaybackMatchType = (typeof WAYBACK_MATCH_TYPES)[number]; + +// The mimetypes a target may ask for. A capture of anything else (an image, a +// stylesheet, a video) is not a page. +export const WAYBACK_PAGE_MIMES = ["text/html", "text/plain", "application/json"] as const; +export const DEFAULT_WAYBACK_MIMES: readonly string[] = ["text/html"]; + +export type WaybackTarget = { + // A URL (exact, prefix), or a host / domain ("example.org"). A scheme is + // allowed and ignored for host and domain. + url: string; + match: WaybackMatchType; + // YYYY[MM[DD[hh[mm[ss]]]]] — the CDX API's own bounds. + from?: string; + to?: string; + mime?: string[]; + // Regexes over the ORIGINAL URL: a capture is kept when it matches + // `include` (when set) and does not match `exclude`. + include?: string; + exclude?: string; +}; + +export type WaybackChannelConfig = { + targets: WaybackTarget[]; + collapse: "digest"; + // The download lane imports new scan rows for this channel (default off: no + // unattended crawling of a host unless the channel opts in). + auto: boolean; +}; + +const TS_RE = /^\d{4,14}$/; + +function str(v: unknown): string | undefined { + return typeof v === "string" && v.trim() ? v.trim() : undefined; +} + +function regexOk(src: string | undefined): string | undefined { + if (!src) return undefined; + try { + new RegExp(src); + return src; + } catch { + return undefined; + } +} + +export function parseWaybackTarget(raw: unknown): WaybackTarget | null { + if (!raw || typeof raw !== "object") return null; + const r = raw as Record<string, unknown>; + const url = str(r.url); + if (!url) return null; + const match: WaybackMatchType = (WAYBACK_MATCH_TYPES as readonly string[]).includes(r.match as string) + ? (r.match as WaybackMatchType) + : "exact"; + const from = str(r.from); + const to = str(r.to); + const mime = Array.isArray(r.mime) + ? [...new Set(r.mime.filter((m): m is string => typeof m === "string" && (WAYBACK_PAGE_MIMES as readonly string[]).includes(m)))] + : []; + const include = regexOk(str(r.include)); + const exclude = regexOk(str(r.exclude)); + return { + url, + match, + ...(from && TS_RE.test(from) ? { from } : {}), + ...(to && TS_RE.test(to) ? { to } : {}), + ...(mime.length ? { mime } : {}), + ...(include ? { include } : {}), + ...(exclude ? { exclude } : {}), + }; +} + +// `config.wayback` of a channel config (or the raw config.json object), or +// null when the channel names no usable target. +export function waybackConfigOf(config: unknown): WaybackChannelConfig | null { + if (!config || typeof config !== "object") return null; + const w = (config as { wayback?: unknown }).wayback; + if (!w || typeof w !== "object") return null; + const r = w as Record<string, unknown>; + const targets = Array.isArray(r.targets) + ? r.targets.map(parseWaybackTarget).filter((t): t is WaybackTarget => t !== null) + : []; + if (targets.length === 0) return null; + return { targets, collapse: "digest", auto: r.auto === true }; +} + +export function isWaybackPagesConfig(config: unknown): boolean { + return waybackConfigOf(config) !== null; +} + +// The identity of a target in the scan file: what it ASKS the CDX API. A +// target whose url, match, bounds or mimes change is a new target (scanned from +// its start); include/exclude only filter what is kept. +export function waybackTargetKey(t: WaybackTarget): string { + return JSON.stringify([t.match, t.url, t.from ?? "", t.to ?? "", (t.mime ?? DEFAULT_WAYBACK_MIMES).join(",")]); +} + +// The `url` the CDX API takes for a target: a host or a domain without its +// scheme or path. +export function cdxUrlParam(t: WaybackTarget): string { + if (t.match === "host" || t.match === "domain") { + try { + return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(t.url) ? t.url : `http://${t.url}`).hostname; + } catch { + return t.url; + } + } + return t.url; +} + +function escapeRegex(s: string): string { + return s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&"); +} + +// The CDX `filter=mimetype:` regex for a target's mimes. +export function cdxMimeFilter(t: WaybackTarget): string { + return `mimetype:${(t.mime ?? DEFAULT_WAYBACK_MIMES).map(escapeRegex).join("|")}`; +} + +// Obvious non-page assets, by the path's extension: dropped from a scan unless +// the target's `include` names them. +const ASSET_EXT_RE = + /\.(?:css|js|mjs|map|png|jpe?g|gif|webp|avif|svg|ico|bmp|tiff?|woff2?|ttf|otf|eot|mp4|m4v|webm|mov|mp3|m4a|ogg|wav|flac|zip|gz|tgz|rar|7z|pdf|swf|flv|exe|dmg|iso)$/i; + +export function isAssetUrl(originalUrl: string): boolean { + let p = originalUrl; + try { + p = new URL(originalUrl).pathname; + } catch { + p = originalUrl.split(/[?#]/)[0] ?? originalUrl; + } + return ASSET_EXT_RE.test(p); +} + +// Whether a capture of `originalUrl` belongs in the target's scan. +export function keepCaptureUrl(t: WaybackTarget, originalUrl: string): boolean { + if (t.exclude && new RegExp(t.exclude).test(originalUrl)) return false; + if (t.include) return new RegExp(t.include).test(originalUrl); + return !isAssetUrl(originalUrl); +} diff --git a/common/testing/web/fakeWayback.d.mts b/common/testing/web/fakeWayback.d.mts @@ -1,4 +1,11 @@ -export type FakeWaybackCapture = { original: string; timestamp: string; statuscode: string; mimetype?: string }; +export type FakeWaybackCapture = { + original: string; + timestamp: string; + statuscode: string; + mimetype?: string; + // (release 37 S2) the content digest the scan listing answers (default DIGEST<timestamp>). + digest?: string; +}; export const CAPTURES: FakeWaybackCapture[]; export const VIDEOS: string[]; @@ -18,4 +25,10 @@ export function startFakeWayback(opts?: { busyTimes?: number; downTimes?: number; streamBusyTimes?: number; + // (release 37 S2) the Nth scan listing request and every one after answer 503. + scanRefuseFrom?: number; }): Promise<FakeWayback>; + +// (release 37 S2) the scan listing: a blog with posts, assets, a 404, a second host. +export const SCAN_CAPTURES: FakeWaybackCapture[]; +export function scanListing(captures: FakeWaybackCapture[], q: URLSearchParams): unknown[]; diff --git a/common/testing/web/fakeWayback.mjs b/common/testing/web/fakeWayback.mjs @@ -23,6 +23,14 @@ // is in opts.streams (default: opts.videos), 404 otherwise — an id in `videos` but // not in `streams` is the live case, the index listing a video Wayback does not hold // opts.busyTimes: the first N CDX requests answer 429 (Retry-After: 1); opts.downTimes: then 503s. +// ── THE SCAN LISTING (release 37 S2, lib/waybackPages/scanCdx.ts) ── +// GET /cdx/search/cdx?…&showResumeKey=true the paged listing a Wayback pages scan asks: +// matchType exact|prefix|host|domain, from/to (timestamp prefixes), every `filter=` +// (`[!]field:regex`, a whole-field match, over statuscode and mimetype), collapse=digest +// (adjacent rows of one URL with one digest listed once), fl (the columns, in order), +// limit, and resumeKey — the answer ends with [] and [<resumeKey>] when rows remain. +// A capture's `digest` is its own when it names one, else DIGEST<timestamp>. +// opts.scanRefuseFrom: the Nth scan request (1-based) and every one after answer 503. // opts.streamBusyTimes: the first N stream requests answer 429 (Retry-After: 1). import http from "node:http"; @@ -57,6 +65,7 @@ export async function startFakeWayback(opts = {}) { const requests = []; let busy = opts.busyTimes ?? 0; let down = opts.downTimes ?? 0; + let scanRequests = 0; const server = http.createServer((req, res) => { const u = new URL(req.url ?? "/", "http://fake"); requests.push({ path: u.pathname + u.search, at: Date.now() }); @@ -73,6 +82,11 @@ export async function startFakeWayback(opts = {}) { down--; return send(503, "text/plain", "Service Unavailable"); } + if (u.searchParams.get("showResumeKey") === "true") { + scanRequests++; + if (opts.scanRefuseFrom && scanRequests >= opts.scanRefuseFrom) return send(503, "text/plain", "Service Unavailable"); + return send(200, "application/json", JSON.stringify(scanListing(captures, u.searchParams))); + } const want = u.searchParams.get("url") ?? ""; const prefix = u.searchParams.get("matchType") === "prefix"; const status = /^statuscode:(\d+)$/.exec(u.searchParams.get("filter") ?? "")?.[1]; @@ -125,3 +139,88 @@ export async function startFakeWayback(opts = {}) { close: () => new Promise((r) => server.close(() => r())), }; } + +// ── THE SCAN LISTING (release 37 S2) ───────────────────────────────────────── +// Its own block: the paged, filtered, collapsed listing a Wayback pages scan +// asks for. Nothing above calls it unless the request carries showResumeKey. + +// Invented page captures for a scan: a blog on blog.example with posts across +// 2014–2015 (one post captured three times, twice with the same content), its +// stylesheet and a logo (assets), a 404, and an about page on a second host of +// the same domain. +export const SCAN_CAPTURES = [ + { original: "https://blog.example/", timestamp: "20140102030405", statuscode: "200", mimetype: "text/html", digest: "HOMEA" }, + { original: "https://blog.example/", timestamp: "20140601000000", statuscode: "200", mimetype: "text/html", digest: "HOMEA" }, + { original: "https://blog.example/", timestamp: "20150101000000", statuscode: "200", mimetype: "text/html", digest: "HOMEB" }, + { original: "https://blog.example/post/101/first-post", timestamp: "20140203000000", statuscode: "200", mimetype: "text/html", digest: "P101A" }, + { original: "https://blog.example/post/101/first-post", timestamp: "20140304000000", statuscode: "200", mimetype: "text/html", digest: "P101A" }, + { original: "https://blog.example/post/101/first-post", timestamp: "20150405000000", statuscode: "200", mimetype: "text/html", digest: "P101B" }, + { original: "https://blog.example/post/102/second-post", timestamp: "20140506000000", statuscode: "200", mimetype: "text/html", digest: "P102A" }, + { original: "https://blog.example/post/103/third-post", timestamp: "20150607000000", statuscode: "200", mimetype: "text/html", digest: "P103A" }, + { original: "https://blog.example/tagged/bread", timestamp: "20150708000000", statuscode: "200", mimetype: "text/html", digest: "TAGA" }, + { original: "https://blog.example/style.css", timestamp: "20140102030406", statuscode: "200", mimetype: "text/html", digest: "CSSA" }, + { original: "https://blog.example/logo.png", timestamp: "20140102030407", statuscode: "200", mimetype: "image/png", digest: "PNGA" }, + { original: "https://blog.example/post/999/gone", timestamp: "20150809000000", statuscode: "404", mimetype: "text/html", digest: "GONEA" }, + { original: "https://about.blog.example/", timestamp: "20140910000000", statuscode: "200", mimetype: "text/html", digest: "ABOUTA" }, +]; + +const SCAN_FIELDS = ["urlkey", "timestamp", "original", "mimetype", "statuscode", "digest", "length"]; + +function hostOf(u) { + try { + return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(u) ? u : `http://${u}`).hostname.toLowerCase(); + } catch { + return ""; + } +} + +const noScheme = (u) => u.replace(/^[a-z][a-z0-9+.-]*:\/\//i, "").replace(/^www\./, ""); + +function matchesTarget(original, want, matchType) { + if (matchType === "prefix") return noScheme(original).startsWith(noScheme(want)); + if (matchType === "host") return hostOf(original).replace(/^www\./, "") === hostOf(want).replace(/^www\./, ""); + if (matchType === "domain") { + const h = hostOf(original); + const d = hostOf(want).replace(/^www\./, ""); + return h === d || h.endsWith(`.${d}`); + } + return noScheme(original) === noScheme(want); +} + +export function scanListing(captures, q) { + const want = q.get("url") ?? ""; + const matchType = q.get("matchType") ?? "exact"; + const from = (q.get("from") ?? "").padEnd(14, "0"); + const to = (q.get("to") ?? "").padEnd(14, "9"); + const filters = q.getAll("filter").map((f) => { + const neg = f.startsWith("!"); + const body = neg ? f.slice(1) : f; + const i = body.indexOf(":"); + return { neg, field: body.slice(0, i), re: new RegExp(`^(?:${body.slice(i + 1)})$`) }; + }); + const fl = (q.get("fl") ?? SCAN_FIELDS.join(",")).split(","); + const limit = Number(q.get("limit") ?? 0) || Infinity; + const offset = Number(/^fake-(\d+)$/.exec(q.get("resumeKey") ?? "")?.[1] ?? 0); + const all = captures + .map((c) => ({ + urlkey: urlkey(c.original), + timestamp: c.timestamp, + original: c.original, + mimetype: c.mimetype ?? "text/html", + statuscode: c.statuscode, + digest: c.digest ?? `DIGEST${c.timestamp}`, + length: "1234", + })) + .filter((c) => matchesTarget(c.original, want, matchType)) + .filter((c) => (!q.get("from") || c.timestamp >= from) && (!q.get("to") || c.timestamp <= to)) + .filter((c) => filters.every((f) => f.re.test(String(c[f.field] ?? "")) !== f.neg)) + .sort((a, b) => a.urlkey.localeCompare(b.urlkey) || a.timestamp.localeCompare(b.timestamp)); + const collapsed = q.get("collapse") === "digest" + ? all.filter((c, i) => i === 0 || !(all[i - 1].urlkey === c.urlkey && all[i - 1].digest === c.digest)) + : all; + const page = collapsed.slice(offset, offset + limit); + const rows = page.map((c) => fl.map((f) => c[f] ?? "")); + const more = offset + page.length < collapsed.length; + if (rows.length === 0 && !more) return []; + return [fl, ...rows, ...(more ? [[], [`fake-${offset + page.length}`]] : [])]; +}