diff --git a/static/dashboard/CHANGELOG.md b/static/dashboard/CHANGELOG.md index 0dcf108dc..c1389991a 100644 --- a/static/dashboard/CHANGELOG.md +++ b/static/dashboard/CHANGELOG.md @@ -4,6 +4,7 @@ One line per version, newest first. Every REST-facing change bumps the version i (the app surfaces it via `/system/dashboard/update-check` and the "Update available" pill), so this file is the human record of what each bump enables. Keep entries short: `version - change (TICKET)`. +- **1.2.3-dev** - Resilient content downloads (ADFA-4894, Area 1 of the ADFA-4893 contract). A network drop mid-job recovers or fails cleanly instead of failing the whole batch at the first blip: a shared `withRetry` backoff helper; job cancel now aborts an in-flight `fetch` (new `AbortSignal` on the runner), not just child processes; **books** get a per-attempt timeout + per-item retry/backoff and no longer fail a batch on one dropped EPUB; **kiwix** prunes the partial `.zim` + `.aria2` on cancel (clean-on-cancel) and gains aria2 reconnect flags (`--max-tries`/`--retry-wait`/`--timeout`, documented divergence from the app's `--max-tries=1` outer-loop model). kiwix also gets an **outer** reconnect loop (`withRetry` around aria2) so a full Wi-Fi drop — where aria2 exits on DNS (code 19) and can't retry itself — recovers across the handoff, resuming via `--continue`; books' retry budget widened to ~30s to outlast a real reassociation. Maps per-layer checkpoint is pending the on-box `tile-extract.py`. Version stays `1.2.3-dev.N` through the PR (device-verified on -dev.1); final bump to `1.2.3` at merge. (ADFA-4894) - **1.2.2** - New `GET /kolibri/subtree/:nodeId`: serves a channel's topic tree in Studio's `contentnode_tree` shape, with per-node byte sizes summed from the local content DB over each node's MPTT range, so the app browses an imported channel's whole tree offline (parsed by the same mapper it uses for Studio). Read-only; **404** when the channel's metadata is not imported, which the app reads as "fall back to Studio". Ships the endpoint PR added without a version bump. (ADFA-5094) - **1.2.1** - Four Kolibri defects found by testing against a real device. `/kolibri/estimate` now reports free space (the call was missing the mandatory `?path=Content` and had been failing silently since it was written) and answers **409** with a readable message for a channel that is not installed, instead of letting Kolibri return a bare 500; `/kolibri/catalog` reports real sizes and resource counts (it was reading Studio's field names on an endpoint that uses Kolibri's); a failed import now carries the cause instead of just the exception class name. Also finishes the English pass: `routes.ts` was the last file the 1.1.6 sweep missed — REST-facing too, since one response string changes (`POST /credentials/kolibri` on 401). (ADFA-4954) - **1.2.0** - Self-update cutover baseline: no endpoint change, but from this version the app updates the dash-node core **live over REST** (`POST /system/dashboard/rebuild`, the blue-green rebuild from ADFA-5011) instead of a proot rebuild. Installs on < 1.2.0 still use the proot path to reach 1.2.0; 1.2.0+ update to 1.2.1+ via REST. (ADFA-5051) diff --git a/static/dashboard/package-lock.json b/static/dashboard/package-lock.json index 4b8383b8f..5e264bbbe 100644 --- a/static/dashboard/package-lock.json +++ b/static/dashboard/package-lock.json @@ -1,12 +1,12 @@ { "name": "dashboard-console", - "version": "1.2.1", + "version": "1.2.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "dashboard-console", - "version": "1.2.1", + "version": "1.2.2", "license": "ISC", "dependencies": { "better-sqlite3": "^12.8.0", diff --git a/static/dashboard/package.json b/static/dashboard/package.json index 51ddbf9ec..85d7fac45 100644 --- a/static/dashboard/package.json +++ b/static/dashboard/package.json @@ -1,10 +1,10 @@ { "name": "dashboard-console", - "version": "1.2.2", + "version": "1.2.3-dev.2", "description": "", "main": "index.js", "scripts": { - "test": "node --require ts-node/register --test sockets/maps.socket.test.ts sockets/rolling-log.test.ts sockets/kolibri.session.test.ts sockets/credentials.test.ts", + "test": "node --require ts-node/register --test sockets/maps.socket.test.ts sockets/rolling-log.test.ts sockets/kolibri.session.test.ts sockets/credentials.test.ts sockets/net-retry.test.ts", "typecheck": "tsc --noEmit", "build": "tsc", "start": "node dist/server.js" diff --git a/static/dashboard/sockets/books.exec.ts b/static/dashboard/sockets/books.exec.ts index 1c9623197..054297e67 100644 --- a/static/dashboard/sockets/books.exec.ts +++ b/static/dashboard/sockets/books.exec.ts @@ -4,11 +4,25 @@ // the EPUB and upload it to the local Calibre-Web. Ported from the Phase 1 books.socket // download_books_batch handler (auth/CSRF + fetch + upload), made durable and reporting // structured per-book progress. A job item is { id, title, url }. -import { jobs, RunnerContext } from './jobs'; +import { jobs, RunnerContext, CanceledError } from './jobs'; import { getCredential } from './credentials'; +import { withRetry, Aborted } from './net-retry'; import fs from 'fs'; import path from 'path'; +// ADFA-4894: a stalled Gutenberg fetch must not hang the job forever, and a transient +// drop must not fail the whole batch at one book. Per-book: bound each attempt with a +// timeout, retry the transient ones with backoff, and make the job's cancel abort an +// in-flight fetch (ctx.signal). A Gutenberg EPUB is a few MB, so a failed attempt is +// re-fetched whole rather than byte-ranged — resume at the item granularity, not the byte. +const FETCH_TIMEOUT_MS = 60_000; +// The retry budget has to outlast a real mobile Wi-Fi drop, not just a sub-second blip: on a +// device, disabling Wi-Fi and re-associating takes several seconds (measured on ADFA-4894). +// 6 tries with 1/2/4/8/15s backoff ≈ a 30s window across the handoff, then the item fails. +const BOOK_TRIES = 6; +const BOOK_RETRY_BASE_MS = 1_000; +const BOOK_RETRY_MAX_MS = 15_000; + const CALIBRE_WEB_LOCAL_URL = 'http://127.0.0.1:8083'; const TMP_DIR = '/tmp/books_downloader/'; const SYSTEM_USER_AGENT = 'K2Go Dashboard/1.0 (https://github.com/appdevforall/KnowledgeToGo)'; @@ -89,24 +103,58 @@ const booksRunner: (ctx: RunnerContext) => Promise = async (ctx) => { const tmp = path.join(TMP_DIR, `pg_${id}.epub`); try { - const response = await fetch(url, { - headers: { 'User-Agent': SYSTEM_USER_AGENT, Accept: 'application/epub+zip' }, - }); - if (!response.ok) throw new Error(`HTTP ${response.status} from Gutenberg`); - - const fileBuffer = await response.arrayBuffer(); - fs.writeFileSync(tmp, Buffer.from(fileBuffer)); - - const form = new FormData(); - form.append('csrf_token', session.csrfToken); - form.append('btn-upload', new Blob([fileBuffer], { type: 'application/epub+zip' }), `${title}.epub`); - - const uploadRes = await fetch(`${CALIBRE_WEB_LOCAL_URL}/upload`, { - method: 'POST', - headers: { Cookie: session.cookie, Referer: `${CALIBRE_WEB_LOCAL_URL}/` }, - body: form, + await withRetry(async () => { + // Cancel (ctx.signal) is terminal; a per-attempt timeout is retryable. Combine both + // for the fetch so a stall aborts, then let withRetry decide whether to try again. + const signal = AbortSignal.any([ctx.signal, AbortSignal.timeout(FETCH_TIMEOUT_MS)]); + + const response = await fetch(url, { + headers: { 'User-Agent': SYSTEM_USER_AGENT, Accept: 'application/epub+zip' }, + signal, + }); + if (!response.ok) { + const e = new Error(`HTTP ${response.status} from Gutenberg`); + (e as { status?: number }).status = response.status; + throw e; + } + + const fileBuffer = await response.arrayBuffer(); + fs.writeFileSync(tmp, Buffer.from(fileBuffer)); + + const form = new FormData(); + form.append('csrf_token', session.csrfToken); + form.append('btn-upload', new Blob([fileBuffer], { type: 'application/epub+zip' }), `${title}.epub`); + + const uploadRes = await fetch(`${CALIBRE_WEB_LOCAL_URL}/upload`, { + method: 'POST', + headers: { Cookie: session.cookie, Referer: `${CALIBRE_WEB_LOCAL_URL}/` }, + body: form, + signal, + }); + if (!uploadRes.ok) { + const e = new Error(`Calibre-Web rejected upload: ${uploadRes.status}`); + (e as { status?: number }).status = uploadRes.status; + throw e; + } + }, { + tries: BOOK_TRIES, + baseMs: BOOK_RETRY_BASE_MS, + maxMs: BOOK_RETRY_MAX_MS, + signal: ctx.signal, + isCanceled: ctx.isCanceled, + // Retry network drops and timeouts and 5xx; a 4xx is the server's final word. + isTransient: (err) => { + const status = (err as { status?: number })?.status; + if (typeof status === 'number') return status >= 500; + return true; + }, + onRetry: ({ attempt, err }) => ctx.log(`[books] retry ${attempt} for "${title}": ${err instanceof Error ? err.message : String(err)}`), }); - if (!uploadRes.ok) throw new Error(`Calibre-Web rejected upload: ${uploadRes.status}`); + } catch (err) { + // withRetry throws Aborted on cancel; surface it as the engine's CanceledError so the + // job lands on 'canceled', not 'error'. + if (err instanceof Aborted || ctx.isCanceled()) throw new CanceledError(); + throw err; } finally { if (fs.existsSync(tmp)) fs.unlinkSync(tmp); } diff --git a/static/dashboard/sockets/jobs.ts b/static/dashboard/sockets/jobs.ts index b8ed24bf9..a385999b7 100644 --- a/static/dashboard/sockets/jobs.ts +++ b/static/dashboard/sockets/jobs.ts @@ -50,6 +50,9 @@ export interface RunnerContext { update(patch: JobUpdate): void; isCanceled(): boolean; throwIfCanceled(): void; + /** ADFA-4894: aborted when the job is canceled, so an in-flight fetch (books) can be + * interrupted — a child process is killed via SIGKILL, but a fetch has no process. */ + readonly signal: AbortSignal; /** Spawn a child that is killed automatically on cancel and untracked on exit. */ spawn(cmd: string, args: string[], opts?: SpawnOptions): ChildProcess; log(line: string): void; @@ -68,7 +71,7 @@ const ACTIVE: JobPhase[] = ['queued', 'downloading', 'indexing', 'processing']; class JobManager { private db: Database.Database; private runners = new Map(); - private runtime = new Map }>(); + private runtime = new Map; ac: AbortController }>(); // ADFA-4879: bounded rolling log tail per job for the live-log REST endpoint. private readonly logTail = new RollingLog(); @@ -134,6 +137,7 @@ class JobManager { if (rt) { rt.canceled = true; for (const p of rt.procs) { try { p.kill('SIGKILL'); } catch { /* already gone */ } } + try { rt.ac.abort(); } catch { /* ADFA-4894: interrupt an in-flight fetch too */ } } if (ACTIVE.includes(job.phase)) this.patch(id, { phase: 'canceled' }); return true; @@ -168,7 +172,7 @@ class JobManager { const runner = this.runners.get(job.type); if (!runner) { this.patch(job.id, { phase: 'error', error: `no runner for ${job.type}` }); return; } - const rt = { canceled: false, procs: new Set() }; + const rt = { canceled: false, procs: new Set(), ac: new AbortController() }; this.runtime.set(job.id, rt); let items: unknown[] = []; @@ -180,6 +184,7 @@ class JobManager { update: (p) => this.patch(job.id, p), isCanceled: () => rt.canceled, throwIfCanceled: () => { if (rt.canceled) throw new CanceledError(); }, + signal: rt.ac.signal, spawn: (cmd, args, opts) => { const child = opts ? spawn(cmd, args, opts) : spawn(cmd, args); rt.procs.add(child); diff --git a/static/dashboard/sockets/kiwix.exec.ts b/static/dashboard/sockets/kiwix.exec.ts index f63fb9eba..4a4cc432e 100644 --- a/static/dashboard/sockets/kiwix.exec.ts +++ b/static/dashboard/sockets/kiwix.exec.ts @@ -6,6 +6,7 @@ // kiwix.socket handler, minus the socket/closure lifetime — the job outlives any // client (see jobs.ts). import { jobs, RunnerContext, CanceledError } from './jobs'; +import { withRetry, Aborted } from './net-retry'; import { execSync } from 'child_process'; import fs from 'fs'; import path from 'path'; @@ -19,9 +20,17 @@ const SAFE_ID = /^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/; const INDEXER = '/usr/bin/iiab-make-kiwix-lib'; const SAFETY_BUFFER_BYTES = 5 * 1024 * 1024 * 1024; // keep >=5 GB free -// ADFA-4832 sync note: these aria2 flags mirror the app-side downloader -// (controller/app/.../Aria2Manager.java) and the Phase 1 socket handler. Keep the -// three in sync; if you change one, change the others and document any divergence. +// ADFA-4832 CANONICAL aria2 flag set — mirrored in three places. If you change a flag here, +// change the others and update this note (nothing enforces it; a silent drift is the risk): +// 1. this file (REST/dash-node kiwix runner) +// 2. controller/app/.../Aria2Manager.java (the Android app downloader) +// 3. the Phase 1 socket handler +// Shared intent: --continue, --check-integrity, --max-connection-per-server=4, --split, no +// --lowest-speed-limit. Two DOCUMENTED divergences from the app, both about the retry model: +// - retry count: app uses --max-tries=1 (its outer InstallService loop re-drives); REST uses +// --max-tries=5 so aria2 absorbs in-flight blips itself (see the outer loop below for the +// total-interface-loss case aria2 can't retry). +// - timeouts: app 10s/5s (aggressive, its loop re-drives fast); REST 60s/15s (no fast re-drive). const ARIA2_ARGS: string[] = [ '-d', ZIMS_DIR, '--continue=true', @@ -35,10 +44,31 @@ const ARIA2_ARGS: string[] = [ '--summary-interval=1', '--download-result=hide', '--async-dns=false', + // ADFA-4894: aria2 absorbs in-flight blips itself (retry-wait never 0 — a 0-wait retry hammers a + // struggling server). A FULL interface loss (exit 19, DNS can't resolve) is not something aria2 + // retries, so that case is handled by the outer withRetry loop below, not here. See the canonical + // note above for the documented divergence from the app's --max-tries=1 model. + '--max-tries=5', + '--retry-wait=5', + '--timeout=60', + '--connect-timeout=15', + // No --lowest-speed-limit, same as the app: it turns a slow link into a hard abort, which is the + // opposite of resilient on the intermittent 3G this contract exists for. '-Z', '-j', '5', ]; +// ADFA-4894: the outer reconnect loop for a FULL interface loss. aria2's --max-tries handles +// in-flight blips, but when Wi-Fi drops entirely aria2 exits (19 = name resolution failed) and +// can't retry a name it can't resolve. So we re-run aria2 — which resumes via --continue — on the +// transient exit codes, across a mobile handoff. NOT retried: 3/4 (not found), 9 (no space), 13 +// (file exists) — those are terminal. Budget ~30s to outlast a Wi-Fi reassociation. +// 1 unknown · 2 timeout · 6 network · 7 unfinished · 19 DNS · 29 HTTP 503 +const ARIA2_TRANSIENT_EXITS = new Set([1, 2, 6, 7, 19, 29]); +const KIWIX_DL_TRIES = 5; +const KIWIX_RETRY_BASE_MS = 2_000; +const KIWIX_RETRY_MAX_MS = 15_000; + /** Convert an aria2 rate token ("34MiB", "512KiB", "1.2MB") to bytes/sec. */ function parseRate(token: string): number { const m = /^([\d.]+)\s*([KMGT]?i?B)?/i.exec(token); @@ -78,6 +108,26 @@ function cleanupMetadata(): void { } catch { /* non-fatal */ } } +/** + * ADFA-4894: clean-on-cancel. aria2 keeps a partial `.zim` + `.aria2` control file so a resume can + * continue — right after a pause, wrong after a cancel, where the user gave the download up. So on + * cancel we prune each requested file's partial and its control/metadata siblings, leaving nothing + * half-written. A file with no `.aria2` is treated as already complete and left alone. + */ +function cleanupPartials(files: string[]): void { + for (const f of files) { + try { + const control = path.join(ZIMS_DIR, `${f}.aria2`); + if (!fs.existsSync(control)) continue; // no control file -> complete, don't delete it + fs.unlinkSync(control); + for (const sibling of [f, `${f}.meta4`, `${f}.torrent`]) { + const p = path.join(ZIMS_DIR, sibling); + if (fs.existsSync(p)) fs.unlinkSync(p); + } + } catch { /* best-effort */ } + } +} + const kiwixRunner: (ctx: RunnerContext) => Promise = async (ctx) => { // ADFA-5042: keep each id's project subdir for the URL; use basename only for the local file/display. const ids = ctx.ids.map(String).map((z) => z.replace(/^\/+/, '')).filter((z) => z.endsWith('.zim')); @@ -98,27 +148,48 @@ const kiwixRunner: (ctx: RunnerContext) => Promise = async (ctx) => { // Each id already carries its project subdir on the mirror (/zim//). const urls = ids.map((z) => BASE_URL + z); - await new Promise((resolve, reject) => { - const dl = ctx.spawn('/usr/bin/aria2c', [...ARIA2_ARGS, ...urls]); - const onData = (buf: Buffer) => { - const text = buf.toString(); - // A single chunk can carry several summary lines; take the LAST %/rate. - const re = /\((\d+)%\).*?DL:([^\s]+)/g; - let m: RegExpExecArray | null; - let lastPct = -1; - let lastRate = ''; - while ((m = re.exec(text)) !== null) { lastPct = parseInt(m[1], 10); lastRate = m[2]; } - if (lastPct >= 0) ctx.update({ phase: 'downloading', percent: lastPct, speed: parseRate(lastRate) }); - }; - dl.stdout?.on('data', onData); - dl.stderr?.on('data', onData); - dl.on('error', reject); - dl.on('exit', (code, signal) => { - if (signal === 'SIGKILL' || ctx.isCanceled()) return reject(new CanceledError()); - if (code === 0) resolve(); - else reject(new Error(`aria2 exited with code ${code}`)); + try { + await withRetry(() => new Promise((resolve, reject) => { + const dl = ctx.spawn('/usr/bin/aria2c', [...ARIA2_ARGS, ...urls]); + const onData = (buf: Buffer) => { + const text = buf.toString(); + // A single chunk can carry several summary lines; take the LAST %/rate. + const re = /\((\d+)%\).*?DL:([^\s]+)/g; + let m: RegExpExecArray | null; + let lastPct = -1; + let lastRate = ''; + while ((m = re.exec(text)) !== null) { lastPct = parseInt(m[1], 10); lastRate = m[2]; } + if (lastPct >= 0) ctx.update({ phase: 'downloading', percent: lastPct, speed: parseRate(lastRate) }); + }; + dl.stdout?.on('data', onData); + dl.stderr?.on('data', onData); + dl.on('error', reject); + dl.on('exit', (code, signal) => { + if (signal === 'SIGKILL' || ctx.isCanceled()) return reject(new CanceledError()); + if (code === 0) return resolve(); + // Carry the aria2 exit code so the outer loop can tell a transient network failure + // (retry, resuming via --continue) from a terminal one (not found / no space). + const err = new Error(`aria2 exited with code ${code}`); + (err as { code?: number }).code = code ?? -1; + reject(err); + }); + }), { + tries: KIWIX_DL_TRIES, + baseMs: KIWIX_RETRY_BASE_MS, + maxMs: KIWIX_RETRY_MAX_MS, + isCanceled: ctx.isCanceled, + isTransient: (e) => ARIA2_TRANSIENT_EXITS.has((e as { code?: number }).code ?? -1), + onRetry: ({ attempt, err }) => ctx.log(`[kiwix] reconnect attempt ${attempt} after: ${err instanceof Error ? err.message : String(err)}`), }); - }); + } catch (e) { + // ADFA-4894: a canceled download leaves nothing half-written; a real error KEEPS the partial + // (+ .aria2) so a later run resumes it via --continue rather than starting from zero. + if (e instanceof CanceledError || e instanceof Aborted || ctx.isCanceled()) { + cleanupPartials(files); + throw new CanceledError(); + } + throw e; + } cleanupMetadata(); ctx.throwIfCanceled(); diff --git a/static/dashboard/sockets/net-retry.test.ts b/static/dashboard/sockets/net-retry.test.ts new file mode 100644 index 000000000..647a5882d --- /dev/null +++ b/static/dashboard/sockets/net-retry.test.ts @@ -0,0 +1,72 @@ +/// +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { withRetry, Aborted } from './net-retry'; + +// A sleep that spends no real time, so the backoff logic is exercised instantly. +const noSleep = async () => { /* immediate */ }; + +test('withRetry: returns on the first success, no retries', async () => { + let calls = 0; + const out = await withRetry(async () => { calls++; return 'ok'; }, { sleep: noSleep }); + assert.equal(out, 'ok'); + assert.equal(calls, 1); +}); + +test('withRetry: retries a transient failure then succeeds', async () => { + let calls = 0; + const out = await withRetry(async (attempt) => { + calls++; + if (attempt < 3) throw new Error('ECONNRESET'); + return attempt; + }, { tries: 4, sleep: noSleep }); + assert.equal(out, 3); + assert.equal(calls, 3); +}); + +test('withRetry: exhausts attempts and throws the last error', async () => { + let calls = 0; + await assert.rejects( + withRetry(async () => { calls++; throw new Error('still down'); }, { tries: 3, sleep: noSleep }), + /still down/, + ); + assert.equal(calls, 3); +}); + +test('withRetry: a non-transient error is not retried', async () => { + let calls = 0; + await assert.rejects( + withRetry(async () => { calls++; throw new Error('HTTP 404'); }, { + tries: 5, sleep: noSleep, + isTransient: (e) => !(e instanceof Error && /HTTP 4\d\d/.test(e.message)), + }), + /HTTP 404/, + ); + assert.equal(calls, 1); // 404 is fatal — tried once, never retried +}); + +test('withRetry: cancellation via isCanceled throws Aborted and stops trying', async () => { + let calls = 0; + let canceled = false; + await assert.rejects( + withRetry(async () => { calls++; canceled = true; throw new Error('boom'); }, { + tries: 5, sleep: noSleep, isCanceled: () => canceled, + }), + (e) => e instanceof Aborted, + ); + assert.equal(calls, 1); // canceled after the first failure -> no second attempt +}); + +test('withRetry: an aborted signal during backoff throws Aborted', async () => { + const ac = new AbortController(); + let calls = 0; + // sleep aborts the signal mid-backoff, so the loop must not run a second attempt. + const abortingSleep = async () => { ac.abort(); throw new Aborted(); }; + await assert.rejects( + withRetry(async () => { calls++; throw new Error('down'); }, { + tries: 5, signal: ac.signal, sleep: abortingSleep, + }), + (e) => e instanceof Aborted, + ); + assert.equal(calls, 1); +}); diff --git a/static/dashboard/sockets/net-retry.ts b/static/dashboard/sockets/net-retry.ts new file mode 100644 index 000000000..2a9830ebf --- /dev/null +++ b/static/dashboard/sockets/net-retry.ts @@ -0,0 +1,82 @@ +// sockets/net-retry.ts — ADFA-4894 +// +// Reconnect/backoff for the REST job runners. A network drop mid-job should recover +// on its own rather than fail the whole job at the first blip — the resilient-download +// contract (ADFA-4893) on an intermittent link, which is the case this exists for. +// +// Pure and dependency-free so it is unit-tested on node without a network: the only +// side effect is waiting, and the wait is injectable (`sleep`) and cancellable. + +/** Thrown when a retry loop is stopped by cancellation or an aborted signal. */ +export class Aborted extends Error { + constructor(message = 'aborted') { super(message); this.name = 'Aborted'; } +} + +export interface RetryOpts { + /** Total attempts, including the first. Default 4. */ + tries?: number; + /** First backoff delay in ms; doubles each attempt. Default 500. */ + baseMs?: number; + /** Upper bound on a single backoff. Default 8000. */ + maxMs?: number; + /** Fraction of jitter added to each delay [0..1]. Default 0.2. */ + jitter?: number; + /** Aborts the loop (between and, via fetch, within attempts). */ + signal?: AbortSignal; + /** Cooperative cancel check, for runners that carry a flag rather than a signal. */ + isCanceled?: () => boolean; + /** Which errors are worth another attempt. Default: everything except an abort. */ + isTransient?: (err: unknown) => boolean; + /** Observability hook, fired before each backoff wait. */ + onRetry?: (info: { attempt: number; delayMs: number; err: unknown }) => void; + /** Injectable wait, so tests don't spend real time. Default a cancellable setTimeout. */ + sleep?: (ms: number, signal?: AbortSignal) => Promise; +} + +/** A cancellable delay: rejects with {@link Aborted} if the signal fires first. */ +export function delay(ms: number, signal?: AbortSignal): Promise { + return new Promise((resolve, reject) => { + if (signal?.aborted) { reject(new Aborted()); return; } + const t = setTimeout(() => { cleanup(); resolve(); }, ms); + const onAbort = () => { cleanup(); reject(new Aborted()); }; + const cleanup = () => { clearTimeout(t); signal?.removeEventListener('abort', onAbort); }; + signal?.addEventListener('abort', onAbort, { once: true }); + }); +} + +function aborted(opts: RetryOpts): boolean { + return !!opts.signal?.aborted || !!opts.isCanceled?.(); +} + +/** + * Run {@code fn} with retry + exponential backoff. Returns its value on the first success; + * rethrows the last error once the attempts run out or the error is not transient; throws + * {@link Aborted} the moment cancellation is observed (never sits in a backoff after that). + * + * @param fn receives the 1-based attempt number. + */ +export async function withRetry(fn: (attempt: number) => Promise, opts: RetryOpts = {}): Promise { + const tries = Math.max(1, opts.tries ?? 4); + const baseMs = opts.baseMs ?? 500; + const maxMs = opts.maxMs ?? 8000; + const jitter = opts.jitter ?? 0.2; + const isTransient = opts.isTransient ?? ((e) => !(e instanceof Aborted)); + const sleep = opts.sleep ?? ((ms, sig) => delay(ms, sig)); + + let lastErr: unknown; + for (let attempt = 1; attempt <= tries; attempt++) { + if (aborted(opts)) throw new Aborted(); + try { + return await fn(attempt); + } catch (err) { + lastErr = err; + if (err instanceof Aborted || aborted(opts)) throw new Aborted(); + if (attempt >= tries || !isTransient(err)) throw err; + const backoff = Math.min(maxMs, baseMs * 2 ** (attempt - 1)); + const delayMs = Math.round(backoff * (1 + Math.random() * jitter)); + opts.onRetry?.({ attempt, delayMs, err }); + await sleep(delayMs, opts.signal); // throws Aborted if the signal fires mid-backoff + } + } + throw lastErr; +}