// THE WEB PACER — every web request a generation run makes (search and page // reads, release 27 D7) goes through ONE in-process queue: one request at a // time, at least WEB_MIN_GAP_MS between one request's end and the next's // start, a plain user agent, and a back-off on 429 / 503 (Retry-After when // the server gives one, else doubling from WEB_BACKOFF_BASE_MS) before the // request is tried again, at most WEB_MAX_ATTEMPTS times. Polite scraping: // one stream, real gaps, back off when told. // // The editor's `web-search` / `web-fetch` actions and a job's agent tools // share the process's pacer (`webPacer`), so two callers in one editor never // make two streams. import { jitterUp } from "../jitter.mjs"; import { pacingJitter } from "../jitter"; import { browserUserAgentOr } from "../browserUserAgent-server"; export const WEB_MIN_GAP_MS = 3_000; export const WEB_BACKOFF_BASE_MS = 10_000; export const WEB_BACKOFF_MAX_MS = 120_000; export const WEB_MAX_ATTEMPTS = 3; export const WEB_TIMEOUT_MS = 30_000; // The user agent a web request presents: the Firefox on this machine (a current // browser, never a pinned one that ages — this was Firefox 128), else the // module's fixed Firefox. No cookies go with it, so any current browser would do. export function webUserAgent(): string { return browserUserAgentOr(); } const BACK_OFF = new Set([429, 503]); export type WebPacerDeps = { fetch?: (url: string, init: RequestInit) => Promise; now?: () => number; sleep?: (ms: number, signal?: AbortSignal) => Promise; random?: () => number; }; export type WebPacerOpts = { minGapMs?: number; backoffBaseMs?: number; backoffMaxMs?: number; maxAttempts?: number; timeoutMs?: number; // The share of itself each gap and back-off is stretched by, at random // (lib/jitter.mjs — only ever longer). Default: the operator's pacing.jitter. jitter?: number; }; export class WebRequestError extends Error { constructor( message: string, readonly status: number | null, ) { super(message); this.name = "WebRequestError"; } } function defaultSleep(ms: number, signal?: AbortSignal): Promise { return new Promise((resolve, reject) => { if (signal?.aborted) return reject(signal.reason ?? new Error("aborted")); const t = setTimeout(() => { signal?.removeEventListener("abort", onAbort); resolve(); }, ms); const onAbort = () => { clearTimeout(t); reject(signal?.reason ?? new Error("aborted")); }; signal?.addEventListener("abort", onAbort, { once: true }); }); } function retryAfterMs(value: string | null, nowMs: number): number | null { if (!value) return null; const v = value.trim(); if (/^\d+$/.test(v)) return Number(v) * 1000; const at = Date.parse(v); return Number.isFinite(at) ? Math.max(0, at - nowMs) : null; } export class WebPacer { private readonly deps: Required; private readonly opts: Required> & { jitter?: number }; private chain: Promise = Promise.resolve(); private lastDoneAt = -Infinity; // Every attempt sent, with when it started (tests and logs). readonly sent: { url: string; at: number }[] = []; constructor(deps: WebPacerDeps = {}, opts: WebPacerOpts = {}) { this.deps = { fetch: deps.fetch ?? ((url, init) => fetch(url, init)), now: deps.now ?? (() => Date.now()), sleep: deps.sleep ?? defaultSleep, random: deps.random ?? Math.random, }; this.opts = { minGapMs: opts.minGapMs ?? WEB_MIN_GAP_MS, backoffBaseMs: opts.backoffBaseMs ?? WEB_BACKOFF_BASE_MS, backoffMaxMs: opts.backoffMaxMs ?? WEB_BACKOFF_MAX_MS, maxAttempts: opts.maxAttempts ?? WEB_MAX_ATTEMPTS, timeoutMs: opts.timeoutMs ?? WEB_TIMEOUT_MS, // Read at each wait, not here: THE process's pacer below is built at // import time, and reading settings then would fix getPaths() to // whatever TRANSCRIPTS_DIR was set before any caller set its own (and // the jitter to the settings of that moment). ...(opts.jitter !== undefined ? { jitter: opts.jitter } : {}), }; } private jitterShare(): number { return this.opts.jitter ?? pacingJitter(); } // Run `fn` after every earlier request (and its gap) has finished. private serial(fn: () => Promise): Promise { const run = this.chain.then(fn, fn); this.chain = run.catch(() => {}); return run; } // One request through the queue. `read` consumes the response inside the // queue's turn (so a body is read before the next request starts). A 429 // or 503 backs off and retries; any other answer is handed to `read`. request( url: string, init: Omit & { signal?: AbortSignal }, read: (res: Response) => Promise, ): Promise { return this.serial(async () => { for (let attempt = 1; ; attempt++) { const gap = Math.ceil(jitterUp(this.opts.minGapMs, this.jitterShare(), this.deps.random)); const wait = this.lastDoneAt + gap - this.deps.now(); if (wait > 0) await this.deps.sleep(wait, init.signal); this.sent.push({ url, at: this.deps.now() }); let res: Response; try { const timeout = AbortSignal.timeout(this.opts.timeoutMs); res = await this.deps.fetch(url, { ...init, signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout, headers: { "user-agent": webUserAgent(), "accept-language": "en", ...(init.headers as Record) }, }); } catch (e) { this.lastDoneAt = this.deps.now(); if (init.signal?.aborted) throw e; throw new WebRequestError(`${new URL(url).host} did not answer: ${(e as Error).message}`, null); } if (BACK_OFF.has(res.status)) { await res.body?.cancel().catch(() => {}); this.lastDoneAt = this.deps.now(); if (attempt >= this.opts.maxAttempts) { throw new WebRequestError( `${new URL(url).host} answered HTTP ${res.status} ${attempt} times — backing off; try later`, res.status, ); } const told = retryAfterMs(res.headers.get("retry-after"), this.deps.now()); const backoff = Math.min(this.opts.backoffMaxMs, told ?? this.opts.backoffBaseMs * 2 ** (attempt - 1)); await this.deps.sleep( Math.ceil(jitterUp(backoff, this.jitterShare(), this.deps.random)), init.signal, ); continue; } try { return await read(res); } finally { this.lastDoneAt = this.deps.now(); } } }); } } // The process's pacer: the editor's actions and every job's tools share it. export const webPacer = new WebPacer();