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

+5 -2
View File
@@ -1,6 +1,9 @@
import type { Book, Hierarchy, SearchResult, Settings } from '../shared/types.ts';
export class ApiError extends Error {}
export class ApiError extends Error {
status: number | undefined;
constructor(message: string, status?: number) { super(message); this.status = status; }
}
async function request<T>(method: string, url: string, body?: unknown): Promise<T> {
let res: Response;
@@ -16,7 +19,7 @@ async function request<T>(method: string, url: string, body?: unknown): Promise<
if (!res.ok) {
let msg = `Request failed (${res.status})`;
try { const j = await res.json(); if (j && typeof j.error === 'string') msg = j.error; } catch { /* keep default */ }
throw new ApiError(msg);
throw new ApiError(msg, res.status);
}
if (res.status === 204) return undefined as T;
const text = await res.text();
+15 -4
View File
@@ -1,7 +1,7 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import type { Book } from '../shared/types.ts';
import { elapsedText, printStatus, queueOrder, rowState } from './bookstate.ts';
import { elapsedText, printStatus, queueOrder, retryText, rowState } from './bookstate.ts';
function book(id: number, over: Partial<Book>): Book {
return {
@@ -16,9 +16,20 @@ const looking = (id: number) => book(id, {});
const attention = (id: number, over: Partial<Book> = {}) => book(id, { status: 'needs_attention', attentionReason: 'No match', ...over });
test('a pending book is "looking", never "no call number"', () => {
assert.deepEqual(rowState(looking(1)), { kind: 'looking', note: null });
assert.deepEqual(rowState(book(1, { attentionReason: 'LC did not answer. Trying again shortly.' })),
{ kind: 'looking', note: 'LC did not answer. Trying again shortly.' });
assert.deepEqual(rowState(looking(1)), { kind: 'looking', retry: null });
const retry = { source: 'Open Library', attempt: 3, waitMs: 12_000 };
assert.deepEqual(rowState(book(1, { retry })), { kind: 'looking', retry });
// A stale note from an older version is not shown as the state.
assert.deepEqual(rowState(book(1, { attentionReason: 'LC did not answer. Trying again shortly.' })), { kind: 'looking', retry: null });
});
test('a waiting lookup names the failing source, the countdown and the try; never the warning style', () => {
const r = { source: 'Open Library', attempt: 3, waitMs: 12_000 };
assert.equal(retryText(r, 100_000, 100_000), "Open Library isn't answering — trying again in 12 s (try 4)");
assert.equal(retryText(r, 100_000, 110_800), "Open Library isn't answering — trying again in 2 s (try 4)");
assert.equal(retryText(r, 100_000, 112_000), 'Asking Open Library again… (try 4)');
assert.equal(retryText({ ...r, waitMs: null }, 0, 0), 'Asking Open Library again… (try 4)');
assert.equal(rowState(book(1, { retry: r })).kind, 'looking');
});
test('ready and attention states', () => {
+15 -3
View File
@@ -1,13 +1,13 @@
import type { Book } from '../shared/types.ts';
import type { Book, LookupRetry } from '../shared/types.ts';
/** The single state a book is shown in. */
export type RowState =
| { kind: 'looking'; note: string | null }
| { kind: 'looking'; retry: LookupRetry | null }
| { kind: 'ready' }
| { kind: 'attention'; reason: string };
export function rowState(book: Book): RowState {
if (book.status === 'pending') return { kind: 'looking', note: book.attentionReason };
if (book.status === 'pending') return { kind: 'looking', retry: book.retry ?? null };
if (book.status === 'resolved' && book.callNumber) return { kind: 'ready' };
if (book.status === 'resolved') return { kind: 'attention', reason: 'No call number was found.' };
return { kind: 'attention', reason: book.attentionReason ?? 'This book needs a look.' };
@@ -44,3 +44,15 @@ export function elapsedText(ms: number): string {
const s = Math.max(0, Math.floor(ms / 1000));
return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min ${String(s % 60).padStart(2, '0')} s`;
}
/**
* What a lookup that is waiting out a failing source says, e.g. "Open Library isn't answering — trying again in 12 s
* (try 4)". `attempt` counts the failures so far, so the next go is try `attempt + 1`. `waitMs` was the time left when
* the page received the book (`receivedAt`), so the countdown does not depend on the server's clock.
*/
export function retryText(retry: LookupRetry, receivedAt: number, now: number): string {
const next = retry.attempt + 1;
const left = retry.waitMs === null ? 0 : retry.waitMs - (now - receivedAt);
if (left <= 0) return `Asking ${retry.source} again… (try ${next})`;
return `${retry.source} isn't answering — trying again in ${Math.ceil(left / 1000)} s (try ${next})`;
}
+2 -1
View File
@@ -2,6 +2,7 @@ import { displayAuthors } from '../../shared/names.ts';
import type { Book } from '../../shared/types.ts';
import { rowState } from '../bookstate.ts';
import { CallNo } from './CallNo.tsx';
import { LookUpAgain } from './LookUpAgain.tsx';
import { StateMark, StateText } from './StateMark.tsx';
function Main({ book, showYear }: { book: Book; showYear: boolean }) {
@@ -24,7 +25,7 @@ export function QueueRow({ book, onFix, onRemove }: { book: Book; onFix: () => v
<CallNo value={kind === 'looking' ? null : book.callNumber} approximate={book.confidence === 'approximate'} source={book.source} />
<Main book={book} showYear={false} />
<span class="row-actions">
{kind === 'attention' ? <button type="button" class="btn" onClick={onFix}>Fix</button> : null}
{kind === 'attention' ? <><LookUpAgain book={book} /><button type="button" class="btn" onClick={onFix}>Fix</button></> : null}
<button type="button" class="btn-icon" onClick={onRemove} aria-label={`Remove "${book.title}"`} title="Remove">×</button>
</span>
</li>
+19 -6
View File
@@ -1,7 +1,8 @@
import { useEffect, useState } from 'preact/hooks';
import { useEffect, useRef, useState } from 'preact/hooks';
import type { Book, SearchResult } from '../../shared/types.ts';
import { displayAuthors } from '../../shared/names.ts';
import { api } from '../api.ts';
import { Cancelled, searchPatiently } from '../patient.ts';
import type { BookPatch } from '../api.ts';
import { getBook, setLastScan, upsertBook, dispatch, useBooks } from '../live.ts';
import { showToast } from '../toast-store.ts';
@@ -204,21 +205,30 @@ function FixSearch({ initial, onPick }: { initial: string; onPick: (r: SearchRes
const [active, setActive] = useState(-1);
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState('');
const [waiting, setWaiting] = useState(0); // the try the search is on once Open Library has not answered (2, 3, ...)
const stop = useRef<AbortController | null>(null);
const seq = useRef(0); // only the newest search may write to the form
async function search() {
const { title, author } = splitTitleAuthor(text);
if (!title) return;
setBusy(true); setMessage(''); setResults(null); setActive(-1);
const mine = ++seq.current;
stop.current?.abort();
const ctl = stop.current = new AbortController();
setBusy(true); setMessage(''); setResults(null); setActive(-1); setWaiting(0);
try {
const found = await api.search(title, author);
const found = await searchPatiently(title, author, ctl.signal, n => { if (mine === seq.current) setWaiting(n); });
if (mine !== seq.current) return;
setResults(found);
if (found.length === 0) setMessage('No matches. Edit the details by hand below.');
} catch (e) {
if (e instanceof Cancelled || mine !== seq.current) return;
setMessage(`The search failed: ${(e as Error).message}`);
}
setBusy(false);
setBusy(false); setWaiting(0);
}
useEffect(() => { if (initial) void search(); }, []);
const cancel = () => { seq.current++; stop.current?.abort(); setBusy(false); setWaiting(0); };
useEffect(() => { if (initial) void search(); return () => { seq.current++; stop.current?.abort(); }; }, []);
const choose = (r: SearchResult) => { onPick(r); setResults(null); setMessage('Details copied below. Check them, then save.'); };
const open = !!results && results.length > 0;
@@ -244,7 +254,10 @@ function FixSearch({ initial, onPick }: { initial: string; onPick: (r: SearchRes
<button type="button" class="btn" disabled={busy || !text.trim()} onClick={() => void search()}>Search</button>
</span>
</label>
{busy ? <p class="help"><Spinner /> Searching…</p> : null}
{busy ? (
<p class="help"><Spinner /> {waiting > 1 ? `Waiting for Open Library… (try ${waiting})` : 'Searching…'}
{waiting > 1 ? <> <button type="button" class="btn" onClick={cancel}>Cancel</button></> : null}</p>
) : null}
{message ? <p class="help" role="status">{message}</p> : null}
{open ? <ResultList id="fix-results" label="Search results" results={results!} active={active} onPick={choose} onHover={setActive} /> : null}
</div>
+18
View File
@@ -0,0 +1,18 @@
import { useState } from 'preact/hooks';
import type { Book } from '../../shared/types.ts';
import { api } from '../api.ts';
import { upsertBook } from '../live.ts';
import { showError } from '../toast-store.ts';
/** Asks the catalogues again for a book that needs attention: they add records over time. Not for hand-entered numbers. */
export function LookUpAgain({ book }: { book: Book }) {
const [busy, setBusy] = useState(false);
if (book.manualOverride) return null;
async function again() {
setBusy(true);
try { upsertBook(await api.retryBook(book.id)); }
catch (e) { showError(`Could not look up "${book.title}" again: ${(e as Error).message}`); }
setBusy(false);
}
return <button type="button" class="btn" disabled={busy} onClick={() => void again()}>Look up again</button>;
}
+6 -6
View File
@@ -1,6 +1,6 @@
import type { Book } from '../../shared/types.ts';
import { elapsedText, rowState } from '../bookstate.ts';
import { lookupStartedAt, useNow } from '../live.ts';
import type { Book, LookupRetry } from '../../shared/types.ts';
import { elapsedText, retryText, rowState } from '../bookstate.ts';
import { lookupStartedAt, retryReceivedAt, useNow } from '../live.ts';
export const LABEL = { looking: 'Looking up…', ready: 'Ready', attention: 'Needs attention' } as const;
@@ -20,12 +20,12 @@ export function StateMark({ book }: { book: Book }) {
return <span class="mark mark-ready" role="img" aria-label={LABEL.ready} title={LABEL.ready}><CheckIcon /></span>;
}
function LookingText({ book, note }: { book: Book; note: string | null }) {
function LookingText({ book, retry }: { book: Book; retry: LookupRetry | null }) {
const now = useNow(true);
return (
<span class="state-text state-looking">
{LABEL.looking} <span class="elapsed">{elapsedText(now - lookupStartedAt(book))}</span>
{note ? <span class="note"> · {note}</span> : null}
{retry ? <span class="note"> · {retryText(retry, retryReceivedAt(book), now)}</span> : null}
</span>
);
}
@@ -33,7 +33,7 @@ function LookingText({ book, note }: { book: Book; note: string | null }) {
/** The worded state under a title: "Looking up… 12 s", or "Needs attention · reason". Nothing when ready. */
export function StateText({ book }: { book: Book }) {
const s = rowState(book);
if (s.kind === 'looking') return <LookingText book={book} note={s.note} />;
if (s.kind === 'looking') return <LookingText book={book} retry={s.retry} />;
if (s.kind === 'attention') return <span class="state-text state-attention">{LABEL.attention} · {s.reason}</span>;
return null;
}
+8 -3
View File
@@ -24,10 +24,15 @@ function trackPending(action: BookAction): void {
const created = Date.parse(b.createdAt);
pendingSince.set(b.id, fromServerTime && Number.isFinite(created) ? Math.min(created, Date.now()) : Date.now());
};
if (action.type === 'upsert') note(action.book, false);
else if (action.type === 'replace') { pendingSince.clear(); action.books.forEach(b => note(b, true)); }
else pendingSince.delete(action.id);
const now = Date.now();
if (action.type === 'upsert') { receivedAt.set(action.book.id, now); note(action.book, false); }
else if (action.type === 'replace') { pendingSince.clear(); receivedAt.clear(); action.books.forEach(b => { receivedAt.set(b.id, now); note(b, true); }); }
else { pendingSince.delete(action.id); receivedAt.delete(action.id); }
}
/** When the page last received each book, so a retry's remaining wait can be counted down locally. */
const receivedAt = new Map<number, number>();
export function retryReceivedAt(book: Book): number { return receivedAt.get(book.id) ?? Date.now(); }
export function lookupStartedAt(book: Book): number { return pendingSince.get(book.id) ?? Date.now(); }
/** Re-renders once a second while `active`, and returns the current time. */
+47
View File
@@ -0,0 +1,47 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { ApiError } from './api.ts';
import { Cancelled, searchPatiently, searchWaitMs } from './patient.ts';
test('the search pause doubles from 2 s and stops at 30 s', () => {
assert.deepEqual([1, 2, 3, 4, 5, 6, 9].map(searchWaitMs), [2000, 4000, 8000, 16000, 30000, 30000, 30000]);
});
test('a 503 is waited out with growing pauses until Open Library answers', async () => {
let calls = 0;
const waits: number[] = [];
const tries: number[] = [];
const hit = [{ title: 'Hit', authors: [], lcc: [] }];
const r = await searchPatiently('a', 'b', new AbortController().signal, (n) => tries.push(n), {
search: async () => { if (++calls < 4) throw new ApiError('Open Library did not answer.', 503); return hit; },
sleep: async (ms) => { waits.push(ms); },
});
assert.deepEqual(r, hit);
assert.deepEqual(waits, [2000, 4000, 8000]);
assert.deepEqual(tries, [2, 3, 4]);
});
test('any other error is final, and cancelling stops the waiting', async () => {
await assert.rejects(searchPatiently('a', 'b', new AbortController().signal, () => {}, {
search: async () => { throw new ApiError('Enter a title or an author', 400); },
}), (e: Error) => e.message === 'Enter a title or an author');
const ctl = new AbortController();
let calls = 0;
await assert.rejects(searchPatiently('a', 'b', ctl.signal, () => ctl.abort(), {
search: async () => { calls++; throw new ApiError('x', 503); },
}), Cancelled);
assert.equal(calls, 1);
});
test('an aborted search reports nothing: no "waiting" note, no error', async () => {
const ctl = new AbortController();
const tries: number[] = [];
await assert.rejects(searchPatiently('a', 'b', ctl.signal, (n) => tries.push(n), {
search: async () => { ctl.abort(); throw new ApiError('Open Library did not answer.', 503); },
}), Cancelled);
assert.deepEqual(tries, []);
const ctl2 = new AbortController();
await assert.rejects(searchPatiently('a', 'b', ctl2.signal, () => {}, {
search: async () => { ctl2.abort(); throw new ApiError('boom', 500); },
}), Cancelled);
});
+44
View File
@@ -0,0 +1,44 @@
import type { SearchResult } from '../shared/types.ts';
import { api, ApiError } from './api.ts';
/** How long the title search waits after its `attempt`th failure (1 = first): 2 s doubling, never more than 30 s. */
export function searchWaitMs(attempt: number): number {
return Math.min(30_000, 2_000 * 2 ** Math.max(0, attempt - 1));
}
export class Cancelled extends Error {}
function sleepUnlessAborted(ms: number, signal: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
if (signal.aborted) { reject(new Cancelled()); return; }
const t = setTimeout(() => { signal.removeEventListener('abort', stop); resolve(); }, ms);
const stop = () => { clearTimeout(t); reject(new Cancelled()); };
signal.addEventListener('abort', stop, { once: true });
});
}
/**
* The title search that waits out a source that is not answering: the server says 503 when Open Library did not
* answer, and this asks again after a growing pause until it does. `onWaiting(n)` is told which try is about to be
* made (2, 3, ...); aborting `signal` rejects with Cancelled. Any other error is final.
*/
export async function searchPatiently(
title: string, author: string, signal: AbortSignal, onWaiting: (attempt: number) => void,
deps: { search?: (t: string, a: string) => Promise<SearchResult[]>; sleep?: (ms: number, s: AbortSignal) => Promise<void> } = {},
): Promise<SearchResult[]> {
const search = deps.search ?? api.search;
const sleep = deps.sleep ?? sleepUnlessAborted;
for (let attempt = 1; ; attempt++) {
if (signal.aborted) throw new Cancelled();
try {
const found = await search(title, author);
if (signal.aborted) throw new Cancelled();
return found;
} catch (e) {
if (signal.aborted) throw new Cancelled(); // a cancelled or replaced search must not report anything
if (!(e instanceof ApiError && e.status === 503)) throw e;
onWaiting(attempt + 1);
await sleep(searchWaitMs(attempt), signal);
}
}
}
+15 -7
View File
@@ -1,7 +1,7 @@
import { useRef, useState } from 'preact/hooks';
import type { RefObject } from 'preact';
import type { SearchResult } from '../../shared/types.ts';
import { api } from '../api.ts';
import { Cancelled, searchPatiently } from '../patient.ts';
import { addByIsbn, addByLccn, addFromResult } from '../actions.ts';
import { classifyEntry } from '../entry.ts';
import { beepAccept, beepLow } from '../sound.ts';
@@ -23,21 +23,26 @@ export function Entry({ inputRef, onEdit }: { inputRef: RefObject<HTMLInputEleme
const open = results !== null;
const count = open ? results.length + 1 : 0; // the last option is always "Not listed?"
const close = () => { seq.current++; setResults(null); setActive(-1); setSearching(false); };
const stop = useRef<AbortController | null>(null);
const [waiting, setWaiting] = useState(0); // the try the title search is on once Open Library has not answered (2, 3, ...)
const close = () => { seq.current++; stop.current?.abort(); setResults(null); setActive(-1); setSearching(false); setWaiting(0); };
async function search(title: string, author: string) {
const mine = ++seq.current;
query.current = { title, author };
setSearching(true); setResults(null); setActive(-1);
setSearching(true); setResults(null); setActive(-1); setWaiting(0);
stop.current?.abort();
const ctl = stop.current = new AbortController();
try {
const found = await api.search(title, author);
const found = await searchPatiently(title, author, ctl.signal, n => { if (mine === seq.current) setWaiting(n); });
if (mine !== seq.current) return;
setResults(found);
} catch (e) {
if (mine !== seq.current) return;
if (e instanceof Cancelled || mine !== seq.current) return;
showError(`The search failed: ${(e as Error).message}`);
}
setSearching(false);
setSearching(false); setWaiting(0);
}
async function submit() {
@@ -83,7 +88,10 @@ export function Entry({ inputRef, onEdit }: { inputRef: RefObject<HTMLInputEleme
value={text} onKeyDown={onKeyDown}
onInput={e => { setText(e.currentTarget.value); setMessage(''); if (open || searching) close(); }} />
<p class={'entry-help' + (message ? ' error' : '')} id="entry-help" role={message ? 'alert' : undefined}>
{message || (searching ? <><Spinner /> Searching…</> : 'Also takes an LCCN, such as 88005934.')}
{message || (searching ? (
<><Spinner /> {waiting > 1 ? `Waiting for Open Library… (try ${waiting})` : 'Searching…'}
{waiting > 1 ? <> <button type="button" class="btn" onClick={close}>Cancel</button></> : null}</>
) : 'Also takes an LCCN, such as 88005934.')}
</p>
{open ? (
<div class="entry-pop">
+2
View File
@@ -5,6 +5,7 @@ import { rowState } from '../bookstate.ts';
import { upsertBook, useBooks, useLastScan } from '../live.ts';
import { showError, showToast } from '../toast-store.ts';
import { CallNo } from '../components/CallNo.tsx';
import { LookUpAgain } from '../components/LookUpAgain.tsx';
import { CheckIcon, LABEL, Spinner, StateText, WarnIcon } from '../components/StateMark.tsx';
/** The book handled last, big enough to read at a glance while looking at the camera. */
@@ -46,6 +47,7 @@ export function LastScan({ onFix }: { onFix: (id: number) => void }) {
<>
<span class="last-mark last-attention" aria-hidden="true"><WarnIcon /></span>
<StateText book={book} />
<LookUpAgain book={book} />
<button type="button" class="btn" onClick={() => onFix(book.id)}>Fix</button>
</>
) : null}