commit c766cb515fcd61c8b3bf52ce75ecaf2ed6b2d2db
parent d53ddc7e382f450c2c56db0382eebe6458fa98b9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 5 Nov 2026 19:50:21 -0500
Merge lane/spn-batch: Save Page Now without keys (anonymous, one shared pacer: one save at a time, >= 60 s apart, rests on 429/503/Retry-After) and save-page-now-batch (a list, resumable, each URL looked up first in the Wayback CDX and archive.today and skipped when a copy exists, a daily cap, an evidence JSON + CSV); a site archive.org refuses as a site (x.com, 523) is asked once per 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"; "politely, of course")
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
21 files changed, 1844 insertions(+), 91 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -191,7 +191,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `import-page` | import-page imports ONE Wayback Machine capture of a page that is not a video into a Wayback pages channel (platform "webpage"): {"slug", "url"} — a capture's replay URL (web.archive.org/web/<timestamp>/<page>) — or {"slug", "url": <the page>, "at": "YYYYMMDD\[hhmmss\]"} for the capture nearest that date (one CDX lookup). An import-page job on the archive.org queue, at archive.org's pace: the raw (id\_) body, at most 2 MB, html, plain text or JSON only, redirects followed inside the archive only and the FINAL capture recorded; stored under the channel's pages/, read by the first site extractor that claims it (else the generic one), its page records written to the channel's posts. Refused, before any job: no such channel, not a Wayback pages channel, a URL that names no capture, a video (use import-video), an X capture outside an X channel while social.x.visibility is "private". A capture already stored is not fetched again. "dryRun" answers what it would fetch and starts nothing. The log ends with @@import-page {ok, slug, url, captureTs, originalUrl, records, written, updated, unchanged, extractor, already?, error?}. archive.today (release 37 lane F): "url" may be an archive.today copy (archive.ph/<id>, /<timestamp>/<page>, /newest/<page>), or the page's own URL with "at" and "source": "archive.today" for its copy nearest that date (one timemap request); the job runs on the platform:archive.today queue at archive.today's pace (one request at a time, 8 s apart; a 429 stops it and rests the client). The copy is stored as served with its source and URL. A check page (a CAPTCHA) is refused, never solved: Connect archive session on the channel page or Settings, then again. The result carries "source", "mementoUrl" and, for a refusal, "refusal": "excluded" (the Wayback Machine answered 403 for the page), "challenge", "rate-limited", …. | `pnpm ops import-page --json '{"slug":"demo-pages","url":"https://web.archive.org/web/20140305120000/https://blog.example/a-post.html","dryRun":true}'`<br>`pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20140301"}' --wait`<br>`pnpm ops import-page --json '{"slug":"demo-pages","url":"https://archive.ph/AbCdE","dryRun":true}'`<br>`pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20190601","source":"archive.today"}' --wait` |
| `reextract-pages` | reextract-pages re-derives a Wayback pages channel's records from the raw captures it stores: {"slug", "dryRun"?}. No request. A reextract-pages job on the archive.org queue (never beside an import into the channel): every stored capture read again by the extractor it goes to now, the records replaced when anything differs. The log ends with @@reextract-pages {captures, stale, records: {added, changed, removed, unchanged, kept}, written}. | `pnpm ops reextract-pages --json '{"slug":"demo-pages","dryRun":true}' --wait` |
| `check-post-availability` | check-post-availability checks which of a posts channel's archived posts are gone at their source: {"slug", "mode"?: "stale" (default) \| "unchecked" \| "all", "limit"?: 200}, as a check-post-availability job. A Wayback pages channel's records are checked by their ORIGINAL URL at its own site (never the Wayback Machine), one request per distinct URL through the editor's web pacer (3 s apart): HEAD, then GET when the HEAD is refused or the platform has a "gone" page; available (2xx on the same site), deleted (404/410, or X's, Tumblr's, Google Docs' or YouTube's "does not exist" page), account\_unavailable (suspended, not shared), error otherwise — with the status. A deleted original means the Wayback copy is the only copy. Verdicts go to posts-availability.json. | `pnpm ops check-post-availability --json '{"slug":"demo-pages","mode":"unchecked"}' --wait` |
-| `save-page-now` | save-page-now asks the Wayback Machine to capture a live page now (Save Page Now, with archive.org's S3 keys): {"url", "slug"?, "dryRun"?}. A save-page-now job on the archive.org queue: the capture asked (the page alone, no outlinks), its status polled until it is made, then — with slug, a Wayback pages channel — an import-page job of the new capture. Refused, before any job: no keys (ARCHIVE\_ORG\_S3\_ACCESS and ARCHIVE\_ORG\_S3\_SECRET in the editor's environment, or the mode-600 file settings archiveOrg.s3KeyFile names), a URL that is not http(s), a page on the Wayback Machine, not a Wayback pages channel, a video, an X page outside an X channel while X is private. The keys are never logged. "dryRun" answers what it would ask and starts nothing. The log ends with @@save-page-now {ok, url, slug?, spnJobId, captureTs, originalUrl, waybackUrl, importJobId?, importError?, polls, error?}. | `pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages","dryRun":true}'`<br>`pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages"}' --wait` |
+| `save-page-now` | save-page-now asks the Wayback Machine to capture a live page now (Save Page Now): {"url", "slug"?, "dryRun"?}. With archive.org's S3 keys (ARCHIVE\_ORG\_S3\_ACCESS and ARCHIVE\_ORG\_S3\_SECRET in the editor's environment, or the mode-600 file settings archiveOrg.s3KeyFile names) it is SPN2 ("mode": "keys"); with none configured it is the public endpoint, anonymously ("mode": "anonymous": archive.org allows 3 a minute and 200 a day). A save-page-now job on the archive.org queue: the capture asked (the page alone, no outlinks), its status polled until it is made, then — with slug, a Wayback pages channel — an import-page job of the new capture. One save at a time in the process, at least 60 s apart anonymous (10 s with keys); a 429/503 rests it (Retry-After, else 2 min doubling to 1 h). Refused, before any job: a key file that is there but readable by others, a URL that is not http(s), a page on the Wayback Machine, not a Wayback pages channel, a video, an X page outside an X channel while X is private. The keys are never logged. "dryRun" answers what it would ask and starts nothing. The log ends with @@save-page-now {ok, url, slug?, mode, spnJobId?, captureTs, originalUrl, waybackUrl, importJobId?, importError?, polls, rateLimited?, error?}. | `pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages","dryRun":true}'`<br>`pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages"}' --wait` |
+| `save-page-now-batch` | save-page-now-batch saves a LIST of pages as ONE resumable job: {"urls": \[...\]} \| {"file": <abs path: a JSON list, {urls}, or a URL a line>} \| {"batch": <id>}, "skipArchived"? (true), "sources"? (\["wayback", "archive.today"\]), "evidence"? (abs path), "dailyCap"? (150 anonymous, at most 200; 5000 with keys), "dryRun"? -> {jobId, batch}. Each URL in turn: looked up (the Wayback CDX, archive.today's timemap, each paced) and archived-already when a copy shows it (a Wayback row that recorded a 200, or an archive.today copy); else saved through Save Page Now's pacer (anonymous without keys), saved or failed with the reason; a site Save Page Now refuses as a site (x.com, 5 Nov: "limitations when it comes to archiving this site") is asked once a run, its other URLs looked up only. archive.today and Ghostarchive are looked up, never asked to save. The state is <transcripts>/.spn-batches/<batch>.json, written after every URL: the same request again, {batch}, a Retry or a restart continues from the first pending URL. The evidence (JSON + CSV: url, status, reason, waybackUrl, waybackCaptureTs, waybackHttpStatus, waybackMimetype, archiveTodayUrl, archiveTodayCaptureTs, shows, savedMode, checkedAt, doneAt) is rewritten after every URL; default <transcripts>/.spn-batches/<batch>.evidence.json. Progress (done/total, ETA) in /jobs. The log ends with @@save-page-now-batch {batch, mode, counts, run, evidence, statePath, etaSeconds, stopped?}. | `pnpm ops save-page-now-batch --json '{"file":"/home/me/lists/posts.json","dryRun":true}'`<br>`pnpm ops save-page-now-batch --json '{"file":"/home/me/lists/posts.json","evidence":"/home/me/evidence/posts"}'`<br>`pnpm ops save-page-now-batch --json '{"batch":"spn-0123456789ab"}'` |
| `archive-lookup` | archive-lookup answers the copies of a page each archive source holds: {"url"} (the page's own URL), "source"?: "wayback" \| "archive.today" (default both), "limit"?: 50 per source (at most 500) -> {url, found, sources: \[{source, label, ok, captures: \[{source, captureTs, originalUrl, mementoUrl, status?, mimetype?}\], refusal?, error?}\]}, oldest first. Each source through its own paced client; one that refuses is its own entry's sentence (refusal "excluded": excluded from the Wayback Machine (cause unknown); "challenge"; "rate-limited"). Read only. wayback-lookup stays. | `pnpm ops archive-lookup --json '{"url":"https://blog.example/a-post.html"}'` |
| `x-search-lead` | x-search-lead acts on one lead of an X search channel (the accounts its posts came from — `get channel <slug> --leads [--limit <n>]` lists them, most matches first): {"slug", "handle", "action": "archive" \| "never" \| "restore"}. "archive" creates <handle>-x, an X channel on NO site, by the New channel form's path and starts its first post fetch ("fetch": false skips it; "name"? names it; "dryRun" answers the fields and creates nothing) -> {slug, jobIds}. Refused: not an X search channel, an account an X channel archives already, a slug taken. "never" hides the handle (the channel's xSearch.exclude), "restore" un-hides it -> {exclude, changed}. No model, no request but the new channel's fetch. | `pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"archive","dryRun":true}'`<br>`pnpm ops x-search-lead --json '{"slug":"demo-search","handle":"example","action":"never"}'` |
| `wayback-lookup` | wayback-lookup answers the Wayback Machine's captures of a page (its CDX API): {"url"} or a record's {"slug", "id"} (its metadata's page, else its availability check's, else the playlist's), "okOnly"?: only the captures that recorded a 200, "limit"?: 100 (at most 500) -> {url, found, captures: \[{timestamp, status, mimetype?, replayUrl}\]}, oldest first. One request through the editor's Wayback client, with archive.org's manners (one at a time, 2 s apart, 429s waited out). Read only. A URL the Wayback Machine answers 403 for is excluded: HTTP 403, "refusal": "excluded" ("excluded from the Wayback Machine (cause unknown)"). | `pnpm ops wayback-lookup --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","okOnly":true}'` |
diff --git a/OPERATING.md b/OPERATING.md
@@ -326,11 +326,51 @@ pnpm ops find-copy --json '{"siteId":"<site>","pages":true,"channel":"old-bl
deleted post does (`posts-availability.json`, merged by the index).
- **Save Page Now** ("Ask the Wayback Machine to capture this now", on the channel page: any URL, or a record whose
original is still up): archive.org captures the page alone, the job waits for it, then imports the capture
- into the channel. It needs archive.org's S3 keys (archive.org/account/s3.php): `ARCHIVE_ORG_S3_ACCESS` and
+ into the channel. With archive.org's S3 keys (archive.org/account/s3.php: `ARCHIVE_ORG_S3_ACCESS` and
`ARCHIVE_ORG_S3_SECRET` in the editor's environment, or two such lines in the mode-600 file
- `settings.archiveOrg.s3KeyFile` names (default `~/.config/archilyzer/archive-org.env`). Without them the button is
- off and says why. One capture at a time, on archive.org's queue. Other code starts one with
+ `settings.archiveOrg.s3KeyFile` names, default `~/.config/archilyzer/archive-org.env`) it is SPN2 (`"mode": "keys"`).
+ With none configured it asks archive.org's public endpoint anonymously (`"mode": "anonymous"`; archive.org allows
+ an anonymous client 3 captures a minute and 200 a day), and the panel says so; a key file that is there but
+ readable by others is refused. One capture at a time in the whole process, at least 60 s apart anonymous (10 s
+ with keys); a 429/503 rests it (Retry-After, else 2 min doubling to 1 h). Other code starts one with
`startSavePageNowJob({url, slug})` (`common/controller/savePageNow.ts`).
+
+### Archive a list of pages politely (evidence)
+
+"Make sure evidence of the pages exists": a list of URLs (posts, pages) checked against the public archives and
+saved where no copy shows them, as ONE resumable job, with an evidence file that says, per URL, where the copy is.
+
+```sh
+pnpm ops save-page-now-batch --json '{"file":"/abs/path/urls.json","dryRun":true}'
+pnpm ops save-page-now-batch --json '{"file":"/abs/path/urls.json","evidence":"/abs/path/evidence/posts"}'
+pnpm ops get job <jobId> # done/total and the ETA, also on /jobs
+pnpm ops save-page-now-batch --json '{"batch":"spn-<id>"}' # continue after a cancel, a stop or a restart
+```
+
+- `file` is a JSON list of URLs, `{"urls": [...]}`, or one URL a line (or pass `"urls": [...]`). The list is
+ deduped; anything not http(s), or already a Wayback URL, is left out and counted.
+- Each URL in turn: **looked up** (`skipArchived`, the default) — the Wayback Machine's CDX and archive.today's
+ timemap, each through its own paced client — and `archived-already` when a copy shows the page (a Wayback row
+ that recorded a 200, or any archive.today copy; a row that recorded only a redirect does not count). Else
+ **saved** with Save Page Now (anonymous without keys), through the same pacer as a single save: `saved` with
+ the new capture's URL, or `failed` with archive.org's reason. A URL archive.org rested on stays `pending` and is
+ asked again after the rest; six rests in a row stop the job (run it again later). A site Save Page Now refuses
+ AS A SITE is asked once a run: **x.com today** (5 Nov, anonymous: HTTP 523, "We're currently facing some
+ limitations when it comes to archiving this site") — every other X URL is still looked up (existing copies are
+ the evidence) and recorded `failed` with `not asked: …`, never asked again that run.
+- Without keys the batch spends at most `dailyCap` saves (150; archive.org's anonymous cap is 200) in any 24 h and
+ waits out the window, saying until when — a list of a thousand runs for days. It has its own queue, so the
+ archive.org queue's page imports are not held behind it.
+- **archive.today and Ghostarchive are looked up, never asked to save**: their save forms put a CAPTCHA in front.
+ An archive.today check (or 429) during the lookups leaves it out for the rest of the run.
+- The state is `<transcripts>/.spn-batches/<batch>.json` (the batch id is the list's hash, so the same request
+ continues the same batch), written after every URL; a restart resumes the job on boot, and Retry continues it.
+- The evidence — `<evidence>.json` and `<evidence>.csv`, default `<transcripts>/.spn-batches/<batch>.evidence.*` —
+ is rewritten after every URL: `url, status, reason, waybackUrl, waybackCaptureTs, waybackHttpStatus,
+ waybackMimetype, archiveTodayUrl, archiveTodayCaptureTs, shows, savedMode, checkedAt, doneAt`. `shows` is what
+ the archive's own row says (`yes` a 200 or an archive.today copy, `redirect`, `no`, `unknown` for a capture made
+ just now, which the CDX lists hours later); no page is downloaded to judge it. An X post's capture can be the
+ login wall even at a 200: open a few.
- **find-copy, page mode** (`"pages": true`): every `page` citation of a report whose original is gone gets the
Wayback capture nearest the citation's date imported into the Wayback pages channel named (`"channel"`), else
the one whose targets cover the page; a cited page record whose original is gone has its capture imported again
diff --git a/common/controller/savePageNow.test.ts b/common/controller/savePageNow.test.ts
@@ -72,9 +72,16 @@ test("the keys: the environment first, else a mode-600 file; a file others can r
assert.equal(sanitizeArchiveOrg({ s3KeyFile: "/etc/keys/ia.env" }).s3KeyFile, "/etc/keys/ia.env");
assert.equal(sanitizeArchiveOrg({}).s3KeyFile, "~/.config/archilyzer/archive-org.env");
// The button: off, with the sentence; on with keys.
- assert.deepEqual(savePageNowAvailability({ settings: SETTINGS, env: ENV }), { on: true });
- const off = savePageNowAvailability({ settings: SETTINGS, env: {} });
+ assert.deepEqual(savePageNowAvailability({ settings: SETTINGS, env: ENV }), { on: true, mode: "keys" });
+ // Lane spn-batch: NO keys configured is anonymous, not off.
+ const anon = savePageNowAvailability({ settings: SETTINGS, env: {} });
+ assert.equal(anon.on && anon.mode, "anonymous");
+ // A key file that is there but unsafe is still off: the operator meant keys.
+ chmodSync(file, 0o644);
+ const off = savePageNowAvailability({ settings: { archiveOrg: { s3KeyFile: file } }, env: {} });
assert.equal(off.on, false);
+ assert.match(off.on ? "" : off.reason, /readable by others/);
+ chmodSync(file, 0o600);
});
test("SPN's answers read: a job id, a refusal by status_ext, the keys refused; pending, success, a failed capture", () => {
@@ -100,7 +107,10 @@ test("refused before any request: no keys, not http(s), a Wayback URL, not a pag
const r = await planSavePageNow(paths, { url, ...(slug ? { slug } : {}), settings: SETTINGS, env });
return r.ok ? "" : r.error;
};
- assert.match(await ask(LIVE, "live-notes", {}), /Save Page Now needs archive\.org S3 keys/);
+ // Lane spn-batch: no keys is not a refusal — the capture is asked anonymously.
+ assert.equal(await ask(LIVE, "live-notes", {}), "");
+ const anonPlan = await planSavePageNow(paths, { url: LIVE, settings: SETTINGS, env: {} });
+ assert.equal(anonPlan.ok && anonPlan.plan.mode, "anonymous");
assert.match(await ask("ftp://live.example/x"), /only http and https/);
assert.match(await ask(`https://web.archive.org/web/2014/${LIVE}`), /on the Wayback Machine already/);
assert.match(await ask(LIVE, "a-video-channel"), /not a Wayback pages channel/);
@@ -110,7 +120,7 @@ test("refused before any request: no keys, not http(s), a Wayback URL, not a pag
assert.equal(await ask(LIVE, "live-notes"), "");
assert.equal(await ask(LIVE), "", "no channel: the capture alone");
// The job door refuses the same way and starts nothing.
- const q = await queueSavePageNow({ paths, url: LIVE, slug: "live-notes", settings: SETTINGS });
+ const q = await queueSavePageNow({ paths, url: "https://www.youtube.com/watch?v=abcdefghijk", slug: "live-notes", settings: SETTINGS });
assert.equal(q.ok, false);
});
diff --git a/common/controller/savePageNow.ts b/common/controller/savePageNow.ts
@@ -9,8 +9,19 @@
// into (absent: the capture is made and named, not
// imported)
//
-// Refused before any request, with the sentence a caller shows: no keys (the
-// button is off and says why), a URL that is not http(s), a page on the
+// WITHOUT KEYS (lane spn-batch, 5 Nov) the capture is asked ANONYMOUSLY, at
+// archive.org's public endpoint (lib/waybackPages/savePageNow.ts
+// parseSpnAnonymous), under its stricter limits: every result and log names
+// its `mode` ("anonymous" | "keys"). A key FILE that is there but unsafe
+// (others can read it, no key lines) is still refused: the operator meant keys.
+//
+// ONE SAVE AT A TIME, process-wide (SpnPacer below): a single job and a batch
+// (controller/savePageNowBatch.ts) take turns through the same pacer — at
+// least SPN_ANON_GAP_MS (60 s) between anonymous saves, SPN_KEYS_GAP_MS (10 s)
+// with keys, both stretched by pacing.jitter; a 429/503 or SPN's own "slow
+// down" codes rest it (Retry-After when sent, else 2 min doubling to 1 h).
+//
+// Refused before any request, with the sentence a caller shows: a URL that is not http(s), a page on the
// Wayback Machine itself, a channel that is not a Wayback pages channel, a
// video ("use import-video"), an X page outside an X-scoped channel while X
// posts are private (importPage's own rule).
@@ -42,6 +53,113 @@ import {
import { readSpnKeys, redactSpnKeys } from "../lib/waybackPages/savePageNow-server";
import { startImportPageJob, WAYBACK_PAGES_QUEUE, xCaptureRefusal } from "./importPage";
import { jitterMs } from "../lib/jitter";
+import {
+ parseSpnAnonymous,
+ spnAnonymousSaveUrl,
+ spnStatusRests,
+ spnUserAgent,
+ type SpnMode,
+} from "../lib/waybackPages/savePageNow";
+import { parseRetryAfterMs } from "../lib/archiveOrgClient";
+import { PROJECT_NAME, PROJECT_URL } from "../lib/project";
+import { existsSync } from "node:fs";
+import os from "node:os";
+import { DEFAULT_ARCHIVE_ORG_S3_KEY_FILE } from "../lib/archiveOrgTorrent";
+
+export type { SpnMode };
+
+export const SPN_USER_AGENT = spnUserAgent(PROJECT_NAME, PROJECT_URL);
+
+// The gap between two saves, from this process (a floor; jitter only adds).
+export const SPN_ANON_GAP_MS = 60_000;
+export const SPN_KEYS_GAP_MS = 10_000;
+// The rest after a 429/503/"slow down": Retry-After when longer, else this,
+// doubling per rest in a row, at most SPN_MAX_REST_MS.
+export const SPN_BASE_REST_MS = 2 * 60_000;
+export const SPN_MAX_REST_MS = 60 * 60_000;
+// How long one anonymous capture GET may take (SPN's own cap is 2 minutes).
+export const SPN_ANON_TIMEOUT_MS = 150_000;
+
+type PacerDeps = { now: () => number; sleep: (ms: number, signal?: AbortSignal) => Promise<void> };
+
+// THE PACER: one save at a time, the gap between saves, and the rest after a
+// refusal — shared by every Save Page Now in the process.
+export class SpnPacer {
+ private chain: Promise<unknown> = Promise.resolve();
+ private lastSaveAt = -Infinity;
+ private restUntil = 0;
+ private restsInARow = 0;
+ constructor(
+ private readonly deps: PacerDeps,
+ private readonly gaps: { anonymous: number; keys: number } = { anonymous: SPN_ANON_GAP_MS, keys: SPN_KEYS_GAP_MS },
+ ) {}
+
+ gapMs(mode: SpnMode): number {
+ return this.gaps[mode];
+ }
+
+ // When the next save may start (epoch ms).
+ nextAt(mode: SpnMode): number {
+ return Math.max(this.lastSaveAt + this.gaps[mode], this.restUntil);
+ }
+
+ resting(): { until: number; inARow: number } | null {
+ return this.restUntil > this.deps.now() ? { until: this.restUntil, inARow: this.restsInARow } : null;
+ }
+
+ // Run one save: after every earlier one, its gap and any rest.
+ turn<T>(mode: SpnMode, fn: () => Promise<T>, o: { signal?: AbortSignal; onWait?: (ms: number, why: string) => void } = {}): Promise<T> {
+ const run = this.chain.then(async () => {
+ const resting = this.restUntil > this.deps.now();
+ const wait = Math.max(this.lastSaveAt + jitterMs(this.gaps[mode]), this.restUntil) - this.deps.now();
+ if (wait > 0) {
+ o.onWait?.(wait, resting ? "resting after archive.org asked us to slow down" : "the gap between saves");
+ await this.deps.sleep(wait, o.signal);
+ }
+ try {
+ return await fn();
+ } finally {
+ this.lastSaveAt = this.deps.now();
+ }
+ });
+ this.chain = run.catch(() => {});
+ return run;
+ }
+
+ // archive.org asked us to slow down: rest (and say how long).
+ rest(retryAfterMs?: number | null): number {
+ this.restsInARow++;
+ const doubling = Math.min(SPN_MAX_REST_MS, SPN_BASE_REST_MS * 2 ** (this.restsInARow - 1));
+ const ms = Math.max(doubling, Math.min(retryAfterMs ?? 0, 24 * 60 * 60_000));
+ this.restUntil = Math.max(this.restUntil, this.deps.now() + ms);
+ return ms;
+ }
+
+ // A save went through: the rests in a row start over.
+ saved(): void {
+ this.restsInARow = 0;
+ }
+}
+
+export const spnPacer = new SpnPacer({ now: () => Date.now(), sleep: (ms, signal) => defaultSleep(ms, signal) });
+
+const expandHome = (p: string) => (p === "~" || p.startsWith("~/") ? os.homedir() + p.slice(1) : p);
+
+// The keys, or anonymous when NONE are configured (no env pair, no key file);
+// a key file that exists but cannot be used is refused with its sentence.
+export function spnKeysOrAnonymous(o: { keyFile?: string; env?: Readonly<Record<string, string | undefined>> }):
+ | { ok: true; mode: "keys"; keys: SpnKeys }
+ | { ok: true; mode: "anonymous" }
+ | { ok: false; reason: string } {
+ const read = readSpnKeys({ ...(o.keyFile ? { keyFile: o.keyFile } : {}), ...(o.env ? { env: o.env } : {}) });
+ if (read.ok) return { ok: true, mode: "keys", keys: read.keys };
+ const file = expandHome(o.keyFile?.trim() || DEFAULT_ARCHIVE_ORG_S3_KEY_FILE);
+ if (existsSync(file)) return { ok: false, reason: read.reason };
+ return { ok: true, mode: "anonymous" };
+}
+
+export const SPN_ANONYMOUS_NOTE =
+ "No archive.org S3 keys: Save Page Now asks anonymously (archive.org allows 3 captures a minute and 200 a day), one at a time, at least 60 s apart.";
export const SAVE_PAGE_NOW_JOB_KIND = "save-page-now";
export const SAVE_PAGE_NOW_RESULT_MARKER = "@@save-page-now ";
@@ -53,17 +171,18 @@ export const SPN_MAX_POLLS = 30;
type SpnSettings = { archiveOrg?: { s3KeyFile?: string }; social?: { x?: { visibility?: unknown } } };
-export type SavePageNowAvailability = { on: true } | { on: false; reason: string };
+export type SavePageNowAvailability = { on: true; mode: "keys" } | { on: true; mode: "anonymous"; note: string } | { on: false; reason: string };
// Whether the button is on, and why not: the keys' presence (never their
// value).
export function savePageNowAvailability(o: { settings?: SpnSettings; env?: Readonly<Record<string, string | undefined>> } = {}): SavePageNowAvailability {
const settings = o.settings ?? (getSettings() as SpnSettings);
- const read = readSpnKeys({ keyFile: settings.archiveOrg?.s3KeyFile, ...(o.env ? { env: o.env } : {}) });
- return read.ok ? { on: true } : { on: false, reason: read.reason };
+ const read = spnKeysOrAnonymous({ keyFile: settings.archiveOrg?.s3KeyFile, ...(o.env ? { env: o.env } : {}) });
+ if (!read.ok) return { on: false, reason: read.reason };
+ return read.mode === "keys" ? { on: true, mode: "keys" } : { on: true, mode: "anonymous", note: SPN_ANONYMOUS_NOTE };
}
-export type SavePageNowPlan = { url: string; slug?: string; keys: SpnKeys };
+export type SavePageNowPlan = { url: string; slug?: string; mode: SpnMode; keys?: SpnKeys };
// Everything checked before a request: the plan, or the refusal.
export async function planSavePageNow(
@@ -92,15 +211,23 @@ export async function planSavePageNow(
const x = xCaptureRefusal(config, slug, url, settings);
if (x) return { ok: false, error: x };
}
- const read = readSpnKeys({ keyFile: settings.archiveOrg?.s3KeyFile, ...(opts.env ? { env: opts.env } : {}) });
+ const read = spnKeysOrAnonymous({ keyFile: settings.archiveOrg?.s3KeyFile, ...(opts.env ? { env: opts.env } : {}) });
if (!read.ok) return { ok: false, error: read.reason };
- return { ok: true, plan: { url, ...(slug ? { slug } : {}), keys: read.keys } };
+ return { ok: true, plan: { url, ...(slug ? { slug } : {}), mode: read.mode, ...(read.mode === "keys" ? { keys: read.keys } : {}) } };
}
export type SavePageNowResult = {
ok: boolean;
url: string;
slug?: string;
+ // "anonymous" (no keys: the public endpoint) or "keys" (SPN2 with S3 keys).
+ mode?: SpnMode;
+ // archive.org asked us to slow down (a 429/503, SPN's "too many"): the
+ // capture was not made, the pacer rests `restMs`; `daily` when it was the
+ // day's cap.
+ rateLimited?: boolean;
+ restMs?: number;
+ daily?: boolean;
dryRun?: boolean;
// What a dry run would ask.
wouldAsk?: string;
@@ -113,11 +240,14 @@ export type SavePageNowResult = {
importJobId?: string;
importError?: string;
polls?: number;
+ // SPN's status_ext for a refusal (error:blocked-url, …), when it named one.
+ code?: string;
error?: string;
};
export type SavePageNowDeps = {
client: Pick<WaybackClient, "send">;
+ pacer: SpnPacer;
sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
// The capture into the channel (default: an import-page job).
importCapture: (slug: string, waybackUrl: string) => Promise<{ jobId: string }>;
@@ -155,15 +285,21 @@ export async function savePageNow(opts: {
const planned = await planSavePageNow(opts.paths, opts);
if (!planned.ok) return { ...base, error: planned.error };
const { plan } = planned;
+ base.mode = plan.mode;
if (opts.dryRun) {
return {
...base,
ok: true,
dryRun: true,
- wouldAsk: `POST ${SPN_SAVE_URL} (url=${plan.url}, capture_outlinks=0), then poll its status${plan.slug ? `, then import the capture into ${plan.slug}` : ""}`,
+ wouldAsk:
+ plan.mode === "keys"
+ ? `POST ${SPN_SAVE_URL} (url=${plan.url}, capture_outlinks=0), then poll its status${plan.slug ? `, then import the capture into ${plan.slug}` : ""}`
+ : `GET ${spnAnonymousSaveUrl(plan.url)} (anonymous: no keys), then poll its status if it names a job${plan.slug ? `, then import the capture into ${plan.slug}` : ""}`,
};
}
const deps: SavePageNowDeps = {
+ // A caller that brings its own sleep (a test) gets its own pacer on it.
+ pacer: opts.deps?.pacer ?? (opts.deps?.sleep ? new SpnPacer({ now: () => Date.now(), sleep: opts.deps.sleep }) : spnPacer),
client: opts.deps?.client ?? defaultWaybackClient,
sleep: opts.deps?.sleep ?? defaultSleep,
importCapture:
@@ -171,70 +307,142 @@ export async function savePageNow(opts: {
((slug, waybackUrl) => startImportPageJob({ slug, url: waybackUrl, requestedBy: "save-page-now", paths: opts.paths })),
};
const log = (line: string) => opts.onLog?.(redactSpnKeys(line, plan.keys));
- const headers = { authorization: spnAuthorization(plan.keys) };
const pollMs = opts.pollMs ?? SPN_POLL_MS;
const maxPolls = opts.maxPolls ?? SPN_MAX_POLLS;
- try {
- log(`Asking the Wayback Machine to capture ${plan.url} now (Save Page Now).`);
- const sent = await deps.client.send(SPN_SAVE_URL, {
- method: "POST",
- headers: { ...headers, "content-type": "application/x-www-form-urlencoded" },
- body: spnSaveBody(plan.url),
- ...(opts.signal ? { signal: opts.signal } : {}),
- });
- const submit = parseSpnSubmit(sent.status, sent.text);
- if (!submit.ok) return { ...base, error: redactSpnKeys(submit.error, plan.keys) };
- log(`Save Page Now job ${submit.jobId}: waiting for the capture.`);
+ const fmtWait = (ms: number) => (ms >= 120_000 ? `${Math.round(ms / 60_000)} min` : `${Math.round(ms / 1000)} s`);
+ return deps.pacer.turn(
+ plan.mode,
+ () => (plan.mode === "keys" ? keyedCapture() : anonymousCapture()),
+ { ...(opts.signal ? { signal: opts.signal } : {}), onWait: (ms, why) => log(`Waiting ${fmtWait(ms)} (${why}).`) },
+ ).catch((e: unknown) => {
+ if (opts.signal?.aborted) return { ...base, error: "cancelled" };
+ throw e;
+ });
+
+ // The capture made: imported when a channel was named.
+ async function captured(spnJobId: string | undefined, polls: number, timestamp: string, originalUrl: string): Promise<SavePageNowResult> {
+ deps.pacer.saved();
+ const waybackUrl = waybackPageUrl({ captureTs: timestamp, originalUrl });
+ log(`Captured: ${waybackUrl}`);
+ const out: SavePageNowResult = {
+ ...base,
+ ok: true,
+ ...(spnJobId ? { spnJobId } : {}),
+ polls,
+ captureTs: timestamp,
+ originalUrl,
+ waybackUrl,
+ };
+ if (plan.slug) {
+ try {
+ const imp = await deps.importCapture(plan.slug, waybackUrl);
+ out.importJobId = imp.jobId;
+ log(`Import into ${plan.slug}: job ${imp.jobId}.`);
+ } catch (e) {
+ out.importError = (e as Error).message;
+ log(`The import into ${plan.slug} was refused: ${out.importError}`);
+ }
+ }
+ return out;
+ }
+
+ function rested(error: string, retryAfterMs?: number | null, daily?: boolean, spnJobId?: string): SavePageNowResult {
+ const restMs = deps.pacer.rest(daily ? Math.max(retryAfterMs ?? 0, 6 * 60 * 60_000) : retryAfterMs);
+ log(`${error}; Save Page Now rests ${fmtWait(restMs)}.`);
+ return { ...base, ...(spnJobId ? { spnJobId } : {}), rateLimited: true, restMs, ...(daily ? { daily: true } : {}), error: `${error}; resting ${fmtWait(restMs)}` };
+ }
+
+ // Poll an SPN job's status until it is made (both modes).
+ async function poll(jobId: string, headers: Record<string, string>): Promise<SavePageNowResult> {
let polls = 0;
for (;;) {
if (polls >= maxPolls) {
return {
...base,
- spnJobId: submit.jobId,
+ spnJobId: jobId,
polls,
- error: `the capture was still pending after ${polls} status checks; archive.org may finish it later (look the page up with wayback-lookup, then import-page it)`,
+ error: `the capture was still pending after ${polls} status checks; archive.org may finish it later (look the page up with archive-lookup, then import-page it)`,
};
}
- // Each poll stretched by up to pacing.jitter (lib/jitter.mjs).
await deps.sleep(jitterMs(pollMs), opts.signal);
polls++;
- const st = await deps.client.send(spnStatusUrl(submit.jobId), {
+ const st = await deps.client.send(spnStatusUrl(jobId), { method: "GET", headers, ...(opts.signal ? { signal: opts.signal } : {}) });
+ const status = parseSpnStatus(st.status, st.text);
+ if (status.state === "pending") continue;
+ if (status.state === "error") {
+ const rest = spnStatusRests(status);
+ if (rest) return rested(redactSpnKeys(status.error, plan.keys), null, rest.daily, jobId);
+ return { ...base, spnJobId: jobId, polls, ...(status.code ? { code: status.code } : {}), error: redactSpnKeys(status.error, plan.keys) };
+ }
+ return captured(jobId, polls, status.timestamp, status.originalUrl);
+ }
+ }
+
+ async function anonymousCapture(): Promise<SavePageNowResult> {
+ try {
+ log(`Asking the Wayback Machine to capture ${plan.url} now (Save Page Now, anonymous: no keys).`);
+ const headers = { "user-agent": SPN_USER_AGENT };
+ const sent = await deps.client.send(spnAnonymousSaveUrl(plan.url), {
method: "GET",
+ accept: "text/html,application/xhtml+xml;q=0.9,application/json;q=0.8,*/*;q=0.5",
headers,
+ noRetry: true,
+ timeoutMs: SPN_ANON_TIMEOUT_MS,
...(opts.signal ? { signal: opts.signal } : {}),
});
- const status = parseSpnStatus(st.status, st.text);
- if (status.state === "pending") continue;
- if (status.state === "error") return { ...base, spnJobId: submit.jobId, polls, error: redactSpnKeys(status.error, plan.keys) };
- const waybackUrl = waybackPageUrl({ captureTs: status.timestamp, originalUrl: status.originalUrl });
- log(`Captured: ${waybackUrl}`);
- const out: SavePageNowResult = {
- ...base,
- ok: true,
- spnJobId: submit.jobId,
- polls,
- captureTs: status.timestamp,
- originalUrl: status.originalUrl,
- waybackUrl,
- };
- if (plan.slug) {
- try {
- const imp = await deps.importCapture(plan.slug, waybackUrl);
- out.importJobId = imp.jobId;
- log(`Import into ${plan.slug}: job ${imp.jobId}.`);
- } catch (e) {
- // The capture exists either way; the import is a click away.
- out.importError = (e as Error).message;
- log(`The import into ${plan.slug} was refused: ${out.importError}`);
- }
+ const h = sent.headers ?? new Headers();
+ const answer = parseSpnAnonymous({
+ status: sent.status,
+ header: (n) => h.get(n),
+ finalUrl: sent.url,
+ text: sent.text,
+ retryAfterMs: parseRetryAfterMs(h.get("retry-after"), Date.now()),
+ });
+ if (answer.state === "success") return captured(undefined, 0, answer.timestamp, answer.originalUrl);
+ if (answer.state === "rate-limited") return rested(answer.error, answer.retryAfterMs, answer.daily);
+ if (answer.state === "unavailable") return rested(answer.error, null);
+ if (answer.state === "error") return { ...base, ...(answer.code ? { code: answer.code } : {}), error: answer.error };
+ log(`Save Page Now job ${answer.jobId}: waiting for the capture.`);
+ return await poll(answer.jobId, headers);
+ } catch (e) {
+ if (opts.signal?.aborted) return { ...base, error: "cancelled" };
+ if (e instanceof ArchiveOrgRequestError) {
+ if (e.rateLimited) return rested(e.message, null);
+ return { ...base, error: e.message };
}
- return out;
+ throw e;
}
+ }
+
+ async function keyedCapture(): Promise<SavePageNowResult> {
+ const headers = { authorization: spnAuthorization(plan.keys!) };
+ try {
+ log(`Asking the Wayback Machine to capture ${plan.url} now (Save Page Now).`);
+ const sent = await deps.client.send(SPN_SAVE_URL, {
+ method: "POST",
+ headers: { ...headers, "content-type": "application/x-www-form-urlencoded" },
+ body: spnSaveBody(plan.url),
+ ...(opts.signal ? { signal: opts.signal } : {}),
+ });
+ const submit = parseSpnSubmit(sent.status, sent.text);
+ if (!submit.ok) {
+ if (submit.code && spnStatusRests({ state: "error", code: submit.code, error: submit.error })) {
+ const rest = spnStatusRests({ state: "error", code: submit.code, error: submit.error })!;
+ return rested(redactSpnKeys(submit.error, plan.keys), null, rest.daily);
+ }
+ return { ...base, ...(submit.code ? { code: submit.code } : {}), error: redactSpnKeys(submit.error, plan.keys) };
+ }
+ log(`Save Page Now job ${submit.jobId}: waiting for the capture.`);
+ return await poll(submit.jobId, headers);
} catch (e) {
if (opts.signal?.aborted) return { ...base, error: "cancelled" };
- if (e instanceof ArchiveOrgRequestError) return { ...base, error: redactSpnKeys(e.message, plan.keys) };
+ if (e instanceof ArchiveOrgRequestError) {
+ if (e.rateLimited) return rested(redactSpnKeys(e.message, plan.keys), null);
+ return { ...base, error: redactSpnKeys(e.message, plan.keys) };
+ }
throw e;
}
+ }
}
// THE JOB: a `save-page-now` job on the archive.org queue, refused (no job)
@@ -258,7 +466,9 @@ export async function queueSavePageNow(opts: {
paths: opts.paths,
...(slug ? { channelSlug: slug } : {}),
fn: async (onLog, signal) => {
- onLog(`Save Page Now: ${planned.plan.url}${slug ? ` into ${slug}` : ""}${opts.requestedBy ? ` for ${opts.requestedBy}` : ""}`);
+ onLog(
+ `Save Page Now (${planned.plan.mode === "keys" ? "with archive.org keys" : "anonymous: no keys"}): ${planned.plan.url}${slug ? ` into ${slug}` : ""}${opts.requestedBy ? ` for ${opts.requestedBy}` : ""}`,
+ );
const result = await savePageNow({
paths: opts.paths,
url: planned.plan.url,
diff --git a/common/controller/savePageNowBatch.test.ts b/common/controller/savePageNowBatch.test.ts
@@ -0,0 +1,337 @@
+// Lane spn-batch: anonymous Save Page Now (no keys) vs SPN2 with keys, the
+// pacer (one save at a time, the gap, a 429's Retry-After and the doubling
+// rest), and the batch — skip-archived, saved, failed, resumed after a
+// restart, evidence JSON + CSV rows. HTTP is stubbed; no network.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/savePageNowBatch.test.ts
+
+import test, { after } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { parseSpnAnonymous, spnCaptureOf, spnLinkMemento } from "../lib/waybackPages/savePageNow";
+import { savePageNow, SpnPacer, SPN_USER_AGENT, type SavePageNowResult } from "./savePageNow";
+import { planSpnBatch, runSpnBatch, spnEvidenceCsv, spnEvidenceRow, type SpnBatchDeps } from "./savePageNowBatch";
+import type { ArchiveLookup } from "../lib/archives/index";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "spn-batch-"));
+after(() => rmSync(ROOT, { recursive: true, force: true }));
+const paths = { channelsDir: path.join(ROOT, "channels"), transcriptsDir: ROOT, jobsDir: path.join(ROOT, "jobs") } as unknown as Paths;
+const NO_KEYS = { archiveOrg: { s3KeyFile: path.join(ROOT, "no-such-keys.env") }, social: { x: { visibility: "public" } } };
+const KEYS_ENV = { ARCHIVE_ORG_S3_ACCESS: "FAKEACCESS0001", ARCHIVE_ORG_S3_SECRET: "FAKESECRET0001" };
+const TS = "20261105120000";
+const PAGE = "https://x.com/someone/status/111";
+
+// A virtual clock: sleep advances it.
+function clock(start = Date.parse("2026-11-05T12:00:00Z")) {
+ let t = start;
+ const sleeps: number[] = [];
+ return {
+ now: () => t,
+ sleep: async (ms: number) => {
+ sleeps.push(ms);
+ t += ms;
+ },
+ sleeps,
+ };
+}
+
+type Sent = { url: string; method: string; headers?: Record<string, string> };
+
+type Answer = { status: number; text?: string; headers?: Record<string, string>; url?: string };
+
+function stubClient(answers: ((s: Sent) => Answer)[]) {
+ const sent: Sent[] = [];
+ return {
+ sent,
+ send: async (url: string, init: { method: "GET" | "POST"; headers?: Record<string, string> }) => {
+ const s = { url, method: init.method, ...(init.headers ? { headers: init.headers } : {}) };
+ sent.push(s);
+ const a: Answer = (answers.shift() ?? ((): Answer => ({ status: 500 })))(s);
+ return { status: a.status, text: a.text ?? "", headers: new Headers(a.headers ?? {}), url: a.url ?? url };
+ },
+ };
+}
+
+test("the anonymous answers read: Content-Location, Link memento, the final URL, a watched job, a runtime error, 429, 5xx", () => {
+ const h = (o: Record<string, string>) => (n: string) => o[n.toLowerCase()] ?? null;
+ assert.deepEqual(parseSpnAnonymous({ status: 200, header: h({ "content-location": `/web/${TS}/${PAGE}` }), text: "" }), { state: "success", timestamp: TS, originalUrl: PAGE });
+ assert.equal(spnLinkMemento(`<${PAGE}>; rel="original", <https://web.archive.org/web/${TS}/${PAGE}>; rel="memento"; datetime="x"`), `https://web.archive.org/web/${TS}/${PAGE}`);
+ assert.equal(parseSpnAnonymous({ status: 200, header: h({ link: `<https://web.archive.org/web/${TS}/${PAGE}>; rel="memento"` }), text: "" }).state, "success");
+ assert.equal(parseSpnAnonymous({ status: 200, header: h({}), finalUrl: `https://web.archive.org/web/${TS}/${PAGE}`, text: "" }).state, "success");
+ assert.equal(spnCaptureOf(`https://evil.example/web/${TS}/${PAGE}`), null, "only an archive.org URL names a capture");
+ assert.deepEqual(parseSpnAnonymous({ status: 200, header: h({}), text: `<script>spn.watchJob("spn2-abc123", "/_static/",6000);</script>` }), { state: "pending", jobId: "spn2-abc123" });
+ const robots = parseSpnAnonymous({ status: 200, header: h({ "x-archive-wayback-runtime-error": "RobotAccessControlException: Blocked By Robots" }), text: "" });
+ assert.equal(robots.state === "error" && robots.code, "blocked-by-robots");
+ const busy = parseSpnAnonymous({ status: 429, header: h({}), text: "", retryAfterMs: 90_000 });
+ assert.deepEqual(busy, { state: "rate-limited", error: "archive.org answered HTTP 429 (too many captures)", retryAfterMs: 90_000 });
+ assert.equal(parseSpnAnonymous({ status: 503, header: h({}), text: "" }).state, "unavailable");
+ // A 523 from the save is THIS URL's failure, with the page's sentence (not a rest).
+ const failed = parseSpnAnonymous({ status: 523, header: h({}), text: "<html><head><title>Wayback Machine</title><script>var x = 'Sorry';</script></head><body><h1>Save Page Now</h1><p>Sorry. Job failed: the server returned a 404.</p></body></html>" });
+ assert.deepEqual(failed, { state: "error", code: "http-523", error: "Save Page Now could not capture the page (HTTP 523): Sorry." });
+ const session = parseSpnAnonymous({ status: 200, header: h({}), text: JSON.stringify({ status: "error", status_ext: "error:user-session-limit", message: "limit" }) });
+ assert.equal(session.state, "rate-limited");
+ const perUrl = parseSpnAnonymous({ status: 200, header: h({}), text: JSON.stringify({ status: "error", status_ext: "error:too-many-daily-captures", message: "This URL has been captured 10 times today." }) });
+ assert.equal(perUrl.state, "error", "a URL captured too often today is that URL's failure, not a rest");
+});
+
+test("anonymous vs keys: no keys → GET /save/<url> with no Authorization and the honest UA; keys → POST /save with LOW", async () => {
+ const c = clock();
+ const anon = stubClient([() => ({ status: 200, headers: { "content-location": `/web/${TS}/${PAGE}` } })]);
+ const r = await savePageNow({ paths, url: PAGE, settings: NO_KEYS, env: {}, deps: { client: anon, sleep: c.sleep } });
+ assert.equal(r.ok, true);
+ assert.equal(r.mode, "anonymous");
+ assert.equal(r.waybackUrl, `https://web.archive.org/web/${TS}/${PAGE}`);
+ assert.equal(anon.sent[0].method, "GET");
+ assert.equal(anon.sent[0].url, `https://web.archive.org/save/${PAGE}`);
+ assert.equal(anon.sent[0].headers?.authorization, undefined);
+ assert.equal(anon.sent[0].headers?.["user-agent"], SPN_USER_AGENT);
+ assert.match(SPN_USER_AGENT, /^Mozilla\/5\.0 \(compatible; Archilyzer Save Page Now; \+https:\/\//);
+
+ const keyed = stubClient([
+ () => ({ status: 200, text: JSON.stringify({ url: PAGE, job_id: "spn2-k1" }) }),
+ () => ({ status: 200, text: JSON.stringify({ status: "success", timestamp: TS, original_url: PAGE }) }),
+ ]);
+ const k = await savePageNow({ paths, url: PAGE, settings: NO_KEYS, env: KEYS_ENV, pollMs: 1, deps: { client: keyed, sleep: c.sleep } });
+ assert.equal(k.ok, true);
+ assert.equal(k.mode, "keys");
+ assert.equal(keyed.sent[0].method, "POST");
+ assert.equal(keyed.sent[0].url, "https://web.archive.org/save");
+ assert.match(keyed.sent[0].headers?.authorization ?? "", /^LOW /);
+ assert.ok(!JSON.stringify(k).includes("FAKESECRET0001"), "the keys are in no result");
+
+ // An anonymous answer that watches a job: its status is polled, anonymously.
+ const watched = stubClient([
+ () => ({ status: 200, text: `spn.watchJob("spn2-w1", "/_static/", 6000)` }),
+ () => ({ status: 200, text: JSON.stringify({ status: "pending" }) }),
+ () => ({ status: 200, text: JSON.stringify({ status: "success", timestamp: TS, original_url: PAGE }) }),
+ ]);
+ const w = await savePageNow({ paths, url: PAGE, settings: NO_KEYS, env: {}, pollMs: 1, deps: { client: watched, sleep: c.sleep } });
+ assert.equal(w.ok && w.spnJobId, "spn2-w1");
+ assert.equal(watched.sent[1].url, "https://web.archive.org/save/status/spn2-w1");
+ assert.equal(watched.sent[1].headers?.authorization, undefined);
+});
+
+test("the pacer: one save at a time, ≥ 60 s apart anonymous (10 s with keys), a 429's Retry-After and the doubling rest", async () => {
+ const c = clock();
+ const pacer = new SpnPacer({ now: c.now, sleep: c.sleep });
+ const order: string[] = [];
+ const slow = (name: string) => async () => {
+ order.push(`start ${name}`);
+ await c.sleep(5_000);
+ order.push(`end ${name}`);
+ };
+ await Promise.all([pacer.turn("anonymous", slow("a")), pacer.turn("anonymous", slow("b"))]);
+ assert.deepEqual(order, ["start a", "end a", "start b", "end b"], "never two at once");
+ assert.ok(c.sleeps.some((ms) => ms >= 60_000), "the second waited the anonymous gap");
+ assert.equal(pacer.gapMs("keys"), 10_000);
+
+ // A 429 with Retry-After 300 s: the result says it rested, and the next save waits it out.
+ const c2 = clock();
+ const p2 = new SpnPacer({ now: c2.now, sleep: c2.sleep });
+ const busy = stubClient([() => ({ status: 429, headers: { "retry-after": "300" } })]);
+ const r = await savePageNow({ paths, url: PAGE, settings: NO_KEYS, env: {}, deps: { client: busy, sleep: c2.sleep, pacer: p2 } });
+ assert.equal(r.ok, false);
+ assert.equal(r.rateLimited, true);
+ assert.equal(r.restMs, 300_000);
+ assert.ok(p2.resting());
+ const before = c2.now();
+ const ok = stubClient([() => ({ status: 200, headers: { "content-location": `/web/${TS}/${PAGE}` } })]);
+ const r2 = await savePageNow({ paths, url: PAGE, settings: NO_KEYS, env: {}, deps: { client: ok, sleep: c2.sleep, pacer: p2 } });
+ assert.equal(r2.ok, true);
+ assert.ok(c2.now() - before >= 299_000, "the next save waited out the Retry-After");
+ // No Retry-After: 2 min, then doubling.
+ const c3 = clock();
+ const p3 = new SpnPacer({ now: c3.now, sleep: c3.sleep });
+ assert.equal(p3.rest(null), 120_000);
+ assert.equal(p3.rest(null), 240_000);
+ p3.saved();
+ assert.equal(p3.rest(null), 120_000, "a save starts the doubling over");
+});
+
+// The batch's world: a lookup table and a save stub.
+function batchDeps(o: {
+ copies: Record<string, ArchiveLookup["sources"]>;
+ saves: ((url: string) => SavePageNowResult)[];
+ c: ReturnType<typeof clock>;
+}): SpnBatchDeps & { looked: string[]; saved: string[] } {
+ const looked: string[] = [];
+ const saved: string[] = [];
+ return {
+ looked,
+ saved,
+ lookup: async (url) => {
+ looked.push(url);
+ return { url, found: 0, sources: o.copies[url] ?? [{ source: "wayback", label: "Wayback Machine", ok: true, captures: [] }] };
+ },
+ save: async (url) => {
+ saved.push(url);
+ const f = o.saves.shift();
+ return f ? f(url) : { ok: false, url, error: "no stub" };
+ },
+ pacer: { gapMs: () => 60_000, resting: () => null },
+ now: o.c.now,
+ sleep: o.c.sleep,
+ };
+}
+
+const wbRow = (url: string, status: string, ts = "20250101000000") => ({ source: "wayback" as const, captureTs: ts, originalUrl: url, mementoUrl: `https://web.archive.org/web/${ts}/${url}`, status, mimetype: "text/html" });
+
+test("the batch: archived already skipped (copy recorded), saved, failed; evidence JSON + CSV; resumed after a restart", async () => {
+ const U = ["https://x.com/a/status/1", "https://x.com/a/status/2", "https://x.com/a/status/3", "https://x.com/a/status/4"];
+ const list = path.join(ROOT, "list.json");
+ writeFileSync(list, JSON.stringify([...U, U[0], "ftp://nope", `https://web.archive.org/web/2020/${U[0]}`]));
+ const evidence = path.join(ROOT, "out", "evidence");
+ const planned = await planSpnBatch(paths, { file: list, evidence }, { settings: NO_KEYS, env: {} });
+ assert.ok(planned.ok);
+ const plan = planned.ok ? planned.plan : (null as never);
+ assert.equal(plan.mode, "anonymous");
+ assert.equal(plan.dailyCap, 150);
+ assert.equal(plan.state.items.length, 4, "deduped; not-http and Wayback URLs left out");
+ assert.equal(plan.rejected.length, 2);
+
+ const c = clock();
+ const copies = {
+ [U[0]]: [
+ { source: "wayback" as const, label: "Wayback Machine", ok: true, captures: [wbRow(U[0], "302", "20240101000000"), wbRow(U[0], "200", "20250101000000")] },
+ { source: "archive.today" as const, label: "archive.today", ok: true, captures: [] },
+ ],
+ // Only a redirect captured: not shown, so saved.
+ [U[1]]: [{ source: "wayback" as const, label: "Wayback Machine", ok: true, captures: [wbRow(U[1], "302")] }],
+ };
+ // Run 1: U0 archived already; U1 saved; then a "crash" (the save throws) on U2.
+ const d1 = batchDeps({
+ copies,
+ c,
+ saves: [
+ (url) => ({ ok: true, url, mode: "anonymous", captureTs: TS, originalUrl: url, waybackUrl: `https://web.archive.org/web/${TS}/${url}` }),
+ () => {
+ throw new Error("process went away");
+ },
+ ],
+ });
+ await assert.rejects(runSpnBatch({ plan, deps: d1 }), /process went away/);
+ assert.deepEqual(d1.saved, [U[1], U[2]]);
+
+ // Run 2, after the "restart": the state is read back; U0, U1 are not asked again.
+ const replanned = await planSpnBatch(paths, { batch: plan.id }, { settings: NO_KEYS, env: {} });
+ assert.ok(replanned.ok);
+ const plan2 = replanned.ok ? replanned.plan : (null as never);
+ assert.equal(plan2.resumed, true);
+ assert.equal(plan2.state.evidence.json, `${evidence}.json`, "the evidence path is kept");
+ const d2 = batchDeps({
+ copies,
+ c,
+ saves: [
+ (url) => ({ ok: true, url, mode: "anonymous", captureTs: TS, originalUrl: url, waybackUrl: `https://web.archive.org/web/${TS}/${url}` }),
+ (url) => ({ ok: false, url, mode: "anonymous", code: "error:blocked-url", error: "Save Page Now refused the capture (HTTP 200, error:blocked-url)" }),
+ ],
+ });
+ const progress: string[] = [];
+ const r = await runSpnBatch({ plan: plan2, deps: d2, onProgress: (p) => progress.push(`${p.done}/${p.total}`) });
+ assert.deepEqual(d2.saved, [U[2], U[3]], "only the pending URLs");
+ assert.ok(!d2.looked.includes(U[0]) && !d2.looked.includes(U[1]), "nothing looked up twice");
+ assert.deepEqual(r.counts, { total: 4, pending: 0, archivedAlready: 1, saved: 2, failed: 1 });
+ assert.equal(r.stopped, undefined);
+ assert.ok(progress.includes("4/4"));
+
+ const ev = JSON.parse(readFileSync(`${evidence}.json`, "utf8")) as { rows: ReturnType<typeof spnEvidenceRow>[] };
+ const byUrl = Object.fromEntries(ev.rows.map((row) => [row.url, row]));
+ assert.equal(byUrl[U[0]].status, "archived-already");
+ assert.equal(byUrl[U[0]].waybackUrl, `https://web.archive.org/web/20250101000000/${U[0]}`, "the copy that recorded a 200");
+ assert.equal(byUrl[U[0]].waybackHttpStatus, "200");
+ assert.equal(byUrl[U[0]].shows, "yes");
+ assert.equal(byUrl[U[1]].status, "saved");
+ assert.equal(byUrl[U[1]].waybackUrl, `https://web.archive.org/web/${TS}/${U[1]}`);
+ assert.equal(byUrl[U[1]].savedMode, "anonymous");
+ assert.equal(byUrl[U[3]].status, "failed");
+ assert.match(byUrl[U[3]].reason, /blocked-url/);
+ const csv = readFileSync(`${evidence}.csv`, "utf8").trim().split("\n");
+ assert.equal(csv[0], "url,status,reason,waybackUrl,waybackCaptureTs,waybackHttpStatus,waybackMimetype,archiveTodayUrl,archiveTodayCaptureTs,shows,savedMode,checkedAt,doneAt");
+ assert.equal(csv.length, 5);
+ assert.match(csv[4], /"Save Page Now refused the capture \(HTTP 200, error:blocked-url\)"/, "a reason with a comma is quoted");
+ assert.equal(spnEvidenceCsv([]).trim().split("\n").length, 1);
+});
+
+test("the batch rests on a 429 and asks the same URL again; stops after too many rests; respects the daily cap", async () => {
+ const U = ["https://x.com/b/status/1", "https://x.com/b/status/2"];
+ const planned = await planSpnBatch(paths, { urls: U, skipArchived: false, dailyCap: 1 }, { settings: NO_KEYS, env: {} });
+ assert.ok(planned.ok);
+ const plan = planned.ok ? planned.plan : (null as never);
+ const c = clock();
+ const rl = (url: string): SavePageNowResult => ({ ok: false, url, rateLimited: true, restMs: 120_000, error: "archive.org answered HTTP 429; resting 2 min" });
+ const ok = (url: string): SavePageNowResult => ({ ok: true, url, captureTs: TS, originalUrl: url, waybackUrl: `https://web.archive.org/web/${TS}/${url}` });
+ const d = batchDeps({ copies: {}, c, saves: [rl, ok, ok] });
+ const r = await runSpnBatch({ plan, deps: d });
+ assert.deepEqual(d.saved, [U[0], U[0], U[1]], "the rested URL asked again, then the next");
+ assert.deepEqual(d.looked, [], "skipArchived: false asks no lookup");
+ assert.equal(r.counts.saved, 2);
+ assert.ok(c.sleeps.some((ms) => ms >= 23 * 60 * 60 * 1000), "the daily cap (1) waited out the 24 h window");
+
+ const planned2 = await planSpnBatch(paths, { urls: ["https://x.com/b/status/9"], skipArchived: false }, { settings: NO_KEYS, env: {} });
+ const plan2 = planned2.ok ? planned2.plan : (null as never);
+ const d2 = batchDeps({ copies: {}, c, saves: Array.from({ length: 10 }, () => rl) });
+ const r2 = await runSpnBatch({ plan: plan2, deps: d2 });
+ assert.match(r2.stopped ?? "", /kept asking us to slow down/);
+ assert.equal(r2.counts.pending, 1, "the URL stays pending for the next run");
+
+ // Refusals before a job.
+ const bad = await planSpnBatch(paths, { urls: ["ftp://x"] }, { settings: NO_KEYS, env: {} });
+ assert.match(bad.ok ? "" : bad.error, /no http\(s\) URLs/);
+ const cap = await planSpnBatch(paths, { urls: U, dailyCap: 500 }, { settings: NO_KEYS, env: {} });
+ assert.match(cap.ok ? "" : cap.error, /at most 200 without keys/);
+ const keyed = await planSpnBatch(paths, { urls: U, dailyCap: 500 }, { settings: NO_KEYS, env: KEYS_ENV });
+ assert.equal(keyed.ok && keyed.plan.mode, "keys");
+ const rel = await planSpnBatch(paths, { urls: U, evidence: "relative/path" }, { settings: NO_KEYS, env: {} });
+ assert.match(rel.ok ? "" : rel.error, /absolute path/);
+ const none = await planSpnBatch(paths, { batch: "spn-000000000000" }, { settings: NO_KEYS, env: {} });
+ assert.match(none.ok ? "" : none.error, /no batch spn-000000000000/);
+});
+
+test("a site Save Page Now refuses (the live x.com answer) is asked once; its other URLs are looked up, not saved", async () => {
+ const U = ["https://x.com/d/status/1", "https://x.com/d/status/2", "https://blog.example/p"];
+ const planned = await planSpnBatch(paths, { urls: U }, { settings: NO_KEYS, env: {} });
+ const plan = planned.ok ? planned.plan : (null as never);
+ const c = clock();
+ const page = "<html><head><title>Wayback Machine</title></head><body><p>Sorry We\u2019re currently facing some limitations when it comes to archiving this site.</p></body></html>";
+ const answer = parseSpnAnonymous({ status: 523, header: () => null, text: page });
+ assert.equal(answer.state === "error" && answer.code, "host-limited");
+ const d = batchDeps({
+ copies: {},
+ c,
+ saves: [
+ (url) => ({ ok: false, url, code: "host-limited", error: answer.state === "error" ? answer.error : "" }),
+ (url) => ({ ok: true, url, captureTs: TS, originalUrl: url, waybackUrl: `https://web.archive.org/web/${TS}/${url}` }),
+ ],
+ });
+ const r = await runSpnBatch({ plan, deps: d });
+ assert.deepEqual(d.saved, [U[0], U[2]], "x.com asked once; the other host still saved");
+ assert.deepEqual(d.looked, U, "every URL still looked up");
+ assert.equal(r.counts.failed, 2);
+ assert.match(plan.state.items[1].reason ?? "", /^not asked: Save Page Now refuses x\.com as a site/);
+});
+
+test("archive.today refusing a check is left out for the rest of the run, never pressed", async () => {
+ const U = ["https://x.com/c/status/1", "https://x.com/c/status/2"];
+ const planned = await planSpnBatch(paths, { urls: U }, { settings: NO_KEYS, env: {} });
+ const plan = planned.ok ? planned.plan : (null as never);
+ const c = clock();
+ const asked: string[][] = [];
+ const d = batchDeps({ copies: {}, c, saves: [] });
+ d.lookup = async (url, o) => {
+ asked.push([...o.sources]);
+ return {
+ url,
+ found: 1,
+ sources: [
+ { source: "wayback", label: "Wayback Machine", ok: true, captures: [wbRow(url, "200")] },
+ ...(o.sources.includes("archive.today") ? [{ source: "archive.today" as const, label: "archive.today", ok: false, captures: [], refusal: "challenge" as const, error: "a check" }] : []),
+ ],
+ };
+ };
+ const r = await runSpnBatch({ plan, deps: d });
+ assert.deepEqual(asked, [["wayback", "archive.today"], ["wayback"]]);
+ assert.equal(r.counts.archivedAlready, 2);
+});
diff --git a/common/controller/savePageNowBatch.ts b/common/controller/savePageNowBatch.ts
@@ -0,0 +1,822 @@
+// 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
+// (<transcripts>/.spn-batches/<batchId>.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: <id>} — 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<Paths, "jobsDir">): string {
+ return path.join(path.dirname(paths.jobsDir), ".spn-batches");
+}
+
+export function spnBatchStatePath(paths: Pick<Paths, "jobsDir">, 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<string>();
+ 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<unknown[]> {
+ 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<SpnBatchState | null> {
+ 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<void> {
+ 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<Record<string, string | undefined>>; 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<ArchiveLookup>;
+ save: (url: string, o: { signal?: AbortSignal; onLog: (l: string) => void }) => Promise<SavePageNowResult>;
+ pacer: Pick<SpnPacer, "gapMs" | "resting">;
+ now: () => number;
+ sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
+};
+
+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<SpnBatchResult> {
+ 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<ArchiveSourceId>(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<string, string>();
+ 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<SpnBatchResult | null> {
+ 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<string, string>();
+
+const defaultSleep = (ms: number, signal?: AbortSignal) =>
+ new Promise<void>((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<SavePageNowDeps>): Promise<SpnBatchDeps> {
+ 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<Record<string, string | undefined>> } = {}) {
+ 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<Record<string, string | undefined>>;
+ deps?: SpnBatchDeps;
+ onDone?: (r: SpnBatchResult) => void;
+}): Promise<StreamActionResult & { batch?: string }> {
+ 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 };
+}
diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts
@@ -300,7 +300,8 @@ test("release 18: every drainable kind but the lane runners and the clip-window
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.
// wayback-scan writes only `wayback-scan.json`, which the index never reads.
- const notIngest = new Set(["fetch-windows", "wayback-scan"]);
+ // save-page-now-batch writes only its own state and evidence (.spn-batches/).
+ const notIngest = new Set(["fetch-windows", "wayback-scan", "save-page-now-batch"]);
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`);
@@ -403,6 +404,7 @@ test("resumeOnBoot: exactly the kinds that continue on a re-run, every one repla
"normalize-transcripts",
"persist-videos",
"refresh-report",
+ "save-page-now-batch",
"whisper-all",
"whisper-bucket-auto-subs",
"whisper-bucket-downloaded-no-transcript",
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -723,6 +723,22 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
queueKeyStrategy: "platform",
network: true,
},
+ // SAVE PAGE NOW, A LIST (lane spn-batch, controller/savePageNowBatch.ts):
+ // each URL looked up (Wayback CDX, archive.today's timemap) and, when no
+ // copy shows it, saved — anonymous without keys — through the process-wide
+ // Save Page Now pacer, one at a time. Its own queue (a long list runs for
+ // days and must not hold the archive.org queue). Drainable (it stops
+ // between URLs), replayable and resumed on boot: the state file holds every
+ // URL's status, and a re-run continues from the first pending one.
+ "save-page-now-batch": {
+ kind: "save-page-now-batch",
+ label: "Save Page Now (list)",
+ drainable: true,
+ replayable: true,
+ queueKeyStrategy: "custom",
+ network: true,
+ resumeOnBoot: true,
+ },
// A screenshot and the attached media of specific archived posts (and the X
// Article a post links to), into the channel's `posts-media/`
// (controller/capturePosts.ts). On the PLATFORM queue, like fetch-posts:
diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts
@@ -39,7 +39,10 @@ export type JobProgressMetric =
| "frames"
// An audio audit (controller/audioAudit.ts, release 31): files decoded of
// those planned. The runner always sets `current`.
- | "files";
+ | "files"
+ // A Save Page Now batch (controller/savePageNowBatch.ts): URLs settled
+ // (archived already, saved, failed) of the list. The runner sets `current`.
+ | "pages";
export type JobProgress = {
metric: JobProgressMetric;
diff --git a/common/lib/archiveOrgClient.ts b/common/lib/archiveOrgClient.ts
@@ -327,18 +327,31 @@ export class ArchiveOrgClient {
// are sent and never put in an error or a log line.
send(
url: string,
- init: { method: "GET" | "POST"; headers?: Record<string, string>; body?: string; accept?: string; signal?: AbortSignal },
- ): Promise<{ status: number; text: string }> {
+ init: {
+ method: "GET" | "POST";
+ headers?: Record<string, string>;
+ body?: string;
+ accept?: string;
+ signal?: AbortSignal;
+ // Lane spn-batch: answer a 429/503/… as it is (one attempt, no
+ // back-off here) — the caller rests on its own terms (Save Page Now's
+ // pacer) instead of asking again within seconds.
+ noRetry?: boolean;
+ // This request's own timeout (an anonymous capture can take 2 minutes).
+ timeoutMs?: number;
+ },
+ ): Promise<{ status: number; text: string; headers: Headers; url: string }> {
return this.serial(async () => {
let lastError = "";
- for (let attempt = 1; attempt <= this.opts.maxAttempts; attempt++) {
+ const attempts = init.noRetry ? 1 : this.opts.maxAttempts;
+ for (let attempt = 1; attempt <= attempts; attempt++) {
const wait = this.lastDoneAt + this.gapMs() - this.deps.now();
if (wait > 0) await this.deps.sleep(wait, init.signal);
this.requests++;
let res: Response | null = null;
let text = "";
try {
- const timeout = AbortSignal.timeout(this.opts.timeoutMs);
+ const timeout = AbortSignal.timeout(init.timeoutMs ?? this.opts.timeoutMs);
res = await this.deps.fetch(url, {
method: init.method,
signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout,
@@ -354,15 +367,17 @@ export class ArchiveOrgClient {
} finally {
this.lastDoneAt = this.deps.now();
}
- if (res && !RETRYABLE.has(res.status)) return { status: res.status, text };
+ if (res && (!RETRYABLE.has(res.status) || init.noRetry)) {
+ return { status: res.status, text, headers: res.headers ?? new Headers(), url: res.url || url };
+ }
if (res) lastError = `HTTP ${res.status}`;
- if (attempt === this.opts.maxAttempts) break;
+ if (attempt === attempts) break;
const retryAfter = res ? parseRetryAfterMs(res.headers.get("retry-after"), this.deps.now()) : null;
const delay = Math.min(this.opts.maxBackoffMs, retryAfter ?? this.backoffMs(attempt));
await this.deps.sleep(delay, init.signal);
}
throw new ArchiveOrgRequestError(
- `archive.org did not answer ${url} after ${this.opts.maxAttempts} attempts (${lastError}); stopping`,
+ `archive.org did not answer ${url} after ${attempts} attempt${attempts === 1 ? "" : "s"} (${lastError}); stopping`,
null,
true,
);
diff --git a/common/lib/waybackClient.ts b/common/lib/waybackClient.ts
@@ -256,8 +256,8 @@ export class WaybackClient {
// lib/waybackPages/savePageNow.ts). ArchiveOrgClient.send's contract.
send(
url: string,
- init: { method: "GET" | "POST"; headers?: Record<string, string>; body?: string; accept?: string; signal?: AbortSignal },
- ): Promise<{ status: number; text: string }> {
+ init: Parameters<ArchiveOrgClient["send"]>[1],
+ ): ReturnType<ArchiveOrgClient["send"]> {
return this.http.send(url, init);
}
diff --git a/common/lib/waybackPages/savePageNow.ts b/common/lib/waybackPages/savePageNow.ts
@@ -104,3 +104,166 @@ export function spnOffSentence(keyFile: string): string {
`environment, or in ${keyFile} (mode 600; settings archiveOrg.s3KeyFile).`
);
}
+
+// ─── ANONYMOUS SAVE PAGE NOW (lane spn-batch, 5 Nov) ────────────────────────
+//
+// With no S3 keys the public endpoint is used, the way archive.org's own
+// "Save Page Now" form and the `savepagenow` library use it: ONE GET of
+//
+// GET https://web.archive.org/save/<url> (no Authorization)
+// → the capture named by Content-Location (/web/<ts>/<url>), a Link
+// rel="memento", or the URL the redirects ended at; or a page that
+// watches an SPN job (spn.watchJob("spn2-…")) whose status is then
+// polled at /save/status/<job_id>; X-Archive-Wayback-Runtime-Error
+// names a refusal (Blocked By Robots, …).
+//
+// archive.org's limits for anonymous captures (the SPN2 doc's Limitations):
+// at most 3 captures a minute and 200 a day (authenticated: 7 and 30k), 5 of
+// one URL a day. The pacing that keeps well inside them is
+// controller/savePageNow.ts's (SpnPacer).
+
+export type SpnMode = "anonymous" | "keys";
+
+// The sentence an SPN HTML page says (its error), scripts and styles left out.
+export function spnPageMessage(html: string): string {
+ const text = html
+ .replace(/<script[\s\S]*?<\/script>/gi, " ")
+ .replace(/<style[\s\S]*?<\/style>/gi, " ")
+ .replace(/<[^>]*>/g, " ")
+ .replace(/ /g, " ")
+ .replace(/&/g, "&")
+ .replace(/'|'/g, "'")
+ .replace(/"/g, '"')
+ .replace(/\s+/g, " ")
+ .trim();
+ // The page's chrome first (the title, "Save Page Now", menus): the message is
+ // the first sentence that reads like one about the capture.
+ const m = /((?:Sorry|Job failed|This (?:URL|host|page)|The (?:server|page|capture|URL)|Cannot|Can't|We couldn't|Live page|Error)[^.!?]{0,200}[.!?]?)/i.exec(text);
+ return (m?.[1] ?? text.slice(0, 160)).trim().slice(0, 240);
+}
+
+// Browser-shaped (archive.org's SPN serves its capture flow to browsers) but
+// honest: it names the project and where it lives, and claims no browser.
+export function spnUserAgent(projectName: string, projectUrl: string): string {
+ return `Mozilla/5.0 (compatible; ${projectName} Save Page Now; +${projectUrl})`;
+}
+
+export function spnAnonymousSaveUrl(url: string): string {
+ return `${ORIGIN}/save/${url}`;
+}
+
+export type SpnAnonymousAnswer =
+ | { state: "success"; timestamp: string; originalUrl: string }
+ | { state: "pending"; jobId: string }
+ // 429, or SPN's own "too many" refusals: the caller rests.
+ | { state: "rate-limited"; error: string; code?: string; retryAfterMs?: number; daily?: boolean }
+ // 502/503/504/520/523: archive.org is struggling; the caller rests.
+ | { state: "unavailable"; error: string }
+ | { state: "error"; error: string; code?: string };
+
+const CAPTURE_PATH = /\/web\/(\d{14})[a-z_]*\/(https?:\/\/.+)$/i;
+
+// A capture named by a URL or path (`/web/<ts>/<url>`, absolute or not).
+export function spnCaptureOf(ref: string | null | undefined): { timestamp: string; originalUrl: string } | null {
+ if (!ref) return null;
+ let p = ref.trim();
+ try {
+ if (/^https?:\/\//i.test(p)) {
+ const u = new URL(p);
+ if (!/(^|\.)archive\.org$/i.test(u.hostname)) return null;
+ p = u.pathname + u.search;
+ }
+ } catch {
+ return null;
+ }
+ const m = CAPTURE_PATH.exec(p);
+ return m ? { timestamp: m[1], originalUrl: m[2] } : null;
+}
+
+// The memento a Link header names (rel="memento", else rel="last memento").
+export function spnLinkMemento(link: string | null | undefined): string | null {
+ if (!link) return null;
+ let best: string | null = null;
+ for (const part of link.split(/,(?=\s*<)/)) {
+ const m = /<([^>]+)>\s*;(.*)$/.exec(part.trim());
+ if (!m) continue;
+ const rel = /rel="?([^";]+)"?/i.exec(m[2])?.[1]?.toLowerCase() ?? "";
+ if (rel === "memento") return m[1];
+ if (rel.includes("memento") && !best) best = m[1];
+ }
+ return best;
+}
+
+const DAILY = /daily|per day|today/i;
+
+// A status_ext that means "rest", not "this URL failed".
+function restingCode(code: string, message: string): { daily: boolean } | null {
+ if (code === "error:too-many-daily-captures") return null; // this URL, 5-10 a day: the URL's own failure
+ if (code === "error:user-session-limit" || code === "error:too-many-requests") return { daily: false };
+ if (/^error:(max-daily-bandwidth|max-daily-bandwidth-from-ip|daily-limit|user-daily-limit)/.test(code)) return { daily: true };
+ if (code.startsWith("error:") && /limit|too many/i.test(code + " " + message)) return { daily: DAILY.test(code + " " + message) };
+ return null;
+}
+
+// What the anonymous endpoint answered. `get(name)` reads a response header.
+export function parseSpnAnonymous(a: {
+ status: number;
+ header: (name: string) => string | null;
+ finalUrl?: string;
+ text: string;
+ retryAfterMs?: number | null;
+}): SpnAnonymousAnswer {
+ const runtime = a.header("x-archive-wayback-runtime-error");
+ if (runtime) {
+ const robots = /robots/i.test(runtime);
+ return { state: "error", code: robots ? "blocked-by-robots" : "runtime-error", error: `Save Page Now refused the capture: ${runtime.trim()}` };
+ }
+ if (a.status === 429) {
+ return {
+ state: "rate-limited",
+ error: "archive.org answered HTTP 429 (too many captures)",
+ ...(a.retryAfterMs != null ? { retryAfterMs: a.retryAfterMs } : {}),
+ };
+ }
+ if ([502, 503, 504].includes(a.status)) return { state: "unavailable", error: `archive.org answered HTTP ${a.status}` };
+ // 520/523 from the save itself (x-location: save-sync): SPN tried THIS URL
+ // and could not capture it — the page says why. A failure of the URL, not a
+ // reason to rest (the live answer for an X post, 5 Nov: 523 in ~2 s, x-rl 0).
+ if (a.status === 520 || a.status === 523) {
+ const said = spnPageMessage(a.text);
+ // "We're currently facing some limitations when it comes to archiving this
+ // site": the SITE is refused (x.com, 5 Nov), not this page — the caller
+ // stops asking for that host.
+ const host = /archiving this site|this site|this host|this domain/i.test(said) ? "host-limited" : `http-${a.status}`;
+ return { state: "error", code: host, error: `Save Page Now could not capture the page (HTTP ${a.status})${said ? `: ${said}` : ""}` };
+ }
+ const body = json(a.text);
+ const ext = str(body?.status_ext);
+ const message = str(body?.message);
+ if (ext) {
+ const rest = restingCode(ext, message);
+ if (rest) return { state: "rate-limited", code: ext, daily: rest.daily, error: `Save Page Now asked us to slow down (${ext})${message ? `: ${message}` : ""}` };
+ }
+ if (a.status === 401 || a.status === 403) {
+ return { state: "error", code: "refused", error: `archive.org refused an anonymous capture (HTTP ${a.status})${message ? `: ${message}` : ""}` };
+ }
+ const cap = spnCaptureOf(a.header("content-location")) ?? spnCaptureOf(spnLinkMemento(a.header("link"))) ?? spnCaptureOf(a.finalUrl);
+ if (a.status >= 200 && a.status < 400 && cap) return { state: "success", ...cap };
+ const jobId = str(body?.job_id) || (/watchJob\(\s*["']([^"']+)["']/.exec(a.text)?.[1] ?? "");
+ if (a.status >= 200 && a.status < 300 && jobId) return { state: "pending", jobId };
+ if (body && str(body.status) === "error") {
+ return { state: "error", ...(ext ? { code: ext } : {}), error: `Save Page Now refused the capture (HTTP ${a.status}${ext ? `, ${ext}` : ""})${message ? `: ${message}` : ""}` };
+ }
+ // The HTML page's own error sentence, when it has one.
+ const said = /<h2[^>]*>([^<]{3,200})<\/h2>/i.exec(a.text)?.[1]?.trim();
+ return {
+ state: "error",
+ error: `Save Page Now named no capture (HTTP ${a.status})${said ? `: ${said}` : ""}`,
+ };
+}
+
+// A status poll's answer read for resting too: SPN's "slow down" codes are
+// not this URL's failure.
+export function spnStatusRests(s: SpnStatus): { daily: boolean } | null {
+ return s.state === "error" && s.code ? restingCode(s.code, s.error) : null;
+}
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **Save Page Now works without archive.org keys, and a whole list of pages can be archived politely, with an evidence file.** The operator wanted every Mr. Obvious post on a public archive ("I'm just trying to make sure evidence of the pages exist"), and Save Page Now refused without S3 keys. With no keys configured it now asks archive.org's public endpoint anonymously (`"mode": "anonymous"` in the log and result; with keys, SPN2 as before, `"mode": "keys"`), and the channel page's Save Page Now panel says which. Every save in the editor takes turns through one pacer: one at a time, at least 60 s apart anonymous (10 s with keys), and a 429/503 or archive.org's "slow down" rests it (Retry-After, else 2 min doubling to 1 h). `pnpm ops save-page-now-batch --json '{"file":"/abs/urls.json"}'` runs ONE resumable job over a list: each URL looked up first (the Wayback CDX and archive.today's timemap, paced) and skipped when a copy shows it, else saved; at most 150 saves a day without keys (archive.org allows 200); progress and an ETA on /jobs; cancel, a restart or `{"batch": "<id>"}` continue from the first pending URL. Its evidence JSON + CSV (default `<transcripts>/.spn-batches/<batch>.evidence.*`, or `evidence`) names, per URL, the status, the Wayback and archive.today copy URLs, the capture time and the HTTP status the archive recorded. archive.today and Ghostarchive are looked up only, never asked to save (their forms put a CAPTCHA in front). Save Page Now refuses x.com as a site today (HTTP 523, "limitations when it comes to archiving this site"): a batch asks such a site once, then only looks its other URLs up and records them as not asked. OPERATING.md, "Archive a list of pages politely (evidence)".
- **umtool: a reel can end on an outro card, and open on an intro its master does not have.** A trailer stopped on its last beat, and a reel with "open on the brand intro" was refused when the take had been rendered without one (the Mr. Obvious X trailer). `umtool trailer-beats <p> --reel <r> outro '{"title":"…","image":"promo/thumbnail.jpg"}'` (`on`, `off`, `none`) ends the reel on a card: the full video's title large (default the reel's title, else the project's), "Full video on the channel" under it (`text`), the site's name small in its accent, over the image blurred and darkened (or the dark ground), 3.5 s (`seconds`) with a 0.5 s fade in from the last beat while its sound fades out, then held to the end; `ls` says `· outro 3.5 s` and the length against the limit counts it. With `intro on` and no intro in the master, the take's `render.intro` (else the dark boot with the mark on the chime) is rendered for the reel; `intro '{"style":"boot-dark","mark":"chime","site":"anilyzer"}'` gives a reel an intro of its own. `umtool trailer --reel` cuts both in; a reel with neither is cut exactly as before. The Trailer page has **end on the outro card** and its fields beside **open on the brand intro**. Shorts get both too: `umtool vertical … --intro` opens a short on the brand intro re-laid 9:16 (the drawing centred between the Shorts overlays: the top 8 %, the bottom 20 %, 12 % either side), a reel's `intro` on does the same, and a reel's outro card is laid out 9:16 inside that safe area (`--no-intro`, `--no-outro`). A landscape intro is unchanged.
- **umtool: a take can be previewed fast, and only what changed can be rendered.** A re-render of a 40-minute cut took 5–40 minutes even reusing everything it could, because its picture is encoded at 1920×1080 on a slow preset, and the operator walked each render and waited for the next. `umtool take <p> --id <t> --preview` renders the take (a draft too) composed exactly as its full render -- the same layout, segments, chrome and sound, so timing and levels judged on it hold -- with only the final picture at 1280×720, x264 veryfast, crf 26 (`render.preview`), into `takes/<t>/out/<slug>.preview.mp4`; the take's full render and its records are never touched, and a preview's encoded chunks are keyed apart and never stand in for a full render's. `umtool take <p> --id <t> --changes [--from <t0>] [--pad 3]` renders a reel of ONLY the items that changed against the take it was made from (added, re-read, re-picked, re-voiced, trimmed, held, fx, …), each with its neighbours, cut to the item ± 3 s and labelled with its time in the full cut ("21:19 · p-… · re-voiced"), into `takes/<t>/out/<slug>.changes.mp4`, and lists them in `takes/<t>/changes.json`. Both run through the queue (`umtool queue add -- take … --preview`), the take card's **Preview render** and **Render changes** (and Play's **Fast render**) queue them and show their state, the file's path with Copy and the file itself, and `umtool take status … --json` reports them. umtool/docs/report-video.md, knobs.md, cli.md.
- **umtool: a reel can end on an outro card, and open on an intro its master does not have.** A trailer stopped on its last beat, and a reel with "open on the brand intro" was refused when the take had been rendered without one (the Mr. Obvious X trailer). `umtool trailer-beats <p> --reel <r> outro '{"title":"…","image":"promo/thumbnail.jpg"}'` (`on`, `off`, `none`) ends the reel on a card: the full video's title large (default the reel's title, else the project's), "Full video on the channel" under it (`text`), the site's name small in its accent, over the image blurred and darkened (or the dark ground), 3.5 s (`seconds`) with a 0.5 s fade in from the last beat while its sound fades out, then held to the end; `ls` says `· outro 3.5 s` and the length against the limit counts it. With `intro on` and no intro in the master, the take's `render.intro` (else the dark boot with the mark on the chime) is rendered for the reel; `intro '{"style":"boot-dark","mark":"chime","site":"anilyzer"}'` gives a reel an intro of its own. `umtool trailer --reel` cuts both in; a reel with neither is cut exactly as before.
diff --git a/editor/app/api/ops/save-page-now-batch/route.ts b/editor/app/api/ops/save-page-now-batch/route.ts
@@ -0,0 +1,53 @@
+import { NextResponse } from "next/server";
+import { savePageNowBatchAction, savePageNowBatchDryRunAction } from "../../../channels/[slug]/waybackLiveActions";
+import { OpsInputError, ops, opsFail, optBool, optPositiveInt, optString, reqStringArray } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { urls: [...] | file: <abs path> | batch: <id>, skipArchived?: true,
+// sources?: ["wayback", "archive.today"], evidence?: <abs path>,
+// dailyCap?, dryRun? } -> { ok: true, jobId, batch } | (dryRun) the plan
+//
+// SAVE PAGE NOW, A LIST (lane spn-batch, controller/savePageNowBatch.ts): ONE
+// resumable save-page-now-batch job. Each URL in turn: looked up (the Wayback
+// Machine's CDX, archive.today's timemap; skipped when a copy shows it), else
+// saved — anonymously without archive.org keys, SPN2 with them — one at a
+// time, ≥ 60 s apart anonymous (≥ 10 s with keys), resting after a 429/503,
+// at most `dailyCap` saves a day (150 anonymous; archive.org allows 200). The
+// state is <transcripts>/.spn-batches/<batch>.json; the same request again (or
+// {batch}) continues it. The evidence JSON + CSV is `evidence` (default
+// beside the state). archive.today and Ghostarchive are looked up, never
+// asked to save. The log ends with `@@save-page-now-batch {batch, mode,
+// counts, run, evidence, statePath, etaSeconds, stopped?}`.
+export async function POST(request: Request) {
+ return ops(request, ["urls", "file", "batch", "skipArchived", "sources", "evidence", "dailyCap", "dryRun"], async (body) => {
+ const urls = body.urls !== undefined ? reqStringArray(body, "urls") : undefined;
+ const file = optString(body, "file")?.trim() || undefined;
+ const batch = optString(body, "batch")?.trim() || undefined;
+ if ([urls, file, batch].filter((v) => v !== undefined).length !== 1) {
+ throw new OpsInputError(`give exactly one of "urls", "file" or "batch"`);
+ }
+ const sources = body.sources !== undefined ? reqStringArray(body, "sources") : undefined;
+ const evidence = optString(body, "evidence")?.trim() || undefined;
+ const skipArchived = optBool(body, "skipArchived");
+ const dailyCap = optPositiveInt(body, "dailyCap");
+ const req = {
+ ...(urls ? { urls } : {}),
+ ...(file ? { file } : {}),
+ ...(batch ? { batch } : {}),
+ ...(sources ? { sources } : {}),
+ ...(evidence ? { evidence } : {}),
+ ...(skipArchived !== undefined ? { skipArchived } : {}),
+ ...(dailyCap !== undefined ? { dailyCap } : {}),
+ };
+ if (optBool(body, "dryRun") === true) {
+ const r = await savePageNowBatchDryRunAction(req);
+ if (!r.ok) return opsFail(r.error, 400);
+ return NextResponse.json(r);
+ }
+ const res = await savePageNowBatchAction(req, "ops");
+ if (!res.ok) return opsFail(res.error, 400);
+ void res.stream.cancel();
+ return NextResponse.json({ ok: true, jobId: res.jobId, batch: res.batch });
+ });
+}
diff --git a/editor/app/channels/[slug]/components/WaybackLivePanel.tsx b/editor/app/channels/[slug]/components/WaybackLivePanel.tsx
@@ -35,7 +35,7 @@ export type WaybackLiveState = {
goneRows: WaybackLiveRow[];
// Records whose original answered, one per original URL (Save Page Now).
liveRows: WaybackLiveRow[];
- spn: { on: true } | { on: false; reason: string };
+ spn: { on: true; mode: "keys" } | { on: true; mode: "anonymous"; note: string } | { on: false; reason: string };
};
function CaptureNow({ slug, url, disabled }: { slug: string; url: string; disabled: boolean }) {
@@ -145,6 +145,11 @@ export function WaybackLivePanel({ slug, state }: { slug: string; state: Wayback
{state.spn.on ? "" : state.spn.reason}
</p>
)}
+ {state.spn.on && state.spn.mode === "anonymous" && (
+ <p role="status" aria-label="save page now anonymous" className="text-xs text-muted-foreground">
+ {state.spn.note}
+ </p>
+ )}
<input
value={url}
onChange={(e) => setUrl(e.target.value)}
diff --git a/editor/app/channels/[slug]/waybackLiveActions.ts b/editor/app/channels/[slug]/waybackLiveActions.ts
@@ -20,6 +20,7 @@ import {
type SavePageNowResult,
} from "yt-dlp-transcript-common/controller/savePageNow";
import { WAYBACK_PAGES_QUEUE } from "yt-dlp-transcript-common/controller/importPage";
+import { queueSpnBatch, spnBatchDryRun, type SpnBatchRequest } from "yt-dlp-transcript-common/controller/savePageNowBatch";
import { findPageCopies } from "yt-dlp-transcript-common/publish/findCopyPages";
import { FIND_COPY_RESULT_MARKER } from "yt-dlp-transcript-common/publish/findCopy";
import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
@@ -37,6 +38,16 @@ export async function savePageNowAction(url: string, slug?: string, requestedBy?
});
}
+// SAVE PAGE NOW, A LIST (lane spn-batch): one resumable save-page-now-batch
+// job (controller/savePageNowBatch.ts), or — dryRun — the plan answered now.
+export async function savePageNowBatchAction(req: SpnBatchRequest, requestedBy?: string): Promise<StreamActionResult & { batch?: string }> {
+ return queueSpnBatch({ paths: getPaths(), req, ...(requestedBy ? { requestedBy } : {}) });
+}
+
+export async function savePageNowBatchDryRunAction(req: SpnBatchRequest) {
+ return spnBatchDryRun(getPaths(), req);
+}
+
// What a capture WOULD ask, answered now (no job, no request).
export async function savePageNowDryRunAction(url: string, slug?: string): Promise<SavePageNowResult> {
return savePageNow({ paths: getPaths(), url: url.trim(), ...(slug?.trim() ? { slug: slug.trim() } : {}), dryRun: true });
diff --git a/editor/app/jobs/components/JobProgressBars.tsx b/editor/app/jobs/components/JobProgressBars.tsx
@@ -164,6 +164,7 @@ const METRIC_LABELS: Record<JobProgressMetric, string> = {
entries: "Entries",
frames: "Frames",
files: "Files",
+ pages: "Pages",
};
// Per-metric glyph for the compact line ("↓ 5/10").
@@ -179,6 +180,7 @@ const METRIC_PREFIX: Record<JobProgressMetric, string> = {
entries: "\u2261 ",
frames: "\u25a3 ",
files: "\u266a ",
+ pages: "\u2691 ",
};
const METRIC_FILL: Record<JobProgressMetric, string> = {
@@ -193,6 +195,7 @@ const METRIC_FILL: Record<JobProgressMetric, string> = {
entries: "bg-success/60",
frames: "bg-info/60",
files: "bg-info/60",
+ pages: "bg-success/60",
};
// One-line textual summary of a job's batch progress, e.g. "↓ 5/10 · ~2m left"
diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts
@@ -8,6 +8,7 @@
// Server-only: reached through the retry actions in actions.ts ("use server"),
// so it is never bundled to the client.
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { savePageNowBatchAction } from "../channels/[slug]/waybackLiveActions";
import { coerceClipCopy } from "yt-dlp-transcript-common/lib/clipWindow";
import { isStoredUrlMode } from "yt-dlp-transcript-common/lib/storedMediaUrl";
import { readChannelSnapshot } from "yt-dlp-transcript-common/controller/channelSnapshot";
@@ -427,6 +428,23 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = {
: undefined,
);
},
+ // Lane spn-batch: the batch's state file holds the list and each URL's
+ // status; the re-run continues from the first pending URL.
+ "save-page-now-batch": (spec) => {
+ const { p } = params(spec);
+ const batch = str(p.batch);
+ if (!batch) return Promise.resolve({ ok: false, error: "Job spec has no batch." });
+ return savePageNowBatchAction(
+ {
+ batch,
+ ...(str(p.evidence) ? { evidence: str(p.evidence) } : {}),
+ ...(bool(p.skipArchived) !== undefined ? { skipArchived: bool(p.skipArchived) } : {}),
+ ...(strings(p.sources) ? { sources: strings(p.sources) } : {}),
+ ...(num(p.dailyCap) !== undefined ? { dailyCap: num(p.dailyCap) } : {}),
+ },
+ "retry",
+ );
+ },
// The ids are the spec's own (a capture is OF specific posts, unlike a
// bucket); the re-run skips whatever the first run already captured.
"capture-posts": (spec) => {
diff --git a/editor/e2e/wayback-live.spec.ts b/editor/e2e/wayback-live.spec.ts
@@ -87,13 +87,15 @@ test("Originals and Save Page Now on a Wayback pages channel: off without keys,
const originals = page.getByRole("region", { name: "originals" });
await expect(originals.getByLabel("originals checked")).toHaveText("0 of 1 original URL checked · 0 gone");
await expect(originals.getByRole("button", { name: "Check originals" })).toBeEnabled();
- // No keys: the button is off and says why; nothing was asked of SPN.
+ // No keys (lane spn-batch): Save Page Now asks anonymously, and says so;
+ // a dry run names the anonymous request and asks nothing of SPN.
const spn = page.getByRole("region", { name: "save page now" });
- await expect(spn.getByLabel("save page now off")).toContainText("Save Page Now needs archive.org S3 keys");
- await expect(spn.getByRole("button", { name: "Ask the Wayback Machine to capture this now" })).toBeDisabled();
- const refused = await request.post(`${baseUrl}/api/ops/save-page-now`, { headers: AUTH, data: { url: LIVE, slug: SLUG } });
- expect(refused.status()).toBe(400);
- expect(((await refused.json()) as { error: string }).error).toContain("needs archive.org S3 keys");
+ await expect(spn.getByLabel("save page now anonymous")).toContainText("Save Page Now asks anonymously");
+ const anon = await request.post(`${baseUrl}/api/ops/save-page-now`, { headers: AUTH, data: { url: LIVE, slug: SLUG, dryRun: true } });
+ expect(anon.status()).toBe(200);
+ const anonBody = (await anon.json()) as { mode: string; wouldAsk: string };
+ expect(anonBody.mode).toBe("anonymous");
+ expect(anonBody.wouldAsk).toContain("anonymous");
expect(wb.requests.filter((r) => r.path.startsWith("/save"))).toEqual([]);
// The original's verdict, as the check writes it: gone — the Wayback copy is the only copy.
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -153,6 +153,9 @@
// pnpm ops check-post-availability --json '{"slug":"demo-pages","mode":"unchecked"}' --wait
// pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages","dryRun":true}'
// pnpm ops save-page-now --json '{"url":"https://blog.example/a-post.html","slug":"demo-pages"}' --wait
+// pnpm ops save-page-now-batch --json '{"file":"/home/me/lists/posts.json","dryRun":true}'
+// pnpm ops save-page-now-batch --json '{"file":"/home/me/lists/posts.json","evidence":"/home/me/evidence/posts"}'
+// pnpm ops save-page-now-batch --json '{"batch":"spn-0123456789ab"}'
// pnpm ops find-copy --json '{"article":"demo-article","pages":true,"dryRun":true}' --wait
// pnpm ops find-copy --json '{"siteId":"demo-site","pages":true,"channel":"demo-pages"}' --wait
// pnpm ops import-page --json '{"slug":"demo-pages","url":"https://archive.ph/AbCdE","dryRun":true}'
@@ -557,6 +560,10 @@ const ACTIONS = [
// keys), the capture imported into slug, as a save-page-now job.
"check-post-availability",
"save-page-now",
+ // SAVE PAGE NOW, A LIST (lane spn-batch): one resumable job over a list of
+ // URLs — each looked up, saved when no copy shows it ({urls | file | batch,
+ // skipArchived?, sources?, evidence?, dailyCap?, dryRun?}).
+ "save-page-now-batch",
// ARCHIVE SOURCES (release 37 lane F): the copies of a page across archive
// sources — the Wayback Machine and archive.today — read only and paced
// ({url, source?, limit?}).
@@ -1995,18 +2002,46 @@ export function usage() {
" Wayback copy is the only copy. Verdicts go to posts-availability.json.",
"",
"save-page-now asks the Wayback Machine to capture a live page now (Save",
- ' Page Now, with archive.org\'s S3 keys): {"url", "slug"?, "dryRun"?}. A',
- " save-page-now job on the archive.org queue: the capture asked (the page",
- " alone, no outlinks), its status polled until it is made, then — with",
- " slug, a Wayback pages channel — an import-page job of the new capture.",
- " Refused, before any job: no keys (ARCHIVE_ORG_S3_ACCESS and",
- " ARCHIVE_ORG_S3_SECRET in the editor's environment, or the mode-600 file",
- " settings archiveOrg.s3KeyFile names), a URL that is not http(s), a page",
- " on the Wayback Machine, not a Wayback pages channel, a video, an X page",
- " outside an X channel while X is private. The keys are never logged.",
- ' "dryRun" answers what it would ask and starts nothing. The log ends with',
- " @@save-page-now {ok, url, slug?, spnJobId, captureTs, originalUrl,",
- " waybackUrl, importJobId?, importError?, polls, error?}.",
+ ' Page Now): {"url", "slug"?, "dryRun"?}. With archive.org\'s S3 keys',
+ " (ARCHIVE_ORG_S3_ACCESS and ARCHIVE_ORG_S3_SECRET in the editor's",
+ " environment, or the mode-600 file settings archiveOrg.s3KeyFile names)",
+ ' it is SPN2 ("mode": "keys"); with none configured it is the public',
+ ' endpoint, anonymously ("mode": "anonymous": archive.org allows 3 a',
+ " minute and 200 a day). A save-page-now job on the archive.org queue: the",
+ " capture asked (the page alone, no outlinks), its status polled until it",
+ " is made, then — with slug, a Wayback pages channel — an import-page job",
+ " of the new capture. One save at a time in the process, at least 60 s",
+ " apart anonymous (10 s with keys); a 429/503 rests it (Retry-After, else",
+ " 2 min doubling to 1 h). Refused, before any job: a key file that is",
+ " there but readable by others, a URL that is not http(s), a page on the",
+ " Wayback Machine, not a Wayback pages channel, a video, an X page outside",
+ " an X channel while X is private. The keys are never logged. \"dryRun\"",
+ " answers what it would ask and starts nothing. The log ends with",
+ " @@save-page-now {ok, url, slug?, mode, spnJobId?, captureTs, originalUrl,",
+ " waybackUrl, importJobId?, importError?, polls, rateLimited?, error?}.",
+ "",
+ "save-page-now-batch saves a LIST of pages as ONE resumable job: {\"urls\":",
+ ' [...]} | {"file": <abs path: a JSON list, {urls}, or a URL a line>} |',
+ ' {"batch": <id>}, "skipArchived"? (true), "sources"? (["wayback",',
+ ' "archive.today"]), "evidence"? (abs path), "dailyCap"? (150 anonymous,',
+ ' at most 200; 5000 with keys), "dryRun"? -> {jobId, batch}. Each URL in',
+ " turn: looked up (the Wayback CDX, archive.today's timemap, each paced)",
+ " and archived-already when a copy shows it (a Wayback row that recorded a",
+ " 200, or an archive.today copy); else saved through Save Page Now's pacer",
+ " (anonymous without keys), saved or failed with the reason; a site Save",
+ " Page Now refuses as a site (x.com, 5 Nov: \"limitations when it comes to",
+ " archiving this site\") is asked once a run, its other URLs looked up only.",
+ " archive.today",
+ " and Ghostarchive are looked up, never asked to save. The state is",
+ " <transcripts>/.spn-batches/<batch>.json, written after every URL: the",
+ " same request again, {batch}, a Retry or a restart continues from the",
+ " first pending URL. The evidence (JSON + CSV: url, status, reason,",
+ " waybackUrl, waybackCaptureTs, waybackHttpStatus, waybackMimetype,",
+ " archiveTodayUrl, archiveTodayCaptureTs, shows, savedMode, checkedAt,",
+ " doneAt) is rewritten after every URL; default",
+ " <transcripts>/.spn-batches/<batch>.evidence.json. Progress (done/total,",
+ " ETA) in /jobs. The log ends with @@save-page-now-batch {batch, mode,",
+ " counts, run, evidence, statePath, etaSeconds, stopped?}.",
"",
'report-draft runs a generation over an article\'s iteration as a',
' report-draft job: {"task": "sweep" | "revise-report" | "revise-video" |',
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -1039,6 +1039,12 @@ test("check-post-availability, save-page-now and find-copy's page mode are POSTs
// Release 37 lane F: the copies of a page across archive sources, and an
// archive.today copy's import, are POSTs to their routes.
+test("save-page-now-batch is a POST to its route, named in the usage", () => {
+ const p = parseArgs(["save-page-now-batch", "--json", '{"file":"/tmp/x.json","dryRun":true}']);
+ assert.equal(p.path, "/api/ops/save-page-now-batch");
+ assert.match(usage(), /save-page-now-batch saves a LIST of pages as ONE resumable job/);
+});
+
test("archive-lookup is a POST to its route; import-page passes source through; both named in the usage", () => {
const p = parseArgs(["archive-lookup", "--json", '{"url":"https://blog.example/a.html","source":"archive.today","limit":5}']);
assert.equal(p.method, "POST");
@@ -1046,7 +1052,7 @@ test("archive-lookup is a POST to its route; import-page passes source through;
assert.deepEqual(p.body, { url: "https://blog.example/a.html", source: "archive.today", limit: 5 });
const i = parseArgs(["import-page", "--json", '{"slug":"old-blog","url":"https://blog.example/a.html","at":"2019","source":"archive.today"}']);
assert.deepEqual(i.body, { slug: "old-blog", url: "https://blog.example/a.html", at: "2019", source: "archive.today" });
- assert.match(usage(), /Actions:.*save-page-now, archive-lookup/);
+ assert.match(usage(), /Actions:.*save-page-now, save-page-now-batch, archive-lookup/);
assert.match(usage(), /archive-lookup answers the copies of a page each archive source holds/);
assert.match(usage(), /excluded from the Wayback Machine \(cause/);
});