// SAVE PAGE NOW, A LIST (lane spn-batch, operator 5 Nov: "Can we just do the // pages with public page archivers? I'm just trying to make sure evidence of // the pages exist"). `save-page-now-batch`: ONE resumable job over a list of // URLs. For each, in order, one at a time: // // 1. (skipArchived, the default) the existing archive lookup // (lib/archives archiveLookup: the Wayback Machine's CDX, archive.today's // timemap — each through its own paced client) — a copy that shows the // page (a Wayback row that recorded a 200, or any archive.today copy) is // recorded and the URL is "archived-already"; // 2. otherwise Save Page Now (controller/savePageNow.ts) — anonymous with no // keys, SPN2 with them — through the process-wide pacer (one save at a // time, ≥ 60 s apart anonymous, ≥ 10 s with keys, a rest after a // 429/503/"slow down"), and the capture recorded: "saved", or "failed" // with the reason. // // Archive.today and Ghostarchive are LOOKED UP only, never asked to save: // their save flows put a CAPTCHA in front, and solving one is not ours to do. // // THE STATE is a file per batch beside the job store // (/.spn-batches/.json), written after every URL, so a // restart (the kind resumes on boot), a cancel or a drain continues where it // stopped: the same request again — or {batch: } — picks it up. The batch // id is the URL list's own hash. THE EVIDENCE (a JSON and a CSV, rewritten // after every URL) is `evidence` (an absolute path; .json and .csv beside // each other), default beside the state. // // ANONYMOUS DAILY BUDGET: archive.org allows an anonymous client 200 captures // a day; the batch spends at most `dailyCap` (default 150) saves in any 24 h, // and waits out the window when it has, saying until when. import { createHash } from "node:crypto"; import { readFile } from "node:fs/promises"; import path from "node:path"; import type { Paths } from "../lib/paths"; import { getSettings } from "../lib/settings"; import { writeFileAtomic } from "../lib/jsonFile-server"; import { isWaybackHost } from "../lib/wayback"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import type { ArchiveCaptureRow, ArchiveSourceId } from "../lib/archives/types"; import type { ArchiveLookup } from "../lib/archives/index"; import { savePageNow, spnKeysOrAnonymous, spnPacer, type SavePageNowDeps, type SavePageNowResult, type SpnMode, type SpnPacer } from "./savePageNow"; export const SPN_BATCH_JOB_KIND = "save-page-now-batch"; export const SPN_BATCH_RESULT_MARKER = "@@save-page-now-batch "; // Its own queue: a batch of a thousand pages runs for days (archive.org's // anonymous cap is 200 a day) and must not hold the archive.org queue the page // imports wait on. One save at a time holds anyway — the pacer is the // process's. export const SPN_BATCH_QUEUE = "save-page-now-batch"; export const SPN_BATCH_MAX_URLS = 20_000; export const SPN_ANON_DAILY_CAP = 150; export const SPN_KEYS_DAILY_CAP = 5_000; const DAY_MS = 24 * 60 * 60 * 1000; // Rests in a row (429s, lookups that keep failing) before the batch stops and // waits for a person. export const SPN_BATCH_MAX_RESTS = 6; export const SPN_BATCH_LOOKUP_LIMIT = 25; export type SpnBatchStatus = "pending" | "archived-already" | "saved" | "failed"; export type SpnBatchCopy = { source: ArchiveSourceId; url: string; captureTs: string; status?: string; mimetype?: string; }; export type SpnBatchItem = { url: string; status: SpnBatchStatus; reason?: string; // The copies the lookup found (the best per source). copies?: SpnBatchCopy[]; // The capture Save Page Now made. saved?: { url: string; captureTs: string; mode: SpnMode }; lookedAt?: string; doneAt?: string; attempts?: number; }; export type SpnBatchState = { version: 1; id: string; createdAt: string; updatedAt: string; sources: ArchiveSourceId[]; skipArchived: boolean; evidence: { json: string; csv: string }; // When each save was made (the daily budget's window). saveTimes: string[]; jobIds: string[]; stopped?: string; items: SpnBatchItem[]; }; export type SpnBatchCounts = { total: number; pending: number; archivedAlready: number; saved: number; failed: number }; export function spnBatchCounts(items: readonly SpnBatchItem[]): SpnBatchCounts { const c = { total: items.length, pending: 0, archivedAlready: 0, saved: 0, failed: 0 }; for (const i of items) { if (i.status === "pending") c.pending++; else if (i.status === "archived-already") c.archivedAlready++; else if (i.status === "saved") c.saved++; else c.failed++; } return c; } export function spnBatchDir(paths: Pick): string { return path.join(path.dirname(paths.jobsDir), ".spn-batches"); } export function spnBatchStatePath(paths: Pick, id: string): string { return path.join(spnBatchDir(paths), `${id}.json`); } // The list as the batch keeps it: trimmed, http(s) only, each once, in order. export function normaliseBatchUrls(raw: readonly unknown[]): { urls: string[]; rejected: string[] } { const seen = new Set(); const urls: string[] = []; const rejected: string[] = []; for (const r of raw) { const u = typeof r === "string" ? r.trim() : ""; if (!u) continue; let ok = false; try { const p = new URL(u); ok = (p.protocol === "http:" || p.protocol === "https:") && !isWaybackHost(p.hostname); } catch { ok = false; } if (!ok) { rejected.push(u); continue; } if (seen.has(u)) continue; seen.add(u); urls.push(u); } return { urls, rejected }; } export function spnBatchId(urls: readonly string[]): string { return `spn-${createHash("sha256").update(urls.join("\n")).digest("hex").slice(0, 12)}`; } // A list file: a JSON array of URLs, {urls: [...]}, or one URL a line. export async function readBatchUrlFile(file: string): Promise { if (!path.isAbsolute(file)) throw new Error(`"file" must be an absolute path (${file})`); const text = await readFile(file, "utf8"); const t = text.trim(); if (t.startsWith("[") || t.startsWith("{")) { const v = JSON.parse(t) as unknown; if (Array.isArray(v)) return v; const urls = (v as { urls?: unknown }).urls; if (Array.isArray(urls)) return urls; throw new Error(`${file} is JSON but neither a list of URLs nor {urls: [...]}`); } return t.split(/\r?\n/).filter((l) => l.trim() && !l.trim().startsWith("#")); } async function readState(file: string): Promise { try { const v = JSON.parse(await readFile(file, "utf8")) as SpnBatchState; return v && v.version === 1 && Array.isArray(v.items) ? v : null; } catch { return null; } } // ─── THE EVIDENCE ─────────────────────────────────────────────────────────── export type SpnEvidenceRow = { url: string; status: SpnBatchStatus; reason: string; waybackUrl: string; waybackCaptureTs: string; waybackHttpStatus: string; waybackMimetype: string; archiveTodayUrl: string; archiveTodayCaptureTs: string; // Whether the copy shows the page, as far as the archive's own row says: // "yes" (a 200 page, or an archive.today copy), "redirect" (3xx), "no" // (4xx/5xx), "unknown" (a capture made just now: its row is listed later). shows: "yes" | "redirect" | "no" | "unknown" | ""; savedMode: SpnMode | ""; checkedAt: string; doneAt: string; }; function showsOf(status: string | undefined, source: ArchiveSourceId): SpnEvidenceRow["shows"] { if (source === "archive.today") return "yes"; if (!status || status === "-") return "unknown"; if (/^2/.test(status)) return "yes"; if (/^3/.test(status)) return "redirect"; return "no"; } export function spnEvidenceRow(i: SpnBatchItem): SpnEvidenceRow { const wb = i.saved ? { url: i.saved.url, captureTs: i.saved.captureTs, status: undefined as string | undefined, mimetype: undefined as string | undefined } : i.copies?.find((c) => c.source === "wayback"); const at = i.copies?.find((c) => c.source === "archive.today"); const shows: SpnEvidenceRow["shows"] = i.saved ? "unknown" : wb ? showsOf(wb.status, "wayback") : at ? "yes" : ""; return { url: i.url, status: i.status, reason: i.reason ?? "", waybackUrl: wb?.url ?? "", waybackCaptureTs: wb?.captureTs ?? "", waybackHttpStatus: wb?.status ?? "", waybackMimetype: wb?.mimetype ?? "", archiveTodayUrl: at?.url ?? "", archiveTodayCaptureTs: at?.captureTs ?? "", shows: shows === "" && at ? "yes" : shows, savedMode: i.saved?.mode ?? "", checkedAt: i.lookedAt ?? "", doneAt: i.doneAt ?? "", }; } const CSV_COLUMNS: (keyof SpnEvidenceRow)[] = [ "url", "status", "reason", "waybackUrl", "waybackCaptureTs", "waybackHttpStatus", "waybackMimetype", "archiveTodayUrl", "archiveTodayCaptureTs", "shows", "savedMode", "checkedAt", "doneAt", ]; const csvCell = (v: string) => (/[",\n\r]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v); export function spnEvidenceCsv(rows: readonly SpnEvidenceRow[]): string { return [CSV_COLUMNS.join(","), ...rows.map((r) => CSV_COLUMNS.map((c) => csvCell(String(r[c] ?? ""))).join(","))].join("\n") + "\n"; } async function writeEvidence(state: SpnBatchState): Promise { const rows = state.items.map(spnEvidenceRow); const doc = { batch: state.id, updatedAt: state.updatedAt, counts: spnBatchCounts(state.items), note: "One row per URL: archived-already (a copy existed: the Wayback row recorded a 200, or archive.today holds one), saved (Save Page Now made a capture now), failed (with the reason), pending. 'shows' is what the archive's own row says (its HTTP status), not a reading of the page.", rows, }; await writeFileAtomic(state.evidence.json, JSON.stringify(doc, null, 2) + "\n", { mkdir: true }); await writeFileAtomic(state.evidence.csv, spnEvidenceCsv(rows), { mkdir: true }); } // ─── THE PLAN ─────────────────────────────────────────────────────────────── export type SpnBatchRequest = { urls?: readonly unknown[]; file?: string; batch?: string; skipArchived?: boolean; sources?: readonly string[]; evidence?: string; dailyCap?: number; dryRun?: boolean; }; type BatchSettings = { archiveOrg?: { s3KeyFile?: string } }; export type SpnBatchPlan = { id: string; statePath: string; state: SpnBatchState; resumed: boolean; mode: SpnMode; dailyCap: number; rejected: string[]; }; const SOURCE_IDS: ArchiveSourceId[] = ["wayback", "archive.today"]; // Everything settled before a job: the list, the state (new or resumed), the // mode, the evidence paths. Refused with the sentence a caller shows. export async function planSpnBatch( paths: Paths, req: SpnBatchRequest, o: { settings?: BatchSettings; env?: Readonly>; now?: () => number } = {}, ): Promise<{ ok: true; plan: SpnBatchPlan } | { ok: false; error: string }> { const now = o.now ?? Date.now; const settings = o.settings ?? (getSettings() as BatchSettings); const mode = spnKeysOrAnonymous({ keyFile: settings.archiveOrg?.s3KeyFile, ...(o.env ? { env: o.env } : {}) }); if (!mode.ok) return { ok: false, error: mode.reason }; const sources = (req.sources?.length ? req.sources : SOURCE_IDS).map(String); const bad = sources.filter((s) => !(SOURCE_IDS as string[]).includes(s)); if (bad.length) return { ok: false, error: `"sources" are "wayback" and "archive.today" (not ${bad.join(", ")})` }; if (req.evidence !== undefined && !path.isAbsolute(req.evidence)) return { ok: false, error: `"evidence" must be an absolute path` }; const dailyCap = req.dailyCap ?? (mode.mode === "keys" ? SPN_KEYS_DAILY_CAP : SPN_ANON_DAILY_CAP); if (!Number.isInteger(dailyCap) || dailyCap < 1) return { ok: false, error: `"dailyCap" must be a positive whole number` }; if (mode.mode === "anonymous" && dailyCap > 200) return { ok: false, error: `"dailyCap" is at most 200 without keys (archive.org's anonymous daily limit)` }; let id: string; let rejected: string[] = []; let urls: string[] | null = null; if (req.batch) { if (!/^spn-[0-9a-f]{12}$/.test(req.batch)) return { ok: false, error: `"batch" is a batch id (spn-<12 hex>), not "${req.batch}"` }; id = req.batch; } else { let raw: readonly unknown[]; try { raw = req.file ? await readBatchUrlFile(req.file) : (req.urls ?? []); } catch (e) { return { ok: false, error: `the list could not be read: ${(e as Error).message}` }; } const n = normaliseBatchUrls(raw); rejected = n.rejected; if (n.urls.length === 0) return { ok: false, error: `no http(s) URLs to save (give "urls" or "file")${rejected.length ? `; ${rejected.length} not http(s) or on the Wayback Machine` : ""}` }; if (n.urls.length > SPN_BATCH_MAX_URLS) return { ok: false, error: `at most ${SPN_BATCH_MAX_URLS} URLs a batch (${n.urls.length} given)` }; urls = n.urls; id = spnBatchId(urls); } const statePath = spnBatchStatePath(paths, id); const existing = await readState(statePath); if (!existing && !urls) return { ok: false, error: `no batch ${id} (its state is not in ${spnBatchDir(paths)})` }; const stamp = new Date(now()).toISOString(); const evidenceBase = req.evidence ? req.evidence.replace(/\.(json|csv)$/i, "") : existing ? existing.evidence.json.replace(/\.json$/, "") : path.join(spnBatchDir(paths), `${id}.evidence`); const state: SpnBatchState = existing ? { ...existing, sources: sources as ArchiveSourceId[], skipArchived: req.skipArchived ?? existing.skipArchived, evidence: { json: `${evidenceBase}.json`, csv: `${evidenceBase}.csv` }, } : { version: 1, id, createdAt: stamp, updatedAt: stamp, sources: sources as ArchiveSourceId[], skipArchived: req.skipArchived ?? true, evidence: { json: `${evidenceBase}.json`, csv: `${evidenceBase}.csv` }, saveTimes: [], jobIds: [], items: urls!.map((url) => ({ url, status: "pending" as const })), }; return { ok: true, plan: { id, statePath, state, resumed: !!existing, mode: mode.mode, dailyCap, rejected } }; } // ─── THE RUN ──────────────────────────────────────────────────────────────── export type SpnBatchDeps = { lookup: (url: string, o: { sources: ArchiveSourceId[]; limit: number; signal?: AbortSignal }) => Promise; save: (url: string, o: { signal?: AbortSignal; onLog: (l: string) => void }) => Promise; pacer: Pick; now: () => number; sleep: (ms: number, signal?: AbortSignal) => Promise; }; export type SpnBatchResult = { batch: string; mode: SpnMode; dryRun: boolean; resumed: boolean; statePath: string; evidence: { json: string; csv: string }; counts: SpnBatchCounts; // This run's own work. run: { looked: number; saved: number; archivedAlready: number; failed: number }; etaSeconds?: number; stopped?: string; rejected?: number; }; // The best copy per source: Wayback's latest that recorded a 200 (else its // latest), archive.today's latest. export function bestCopies(lookup: ArchiveLookup): SpnBatchCopy[] { const out: SpnBatchCopy[] = []; for (const entry of lookup.sources) { if (!entry.ok || entry.captures.length === 0) continue; const rows = [...entry.captures].sort((a, b) => b.captureTs.localeCompare(a.captureTs)); const pick: ArchiveCaptureRow = (entry.source === "wayback" ? rows.find((r) => r.status === "200") : undefined) ?? rows[0]; out.push({ source: entry.source, url: pick.mementoUrl, captureTs: pick.captureTs, ...(pick.status ? { status: pick.status } : {}), ...(pick.mimetype ? { mimetype: pick.mimetype } : {}), }); } return out; } const shown = (c: SpnBatchCopy) => c.source === "archive.today" || c.status === "200"; function fmtDuration(s: number): string { if (s < 90) return `${Math.round(s)} s`; if (s < 5400) return `${Math.round(s / 60)} min`; if (s < 2 * 86400) return `${(s / 3600).toFixed(1)} h`; return `${(s / 86400).toFixed(1)} days`; } // The time left: a save a gap; archive.org's daily budget in whole days. export function spnBatchEtaSeconds(o: { pending: number; gapMs: number; dailyCap: number; savesShare: number }): number { const saves = Math.ceil(o.pending * Math.min(1, Math.max(0, o.savesShare))); const perSave = o.gapMs / 1000 + 15; const lookups = o.pending * 12; const capDays = Math.max(0, Math.ceil(saves / o.dailyCap) - 1); return Math.round(Math.max(saves * perSave + lookups, capDays * 86400 + (saves % o.dailyCap) * perSave)); } export async function runSpnBatch(opts: { plan: SpnBatchPlan; dryRun?: boolean; deps: SpnBatchDeps; jobId?: string; onLog?: (line: string) => void; onProgress?: (p: { done: number; total: number; initial: number; detail: string }) => void; signal?: AbortSignal; drainSignal?: AbortSignal; }): Promise { const { plan, deps } = opts; const state = plan.state; const log = (l: string) => opts.onLog?.(l); const run = { looked: 0, saved: 0, archivedAlready: 0, failed: 0 }; const iso = () => new Date(deps.now()).toISOString(); const persist = async () => { state.updatedAt = iso(); await writeFileAtomic(plan.statePath, JSON.stringify(state, null, 2) + "\n", { mkdir: true }); await writeEvidence(state); }; const initialDone = state.items.filter((i) => i.status !== "pending").length; let lookedThisRun = 0; let savesThisRun = 0; const savesShare = () => (lookedThisRun >= 5 ? savesThisRun / lookedThisRun : state.skipArchived ? 0.8 : 1); const eta = () => { const pending = state.items.filter((i) => i.status === "pending").length; return spnBatchEtaSeconds({ pending, gapMs: deps.pacer.gapMs(plan.mode), dailyCap: plan.dailyCap, savesShare: savesShare() }); }; const progress = (detail?: string) => { const done = state.items.filter((i) => i.status !== "pending").length; const c = spnBatchCounts(state.items); opts.onProgress?.({ done, total: state.items.length, initial: initialDone, detail: detail ?? `${done}/${state.items.length} · ${c.archivedAlready} archived already · ${c.saved} saved · ${c.failed} failed · ETA ~${fmtDuration(eta())}`, }); }; const result = (stopped?: string): SpnBatchResult => ({ batch: plan.id, mode: plan.mode, dryRun: opts.dryRun === true, resumed: plan.resumed, statePath: plan.statePath, evidence: state.evidence, counts: spnBatchCounts(state.items), run, etaSeconds: eta(), ...(stopped ? { stopped } : {}), ...(plan.rejected.length ? { rejected: plan.rejected.length } : {}), }); const c0 = spnBatchCounts(state.items); log( `Batch ${plan.id} (${plan.resumed ? "resumed" : "new"}), mode ${plan.mode}: ${c0.total} URLs — ${c0.pending} pending, ${c0.archivedAlready} archived already, ${c0.saved} saved, ${c0.failed} failed. ` + `${state.skipArchived ? `Each looked up first (${state.sources.join(" + ")}); ` : ""}saves ≥ ${Math.round(deps.pacer.gapMs(plan.mode) / 1000)} s apart, at most ${plan.dailyCap} a day. Evidence: ${state.evidence.json} (+ .csv).`, ); if (plan.rejected.length) log(`${plan.rejected.length} entries skipped (not http(s), or on the Wayback Machine): ${plan.rejected.slice(0, 5).join(", ")}${plan.rejected.length > 5 ? ", …" : ""}`); if (opts.dryRun) { log(`Dry run: nothing asked, nothing written. ETA for the pending URLs: ~${fmtDuration(eta())}.`); return result(); } if (opts.jobId && !state.jobIds.includes(opts.jobId)) state.jobIds.push(opts.jobId); delete state.stopped; await persist(); progress(); const sources = new Set(state.sources); // Hosts Save Page Now refused as a SITE ("limitations when it comes to // archiving this site"): their other URLs are looked up, never asked again. const refusedHosts = new Map(); const hostOf = (u: string) => { try { return new URL(u).hostname.replace(/^(www|mobile)\./, ""); } catch { return ""; } }; let restsInARow = 0; const stop = async (why: string) => { state.stopped = why; await persist(); log(`Stopped: ${why}`); return result(why); }; for (const item of state.items) { if (item.status !== "pending") continue; if (opts.signal?.aborted) return stop("cancelled"); if (opts.drainSignal?.aborted) return stop("drained: run the same request again to continue"); // 1. THE LOOKUP (once per URL; a resumed batch keeps what it found). if (state.skipArchived && !item.lookedAt && sources.size > 0) { let lookup: ArchiveLookup; try { lookup = await deps.lookup(item.url, { sources: [...sources], limit: SPN_BATCH_LOOKUP_LIMIT, ...(opts.signal ? { signal: opts.signal } : {}) }); } catch (e) { if (opts.signal?.aborted) return stop("cancelled"); throw e; } lookedThisRun++; run.looked++; let failedLookup = false; for (const entry of lookup.sources) { if (entry.ok) continue; if (entry.source === "archive.today") { // Never pressed: a check, a 429 or no answer at all, and archive.today // is left out of the lookups for the rest of the run. sources.delete("archive.today"); log(`archive.today did not answer the lookup (${entry.refusal ?? "error"}): it is left out of the lookups for the rest of this run. ${entry.error ?? ""}`.trim()); } else if (entry.source === "wayback" && entry.refusal !== "excluded") { failedLookup = true; log(`The Wayback lookup of ${item.url} failed: ${entry.error ?? "no answer"}`); } } if (failedLookup) { restsInARow++; if (restsInARow >= SPN_BATCH_MAX_RESTS) return stop(`the Wayback Machine's lookups kept failing (${restsInARow} in a row); run it again later`); const ms = Math.min(60 * 60_000, 5 * 60_000 * 2 ** (restsInARow - 1)); log(`Resting ${fmtDuration(ms / 1000)} before the next lookup.`); progress(`resting ${fmtDuration(ms / 1000)} (lookups failing)`); try { await deps.sleep(ms, opts.signal); } catch { return stop("cancelled"); } continue; } const excluded = lookup.sources.find((e) => e.source === "wayback" && e.refusal === "excluded"); item.copies = bestCopies(lookup); item.lookedAt = iso(); if (excluded) { item.status = "failed"; item.reason = excluded.error ?? "excluded from the Wayback Machine"; item.doneAt = iso(); run.failed++; await persist(); progress(); continue; } if (item.copies.some(shown)) { item.status = "archived-already"; item.doneAt = iso(); run.archivedAlready++; const c = item.copies.find(shown)!; log(`${item.url}: archived already — ${c.url}`); await persist(); progress(); continue; } if (item.copies.length) log(`${item.url}: copies exist but none recorded the page (${item.copies.map((c) => `${c.source} ${c.status ?? "?"}`).join(", ")}); saving.`); await persist(); } const refusedWhy = refusedHosts.get(hostOf(item.url)); if (refusedWhy) { item.status = "failed"; item.reason = `not asked: ${refusedWhy}`; item.doneAt = iso(); run.failed++; await persist(); progress(); continue; } // 2. THE DAILY BUDGET. const nowMs = deps.now(); state.saveTimes = state.saveTimes.filter((t) => nowMs - Date.parse(t) < DAY_MS); if (state.saveTimes.length >= plan.dailyCap) { const until = Date.parse(state.saveTimes[0]) + DAY_MS + 60_000; const ms = Math.max(0, until - nowMs); log(`${state.saveTimes.length} saves in the last 24 h (the cap is ${plan.dailyCap}): waiting until ${new Date(until).toISOString()}.`); await persist(); progress(`daily cap reached: waiting until ${new Date(until).toISOString()}`); try { await deps.sleep(ms, opts.signal); } catch { return stop("cancelled"); } if (opts.drainSignal?.aborted) return stop("drained: run the same request again to continue"); } // 3. THE SAVE. savesThisRun++; item.attempts = (item.attempts ?? 0) + 1; let r: SavePageNowResult; try { r = await deps.save(item.url, { onLog: log, ...(opts.signal ? { signal: opts.signal } : {}) }); } catch (e) { if (opts.signal?.aborted) return stop("cancelled"); throw e; } if (opts.signal?.aborted || r.error === "cancelled") return stop("cancelled"); if (r.ok && r.waybackUrl && r.captureTs) { restsInARow = 0; item.status = "saved"; item.saved = { url: r.waybackUrl, captureTs: r.captureTs, mode: plan.mode }; item.doneAt = iso(); delete item.reason; state.saveTimes.push(iso()); run.saved++; } else if (r.rateLimited) { // The URL stays pending; the pacer rests before the next save. restsInARow++; state.saveTimes.push(iso()); item.reason = r.error; if (restsInARow >= SPN_BATCH_MAX_RESTS) { return stop(`archive.org kept asking us to slow down (${restsInARow} rests in a row); run the same request again later`); } await persist(); progress(`resting: ${r.error ?? "archive.org asked us to slow down"}`); // Try this URL again after the rest (the loop's next pass, below). const again = await retrySameItem(item); if (again) return again; continue; } else { restsInARow = 0; state.saveTimes.push(iso()); item.status = "failed"; item.reason = r.error ?? "Save Page Now failed"; item.doneAt = iso(); run.failed++; if (r.code === "host-limited") { const host = hostOf(item.url); refusedHosts.set(host, `Save Page Now refuses ${host} as a site (asked once, for ${item.url}: ${r.error ?? "refused"})`); log(`Save Page Now refuses ${host} as a site: its other URLs are looked up, not asked to be saved, this run.`); } } await persist(); progress(); } const c = spnBatchCounts(state.items); if (c.pending > 0) return stop(`${c.pending} URLs still pending (rested or still being captured); run the same request again to continue`); await persist(); log(`Done: ${c.archivedAlready} archived already, ${c.saved} saved, ${c.failed} failed, of ${c.total}.`); return result(); // A rested URL is asked again, as many times as the rests allow, before the // batch moves on: order is kept, and the pacer's rest is the wait. async function retrySameItem(item: SpnBatchItem): Promise { for (;;) { if (opts.signal?.aborted) return stop("cancelled"); if (opts.drainSignal?.aborted) return stop("drained: run the same request again to continue"); item.attempts = (item.attempts ?? 0) + 1; const r = await deps.save(item.url, { onLog: log, ...(opts.signal ? { signal: opts.signal } : {}) }); if (opts.signal?.aborted || r.error === "cancelled") return stop("cancelled"); state.saveTimes.push(iso()); if (r.ok && r.waybackUrl && r.captureTs) { restsInARow = 0; item.status = "saved"; item.saved = { url: r.waybackUrl, captureTs: r.captureTs, mode: plan.mode }; item.doneAt = iso(); delete item.reason; run.saved++; await persist(); progress(); return null; } if (r.rateLimited) { restsInARow++; item.reason = r.error; if (restsInARow >= SPN_BATCH_MAX_RESTS) { return stop(`archive.org kept asking us to slow down (${restsInARow} rests in a row); run the same request again later`); } await persist(); progress(`resting: ${r.error ?? "archive.org asked us to slow down"}`); continue; } restsInARow = 0; item.status = "failed"; item.reason = r.error ?? "Save Page Now failed"; item.doneAt = iso(); run.failed++; await persist(); progress(); return null; } } } // ─── THE JOB ──────────────────────────────────────────────────────────────── const running = new Map(); const defaultSleep = (ms: number, signal?: AbortSignal) => new Promise((resolve, reject) => { if (signal?.aborted) return reject(signal.reason ?? new Error("aborted")); const t = setTimeout(resolve, ms); signal?.addEventListener( "abort", () => { clearTimeout(t); reject(signal.reason ?? new Error("aborted")); }, { once: true }, ); }); export async function defaultSpnBatchDeps(paths: Paths, settings?: BatchSettings, spnDeps?: Partial): Promise { const { archiveLookup } = await import("../lib/archives/index"); return { lookup: (url, o) => o.sources.length === 2 ? archiveLookup(url, { limit: o.limit, ...(o.signal ? { signal: o.signal } : {}) }) : archiveLookup(url, { source: o.sources[0], limit: o.limit, ...(o.signal ? { signal: o.signal } : {}) }), save: (url, o) => savePageNow({ paths, url, onLog: o.onLog, ...(o.signal ? { signal: o.signal } : {}), ...(settings ? { settings } : {}), ...(spnDeps ? { deps: spnDeps } : {}) }), pacer: spnDeps?.pacer ?? spnPacer, now: () => Date.now(), sleep: defaultSleep, }; } // A dry run, answered now (no job, no request): the plan and the ETA. export async function spnBatchDryRun(paths: Paths, req: SpnBatchRequest, o: { settings?: BatchSettings; env?: Readonly> } = {}) { const planned = await planSpnBatch(paths, req, o); if (!planned.ok) return planned; const lines: string[] = []; const r = await runSpnBatch({ plan: planned.plan, dryRun: true, deps: { lookup: async () => ({ url: "", found: 0, sources: [] }), save: async (url) => ({ ok: false, url, error: "dry run" }), pacer: spnPacer, now: () => Date.now(), sleep: async () => {}, }, onLog: (l) => lines.push(l), }); return { ok: true as const, ...r, log: lines }; } // THE JOB: one `save-page-now-batch` job on its own queue, the state resumed // when there is one. Refused (no job) with the plan's sentence, or when the // same batch already runs. export async function queueSpnBatch(opts: { paths: Paths; req: SpnBatchRequest; requestedBy?: string; settings?: BatchSettings; env?: Readonly>; deps?: SpnBatchDeps; onDone?: (r: SpnBatchResult) => void; }): Promise { const planned = await planSpnBatch(opts.paths, opts.req, { ...(opts.settings ? { settings: opts.settings } : {}), ...(opts.env ? { env: opts.env } : {}) }); if (!planned.ok) return { ok: false, error: planned.error }; const { plan } = planned; const already = running.get(plan.id); if (already) return { ok: false, error: `batch ${plan.id} is already queued or running${already === "starting" ? "" : ` as job ${already}`}` }; running.set(plan.id, "starting"); const res = await runManagedFunction({ kind: SPN_BATCH_JOB_KIND, queueKey: SPN_BATCH_QUEUE, paths: opts.paths, // A spec needs a slug; the replay reads params.batch (the state holds the list). spec: { kind: SPN_BATCH_JOB_KIND, slug: "_spn-batch", params: { batch: plan.id, evidence: plan.state.evidence.json, skipArchived: plan.state.skipArchived, sources: plan.state.sources, dailyCap: plan.dailyCap } }, fn: async (onLog, signal, setProgress, ctx) => { try { onLog(`Save Page Now, a list${opts.requestedBy ? ` for ${opts.requestedBy}` : ""}: batch ${plan.id}.`); // Re-read at the start: a queued job resumes from the state as it is then. const fresh = await planSpnBatch(opts.paths, { ...opts.req, batch: plan.id, evidence: plan.state.evidence.json, dailyCap: plan.dailyCap }, { ...(opts.settings ? { settings: opts.settings } : {}), ...(opts.env ? { env: opts.env } : {}), }); if (!fresh.ok) throw new Error(fresh.error); const taskId = `spn-batch-${plan.id}`; ctx.addTask({ id: taskId, label: `Save Page Now: ${plan.state.items.length} pages`, kind: "download", startedAt: Date.now() }); const r = await runSpnBatch({ plan: fresh.plan, deps: opts.deps ?? (await defaultSpnBatchDeps(opts.paths, opts.settings)), jobId: ctx.jobId, onLog, onProgress: (p) => { setProgress({ metric: "pages", initial: p.initial, target: p.total, current: p.done }); ctx.updateTask(taskId, { fraction: p.total ? p.done / p.total : 0, detail: p.detail }); }, signal, drainSignal: ctx.drainSignal, }); ctx.removeTask(taskId); onLog(`${SPN_BATCH_RESULT_MARKER}${JSON.stringify(r)}`); opts.onDone?.(r); if (r.stopped === "cancelled") throw new Error("cancelled"); if (r.stopped && !r.stopped.startsWith("drained")) throw new Error(r.stopped); } finally { running.delete(plan.id); } }, }); if (!res.ok) running.delete(plan.id); else if (running.has(plan.id)) running.set(plan.id, res.jobId); return { ...res, batch: plan.id }; }