From e65b10c0fba77301984bae1c07138b6fa169c8d7 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sun, 22 Nov 2026 11:35:37 -0700 Subject: [PATCH] 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 --- src/server/app.test.ts | 18 ++- src/server/app.ts | 9 +- src/server/db.ts | 40 ++++- src/server/jobs.test.ts | 222 +++++++++++++++++++++++++--- src/server/jobs.ts | 107 +++++++++++--- src/server/resolve/resolver.test.ts | 30 ++++ src/server/resolve/resolver.ts | 27 +++- src/server/sources/http.test.ts | 23 ++- src/server/sources/http.ts | 68 ++++++++- src/server/sources/loc.ts | 15 +- src/server/sources/openlibrary.ts | 9 +- src/shared/types.ts | 8 + src/web/api.ts | 7 +- src/web/bookstate.test.ts | 19 ++- src/web/bookstate.ts | 18 ++- src/web/components/BookRow.tsx | 3 +- src/web/components/Editor.tsx | 25 +++- src/web/components/LookUpAgain.tsx | 18 +++ src/web/components/StateMark.tsx | 12 +- src/web/live.ts | 11 +- src/web/patient.test.ts | 47 ++++++ src/web/patient.ts | 44 ++++++ src/web/views/Entry.tsx | 22 ++- src/web/views/LastScan.tsx | 2 + 24 files changed, 700 insertions(+), 104 deletions(-) create mode 100644 src/web/components/LookUpAgain.tsx create mode 100644 src/web/patient.test.ts create mode 100644 src/web/patient.ts diff --git a/src/server/app.test.ts b/src/server/app.test.ts index 8ac7733..f224de0 100644 --- a/src/server/app.test.ts +++ b/src/server/app.test.ts @@ -18,7 +18,7 @@ function setup(resolve: (i?: any, o?: any) => Promise = async () => const db = openDb(':memory:'); const events = createEventBus(); const resolver = { resolve, tail: async () => [], edition: async () => '', search: async () => [{ title: 'Hit', authors: [], lcc: [] }] }; - const jobs = createJobs({ db, resolver, onChange: (b) => events.emitBook(b), retryDelaysMs: [0], log: () => {} }); + const jobs = createJobs({ db, resolver, onChange: (b) => events.emitBook(b), backoff: () => 0, retryDelaysMs: [0], log: () => {} }); const pdfCalls: { cards: CardData[]; opts: Settings & { startPosition: number } }[] = []; const app = createApp({ db, jobs, resolver, events, port, @@ -240,7 +240,7 @@ test('debug capture: saves a PNG, keeps the newest 30, refuses other bodies', as try { const db = openDb(':memory:'); const resolver = { resolve: async () => found, tail: async () => [], edition: async () => '', search: async () => [] }; - const jobs = createJobs({ db, resolver, onChange: () => {}, retryDelaysMs: [0], log: () => {} }); + const jobs = createJobs({ db, resolver, onChange: () => {}, backoff: () => 0, retryDelaysMs: [0], log: () => {} }); const app = createApp({ db, jobs, resolver, capturesDir: join(dir, 'captures'), renderCardsPdf: async () => new Uint8Array(), renderCalibrationPdf: async () => new Uint8Array(), @@ -346,3 +346,17 @@ test('a title search that hits a temporary failure is retried, then answers 503 assert.equal(bad.status, 503); assert.match(((await bad.json()) as any).error, /Open Library did not answer/); }); + +test('removing a card cancels its lookup job (and its waiting retry)', async () => { + const resolver = { resolve: async () => found, tail: async () => [], edition: async () => '', search: async () => [] }; + const db = openDb(':memory:'); + const cancelled: number[] = []; + const jobs = { ...createJobs({ db, resolver, onChange: () => {}, log: () => {} }), cancel: (id: number) => { cancelled.push(id); } }; + const app = createApp({ + db, jobs, resolver, renderCardsPdf: async () => new Uint8Array(), renderCalibrationPdf: async () => new Uint8Array(), + classNames: () => ({ className: '', subclassName: '' }), + }); + const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); + assert.equal((await app.request(`/api/books/${book.id}`, { method: 'DELETE' })).status, 200); + assert.deepEqual(cancelled, [book.id]); +}); diff --git a/src/server/app.ts b/src/server/app.ts index 5815832..77692f8 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -49,7 +49,7 @@ export interface AppDeps { events?: EventBus; /** Where pictures the scanner failed to read are kept for tuning (the newest 30). */ capturesDir?: string; - /** Waits between tries of a title search that hit a temporary failure (default 1 s, 3 s). */ + /** Waits between tries of a title search that hit a temporary failure (default one, 0.8 s: the page keeps asking, with its own backoff). */ searchRetryDelaysMs?: number[]; } @@ -172,8 +172,8 @@ export function createApp(deps: AppDeps): Hono { const title = c.req.query('title')?.trim() ?? ''; const author = c.req.query('author')?.trim() ?? ''; if (!title && !author) throw new HttpError(400, 'Enter a title or an author'); - // Open Library drops connections now and then: ask again a couple of times, then say so plainly. - const delays = deps.searchRetryDelaysMs ?? [1_000, 3_000]; + // Open Library drops connections now and then: ask once more quickly, then answer 503 so the page can wait and ask again. + const delays = deps.searchRetryDelaysMs ?? [800]; for (let n = 0; ; n++) { try { const results: SearchResult[] = await resolver.search(title, author); @@ -182,7 +182,7 @@ export function createApp(deps: AppDeps): Hono { if (!(e instanceof TemporaryError)) throw e; if (n >= delays.length) { console.error(`[search] ${e.message}`); - throw new HttpError(503, 'Open Library did not answer. Try the search again in a moment.'); + throw new HttpError(503, 'Open Library did not answer.'); } await new Promise((r) => setTimeout(r, delays[n])); } @@ -257,6 +257,7 @@ export function createApp(deps: AppDeps): Hono { app.delete('/api/books/:id', (c) => { const book = bookParam(c); + jobs.cancel(book.id); db.deleteBook(book.id); events.emitDeleted(book.id); return c.json({ ok: true }); diff --git a/src/server/db.ts b/src/server/db.ts index 7301087..262ffe0 100644 --- a/src/server/db.ts +++ b/src/server/db.ts @@ -3,7 +3,7 @@ import { compareShelf } from '../shared/shelf.ts'; import { displayAuthors } from '../shared/names.ts'; import { mkdirSync } from 'node:fs'; import { dirname } from 'node:path'; -import type { Book, Confidence, Settings, Source, Status } from '../shared/types.ts'; +import type { Book, Confidence, LookupRetry, Settings, Source, Status } from '../shared/types.ts'; import type { ForgettableCache, SourceCache } from './sources/http.ts'; export type { SourceCache }; @@ -15,7 +15,7 @@ export interface NewBook { source?: Source | null; dewey?: string | null; status?: Status; attentionReason?: string | null; manualOverride?: boolean; inQueue?: boolean; hierarchyTail?: string[] | null; edition?: string | null; } -export type BookPatch = Partial>; +export type BookPatch = Partial>; export type Filter = 'all' | 'queue' | 'attention'; export interface Db { @@ -26,6 +26,13 @@ export interface Db { updateBook(id: number, patch: BookPatch): Book | null; deleteBook(id: number): boolean; listPendingIds(): number[]; + /** Remembers (in memory only) why a pending lookup is waiting; null clears it. Shows on the book from then on. */ + setRetry(id: number, retry: { source: string; attempt: number; nextAt: number | null } | null): void; + /** + * Books an earlier version left in "needs attention" only because a source could not be asked (network error, + * timeout, 5xx, block page): they go back to pending, not hand-entered ones. Returns how many. + */ + requeueTemporaryFailures(): number; /** Books that are not pending and whose hierarchy tail has not been looked for yet. */ listTailMissingIds(): number[]; /** Books that are not pending and whose edition has not been looked for yet (NULL). */ @@ -125,6 +132,15 @@ export function openDb(path: string): Db { VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(isbn13) DO NOTHING`); + // Why pending lookups are waiting (see Db.setRetry): never saved, a restart starts the lookups over anyway. + const retries = new Map(); + const book = (r: Row): Book => { + const b = toBook(r); + const x = b.status === 'pending' ? retries.get(b.id) : undefined; + if (x) b.retry = { source: x.source, attempt: x.attempt, waitMs: x.nextAt === null ? null : Math.max(0, x.nextAt - Date.now()) }; + return b; + }; + const self: Db = { insertPending(f) { const now = new Date().toISOString(); @@ -141,11 +157,11 @@ export function openDb(path: string): Db { }, getBook(id) { const r = getById.get(id) as Row | undefined; - return r ? toBook(r) : null; + return r ? book(r) : null; }, findByIsbn(isbn) { const r = getByIsbn.get(isbn) as Row | undefined; - return r ? toBook(r) : null; + return r ? book(r) : null; }, listBooks({ filter = 'all', q } = {}) { const where: string[] = []; @@ -158,7 +174,7 @@ export function openDb(path: string): Db { } const sql = `SELECT * FROM books ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY sort_key IS NULL, sort_key, id`; - const books = (db.prepare(sql).all(...params) as Row[]).map(toBook); + const books = (db.prepare(sql).all(...params) as Row[]).map((r) => book(r)); const found = needle ? books.filter((b) => [b.title, b.authors.join(' '), displayAuthors(b.authors).join(' '), b.isbn13 ?? '', b.callNumber ?? ''] .some((s) => s.toLowerCase().includes(needle))) @@ -175,8 +191,22 @@ export function openDb(path: string): Db { return r.changes ? self.getBook(id) : null; }, deleteBook(id) { + retries.delete(id); return db.prepare('DELETE FROM books WHERE id = ?').run(id).changes > 0; }, + setRetry(id, retry) { + if (retry) retries.set(id, retry); else retries.delete(id); + }, + requeueTemporaryFailures() { + // The reasons older versions recorded when a source could not be asked (see "Lookup failed" in jobs.ts). + const r = db.prepare(`UPDATE books SET status = 'pending', attention_reason = NULL, updated_at = ? + WHERE status = 'needs_attention' AND manual_override = 0 AND ( + attention_reason LIKE 'Lookup failed: Network error%' OR attention_reason LIKE 'Lookup failed: Timed out%' + OR attention_reason LIKE 'Lookup failed: HTTP 5%' OR attention_reason LIKE 'Lookup failed: HTTP 429%' + OR attention_reason LIKE 'Lookup failed: Library of Congress returned a block page%' + OR attention_reason LIKE 'Lookup failed: Open Library returned invalid JSON%')`).run(new Date().toISOString()); + return Number(r.changes); + }, listPendingIds() { return (db.prepare("SELECT id FROM books WHERE status = 'pending' ORDER BY id").all() as Row[]).map((r) => r.id); }, diff --git a/src/server/jobs.test.ts b/src/server/jobs.test.ts index 2c0c953..0224e9f 100644 --- a/src/server/jobs.test.ts +++ b/src/server/jobs.test.ts @@ -1,11 +1,14 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { openDb } from './db.ts'; -import { createJobs, DEFAULT_RETRY_DELAYS_MS } from './jobs.ts'; +import { backoffMs, createJobs, DEFAULT_RETRY_DELAYS_MS, SETTLE_AFTER_ATTEMPTS } from './jobs.ts'; import type { ResolverLike } from './jobs.ts'; import type { NewBook } from './db.ts'; import type { Book, Resolution } from '../shared/types.ts'; +import { createResolver, TemporaryError as RealTemporaryError } from './resolve/resolver.ts'; +import { fixtureFetch } from './sources/fixture-fetch.ts'; + class TemporaryError extends Error {} const found: Resolution = { @@ -19,7 +22,7 @@ function setup(resolve: ResolverLike['resolve'], delays = [0, 0, 0]) { const changes: Book[] = []; const logs: string[] = []; const resolver: ResolverLike = { resolve, tail: async () => [], edition: async () => '', search: async () => [] }; - const jobs = createJobs({ db, resolver, onChange: (b) => changes.push(b), retryDelaysMs: delays, log: (l) => logs.push(l) }); + const jobs = createJobs({ db, resolver, onChange: (b) => changes.push(b), backoff: (n) => delays[Math.min(n, delays.length) - 1] ?? 0, retryDelaysMs: delays, log: (l) => logs.push(l) }); return { db, jobs, changes, logs }; } @@ -71,16 +74,54 @@ test('temporary failures retry then succeed', async () => { assert.equal(db.getBook(book.id)!.status, 'resolved'); }); -test('failure after all retries -> needs_attention', async () => { +test('a temporary failure never gives up: the book stays pending and is asked again until a source answers', async () => { let calls = 0; - const { db, jobs } = setup(async () => { calls++; throw new TemporaryError('blocked'); }); + const { db, jobs, changes } = setup(async () => { if (++calls <= 12) throw new TemporaryError('blocked'); return found; }); const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); jobs.enqueue(book.id); await jobs.idle(); - assert.equal(calls, 4); - const b = db.getBook(book.id)!; - assert.equal(b.status, 'needs_attention'); - assert.equal(b.attentionReason, 'Lookup failed: blocked'); + assert.equal(calls, 13); + assert.equal(db.getBook(book.id)!.status, 'resolved'); + assert.ok(changes.every((c) => c.status !== 'needs_attention'), 'never handed to the person'); +}); + +test('a definitive "no call number" is the only thing that asks the person to look', async () => { + const { db, jobs } = setup(async () => ({ ...found, callNumber: null, sortKey: null, reason: 'Not found in Open Library or the Library of Congress' })); + const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); + jobs.enqueue(book.id); + await jobs.idle(); + assert.equal(db.getBook(book.id)!.status, 'needs_attention'); +}); + +test('the backoff doubles from 2 s to a 5 min cap, with +/-25 % jitter', () => { + const mid = () => 0.5; + assert.deepEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 40].map((n) => backoffMs(n, undefined, mid)), + [2000, 4000, 8000, 16000, 32000, 64000, 128000, 256000, 300000, 300000, 300000]); + assert.equal(backoffMs(3, undefined, () => 0), 6000); + assert.equal(backoffMs(3, undefined, () => 1), 10000); + assert.equal(backoffMs(9, undefined, () => 1), 375000); +}); + +test('Retry-After from the server is a floor for the wait', () => { + assert.equal(backoffMs(1, 45_000, () => 0.5), 45_000); + assert.equal(backoffMs(8, 45_000, () => 0.5), 256_000); +}); + +test('the wait before each retry comes from the backoff, with the Retry-After the error carried', async () => { + const waits: [number, number | undefined][] = []; + const db = openDb(':memory:'); + let calls = 0; + const resolver: ResolverLike = { + resolve: async () => { + if (++calls <= 2) throw Object.assign(new TemporaryError('HTTP 429 from https://openlibrary.org/x'), { retryAfterMs: calls === 1 ? 9000 : undefined, source: 'Open Library' }); + return found; + }, tail: async () => [], edition: async () => '', search: async () => [], + }; + const jobs = createJobs({ db, resolver, onChange: () => {}, backoff: (n, ra) => { waits.push([n, ra]); return 0; }, log: () => {} }); + const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); + jobs.enqueue(book.id); + await jobs.idle(); + assert.deepEqual(waits, [[1, 9000], [2, undefined]]); }); test('a non-temporary error never loses the book or stops the queue', async () => { @@ -163,7 +204,7 @@ test('a waiting retry does not block the books behind it', async () => { assert.equal(db.getBook(a.id)!.status, 'resolved'); }); -test('a book waiting for a retry stays pending with a progress note, cleared when it resolves', async () => { +test('a book waiting for a retry stays pending and says who is failing, which try it is and when the next starts', async () => { let calls = 0; const { db, jobs, changes } = setup(async () => { if (++calls === 1) throw new TemporaryError('Network error for https://lx2.loc.gov/sru/lcdb: fetch failed'); @@ -174,12 +215,64 @@ test('a book waiting for a retry stays pending with a progress note, cleared whe await new Promise((r) => setTimeout(r, 15)); const mid = db.getBook(book.id)!; assert.equal(mid.status, 'pending'); - assert.equal(mid.attentionReason, 'Library of Congress did not answer. Trying again shortly.'); - assert.ok(changes.some((c) => c.attentionReason === mid.attentionReason), 'a change was emitted'); + assert.equal(mid.retry?.source, 'Library of Congress'); + assert.equal(mid.retry?.attempt, 1); + assert.ok(mid.retry!.waitMs! > 0 && mid.retry!.waitMs! <= 40); + assert.ok(changes.some((c) => c.retry?.attempt === 1), 'a change carrying the retry was emitted'); await jobs.idle(); const done = db.getBook(book.id)!; assert.equal(done.status, 'resolved'); - assert.equal(done.attentionReason, null); + assert.equal(done.retry, undefined); + assert.equal(changes.at(-1)!.retry, undefined); +}); + +test('removing a book cancels its waiting retry and leaves nothing behind', async () => { + let calls = 0; + const { db, jobs } = setup(async () => { calls++; throw new TemporaryError('x'); }, [60_000]); + const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); + jobs.enqueue(book.id); + await new Promise((r) => setTimeout(r, 15)); + assert.equal(calls, 1); + jobs.cancel(book.id); + db.deleteBook(book.id); + await jobs.idle(); // returns at once: no timer is left + assert.equal(calls, 1); +}); + +test('a book asked for while its lookup runs is looked up once more afterwards, never two at a time', async () => { + let active = 0, maxActive = 0, calls = 0; + const { db, jobs } = setup(async () => { + calls++; active++; maxActive = Math.max(maxActive, active); + await new Promise((r) => setTimeout(r, 20)); + active--; + return found; + }); + const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); + jobs.enqueue(book.id); + await new Promise((r) => setTimeout(r, 5)); + db.updateBook(book.id, { status: 'pending', attentionReason: null }); + jobs.enqueue(book.id, { fresh: true }); + await jobs.idle(); + assert.equal(maxActive, 1); + assert.equal(calls, 2); + assert.equal(db.getBook(book.id)!.status, 'resolved'); +}); + +test('resume() after a restart picks up pending books and those an older version gave up on only for a network reason', async () => { + const seen: string[] = []; + const { db, jobs } = setup(async (i) => { seen.push(i.isbn13!); return found; }); + const mk = (isbn: string, f: Partial) => db.insertPending({ isbn13: isbn, title: isbn, ...f }).book; + const pend = mk('9781593278281', { status: 'pending' }); + const net = mk('9780201835953', { status: 'needs_attention', attentionReason: 'Lookup failed: Network error for https://openlibrary.org/x: fetch failed' }); + const tmo = mk('9780321125217', { status: 'needs_attention', attentionReason: 'Lookup failed: Timed out after 15 s waiting for https://openlibrary.org/x' }); + const real = mk('9780131103627', { status: 'needs_attention', attentionReason: 'No Library of Congress number found' }); + const hand = mk('9780596517748', { status: 'needs_attention', attentionReason: 'Lookup failed: HTTP 503 from x', manualOverride: true }); + jobs.resume(); + await jobs.idle(); + assert.deepEqual(seen.sort(), [pend, net, tmo].map((b) => b.isbn13!).sort()); + assert.equal(db.getBook(real.id)!.status, 'needs_attention'); + assert.equal(db.getBook(hand.id)!.status, 'needs_attention'); + assert.equal(db.getBook(net.id)!.status, 'resolved'); }); test('retry timers are unref\'d', async () => { @@ -197,18 +290,17 @@ test('retry timers are unref\'d', async () => { } finally { globalThis.setTimeout = real; } }); -test('only the final attempt asks the resolver to tolerate LoC failure', async () => { +test('the resolver is asked to settle with what it has only after the bound, never before', async () => { const flags: (boolean | undefined)[] = []; const { db, jobs } = setup(async (_i, o) => { flags.push(o?.tolerateLocFailure); - if (flags.length < 4) throw new TemporaryError('blocked'); + if (flags.length < 9) throw new TemporaryError('blocked'); return found; }); const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); jobs.enqueue(book.id); await jobs.idle(); - assert.deepEqual(flags, [false, false, false, true]); - assert.equal(db.getBook(book.id)!.status, 'resolved'); + assert.deepEqual(flags, [false, false, false, false, false, false, true, true, true]); }); test('"Look up again" while waiting restarts the retries at once', async () => { @@ -288,7 +380,7 @@ test('tail backfill changes only the tail, emits the update, and never touches s resolve: async () => { throw new Error('no lookup'); }, search: async () => [], edition: async () => '', tail: async (i) => { calls.push(i); return ['Utah', 'Uinta Mountains']; }, }; - const j = createJobs({ db, resolver, onChange: (b) => changes.push(b), retryDelaysMs: [0], log: () => {} }); + const j = createJobs({ db, resolver, onChange: (b) => changes.push(b), backoff: () => 0, retryDelaysMs: [0], log: () => {} }); const printed = '2026-02-03T00:00:00.000Z'; const b = tailBook(db, { isbn13: '9781593278281' }); db.updateBook(b.id, { printedAt: printed, inQueue: true, confidence: 'approximate' }); @@ -308,7 +400,7 @@ test('tail backfill: hand entries get [] without asking; every other book is ask const { db } = setup(async () => found); const asked: unknown[] = []; const resolver: ResolverLike = { resolve: async () => found, search: async () => [], edition: async () => '', tail: async (i) => { asked.push(i); return ['X']; } }; - const jobs = createJobs({ db, resolver, onChange: () => {}, retryDelaysMs: [0], log: () => {} }); + const jobs = createJobs({ db, resolver, onChange: () => {}, backoff: () => 0, retryDelaysMs: [0], log: () => {} }); const none = tailBook(db, { title: 'no ids' }); const manual = tailBook(db, { isbn13: '9780000000002', manualOverride: true, source: 'manual' }); const similar = tailBook(db, { isbn13: '9780000000019', source: 'similar' }); @@ -329,7 +421,7 @@ test('tail rules version: books with [] are checked again once, hand entries and resolve: async () => found, search: async () => [], edition: async () => '', tail: async (i) => { asked.push(i.isbn13 ?? ''); return ['Utah']; }, }; - const mk = () => createJobs({ db, resolver, onChange: () => {}, retryDelaysMs: [0], log: () => {} }); + const mk = () => createJobs({ db, resolver, onChange: () => {}, backoff: () => 0, retryDelaysMs: [0], log: () => {} }); const empty = tailBook(db, { isbn13: '9780000000002', hierarchyTail: [] }); const has = tailBook(db, { isbn13: '9780000000019', hierarchyTail: ['Nevada'] }); const hand = tailBook(db, { isbn13: '9780000000026', hierarchyTail: [], manualOverride: true, source: 'manual' }); @@ -359,7 +451,7 @@ test('tail backfill: a temporary failure is retried, then left NULL for the next resolve: async () => found, search: async () => [], edition: async () => '', tail: async (i) => { n++; if (i.isbn13 === '9780000000002') throw new TemporaryError('loc.gov busy'); return []; }, }; - const jobs = createJobs({ db, resolver, onChange: () => {}, retryDelaysMs: [0, 0], isTemporary: (e) => e instanceof TemporaryError, log: (l) => logs.push(l) }); + const jobs = createJobs({ db, resolver, onChange: () => {}, backoff: () => 0, retryDelaysMs: [0, 0], isTemporary: (e) => e instanceof TemporaryError, log: (l) => logs.push(l) }); const busy = tailBook(db, { isbn13: '9780000000002' }); const empty = tailBook(db, { isbn13: '9780000000019' }); jobs.resumeTails(); @@ -377,7 +469,7 @@ function editionSetup(edition: ResolverLike['edition']) { const changes: Book[] = []; const logs: string[] = []; const resolver: ResolverLike = { resolve: async () => { throw new Error('no lookup'); }, search: async () => [], tail: async () => [], edition }; - const jobs = createJobs({ db, resolver, onChange: (b) => changes.push(b), retryDelaysMs: [0], log: (l) => logs.push(l), isTemporary: (e) => e instanceof TemporaryError }); + const jobs = createJobs({ db, resolver, onChange: (b) => changes.push(b), backoff: () => 0, retryDelaysMs: [0], log: (l) => logs.push(l), isTemporary: (e) => e instanceof TemporaryError }); return { db, jobs, changes, logs }; } @@ -444,3 +536,91 @@ test('edition backfill: a network failure leaves NULL (retried next start), and await jobs.idle(); assert.equal(db.getBook(b.id)!.edition, 'Second edition'); }); + +// A real resolver over the fixtures, with some requests that never succeed. +function settleSetup(fail: (url: string) => boolean, waitMs = 0) { + const f = fixtureFetch(); + const fe = (async (i: string | URL | Request, o?: RequestInit) => fail(String(i)) ? new Response('x', { status: 503 }) : f.fetch(i as string, o)) as typeof fetch; + const real = createResolver({ fetch: fe, cache: { get: () => null, set: () => {} }, sleep: async () => {} }); + let tries = 0; + const resolver: ResolverLike = { ...real, resolve: (i, o) => { tries++; return real.resolve(i, o); } }; + const db = openDb(':memory:'); + const jobs = createJobs({ db, resolver, onChange: () => {}, backoff: () => waitMs, isTemporary: (e) => e instanceof RealTemporaryError, log: () => {} }); + return { db, jobs, tries: () => tries }; +} + +test('a number in hand settles after a bounded number of tries when the Library of Congress never answers', async () => { + const { db, jobs, tries } = settleSetup((u) => /loc\.gov/.test(u)); + const { book } = db.insertPending({ isbn13: '9780441172719', title: 'x' }); + jobs.enqueue(book.id); + await jobs.idle(); + assert.equal(tries(), SETTLE_AFTER_ATTEMPTS + 1); + const b = db.getBook(book.id)!; + assert.equal(b.status, 'resolved'); + assert.match(b.callNumber!, /^PS3558/); + assert.equal(b.confidence, 'approximate'); + assert.equal(b.edition, null); + assert.equal(b.hierarchyTail, null); +}); + +test('a number in hand settles when only the edition lookup at Open Library never answers', async () => { + const { db, jobs, tries } = settleSetup((u) => /openlibrary\.org\/isbn\//.test(u)); + const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); + jobs.enqueue(book.id); + await jobs.idle(); + assert.equal(tries(), SETTLE_AFTER_ATTEMPTS + 1); + const b = db.getBook(book.id)!; + assert.equal(b.status, 'resolved'); + assert.equal(b.callNumber, 'QA76.73.R87 K53 2018'); + assert.equal(b.edition, null); +}); + +test('a number in hand settles when the Library of Congress searches for the tail never answer', async () => { + const { db, jobs, tries } = settleSetup((u) => /loc\.gov/.test(u) && !/bath\.isbn|lccn\.loc/.test(decodeURIComponent(u))); + const { book } = db.insertPending({ isbn13: '9780441172719', title: 'x' }); + jobs.enqueue(book.id); + await jobs.idle(); + assert.equal(tries(), SETTLE_AFTER_ATTEMPTS + 1); + const b = db.getBook(book.id)!; + assert.equal(b.status, 'resolved'); + assert.match(b.callNumber!, /^PS3558/); + assert.equal(b.hierarchyTail, null); +}); + +test('with no number at all a permanent failure is retried well past the bound, and never needs attention', async () => { + const { db, jobs, tries } = settleSetup((u) => /loc\.gov|openlibrary\.org/.test(u), 3); + const { book } = db.insertPending({ isbn13: '9780441172719', title: 'x' }); + jobs.enqueue(book.id); + await new Promise((r) => setTimeout(r, 150)); + assert.ok(tries() > SETTLE_AFTER_ATTEMPTS + 3, `tries ${tries()}`); + assert.equal(db.getBook(book.id)!.status, 'pending'); + jobs.cancel(book.id); + db.deleteBook(book.id); + await jobs.idle(); +}); + +test('"Look up again" during a backoff clears the countdown on the page at once', async () => { + let calls = 0; + const { db, jobs, changes } = setup(async () => { if (++calls === 1) throw new TemporaryError('x'); await new Promise((r) => setTimeout(r, 30)); return found; }, [60_000]); + const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); + jobs.enqueue(book.id); + await new Promise((r) => setTimeout(r, 15)); + assert.ok(db.getBook(book.id)!.retry); + changes.length = 0; + jobs.enqueue(book.id, { fresh: true }); + assert.equal(changes[0]?.retry, undefined); + assert.equal(db.getBook(book.id)!.retry, undefined); + await jobs.idle(); +}); + +test('a failing change notification cannot leave a book pending without a retry timer', async () => { + let calls = 0; + const db = openDb(':memory:'); + const resolver: ResolverLike = { resolve: async () => { if (++calls === 1) throw new TemporaryError('x'); return found; }, tail: async () => [], edition: async () => '', search: async () => [] }; + let boom = true; + const jobs = createJobs({ db, resolver, backoff: () => 0, log: () => {}, onChange: () => { if (boom) { boom = false; throw new Error('listener failed'); } } }); + const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); + jobs.enqueue(book.id); + await jobs.idle(); + assert.equal(db.getBook(book.id)!.status, 'resolved'); +}); diff --git a/src/server/jobs.ts b/src/server/jobs.ts index 12d1fce..7ece447 100644 --- a/src/server/jobs.ts +++ b/src/server/jobs.ts @@ -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(); const attempts = new Map(); const fresh = new Set(); + // What each pending lookup has been definitively told so far (see jobMemo): a retry asks only for the rest. + const memos = new Map>(); + // 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(); // Books waiting for a retry: they hold no worker; a timer puts them back in the queue. const waiting = new Map>(); // 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 { 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(); + 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 { 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`); diff --git a/src/server/resolve/resolver.test.ts b/src/server/resolve/resolver.test.ts index e5c6d5e..fa7e108 100644 --- a/src/server/resolve/resolver.test.ts +++ b/src/server/resolve/resolver.test.ts @@ -5,6 +5,7 @@ import type { SourceCache } from './resolver.ts'; import { createLoc } from '../sources/loc.ts'; import { createOpenLibrary } from '../sources/openlibrary.ts'; import { fixtureFetch } from '../sources/fixture-fetch.ts'; +import { jobMemo } from '../sources/http.ts'; import { readFileSync } from 'node:fs'; import { join } from 'node:path'; @@ -575,3 +576,32 @@ test('edition(): same rules without a lookup; cached answers; nothing to ask wit assert.equal(await r.edition({}), ''); await assert.rejects(createResolver({ fetch: locDown(fixtureFetch()), cache: memCache(), sleep: noSleep }).edition({ isbn13: '9781593278281' }), TemporaryError); }); + +test('within one job, a retry does not repeat a request that already got a real answer', async () => { + const f = fixtureFetch(); + const answered = new Map(); + const failedOnce = new Set(); + // Every URL fails (connection reset) the first time it is asked and answers the second time. + const flaky = (async (input: string | URL | Request, init?: RequestInit) => { + const u = String(input); + if (!failedOnce.has(u)) { failedOnce.add(u); throw new TypeError('fetch failed'); } + answered.set(u, (answered.get(u) ?? 0) + 1); + return f.fetch(input as string, init); + }) as typeof fetch; + const r = createResolver({ fetch: flaky, cache: memCache(), sleep: noSleep }); + const memo = new Map(); + let res; + let attempts = 0; + while (!res) { + attempts++; + assert.ok(attempts < 30, 'keeps failing'); + try { res = await jobMemo.run(memo, () => r.resolve({ isbn13: '9781593278281' })); } catch (e) { assert.ok(e instanceof TemporaryError); } + } + assert.ok(res.callNumber!.startsWith('QA76.73.R87')); + assert.ok(attempts > 1); + assert.ok([...answered.values()].every((n) => n === 1), JSON.stringify([...answered])); + // Without a job around it, nothing is remembered. + const bare = createResolver({ fetch: flaky, cache: memCache(), sleep: noSleep }); + await bare.resolve({ isbn13: '9781593278281' }); + assert.ok([...answered.values()].some((n) => n > 1)); +}); diff --git a/src/server/resolve/resolver.ts b/src/server/resolve/resolver.ts index c63548e..17d3046 100644 --- a/src/server/resolve/resolver.ts +++ b/src/server/resolve/resolver.ts @@ -19,7 +19,11 @@ export type { SourceCache }; export interface ResolveOpts { onMeta?: (meta: BookMeta) => void; - /** Last-attempt mode: a Library of Congress failure is not fatal; use Open Library's numbers if it has any. */ + /** + * Settling mode, for a lookup that has failed for a while: a source that cannot be asked no longer blocks a number + * already in hand (the other source's check, the edition, the tail stay unknown, to be filled in later). With no + * number at all it still throws, so the lookup goes on. + */ tolerateLocFailure?: boolean; /** Called when the similar-books tier chose the number, for example "GV199.42.W8 (4 of 9 candidates)". */ onSimilar?: (detail: string) => void; @@ -132,11 +136,15 @@ export function createResolver(deps: { } return r.v ? { ...r.v, meta: withoutLccn(r.v.meta) } : null; }; + let olError: unknown = null; if (isbn) { workP = ol.work(isbn).then((v) => ({ v }), (e: unknown) => ({ e })); - edition = await ol.edition(isbn); + try { edition = await ol.edition(isbn); } catch (e) { + if (!(opts?.tolerateLocFailure && e instanceof TemporaryError)) throw e; + olError = e; // settling: the Library of Congress may still have the number + } if (edition) notify(mergeMeta([edition.meta])); - else { work = await getWork(true); notify(mergeMeta([work?.meta])); } + else { work = await getWork(!olError); notify(mergeMeta([work?.meta])); } } // Library of Congress: by LCCN when known, else by ISBN. @@ -171,8 +179,12 @@ export function createResolver(deps: { // a work-level record, another edition or the similar-books search. The Library of Congress first, then Open // Library's edition record. null (unknown, asked again later) when the Library of Congress failed and had none. let edit: string | null = locRecs.find((r) => r.edition)?.edition ?? null; - if (edit === null && isbn && !locError) edit = (await ol.editionName(isbn)) ?? ''; - else if (edit === null && !isbn && !locError) edit = ''; + if (edit === null && isbn && !locError) { + try { edit = (await ol.editionName(isbn)) ?? ''; } catch (e) { + // Settling with a number in hand: the edition stays unknown (NULL) and is looked for later. + if (!(opts?.tolerateLocFailure && e instanceof TemporaryError)) throw e; + } + } else if (edit === null && !isbn && !locError) edit = ''; const olEditionCands: Candidate[] = edition?.lcc ?? []; const metaOf = (extra: Partials = []): BookMeta | null => @@ -221,7 +233,6 @@ export function createResolver(deps: { ); // Tier 5: borrow the class from similar books. Last resort, and only for a book with a title. - let olError: unknown = null; const similarRecs: MarcFields[] = []; let similarSearched = false; if (!chosen && meta?.title) { @@ -306,9 +317,11 @@ export function createResolver(deps: { if (ownRec) opts?.onTailSource?.({ step: 'own', records: [ownRec] }); if (chosen) { + // Settled with a source unasked: the number was not checked against it, so it is marked as approximate. + const settled = !!opts?.tolerateLocFailure && !!(locError || olError); return { meta, callNumber: chosen.callNumber, sortKey: chosen.sortKey, - confidence: chosen.confidence, source: chosen.source, dewey, tail, edition: edit, reason: null, + confidence: settled && chosen.confidence === 'exact' ? 'approximate' : chosen.confidence, source: chosen.source, dewey, tail, edition: edit, reason: null, }; } // Open Library had nothing and the LoC could not be asked: report that, not "no number found". diff --git a/src/server/sources/http.test.ts b/src/server/sources/http.test.ts index 207dac1..5b778fa 100644 --- a/src/server/sources/http.test.ts +++ b/src/server/sources/http.test.ts @@ -1,6 +1,6 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { describeError, getText, REQUEST_TIMEOUT_MS, TemporaryError } from './http.ts'; +import { describeError, getText, parseRetryAfter, PER_HOST_LIMIT, REQUEST_TIMEOUT_MS, TemporaryError } from './http.ts'; test('every request carries a 15 s abort signal', async () => { assert.equal(REQUEST_TIMEOUT_MS, 15_000); @@ -42,3 +42,24 @@ test('describeError lists every address of an aggregate failure once', () => { const e = Object.assign(new TypeError('fetch failed'), { cause: Object.assign(new Error(''), { errors: [{ code: 'ETIMEDOUT' }, { code: 'ENETUNREACH' }, { code: 'ETIMEDOUT' }] }) }); assert.equal(describeError(e), 'fetch failed (ETIMEDOUT; ENETUNREACH)'); }); + +test('a 429 or 503 carries its Retry-After, and names who said it', async () => { + const f = (async () => new Response('', { status: 429, headers: { 'Retry-After': '17' } })) as typeof fetch; + await assert.rejects(getText(f, 'https://openlibrary.org/x'), (e: TemporaryError) => + e.retryAfterMs === 17_000 && e.source === 'Open Library'); + assert.equal(parseRetryAfter('120'), 120_000); + assert.equal(parseRetryAfter('Wed, 21 Oct 2015 07:28:30 GMT', Date.parse('Wed, 21 Oct 2015 07:28:00 GMT')), 30_000); + assert.equal(parseRetryAfter('86400'), 600_000); + assert.equal(parseRetryAfter('soon'), undefined); + assert.equal(parseRetryAfter(null), undefined); +}); + +test('no more than PER_HOST_LIMIT requests to one host run at once; other hosts are not held up', async () => { + let active = 0, peak = 0; + const slow = (async () => { active++; peak = Math.max(peak, active); await new Promise((r) => setTimeout(r, 15)); active--; return new Response('ok'); }) as typeof fetch; + await Promise.all(Array.from({ length: 7 }, (_, i) => getText(slow, `https://limit.test/${i}`))); + assert.equal(peak, PER_HOST_LIMIT); + active = 0; peak = 0; + await Promise.all(['https://a.test/', 'https://b.test/', 'https://c.test/'].map((u) => getText(slow, u))); + assert.equal(peak, 3); +}); diff --git a/src/server/sources/http.ts b/src/server/sources/http.ts index bf96d1d..26510c6 100644 --- a/src/server/sources/http.ts +++ b/src/server/sources/http.ts @@ -1,4 +1,54 @@ -export class TemporaryError extends Error {} +import { AsyncLocalStorage } from 'node:async_hooks'; + +/** + * A source could not be asked right now (network error, timeout, 5xx, 429): the answer is "not yet", never "no". + * `source` names who is failing for the page; `retryAfterMs` is what the server asked us to wait, when it said. + */ +export class TemporaryError extends Error { + source: string | undefined; + retryAfterMs: number | undefined; + constructor(message: string, opts?: { source?: string | undefined; retryAfterMs?: number | undefined }) { + super(message); + this.source = opts?.source; + this.retryAfterMs = opts?.retryAfterMs; + } +} + +/** Who a URL belongs to, in words for the page. */ +export function sourceName(url: string): string { + let host = ''; + try { host = new URL(url).hostname; } catch { /* not a URL */ } + if (host === 'openlibrary.org' || host.endsWith('.openlibrary.org')) return 'Open Library'; + if (host === 'loc.gov' || host.endsWith('.loc.gov')) return 'Library of Congress'; + return host || 'A lookup service'; +} + +/** + * Definitive answers (a real 200 or 404) of one lookup job, by request, so a retry after a failure asks again only + * for what it does not have yet. The job runs its attempts inside `jobMemo.run(map, ...)`; outside one, nothing is kept. + */ +export const jobMemo = new AsyncLocalStorage>(); + +/** Retry-After: seconds or a date. Capped, so a silly value cannot park a book for hours. */ +export function parseRetryAfter(value: string | null, now = Date.now()): number | undefined { + if (!value) return undefined; + const v = value.trim(); + const ms = /^\d+(\.\d+)?$/.test(v) ? Number(v) * 1000 : Date.parse(v) - now; + return Number.isFinite(ms) && ms >= 0 ? Math.min(Math.round(ms), 600_000) : undefined; +} + +/** At most this many requests to one host at a time, so retries from many books do not stampede it. */ +export const PER_HOST_LIMIT = 2; +const hostSlots = new Map void)[] }>(); +async function acquireHost(url: string): Promise<() => void> { + let host = url; + try { host = new URL(url).host; } catch { /* keep the raw string */ } + const slot = hostSlots.get(host) ?? { active: 0, waiters: [] }; + hostSlots.set(host, slot); + if (slot.active >= PER_HOST_LIMIT) await new Promise((r) => slot.waiters.push(r)); + else slot.active++; + return () => { const next = slot.waiters.shift(); if (next) next(); else slot.active--; }; +} export interface SourceCache { get(key: string): string | null; set(key: string, body: string): void } @@ -38,6 +88,12 @@ export function describeError(e: unknown): string { export async function getText( f: typeof fetch, url: string, timeoutMs = REQUEST_TIMEOUT_MS, retryDelaysMs: number[] = [], ): Promise { + const release = await acquireHost(url); + try { return await getTextNow(f, url, timeoutMs, retryDelaysMs); } finally { release(); } +} + +async function getTextNow(f: typeof fetch, url: string, timeoutMs: number, retryDelaysMs: number[]): Promise { + const source = sourceName(url); let signal = AbortSignal.timeout(timeoutMs); const timedOut = (e: unknown) => signal.aborted || (e as Error)?.name === 'TimeoutError'; let res: Response | undefined; @@ -45,19 +101,19 @@ export async function getText( try { res = await f(url, { headers: { 'User-Agent': USER_AGENT }, signal }); } catch (e) { - if (timedOut(e)) throw new TemporaryError(`Timed out after ${Math.round(timeoutMs / 1000)} s waiting for ${url}`); - if (n >= retryDelaysMs.length) throw new TemporaryError(`Network error for ${url}: ${describeError(e)}`); + if (timedOut(e)) throw new TemporaryError(`Timed out after ${Math.round(timeoutMs / 1000)} s waiting for ${url}`, { source }); + if (n >= retryDelaysMs.length) throw new TemporaryError(`Network error for ${url}: ${describeError(e)}`, { source }); await new Promise((r) => setTimeout(r, retryDelaysMs[n])); signal = AbortSignal.timeout(timeoutMs); } } - if (res.status >= 500 || res.status === 429) throw new TemporaryError(`HTTP ${res.status} from ${url}`); + if (res.status >= 500 || res.status === 429) throw new TemporaryError(`HTTP ${res.status} from ${url}`, { source, retryAfterMs: parseRetryAfter(res.headers.get('Retry-After')) }); let body: string; try { body = await res.text(); } catch (e) { - if (timedOut(e)) throw new TemporaryError(`Timed out after ${Math.round(timeoutMs / 1000)} s waiting for ${url}`); - throw new TemporaryError(`Network error reading ${url}: ${describeError(e)}`); + if (timedOut(e)) throw new TemporaryError(`Timed out after ${Math.round(timeoutMs / 1000)} s waiting for ${url}`, { source }); + throw new TemporaryError(`Network error reading ${url}: ${describeError(e)}`, { source }); } return { status: res.status, body }; } diff --git a/src/server/sources/loc.ts b/src/server/sources/loc.ts index fe316d4..a7548c3 100644 --- a/src/server/sources/loc.ts +++ b/src/server/sources/loc.ts @@ -1,5 +1,5 @@ import { mainEntry } from '../../shared/cutter.ts'; -import { getText, TemporaryError } from './http.ts'; +import { getText, TemporaryError, jobMemo } from './http.ts'; import type { SourceCache } from './http.ts'; import { parseMarcXml } from './marc.ts'; import type { MarcFields } from './marc.ts'; @@ -48,7 +48,7 @@ export function createLoc(deps: { interval = Math.min(interval * 2, MAX_INTERVAL_MS); tokens = 0; // the next call waits one (doubled) interval from the block lastRefill = Date.now(); - throw new TemporaryError('Library of Congress returned a block page'); + throw new TemporaryError('Library of Congress returned a block page', { source: 'Library of Congress' }); } function ok(): void { @@ -56,7 +56,7 @@ export function createLoc(deps: { } async function sru(cacheKey: string, query: string, max: number): Promise { - const hit = deps.cache.get(cacheKey); + const hit = deps.cache.get(cacheKey) ?? jobMemo.getStore()?.get(cacheKey) ?? null; if (hit !== null) return parseMarcXml(hit); const qs = new URLSearchParams({ version: '1.1', operation: 'searchRetrieve', query, @@ -78,6 +78,7 @@ export function createLoc(deps: { ok(); const recs = parseMarcXml(body); if (recs.length > 0) deps.cache.set(cacheKey, body); // a miss is not cached: asking again may find it + jobMemo.getStore()?.set(cacheKey, body); // ...but within this job a miss is an answer, so a retry does not repeat it return recs; } @@ -85,16 +86,18 @@ export function createLoc(deps: { byIsbn: (isbn) => sru(`loc-isbn:${isbn}`, `bath.isbn=${isbn}`, 1), async byLccn(lccn) { const key = `loc-lccn:${lccn}`; - const hit = deps.cache.get(key); - if (hit !== null) return parseMarcXml(hit); + const memo = jobMemo.getStore(); + const hit = deps.cache.get(key) ?? memo?.get(key) ?? null; + if (hit !== null) return hit === '' ? [] : parseMarcXml(hit); await throttle(); const res = await getText(deps.fetch, `https://lccn.loc.gov/${encodeURIComponent(lccn)}/marcxml`); // lccn.loc.gov answers an unknown number with 200 and a short Record not found body. - if (res.status === 404 || /\s*Record not found/i.test(res.body)) { ok(); return []; } + if (res.status === 404 || /\s*Record not found/i.test(res.body)) { ok(); memo?.set(key, ''); return []; } if (res.status >= 400 || !isLocXml(res.body)) blocked(); ok(); const recs = parseMarcXml(res.body); if (recs.length > 0) deps.cache.set(key, res.body); + memo?.set(key, res.body); return recs; }, byTitle(title, author) { diff --git a/src/server/sources/openlibrary.ts b/src/server/sources/openlibrary.ts index 87d2ddd..b7198d0 100644 --- a/src/server/sources/openlibrary.ts +++ b/src/server/sources/openlibrary.ts @@ -1,7 +1,7 @@ import type { BookMeta, Candidate, SearchResult } from '../../shared/types.ts'; import { formatCallNumber, parseCallNumber } from '../../shared/callnumber.ts'; import { cleanEdition } from './marc.ts'; -import { getText, trimPunct, TemporaryError, CONNECT_RETRY_DELAYS_MS } from './http.ts'; +import { getText, trimPunct, TemporaryError, CONNECT_RETRY_DELAYS_MS, jobMemo } from './http.ts'; import type { SourceCache } from './http.ts'; export interface OlInfo { @@ -30,7 +30,7 @@ function yearOf(s: unknown): number | undefined { } function parseJson(body: string): unknown { - try { return JSON.parse(body); } catch { throw new TemporaryError('Open Library returned invalid JSON'); } + try { return JSON.parse(body); } catch { throw new TemporaryError('Open Library returned invalid JSON', { source: 'Open Library' }); } } /** Parse the api/books response; null when the ISBN is unknown ({}). */ @@ -155,10 +155,15 @@ export function createOpenLibrary(deps: { fetch: typeof fetch; cache: SourceCach const hit = deps.cache.get(key); if (hit !== null) return hit; } + // A definitive answer already given in this job (a retry after another request failed) is not asked for again. + const memo = jobMemo.getStore(); + const remembered = memo?.get(url); + if (remembered !== undefined) return remembered; const res = await getText(deps.fetch, url, undefined, CONNECT_RETRY_DELAYS_MS); // Other 4xx: treat as an empty answer rather than an error. const text = res.status >= 400 ? '{}' : res.body; parseJson(text); // reject HTML overload pages before they reach the cache + memo?.set(url, text); // a miss counts too: for the rest of this job, Open Library has said it has nothing if (key && res.status < 400 && hasRecord(text)) deps.cache.set(key, text); return text; } diff --git a/src/shared/types.ts b/src/shared/types.ts index 8ad3f78..795fba9 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -1,6 +1,12 @@ export type Confidence = 'exact' | 'approximate' | 'manual'; export type Status = 'pending' | 'resolved' | 'needs_attention'; export type Source = 'loc-isbn' | 'loc-lccn' | 'ol-edition' | 'loc-title' | 'ol-work' | 'similar' | 'manual'; +/** + * Why a pending lookup is waiting: who is not answering, how many tries have failed, and how many ms were left before + * the next one when the server sent this (null: asking now). A remaining time, not a clock time, so it does not + * depend on the browser's clock agreeing with the server's. + */ +export interface LookupRetry { source: string; attempt: number; waitMs: number | null } export interface Book { id: number; isbn13: string | null; lccn: string | null; title: string; subtitle: string | null; authors: string[]; @@ -13,6 +19,8 @@ export interface Book { hierarchyTail: string[] | null; /** The edition statement ("Third edition") from a record for this exact edition. null: not looked up yet; '': looked, none. */ edition: string | null; + /** Only while a pending lookup is backing off after a temporary failure; kept in memory, not saved. */ + retry?: LookupRetry | null; } /** A call number explained in plain words: `outline` from the LC outline (main class first), `tail` from the record's subject. */ export interface Hierarchy { outline: string[]; tail: string[] } diff --git a/src/web/api.ts b/src/web/api.ts index d4b6abb..6e41c00 100644 --- a/src/web/api.ts +++ b/src/web/api.ts @@ -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(method: string, url: string, body?: unknown): Promise { let res: Response; @@ -16,7 +19,7 @@ async function request(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(); diff --git a/src/web/bookstate.test.ts b/src/web/bookstate.test.ts index 1df29a4..5725c48 100644 --- a/src/web/bookstate.test.ts +++ b/src/web/bookstate.test.ts @@ -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 { return { @@ -16,9 +16,20 @@ const looking = (id: number) => book(id, {}); const attention = (id: number, over: Partial = {}) => 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', () => { diff --git a/src/web/bookstate.ts b/src/web/bookstate.ts index e414397..f1d8c51 100644 --- a/src/web/bookstate.ts +++ b/src/web/bookstate.ts @@ -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})`; +} diff --git a/src/web/components/BookRow.tsx b/src/web/components/BookRow.tsx index c2c8357..02dcc7d 100644 --- a/src/web/components/BookRow.tsx +++ b/src/web/components/BookRow.tsx @@ -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
- {kind === 'attention' ? : null} + {kind === 'attention' ? <> : null} diff --git a/src/web/components/Editor.tsx b/src/web/components/Editor.tsx index eb97b52..680079c 100644 --- a/src/web/components/Editor.tsx +++ b/src/web/components/Editor.tsx @@ -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(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 - {busy ?

Searching…

: null} + {busy ? ( +

{waiting > 1 ? `Waiting for Open Library… (try ${waiting})` : 'Searching…'} + {waiting > 1 ? <> : null}

+ ) : null} {message ?

{message}

: null} {open ? : null} diff --git a/src/web/components/LookUpAgain.tsx b/src/web/components/LookUpAgain.tsx new file mode 100644 index 0000000..aa2eed2 --- /dev/null +++ b/src/web/components/LookUpAgain.tsx @@ -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 ; +} diff --git a/src/web/components/StateMark.tsx b/src/web/components/StateMark.tsx index f3015cd..8d3786e 100644 --- a/src/web/components/StateMark.tsx +++ b/src/web/components/StateMark.tsx @@ -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 ; } -function LookingText({ book, note }: { book: Book; note: string | null }) { +function LookingText({ book, retry }: { book: Book; retry: LookupRetry | null }) { const now = useNow(true); return ( {LABEL.looking} {elapsedText(now - lookupStartedAt(book))} - {note ? · {note} : null} + {retry ? · {retryText(retry, retryReceivedAt(book), now)} : null} ); } @@ -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 ; + if (s.kind === 'looking') return ; if (s.kind === 'attention') return {LABEL.attention} · {s.reason}; return null; } diff --git a/src/web/live.ts b/src/web/live.ts index ea695a6..57cf93e 100644 --- a/src/web/live.ts +++ b/src/web/live.ts @@ -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(); +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. */ diff --git a/src/web/patient.test.ts b/src/web/patient.test.ts new file mode 100644 index 0000000..5bb62e3 --- /dev/null +++ b/src/web/patient.test.ts @@ -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); +}); diff --git a/src/web/patient.ts b/src/web/patient.ts new file mode 100644 index 0000000..d87ce48 --- /dev/null +++ b/src/web/patient.ts @@ -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 { + 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; sleep?: (ms: number, s: AbortSignal) => Promise } = {}, +): Promise { + 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); + } + } +} diff --git a/src/web/views/Entry.tsx b/src/web/views/Entry.tsx index d4bc5cc..5a302d0 100644 --- a/src/web/views/Entry.tsx +++ b/src/web/views/Entry.tsx @@ -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 { seq.current++; setResults(null); setActive(-1); setSearching(false); }; + const stop = useRef(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 { setText(e.currentTarget.value); setMessage(''); if (open || searching) close(); }} />

- {message || (searching ? <> Searching… : 'Also takes an LCCN, such as 88005934.')} + {message || (searching ? ( + <> {waiting > 1 ? `Waiting for Open Library… (try ${waiting})` : 'Searching…'} + {waiting > 1 ? <> : null} + ) : 'Also takes an LCCN, such as 88005934.')}

{open ? (
diff --git a/src/web/views/LastScan.tsx b/src/web/views/LastScan.tsx index d176cca..78c6017 100644 --- a/src/web/views/LastScan.tsx +++ b/src/web/views/LastScan.tsx @@ -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 }) { <> + ) : null}