Keep retrying lookups until the sources answer

A network error, timeout, 5xx or 429 no longer ends a lookup or sends a
book to Needs attention. Lookups back off exponentially with jitter (2 s
doubling to 5 min, honouring Retry-After) for as long as the book is
pending, keep each definitive answer so a retry only asks for what is
missing, and limit requests to two at a time per host. Once a call number
is in hand, a step that still fails after six tries is left for the
backfills. Books an earlier version failed for a temporary reason are
queued again at startup.

The cards show which source is not answering and when the next try is,
title search waits for Open Library with a Cancel button, and Look up
again sits next to Fix.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-22 11:35:37 -07:00
1 parent ee10e00ccd
commit e65b10c0fb
24 files changed
+700 -104

No files matched your search

+89 -18
View File
@@ -1,9 +1,30 @@
import type { Book, BookMeta, ResolveInput } from '../shared/types.ts';
import type { Db } from './db.ts';
import type { Resolver } from './resolve/resolver.ts';
import { jobMemo, sourceName } from './sources/http.ts';
/** The fixed schedule of the tail and edition backfills, which give up until the next start. Lookups never give up. */
export const DEFAULT_RETRY_DELAYS_MS = [5_000, 30_000, 120_000];
/**
* Failed tries after which a lookup that already has a call number stops insisting on the rest (the other source's
* check, the edition, the tail) and settles with what it has: about two minutes of backoff. With no number it never does.
*/
export const SETTLE_AFTER_ATTEMPTS = 6;
export const BACKOFF_FIRST_MS = 2_000;
export const BACKOFF_CAP_MS = 300_000;
/**
* How long a pending lookup waits after its `attempt`th temporary failure (1 = first): 2 s doubling up to 5 min, spread
* by +/-25 % so books that failed together do not come back together. A Retry-After from the server is a floor.
*/
export function backoffMs(attempt: number, retryAfterMs?: number, random: () => number = Math.random): number {
const base = Math.min(BACKOFF_CAP_MS, BACKOFF_FIRST_MS * 2 ** Math.max(0, attempt - 1));
const jittered = Math.round(base * (0.75 + 0.5 * random()));
return Math.max(jittered, retryAfterMs ?? 0);
}
/**
* Version of the rules that decide a book's hierarchy tail. Raising it sends every book with an empty tail (not
* hand-entered) through the backfill once more at the next start. 2: other records with the book's class key count.
@@ -15,6 +36,9 @@ export type ResolverLike = Resolver;
export interface Jobs {
/** `fresh`: the lookup ignores every cached source answer ("Look up again"), through its retries too. */
enqueue(id: number, opts?: { fresh?: boolean }): void;
/** The book was removed: its waiting retry, queue place and remembered answers all go. */
cancel(id: number): void;
/** At start: pending books (and books an older version gave up on only because a source was unreachable) go on. */
resume(): void;
/**
* Backfill, for books made before the hierarchy tail existed: look up only the tail (nothing else about the book
@@ -38,26 +62,41 @@ function defaultIsTemporary(e: unknown): boolean {
return false;
}
/** What the page shows while a book waits for another try. */
export function retryNote(message: string): string {
const who = /loc\.gov|Library of Congress/i.test(message) ? 'Library of Congress'
/** Who is not answering, for the page: the error says so, else the URL in its message does. */
function failingSource(e: unknown, message: string): string {
const named = (e as { source?: unknown } | null)?.source;
if (typeof named === 'string' && named) return named;
const url = /https?:\/\/[^\s:]+(?::\d+)?[^\s]*/.exec(message)?.[0];
if (url) return sourceName(url);
return /loc\.gov|Library of Congress/i.test(message) ? 'Library of Congress'
: /openlibrary|Open Library/i.test(message) ? 'Open Library' : 'A lookup service';
return `${who} did not answer. Trying again shortly.`;
}
export function createJobs(deps: {
db: Db; resolver: ResolverLike; onChange: (book: Book) => void;
retryDelaysMs?: number[]; isTemporary?: (e: unknown) => boolean;
/** The tail and edition backfills' schedule (they give up until the next start). */
retryDelaysMs?: number[];
/** Wait before a lookup's `attempt`th retry. Lookups retry for as long as the book is pending. */
backoff?: (attempt: number, retryAfterMs?: number) => number;
now?: () => number;
isTemporary?: (e: unknown) => boolean;
log?: (line: string) => void;
}): Jobs {
const { db, resolver, onChange } = deps;
const delays = deps.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
const backoff = deps.backoff ?? backoffMs;
const now = deps.now ?? Date.now;
const isTemporary = deps.isTemporary ?? defaultIsTemporary;
const log = deps.log ?? ((line: string) => console.log(line));
const queue: number[] = [];
const queued = new Set<number>();
const attempts = new Map<number, number>();
const fresh = new Set<number>();
// What each pending lookup has been definitively told so far (see jobMemo): a retry asks only for the rest.
const memos = new Map<number, Map<string, string>>();
// The lookup being attempted now, and the books asked for again meanwhile (true: "fresh"): they run once more after.
let current: number | null = null;
const again = new Map<number, boolean>();
// Books waiting for a retry: they hold no worker; a timer puts them back in the queue.
const waiting = new Map<number, ReturnType<typeof setTimeout>>();
// The tail backfill queues behind real lookups, and retries on its own timers.
@@ -90,6 +129,11 @@ export function createJobs(deps: {
if (Object.keys(patch).length) emit(id, patch);
}
/** Everything remembered about a lookup that has ended (or been dropped). */
function forget(id: number): void {
attempts.delete(id); fresh.delete(id); memos.delete(id); db.setRetry(id, null);
}
function schedule(id: number, delayMs: number): void {
if (delayMs <= 0) { queued.add(id); queue.push(id); start(); return; }
const t = setTimeout(() => {
@@ -105,9 +149,8 @@ export function createJobs(deps: {
async function attempt(id: number): Promise<void> {
const book = db.getBook(id);
if (!book || book.status !== 'pending') { attempts.delete(id); fresh.delete(id); return; }
if (!book || book.status !== 'pending') { forget(id); return; }
const n = attempts.get(id) ?? 0;
const final = n >= delays.length;
const input: ResolveInput = {};
if (book.isbn13) input.isbn13 = book.isbn13;
if (book.lccn) input.lccn = book.lccn;
@@ -120,10 +163,16 @@ export function createJobs(deps: {
const started = Date.now();
let similar = '';
const took = () => `${Date.now() - started} ms`;
const memo = memos.get(id) ?? new Map<string, string>();
memos.set(id, memo);
// Asking again now: the page stops counting down and says so.
if (n > 0) { const r = book.retry; if (r) { db.setRetry(id, { source: r.source, attempt: r.attempt, nextAt: null }); emit(id, {}); } }
try {
const wasFresh = fresh.has(id);
const res = await resolver.resolve(input, { onMeta: (m) => applyMeta(id, m), tolerateLocFailure: final, fresh: wasFresh, onSimilar: (d) => { similar = d; } });
attempts.delete(id); fresh.delete(id);
const res = await jobMemo.run(memo, () => resolver.resolve(input, { onMeta: (m) => applyMeta(id, m), tolerateLocFailure: n >= SETTLE_AFTER_ATTEMPTS, fresh: wasFresh, onSimilar: (d) => { similar = d; } }));
// Asked for again while this ran ("Look up again"): this answer is stale, the next run replaces it.
if (again.has(id)) return;
forget(id);
const cur = db.getBook(id);
if (!cur) return;
if (res.meta) applyMeta(id, res.meta);
@@ -145,21 +194,26 @@ export function createJobs(deps: {
});
log(`[lookup] ${label}: ${res.callNumber} (${res.source === 'similar' && similar ? `similar ${similar}` : res.source}) in ${took()}`);
} else {
// Only here, with every source answered for real, is the person asked to look.
const reason = res.reason ?? 'No Library of Congress number found';
emit(id, { dewey, status: 'needs_attention', attentionReason: reason, ...tail });
log(`[lookup] ${label}: no call number, ${reason} in ${took()}`);
}
} catch (e) {
if (again.has(id)) return;
const message = e instanceof Error ? e.message : String(e);
if (isTemporary(e) && !final) {
if (isTemporary(e)) {
// A source could not be asked: that is "not yet", never "no". Back off and go on, for as long as the book is pending.
if (db.getBook(id)?.status !== 'pending') { forget(id); return; }
attempts.set(id, n + 1);
const delay = delays[n]!;
const delay = backoff(n + 1, (e as { retryAfterMs?: number }).retryAfterMs);
db.setRetry(id, { source: failingSource(e, message), attempt: n + 1, nextAt: now() + delay });
log(`[lookup] ${label}: attempt ${n + 1} failed, ${message}; trying again in ${Math.round(delay / 1000)} s (${took()})`);
if (db.getBook(id)?.status === 'pending') emit(id, { attentionReason: retryNote(message) });
schedule(id, delay);
schedule(id, delay); // first: the book must never be left pending without a timer
try { emit(id, { attentionReason: null }); } catch { /* the page catches up at the next change or reconnect */ }
return;
}
attempts.delete(id); fresh.delete(id);
forget(id);
log(`[lookup] ${label}: failed, ${message} in ${took()}`);
const cur = db.getBook(id);
if (cur && !cur.manualOverride) {
@@ -168,7 +222,6 @@ export function createJobs(deps: {
}
}
async function backfillTail(id: number): Promise<void> {
const book = db.getBook(id);
if (!book || book.hierarchyTail !== null || book.status === 'pending') { tailAttempts.delete(id); return; }
@@ -240,7 +293,11 @@ export function createJobs(deps: {
if (queue.length) {
const id = queue.shift()!;
queued.delete(id);
current = id;
try { await attempt(id); } catch { /* a failure on one book must not stop the queue */ }
current = null;
const f = again.get(id);
if (f !== undefined) { again.delete(id); if (f) fresh.add(id); if (!queued.has(id)) { queued.add(id); queue.push(id); } }
} else if (tailQueue.length) {
const id = tailQueue.shift()!;
try { await backfillTail(id); } catch { /* ditto */ }
@@ -258,16 +315,30 @@ export function createJobs(deps: {
return {
enqueue(id, opts) {
if (opts?.fresh) fresh.add(id);
if (opts?.fresh) { fresh.add(id); memos.delete(id); }
// A fresh request (scan, "Look up again") overrides any wait and starts the retries over.
const t = waiting.get(id);
if (t) { clearTimeout(t); waiting.delete(id); attempts.delete(id); }
if (t) { clearTimeout(t); waiting.delete(id); attempts.delete(id); db.setRetry(id, null); emit(id, {}); } // the page drops the countdown
// One lookup per book at a time: asked for while it runs, it runs once more afterwards.
if (current === id) { again.set(id, (again.get(id) ?? false) || !!opts?.fresh); return; }
if (queued.has(id)) return;
queued.add(id);
queue.push(id);
start();
},
resume() { for (const id of db.listPendingIds()) this.enqueue(id); },
cancel(id) {
const t = waiting.get(id);
if (t) { clearTimeout(t); waiting.delete(id); }
const i = queue.indexOf(id);
if (i >= 0) queue.splice(i, 1);
queued.delete(id); again.delete(id);
forget(id);
},
resume() {
const n = db.requeueTemporaryFailures();
if (n > 0) log(`[lookup] ${n} book(s) an earlier version gave up on because a source did not answer will be looked up again`);
for (const id of db.listPendingIds()) this.enqueue(id);
},
resumeTails() {
const n = db.recheckEmptyTails(TAIL_RULES_VERSION);
if (n > 0) log(`[tail] ${n} book(s) with an empty tail will be checked again under the newer rules`);