Rework scan screen, make lookups non-blocking, fix review findings

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-18 10:19:32 -07:00
1 parent 468cafc6db
commit b5defb4e4f
46 files changed
+1957 -406

No files matched your search

+104 -58
View File
@@ -2,6 +2,8 @@ import type { Book, BookMeta, ResolveInput } from '../shared/types.ts';
import type { Db } from './db.ts';
import type { Resolver } from './resolve/resolver.ts';
export const DEFAULT_RETRY_DELAYS_MS = [5_000, 30_000, 120_000];
export type ResolverLike = Resolver;
export interface Jobs { enqueue(id: number): void; resume(): void; idle(): Promise<void> }
@@ -14,86 +16,118 @@ function defaultIsTemporary(e: unknown): boolean {
return false;
}
function sleep(ms: number): Promise<void> {
if (ms <= 0) return Promise.resolve();
return new Promise((resolve) => { setTimeout(resolve, ms).unref(); });
/** 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'
: /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;
log?: (line: string) => void;
}): Jobs {
const { db, resolver, onChange } = deps;
const delays = deps.retryDelaysMs ?? [30000, 120000, 600000];
const delays = deps.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
const isTemporary = deps.isTemporary ?? defaultIsTemporary;
const log = deps.log ?? ((line: string) => console.log(line));
const queue: number[] = [];
const queued = new Set<number>();
const attempts = new Map<number, number>();
// Books waiting for a retry: they hold no worker; a timer puts them back in the queue.
const waiting = new Map<number, ReturnType<typeof setTimeout>>();
let running: Promise<void> | null = null;
let idlers = 0;
let wake: (() => void)[] = [];
const notify = () => { const w = wake; wake = []; for (const f of w) f(); };
function emit(id: number, patch: Parameters<Db['updateBook']>[1]): void {
const b = db.updateBook(id, patch);
if (b) onChange(b);
}
/** Lookup metadata only fills what is empty; the placeholder title (the ISBN or LCCN) counts as empty. */
function applyMeta(id: number, meta: BookMeta): void {
const cur = db.getBook(id);
if (!cur) return;
const patch: Parameters<Db['updateBook']>[1] = {
subtitle: meta.subtitle ?? cur.subtitle ?? undefined,
publisher: meta.publisher ?? cur.publisher ?? undefined,
year: meta.year ?? cur.year ?? undefined,
subjects: meta.subjects.length ? meta.subjects : cur.subjects,
lccn: meta.lccn ?? cur.lccn ?? undefined,
};
// A hand-edited book keeps the title and authors the user typed.
if (!cur.manualOverride) {
if (meta.title) patch.title = meta.title;
if (meta.authors.length) patch.authors = meta.authors;
}
emit(id, patch);
const patch: Parameters<Db['updateBook']>[1] = {};
if (meta.title && (cur.title === cur.isbn13 || cur.title === cur.lccn || !cur.title.trim())) patch.title = meta.title;
if (meta.authors.length && cur.authors.length === 0) patch.authors = meta.authors;
if (meta.subtitle && !cur.subtitle) patch.subtitle = meta.subtitle;
if (meta.publisher && !cur.publisher) patch.publisher = meta.publisher;
if (meta.year && !cur.year) patch.year = meta.year;
if (meta.subjects.length && cur.subjects.length === 0) patch.subjects = meta.subjects;
if (meta.lccn && !cur.lccn) patch.lccn = meta.lccn;
if (Object.keys(patch).length) emit(id, patch);
}
async function lookup(id: number): Promise<void> {
for (let attempt = 0; ; attempt++) {
const book = db.getBook(id);
if (!book || book.status !== 'pending') return;
const input: ResolveInput = {};
if (book.isbn13) input.isbn13 = book.isbn13;
if (book.lccn) input.lccn = book.lccn;
if (!book.isbn13) {
input.title = book.title;
if (book.authors[0]) input.author = book.authors[0];
function schedule(id: number, delayMs: number): void {
if (delayMs <= 0) { queued.add(id); queue.push(id); start(); return; }
const t = setTimeout(() => {
waiting.delete(id);
queued.add(id); queue.push(id);
start();
notify();
}, delayMs);
// Do not hold the process open for a retry, unless a test is awaiting idle().
if (idlers === 0) t.unref();
waiting.set(id, t);
}
async function attempt(id: number): Promise<void> {
const book = db.getBook(id);
if (!book || book.status !== 'pending') { attempts.delete(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;
if (!book.isbn13) {
input.title = book.title;
if (book.authors[0]) input.author = book.authors[0];
}
if (book.year) input.year = book.year;
const label = book.isbn13 ?? book.title;
const started = Date.now();
const took = () => `${Date.now() - started} ms`;
try {
const res = await resolver.resolve(input, { onMeta: (m) => applyMeta(id, m), tolerateLocFailure: final });
attempts.delete(id);
const cur = db.getBook(id);
if (!cur) return;
if (res.meta) applyMeta(id, res.meta);
const dewey = res.dewey ?? cur.dewey ?? undefined;
if (cur.manualOverride) {
emit(id, { dewey });
log(`[lookup] ${label}: kept the hand-entered call number (${took()})`);
} else if (res.callNumber) {
emit(id, {
callNumber: res.callNumber, sortKey: res.sortKey, confidence: res.confidence,
source: res.source, dewey, status: 'resolved', attentionReason: null,
});
log(`[lookup] ${label}: ${res.callNumber} (${res.source}) in ${took()}`);
} else {
const reason = res.reason ?? 'No Library of Congress number found';
emit(id, { dewey, status: 'needs_attention', attentionReason: reason });
log(`[lookup] ${label}: no call number, ${reason} in ${took()}`);
}
if (book.year) input.year = book.year;
try {
const res = await resolver.resolve(input, { onMeta: (m) => applyMeta(id, m) });
const cur = db.getBook(id);
if (!cur) return;
if (res.meta) applyMeta(id, res.meta);
const dewey = res.dewey ?? cur.dewey ?? undefined;
if (cur.manualOverride) {
emit(id, { dewey });
} else if (res.callNumber) {
emit(id, {
callNumber: res.callNumber, sortKey: res.sortKey, confidence: res.confidence,
source: res.source, dewey, status: 'resolved', attentionReason: null,
});
} else {
emit(id, { dewey, status: 'needs_attention', attentionReason: res.reason ?? 'No Library of Congress number found' });
}
return;
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
if (isTemporary(e) && attempt < delays.length) {
await sleep(delays[attempt]!);
continue;
}
const cur = db.getBook(id);
if (cur && !cur.manualOverride) {
emit(id, { status: 'needs_attention', attentionReason: 'Lookup failed: ' + message });
}
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
if (isTemporary(e) && !final) {
attempts.set(id, n + 1);
const delay = delays[n]!;
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);
return;
}
attempts.delete(id);
log(`[lookup] ${label}: failed, ${message} in ${took()}`);
const cur = db.getBook(id);
if (cur && !cur.manualOverride) {
emit(id, { status: 'needs_attention', attentionReason: 'Lookup failed: ' + message });
}
}
}
@@ -101,17 +135,20 @@ export function createJobs(deps: {
while (queue.length) {
const id = queue.shift()!;
queued.delete(id);
try { await lookup(id); } catch { /* a failure on one book must not stop the queue */ }
try { await attempt(id); } catch { /* a failure on one book must not stop the queue */ }
}
}
function start(): void {
if (running) return;
running = drain().finally(() => { running = null; if (queue.length) start(); });
running = drain().finally(() => { running = null; if (queue.length) start(); notify(); });
}
return {
enqueue(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 (queued.has(id)) return;
queued.add(id);
queue.push(id);
@@ -119,7 +156,16 @@ export function createJobs(deps: {
},
resume() { for (const id of db.listPendingIds()) this.enqueue(id); },
async idle() {
while (running || queue.length) await running;
idlers++;
for (const t of waiting.values()) t.ref();
try {
while (running || queue.length || waiting.size) {
if (running) await running;
else await new Promise<void>((r) => { wake.push(r); });
}
} finally {
if (--idlers === 0) for (const t of waiting.values()) t.unref();
}
},
};
}