/** * Copyright 2026 aphrody-code * SPDX-License-Identifier: Apache-2.0 */ /** * `bxc revalidate` — refresh the local index with HTTP validators. * * For documents older than `--older-than`, send a conditional GET * (`If-None-Match` / `If-Modified-Since`). `304 Not Modified` only refreshes * the fetch time; a `200` is re-processed and upserted, which is a no-op when * the content hash did not change. */ import { BxcDB } from "../db/BxcDB.ts"; import { processDocument } from "../crawler/document-pipeline.ts"; import { type CommonOptions, logger } from "./shared.ts"; export interface RevalidateSummary { checked: number; notModified: number; unchanged: number; changed: number; failed: number; } export interface RevalidateOptions { dbPath?: string; olderThanMs?: number; limit?: number; concurrency?: number; fetchImpl?: typeof fetch; } function parseDuration(value: string): number { const match = /^(\d+(?:\.\d+)?)(ms|s|m|h|d)?$/.exec(value.trim()); if (!match) throw new Error(`invalid duration: ${value}`); const unit = { ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[(match[2] ?? "ms") as "ms"]; return Number(match[1]) * unit; } export async function revalidate(options: RevalidateOptions = {}): Promise { const db = new BxcDB(options.dbPath); const fetchImpl = options.fetchImpl ?? fetch; const summary: RevalidateSummary = { checked: 0, notModified: 0, unchanged: 0, changed: 0, failed: 0 }; try { const candidates = db.getRevalidationCandidates(options.olderThanMs ?? 86_400_000, options.limit ?? 500); let cursor = 0; const worker = async () => { while (cursor < candidates.length) { const doc = candidates[cursor++]; if (!doc) break; summary.checked++; try { const headers: Record = {}; if (doc.etag) headers["if-none-match"] = doc.etag; if (doc.last_modified) headers["if-modified-since"] = doc.last_modified; const res = await fetchImpl(doc.url, { headers, redirect: "follow", signal: AbortSignal.timeout(20_000) }); if (res.status === 304) { db.markRevalidated(doc.id, 304, { etag: res.headers.get("etag"), lastModified: res.headers.get("last-modified"), }); summary.notModified++; continue; } if (!res.ok) { summary.failed++; continue; } const html = await res.text(); const processed = processDocument(html, doc.url); const result = db.upsertDocument({ url: doc.url, profile: "http", status: res.status, content: html, metadata: { title: processed.title, byline: processed.byline, published: processed.published }, markdown: processed.markdown, provenance: { canonicalUrl: processed.canonicalUrl, contentHash: processed.contentHash, simhash: processed.simhash, etag: res.headers.get("etag"), lastModified: res.headers.get("last-modified"), fetchedAt: Date.now(), }, chunks: processed.chunks, }); if (result.changed) summary.changed++; else summary.unchanged++; } catch { summary.failed++; } } }; await Promise.all(Array.from({ length: Math.max(1, options.concurrency ?? 8) }, worker)); return summary; } finally { db.close(); } } function printUsage(): void { Bun.stdout.write(`bxc revalidate — refresh indexed pages with conditional requests Usage: bxc revalidate [--db ] [--older-than 24h] [--limit 500] [--concurrency 8] [--json] `); } export async function main(argv: string[], opts: CommonOptions): Promise { const options: RevalidateOptions = {}; for (let i = 0; i < argv.length; i++) { const arg = argv[i]; if (arg === "--help" || arg === "-h") return printUsage(); if (arg === "--db") options.dbPath = argv[++i]; else if (arg === "--older-than") options.olderThanMs = parseDuration(argv[++i] ?? ""); else if (arg === "--limit") options.limit = Number.parseInt(argv[++i] ?? "", 10); else if (arg === "--concurrency") options.concurrency = Number.parseInt(argv[++i] ?? "", 10); } const summary = await revalidate(options); if (opts.json) Bun.stdout.write(`${JSON.stringify(summary)}\n`); else logger.log( `checked=${summary.checked} not-modified=${summary.notModified} unchanged=${summary.unchanged} changed=${summary.changed} failed=${summary.failed}`, ); }