// 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//wayback-scan.json` (lib/waybackPages/scanFile.ts) — a // `wayback-scan` job, `pnpm ops wayback-scan {slug, dryRun?, maxRows?, full?}`, // `archilyzer wayback scan `, 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 { isSafeChannelSegment } from "../lib/citations/moments"; import { ArchiveOrgRequestError } from "../lib/archiveOrgClient"; import { WAYBACK_EXCLUDED_PHRASE, WAYBACK_ORIGIN, isWaybackExcluded, waybackClient } from "../lib/waybackClient"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; 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 { readChannelConfig } from "./channels"; import { WAYBACK_PAGES_QUEUE } from "./importPage"; 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 = WAYBACK_PAGES_QUEUE; 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 }; export type WaybackScanBody = { slug: string; dryRun: boolean; maxRows: number; full: boolean; }; export function parseWaybackScanBody(raw: Record): 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`, through the channel config's schema. export async function readWaybackChannelConfig(paths: Paths, slug: string): Promise { return waybackConfigOf(await readChannelConfig(paths, slug)); } // Why a channel cannot be scanned, or null. export async function waybackScanRefusal(paths: Paths, slug: string): Promise { const config = await readChannelConfig(paths, slug); if (!config) return `No channel "${slug}".`; if (!waybackConfigOf(config)) { 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; // Release 38 lane C: the Wayback Machine answered 403 for this target's // listing — "excluded from the Wayback Machine (cause unknown)". A fact about // the URL, not an outage: the target is done for this pass and the run goes // on to the next one. refusal?: "excluded"; error?: 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; // Release 38 lane C: the targets the Wayback Machine excludes (their URLs). excluded?: 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): 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, excluded: _x, ...rest } = t; return { ...rest, complete: false, rows: 0, ...(passFrom ? { passFrom } : {}) }; }); } export async function runWaybackScan(opts: RunWaybackScanOpts): Promise { const log = (l: string) => opts.onLog?.(l); const now = opts.now ?? (() => new Date()); const client = opts.client ?? waybackClient; // The process client sends web.archive.org to the e2e fake when one is named // (waybackClient.ts, E2E_WAYBACK_ORIGIN_FILE). const origin = opts.origin ?? WAYBACK_ORIGIN; 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( 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 excluded: string[] = []; const result = (extra: Partial = {}): 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), ...(excluded.length ? { excluded: [...excluded] } : {}), ...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; } if (isWaybackExcluded(e)) { // Release 38 lane C: an excluded target is answered, not failed — // done for this pass (a new pass asks again), the next target goes on. t.complete = true; t.completedAt = now().toISOString(); t.excluded = WAYBACK_EXCLUDED_PHRASE; delete t.resumeKey; r.complete = true; r.refusal = "excluded"; r.error = (e as Error).message; delete r.resumeKey; excluded.push(t.url); log(` ${WAYBACK_EXCLUDED_PHRASE}: the listing answered HTTP 403; the next target goes on`); await flush(); break; } 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, deps: { paths: Paths; onDone?: (slug: string) => void; client?: CdxPager; now?: () => Date; background?: boolean }, ): Promise { 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"); }, }); }