// RE-EXTRACT A WAYBACK PAGES CHANNEL (release 37 S1, `reextract-pages`, // `archilyzer wayback pages reextract`): every page record re-derived from // the raw bodies the channel stores under `pages/` — no request, no network. // What an improved (or new) extractor is for: the captures whose extractor or // version is no longer the one a capture would go to now are STALE, and a // re-extract makes the channel's records what an import today would make. // // The records are recomputed from EVERY stored capture (oldest first, merged // as an import merges them), the versions re-assigned, and the channel's page // records replaced whole (posts-server replaceChannelPosts) when anything // differs — so a record may move month (a page's own date read at last), and // an id the new extraction no longer makes is removed. A record whose capture // is NOT stored (nothing to re-derive it from) is kept as it is. // // One writer: in the editor it runs as a job on the archive.org queue, the // queue every import into the channel runs on. The CLI runs it in-process, // with the editor stopped (or no import running on the channel). import path from "node:path"; import { getPaths, type Paths } from "../lib/paths"; import type { Post } from "../lib/posts"; import { readAllPosts, replaceChannelPosts } from "../lib/posts-server"; import { readChannelConfig } from "./channels"; import { isWaybackPagesChannel } from "../lib/waybackPages/config"; import { chooseExtractor } from "../lib/waybackPages/extract"; import { asStored, assignPageVersions, mergePageRecord, stableRecordJson } from "../lib/waybackPages/toPost"; import { listStoredCaptures, pageCaptureDirName, readStoredCaptureBody, updateStoredCapture, } from "../lib/waybackPages/store-server"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { extractInputOfCapture, recordsOfCapture, WAYBACK_PAGES_QUEUE } from "./importPage"; export const REEXTRACT_PAGES_JOB_KIND = "reextract-pages"; export const REEXTRACT_PAGES_RESULT_MARKER = "@@reextract-pages "; export type ReextractPagesResult = { ok: boolean; slug: string; dryRun: boolean; captures: number; // Captures whose stored extractor/version is not what they would go to now. stale: number; // Captures whose body could not be read. unreadable: number; records: { added: number; changed: number; removed: number; unchanged: number; kept: number }; written: boolean; error?: string; }; function samePost(a: Post, b: Post): boolean { return stableRecordJson(asStored(a)) === stableRecordJson(asStored(b)); } export async function reextractPages(opts: { paths: Paths; slug: string; dryRun?: boolean; onLog?: (line: string) => void; }): Promise { const log = (line: string) => opts.onLog?.(line); const dryRun = opts.dryRun === true; const out: ReextractPagesResult = { ok: false, slug: opts.slug, dryRun, captures: 0, stale: 0, unreadable: 0, records: { added: 0, changed: 0, removed: 0, unchanged: 0, kept: 0 }, written: false, }; const config = await readChannelConfig(opts.paths, opts.slug); if (!config) return { ...out, error: `No such channel: ${opts.slug}` }; if (!isWaybackPagesChannel(config)) { return { ...out, error: `${opts.slug} is not a Wayback pages channel (platform "webpage")` }; } const channelRoot = path.join(opts.paths.channelsDir, opts.slug); const captures = await listStoredCaptures(channelRoot); out.captures = captures.length; const desired = new Map(); // Captures whose records are re-derived (stored and readable). const derivable = new Set(); const captureUpdates: { dir: string; next: (typeof captures)[number]["capture"] }[] = []; for (const { dir, name, capture } of captures) { let body: Buffer; try { body = await readStoredCaptureBody(dir); } catch (e) { out.unreadable++; log(`${name}: the stored body is unreadable (${(e as Error).message}); its records are kept as they are.`); continue; } derivable.add(name); // Release 37 lane F: what the extractors read (an archive.today copy // unwrapped), as an import reads it. const now = chooseExtractor(extractInputOfCapture(capture, body).input); const isStale = now.name !== capture.extractor || now.version !== capture.extractorVersion || !!capture.extractorFallback; if (isStale) out.stale++; const made = recordsOfCapture(opts.slug, capture, body); for (const p of made.posts) { const prev = desired.get(p.id); desired.set(p.id, prev ? (mergePageRecord(prev, p) ?? prev) : p); } const next = { ...capture, extractor: made.extractor.name, extractorVersion: made.extractor.version, records: made.posts.map((p) => p.id), }; if (made.fallback) next.extractorFallback = made.fallback; else delete next.extractorFallback; if (JSON.stringify(next) !== JSON.stringify(capture)) captureUpdates.push({ dir, next }); } for (const v of assignPageVersions([...desired.values()])) desired.set(v.id, v); // What the channel holds now. A record is re-derivable when its capture is // stored and readable; anything else stays exactly as it is. const existing = await readAllPosts(channelRoot); const final = new Map(desired); for (const p of existing) { const capName = p.page ? pageCaptureDirName(p.page.captureTs, p.page.originalUrl) : null; const rederivable = capName !== null && derivable.has(capName); const want = desired.get(p.id); if (want) { if (samePost(p, want)) out.records.unchanged++; else out.records.changed++; } else if (rederivable) { out.records.removed++; } else { final.set(p.id, p); out.records.kept++; } } const existingIds = new Set(existing.map((p) => p.id)); for (const id of desired.keys()) if (!existingIds.has(id)) out.records.added++; const r = out.records; const dirty = r.added + r.changed + r.removed > 0; log( `${opts.slug}: ${out.captures} stored capture(s), ${out.stale} stale; records ${r.added} new, ${r.changed} changed, ` + `${r.removed} removed, ${r.unchanged} unchanged${r.kept ? `, ${r.kept} kept (no stored capture)` : ""}.`, ); if (dryRun) { log("Dry run: nothing written."); return { ...out, ok: true }; } if (dirty) { await replaceChannelPosts(channelRoot, [...final.values()]); out.written = true; log("The channel's page records are rewritten; the index picks them up on its next build."); } for (const u of captureUpdates) await updateStoredCapture(u.dir, u.next); if (!dirty && captureUpdates.length === 0) log("Nothing to change."); return { ...out, ok: true }; } // THE JOB (the channel page's Re-extract button, `pnpm ops reextract-pages`): // on the archive.org queue, so it never runs beside an import into the // channel. export async function queueReextractPages(opts: { paths?: Paths; slug: string; dryRun?: boolean; }): Promise { const paths = opts.paths ?? getPaths(); const config = await readChannelConfig(paths, opts.slug); if (!config) return { ok: false, error: `No such channel: ${opts.slug}` }; if (!isWaybackPagesChannel(config)) { return { ok: false, error: `${opts.slug} is not a Wayback pages channel (platform "webpage")` }; } return runManagedFunction({ kind: REEXTRACT_PAGES_JOB_KIND, queueKey: WAYBACK_PAGES_QUEUE, paths, channelSlug: opts.slug, fn: async (onLog) => { onLog(`Re-extract the stored captures of ${opts.slug}${opts.dryRun ? " (dry run)" : ""}`); const result = await reextractPages({ paths, slug: opts.slug, dryRun: opts.dryRun, onLog }); onLog(`${REEXTRACT_PAGES_RESULT_MARKER}${JSON.stringify(result)}`); if (!result.ok) throw new Error(result.error ?? "Re-extract failed"); }, }); }