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 type { ResolverLike } from './jobs.ts'; import type { NewBook } from './db.ts'; import type { Book, Resolution } from '../shared/types.ts'; class TemporaryError extends Error {} const found: Resolution = { meta: { title: 'The Rust Book', authors: ['Klabnik, Steve'], subjects: ['Rust'], year: 2018, publisher: 'No Starch' }, callNumber: 'QA76.73.R87 K53 2018', sortKey: 'QA 76', confidence: 'exact', source: 'loc-isbn', dewey: '005.1', reason: null, }; function setup(resolve: ResolverLike['resolve'], delays = [0, 0, 0]) { const db = openDb(':memory:'); 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) }); return { db, jobs, changes, logs }; } test('success resolves the book and emits changes', async () => { const { db, jobs, changes } = setup(async (_i, o) => { o?.onMeta?.(found.meta!); return found; }); const { book } = db.insertPending({ isbn13: '9781593278281', title: '9781593278281' }); jobs.enqueue(book.id); await jobs.idle(); const b = db.getBook(book.id)!; assert.equal(b.status, 'resolved'); assert.equal(b.title, 'The Rust Book'); assert.equal(b.callNumber, 'QA76.73.R87 K53 2018'); assert.equal(b.confidence, 'exact'); assert.equal(b.dewey, '005.1'); assert.ok(changes.length >= 2); }); test('no call number -> needs_attention with reason, metadata kept', async () => { const { db, jobs } = setup(async () => ({ ...found, callNumber: null, sortKey: null, confidence: null, source: null, reason: 'No Library of Congress number found' })); const { book } = db.insertPending({ isbn13: '9781593278281', title: '9781593278281' }); jobs.enqueue(book.id); await jobs.idle(); const b = db.getBook(book.id)!; assert.equal(b.status, 'needs_attention'); assert.equal(b.attentionReason, 'No Library of Congress number found'); assert.equal(b.title, 'The Rust Book'); }); test('no metadata -> needs_attention', async () => { const reason = 'Not found in Open Library or the Library of Congress'; const { db, jobs } = setup(async () => ({ meta: null, callNumber: null, sortKey: null, confidence: null, source: null, dewey: null, reason })); const { book } = db.insertPending({ isbn13: '9781593278281', title: '9781593278281' }); jobs.enqueue(book.id); await jobs.idle(); assert.equal(db.getBook(book.id)!.attentionReason, reason); assert.equal(db.getBook(book.id)!.title, '9781593278281'); }); test('temporary failures retry then succeed', async () => { let calls = 0; const { db, jobs } = setup(async () => { if (++calls < 3) throw new TemporaryError('blocked'); return found; }); const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); jobs.enqueue(book.id); await jobs.idle(); assert.equal(calls, 3); assert.equal(db.getBook(book.id)!.status, 'resolved'); }); test('failure after all retries -> needs_attention', async () => { let calls = 0; const { db, jobs } = setup(async () => { calls++; throw new TemporaryError('blocked'); }); 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'); }); test('a non-temporary error never loses the book or stops the queue', async () => { let n = 0; const { db, jobs } = setup(async () => { if (n++ === 0) throw new Error('boom'); return found; }); const a = db.insertPending({ isbn13: '9781593278281', title: 'a' }).book; const b = db.insertPending({ isbn13: '9780201835953', title: 'b' }).book; jobs.enqueue(a.id); jobs.enqueue(b.id); await jobs.idle(); assert.equal(db.getBook(a.id)!.attentionReason, 'Lookup failed: boom'); assert.equal(db.getBook(b.id)!.status, 'resolved'); }); test('manual override keeps its call number', async () => { const { db, jobs } = setup(async () => found); const { book } = db.insertPending({ isbn13: '9781593278281', title: 'Mine', callNumber: 'PS3558.E63 D8 2005', sortKey: 'PS', confidence: 'manual', source: 'manual', manualOverride: true }); jobs.enqueue(book.id); await jobs.idle(); const b = db.getBook(book.id)!; assert.equal(b.callNumber, 'PS3558.E63 D8 2005'); assert.equal(b.confidence, 'manual'); assert.equal(b.title, 'Mine'); }); test('manual override set while pending is not clobbered', async () => { const { db, jobs } = setup(async () => found); const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); jobs.enqueue(book.id); db.updateBook(book.id, { manualOverride: true, callNumber: 'PS3558', status: 'resolved', confidence: 'manual' }); await jobs.idle(); const b = db.getBook(book.id)!; assert.equal(b.callNumber, 'PS3558'); assert.equal(b.status, 'resolved'); }); test('one job at a time, and resume() picks up pending rows', async () => { let active = 0, peak = 0; const { db, jobs } = setup(async () => { peak = Math.max(peak, ++active); await new Promise((r) => setImmediate(r)); active--; return found; }); const ids = ['9781593278281', '9780201835953', '9780441172719'].map((i) => db.insertPending({ isbn13: i, title: i }).book.id); db.updateBook(ids[2]!, { status: 'resolved' }); jobs.resume(); await jobs.idle(); assert.equal(peak, 1); assert.equal(db.getBook(ids[0]!)!.status, 'resolved'); assert.equal(db.getBook(ids[1]!)!.status, 'resolved'); }); test('deleting a book mid-queue is harmless', async () => { const { db, jobs } = setup(async () => found); const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); jobs.enqueue(book.id); db.deleteBook(book.id); await jobs.idle(); assert.equal(db.getBook(book.id), null); }); test('default retry delays are 5 s, 30 s, 120 s', () => { assert.deepEqual(DEFAULT_RETRY_DELAYS_MS, [5000, 30000, 120000]); }); test('a waiting retry does not block the books behind it', async () => { const order: string[] = []; let aCalls = 0; const { db, jobs } = setup(async (i) => { if (i.isbn13 === '9781593278281' && ++aCalls === 1) throw new TemporaryError('LoC did not answer'); order.push(i.isbn13!); return found; }, [60, 60, 60]); const a = db.insertPending({ isbn13: '9781593278281', title: 'a' }).book; const b = db.insertPending({ isbn13: '9780201835953', title: 'b' }).book; jobs.enqueue(a.id); jobs.enqueue(b.id); await jobs.idle(); assert.deepEqual(order, ['9780201835953', '9781593278281']); 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 () => { 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'); return found; }, [40, 40, 40]); const { book } = db.insertPending({ isbn13: '9781593278281', title: '9781593278281' }); jobs.enqueue(book.id); 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'); await jobs.idle(); const done = db.getBook(book.id)!; assert.equal(done.status, 'resolved'); assert.equal(done.attentionReason, null); }); test('retry timers are unref\'d', async () => { const real = globalThis.setTimeout; const made: ReturnType[] = []; globalThis.setTimeout = ((fn: () => void, ms?: number) => { const t = real(fn, ms); made.push(t); return t; }) as typeof setTimeout; try { const { db, jobs } = setup(async () => { throw new TemporaryError('x'); }, [60_000]); const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); jobs.enqueue(book.id); await new Promise((r) => real(r, 20)); assert.equal(made.length, 1); assert.equal(made[0]!.hasRef(), false); jobs.enqueue(book.id); // cancels the wait; ends the test cleanly } finally { globalThis.setTimeout = real; } }); test('only the final attempt asks the resolver to tolerate LoC failure', async () => { const flags: (boolean | undefined)[] = []; const { db, jobs } = setup(async (_i, o) => { flags.push(o?.tolerateLocFailure); if (flags.length < 4) 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'); }); test('"Look up again" while waiting restarts the retries at once', async () => { let calls = 0; const { db, jobs } = setup(async () => { if (++calls === 1) throw new TemporaryError('x'); return found; }, [60_000]); const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); jobs.enqueue(book.id); await new Promise((r) => setTimeout(r, 15)); assert.equal(db.getBook(book.id)!.status, 'pending'); jobs.enqueue(book.id); await jobs.idle(); assert.equal(db.getBook(book.id)!.status, 'resolved'); }); test('one log line per attempt: ISBN, outcome and elapsed ms', async () => { let calls = 0; const { db, jobs, logs } = setup(async () => { if (++calls === 1) throw new TemporaryError('timed out'); return found; }); const { book } = db.insertPending({ isbn13: '9781593278281', title: 'x' }); jobs.enqueue(book.id); await jobs.idle(); assert.equal(logs.length, 2); assert.match(logs[0]!, /9781593278281.*timed out.*\d+ ms/); assert.match(logs[1]!, /9781593278281.*QA76\.73\.R87 K53 2018 \(loc-isbn\).* in \d+ ms/); const t = setup(async () => ({ ...found, callNumber: null, sortKey: null, confidence: null, source: null, reason: 'No Library of Congress number found' })); const nb = t.db.insertPending({ title: 'Some Title', authors: ['A'] }).book; t.jobs.enqueue(nb.id); await t.jobs.idle(); assert.match(t.logs[0]!, /Some Title.*No Library of Congress number found.*\d+ ms/); }); test('lookup metadata fills empty fields but never overwrites what the user typed', async () => { const { db, jobs } = setup(async (_i, o) => { o?.onMeta?.(found.meta!); return found; }); const typed = db.insertPending({ isbn13: '9781593278281', title: 'My Title', authors: ['Me Myself'], publisher: 'Mine', year: 1999 }).book; const bare = db.insertPending({ isbn13: '9780201835953', title: '9780201835953' }).book; jobs.enqueue(typed.id); jobs.enqueue(bare.id); await jobs.idle(); const t = db.getBook(typed.id)!; assert.deepEqual([t.title, t.authors, t.publisher, t.year], ['My Title', ['Me Myself'], 'Mine', 1999]); assert.deepEqual(t.subjects, ['Rust']); // was empty, so filled const b = db.getBook(bare.id)!; assert.deepEqual([b.title, b.authors, b.publisher, b.year], ['The Rust Book', ['Klabnik, Steve'], 'No Starch', 2018]); }); test('an LCCN placeholder title counts as empty', async () => { const { db, jobs } = setup(async (_i, o) => { o?.onMeta?.(found.meta!); return found; }); const { book } = db.insertPending({ lccn: '88005934', title: '88005934' }); jobs.enqueue(book.id); await jobs.idle(); assert.equal(db.getBook(book.id)!.title, 'The Rust Book'); }); function tailBook(db: ReturnType, over: Partial) { return db.insertPending({ status: 'resolved', callNumber: 'GV199.42.U82 U564 2024', sortKey: 'GV 0199.42 U82', confidence: 'exact', source: 'loc-isbn', inQueue: false, title: 'T', ...over, }).book; } test('lookup stores the tail; the tail stays unknown (NULL) when the catalogue could not be asked', async () => { const a = setup(async () => ({ ...found, tail: ['Utah'] })); const x = a.db.insertPending({ isbn13: '9781593278281', title: '9781593278281' }).book; a.jobs.enqueue(x.id); await a.jobs.idle(); assert.deepEqual(a.db.getBook(x.id)!.hierarchyTail, ['Utah']); const b = setup(async () => ({ ...found, tail: null })); const y = b.db.insertPending({ isbn13: '9781593278281', title: '9781593278281' }).book; b.jobs.enqueue(y.id); await b.jobs.idle(); assert.equal(b.db.getBook(y.id)!.status, 'resolved'); assert.equal(b.db.getBook(y.id)!.hierarchyTail, null); }); test('tail backfill changes only the tail, emits the update, and never touches status or the number', async () => { const calls: unknown[] = []; const { db, changes } = setup(async () => found); const resolver: ResolverLike = { 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 printed = '2026-02-03T00:00:00.000Z'; const b = tailBook(db, { isbn13: '9781593278281' }); db.updateBook(b.id, { printedAt: printed, inQueue: true, confidence: 'approximate' }); const before = db.getBook(b.id)!; j.resumeTails(); await j.idle(); const after = db.getBook(b.id)!; assert.deepEqual(after.hierarchyTail, ['Utah', 'Uinta Mountains']); for (const k of ['callNumber', 'sortKey', 'confidence', 'source', 'status', 'attentionReason', 'inQueue', 'printedAt', 'manualOverride'] as const) { assert.deepEqual(after[k], before[k], k); } assert.ok(changes.some((c) => c.id === b.id && c.hierarchyTail !== null), 'book-updated event'); assert.equal(calls.length, 1); }); test('tail backfill: hand entries get [] without asking; every other book is asked, whatever its source', async () => { 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 none = tailBook(db, { title: 'no ids' }); const manual = tailBook(db, { isbn13: '9780000000002', manualOverride: true, source: 'manual' }); const similar = tailBook(db, { isbn13: '9780000000019', source: 'similar' }); const byHand = tailBook(db, { lccn: '2012047313', source: 'manual' }); const pending = db.insertPending({ isbn13: '9780000000026', title: 'p' }).book; // status pending: the lookup's job jobs.resumeTails(); await jobs.idle(); for (const b of [manual, byHand]) assert.deepEqual(db.getBook(b.id)!.hierarchyTail, [], b.title); for (const b of [none, similar]) assert.deepEqual(db.getBook(b.id)!.hierarchyTail, ['X'], b.title); assert.equal(db.getBook(pending.id)!.hierarchyTail, null); assert.equal(asked.length, 2); }); test('tail rules version: books with [] are checked again once, hand entries and non-empty tails are left alone', async () => { const { db } = setup(async () => found); const asked: string[] = []; const resolver: ResolverLike = { 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 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' }); const before = db.getBook(empty.id)!; const first = mk(); first.resumeTails(); await first.idle(); assert.deepEqual(asked, ['9780000000002']); assert.deepEqual(db.getBook(empty.id)!.hierarchyTail, ['Utah']); assert.deepEqual(db.getBook(has.id)!.hierarchyTail, ['Nevada']); assert.deepEqual(db.getBook(hand.id)!.hierarchyTail, []); for (const k of ['callNumber', 'sortKey', 'confidence', 'source', 'status', 'inQueue', 'printedAt'] as const) assert.deepEqual(db.getBook(empty.id)![k], before[k], k); // A later start does not ask again, even for a book that is [] again. db.updateBook(empty.id, { hierarchyTail: [] }); const second = mk(); second.resumeTails(); await second.idle(); assert.equal(asked.length, 1); assert.deepEqual(db.getBook(empty.id)!.hierarchyTail, []); }); test('tail backfill: a temporary failure is retried, then left NULL for the next start; a missing record stores []', async () => { const { db } = setup(async () => found); let n = 0; const logs: string[] = []; const resolver: ResolverLike = { 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 busy = tailBook(db, { isbn13: '9780000000002' }); const empty = tailBook(db, { isbn13: '9780000000019' }); jobs.resumeTails(); await jobs.idle(); assert.equal(db.getBook(busy.id)!.hierarchyTail, null); assert.equal(db.getBook(busy.id)!.status, 'resolved'); assert.deepEqual(db.getBook(empty.id)!.hierarchyTail, []); assert.equal(n, 4); // busy: first try and two retries; empty: once assert.ok(logs.some((l) => l.includes('left for the next start'))); }); // The edition backfill. function editionSetup(edition: ResolverLike['edition']) { const { db } = setup(async () => found); 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 }); return { db, jobs, changes, logs }; } test('a lookup sets the edition of a book not looked up yet; "look up again" replaces it, but never with nothing', async () => { const a = setup(async () => ({ ...found, edition: 'Third edition' })); const x = a.db.insertPending({ isbn13: '9781593278281', title: '9781593278281' }).book; a.jobs.enqueue(x.id); await a.jobs.idle(); assert.equal(a.db.getBook(x.id)!.edition, 'Third edition'); // A normal lookup leaves a value (for example one typed by hand) alone. a.db.updateBook(x.id, { edition: 'By hand', status: 'pending' }); a.jobs.enqueue(x.id); await a.jobs.idle(); assert.equal(a.db.getBook(x.id)!.edition, 'By hand'); a.db.updateBook(x.id, { status: 'pending' }); a.jobs.enqueue(x.id, { fresh: true }); await a.jobs.idle(); assert.equal(a.db.getBook(x.id)!.edition, 'Third edition'); const b = setup(async () => ({ ...found, edition: null })); const y = b.db.insertPending({ isbn13: '9781593278281', title: '9781593278281' }).book; b.jobs.enqueue(y.id); await b.jobs.idle(); assert.equal(b.db.getBook(y.id)!.status, 'resolved'); assert.equal(b.db.getBook(y.id)!.edition, null); // unknown: the backfill asks later }); test('edition backfill fills only NULL rows and changes nothing else about the book', async () => { const asked: unknown[] = []; const { db, jobs, changes } = editionSetup(async (i) => { asked.push(i); return 'Third edition'; }); const printed = '2026-02-03T00:00:00.000Z'; const b = tailBook(db, { isbn13: '9781593278281', hierarchyTail: ['Utah'] }); db.updateBook(b.id, { printedAt: printed, inQueue: true, confidence: 'approximate' }); const typed = tailBook(db, { isbn13: '9780000000002', edition: 'By hand' }); const none = tailBook(db, { isbn13: '9780000000019', edition: '' }); const noIds = tailBook(db, { title: 'no ids' }); const pending = db.insertPending({ isbn13: '9780000000026', title: 'p' }).book; const before = db.getBook(b.id)!; jobs.resumeEditions(); await jobs.idle(); const after = db.getBook(b.id)!; assert.equal(after.edition, 'Third edition'); for (const k of ['callNumber', 'sortKey', 'confidence', 'source', 'status', 'attentionReason', 'inQueue', 'printedAt', 'manualOverride', 'hierarchyTail', 'title', 'publisher', 'year'] as const) { assert.deepEqual(after[k], before[k], k); } assert.equal(db.getBook(typed.id)!.edition, 'By hand'); assert.equal(db.getBook(none.id)!.edition, ''); assert.equal(db.getBook(noIds.id)!.edition, ''); // neither ISBN nor LCCN: nothing to ask assert.equal(db.getBook(pending.id)!.edition, null); // the lookup will set it assert.deepEqual(asked, [{ isbn13: '9781593278281', lccn: null }]); assert.ok(changes.some((c) => c.id === b.id)); }); test('edition backfill: a network failure leaves NULL (retried next start), and a later answer is not overwritten if typed meanwhile', async () => { let down = true; const { db, jobs, logs } = editionSetup(async () => { if (down) throw new TemporaryError('Library of Congress timed out'); return 'Second edition'; }); const b = tailBook(db, { isbn13: '9781593278281' }); jobs.resumeEditions(); await jobs.idle(); assert.equal(db.getBook(b.id)!.edition, null); assert.ok(logs.some((l) => l.includes('left for the next start'))); assert.deepEqual(db.listEditionMissingIds(), [b.id]); down = false; jobs.resumeEditions(); await jobs.idle(); assert.equal(db.getBook(b.id)!.edition, 'Second edition'); });