Files
booksorter/src/server/jobs.ts
T
swaitsandClaude Fable 5.2 3208d4f19c Add property tests, an old-database test and a live lookup check
The queue test runs random sequences of enqueue, look up again, cancel,
failure, time and restart. It found a book left pending for ever when
Look up again landed on a book already queued for its weekly re-check;
that lookup now counts as a real one.

Also: the three-frame camera rule against an independent model, a
pre-looked_up_at database opening intact, a script that checks nine
books against the live catalogues, and the sisi contract naming them.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-22 19:55:31 -07:00

408 lines
20 KiB
TypeScript

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;
/** A book with no number, or only an approximate one, is asked about again at the next start once this old. */
export const RECHECK_AFTER_MS = 7 * 24 * 60 * 60 * 1000;
/** The most digits of an ISBN that may differ for a book already here to be named as the likely original of a misread. */
export const MISREAD_MAX_DIFF = 3;
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.
*/
export const TAIL_RULES_VERSION = 2;
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; recheck?: 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, and
* books with no number or an approximate one that were last looked up over 7 days ago are asked about again.
* A hand-entered number is never touched; a recheck never takes a number away or swaps one guess for another.
*/
resume(): void;
/**
* Backfill, for books made before the hierarchy tail existed: look up only the tail (nothing else about the book
* changes). Books that cannot have one get [] at once; a temporary failure leaves NULL for the next start.
*/
resumeTails(): void;
/**
* Backfill, for books made before the edition statement was collected: look up only the edition (nothing else about
* the book changes, and a hand-typed edition is never touched: only NULL rows are filled). A book with neither ISBN
* nor LCCN gets '' at once; a temporary failure leaves NULL for the next start.
*/
resumeEditions(): void;
idle(): Promise<void>;
}
// TemporaryError lives in resolve/resolver.ts; match by class name unless the caller injects a test.
function defaultIsTemporary(e: unknown): boolean {
for (let p = e != null && typeof e === 'object' ? Object.getPrototypeOf(e) : null; p; p = Object.getPrototypeOf(p)) {
if (p.constructor?.name === 'TemporaryError') return true;
}
return false;
}
/** 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';
}
/** How many of the 13 digits differ; null when either is not 13 digits. */
function isbnDistance(a: string, b: string): number | null {
if (a.length !== 13 || b.length !== 13) return null;
let n = 0;
for (let i = 0; i < 13; i++) if (a[i] !== b[i]) n++;
return n;
}
export function createJobs(deps: {
db: Db; resolver: ResolverLike; onChange: (book: Book) => void;
/** The tail and edition backfills' schedule (they give up until the next start). */
retryDelaysMs?: number[];
/** Wait before a lookup's `attempt`th retry. Lookups retry for as long as the book is pending. */
backoff?: (attempt: number, retryAfterMs?: number) => number;
now?: () => number;
isTemporary?: (e: unknown) => boolean;
log?: (line: string) => void;
}): Jobs {
const { db, resolver, onChange } = deps;
const delays = deps.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
const backoff = deps.backoff ?? backoffMs;
const now = deps.now ?? Date.now;
const isTemporary = deps.isTemporary ?? defaultIsTemporary;
const log = deps.log ?? ((line: string) => console.log(line));
const queue: number[] = [];
const queued = new Set<number>();
const attempts = new Map<number, number>();
const fresh = new Set<number>();
// Books asked about again at start although they are not pending: their lookup must not disturb what they have.
const rechecks = new Set<number>();
// What each pending lookup has been definitively told so far (see jobMemo): a retry asks only for the rest.
const memos = new Map<number, Map<string, string>>();
// The lookup being attempted now, and the books asked for again meanwhile (true: "fresh"): they run once more after.
let current: number | null = null;
const again = new Map<number, boolean>();
// Books waiting for a retry: they hold no worker; a timer puts them back in the queue.
const waiting = new Map<number, ReturnType<typeof setTimeout>>();
// The tail backfill queues behind real lookups, and retries on its own timers.
const tailQueue: number[] = [];
const tailAttempts = new Map<number, number>();
const editionQueue: number[] = [];
const editionAttempts = new Map<number, number>();
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] = {};
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);
}
/** Everything remembered about a lookup that has ended (or been dropped). */
function forget(id: number): void {
attempts.delete(id); fresh.delete(id); rechecks.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(() => {
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' && !rechecks.has(id))) { forget(id); return; }
// A book that was made pending meanwhile ("Look up again") is a real lookup, not a recheck: it must end resolved or needs-attention.
const recheck = rechecks.has(id) && book.status !== 'pending';
const n = attempts.get(id) ?? 0;
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();
let similar = '';
const took = () => `${Date.now() - started} ms`;
const memo = memos.get(id) ?? new Map<string, string>();
memos.set(id, memo);
// Asking again now: the page stops counting down and says so.
if (n > 0) { const r = book.retry; if (r) { db.setRetry(id, { source: r.source, attempt: r.attempt, nextAt: null }); emit(id, {}); } }
try {
const wasFresh = fresh.has(id);
const res = await 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);
const dewey = res.dewey ?? cur.dewey ?? undefined;
const tail: Parameters<Db['updateBook']>[1] = res.tail !== undefined && res.tail !== null ? { hierarchyTail: res.tail } : {};
// The edition: a normal lookup fills only a book not looked up yet (NULL); "Look up again" replaces it with
// what the catalogue says now, but never erases a value with "none".
if (res.edition !== undefined && res.edition !== null) {
if (cur.edition === null) tail.edition = res.edition;
else if (wasFresh && res.edition !== '') tail.edition = res.edition;
}
const lookedUpAt = new Date(now()).toISOString();
// A recheck of a book that has an approximate number takes nothing away and swaps one guess for another never:
// it only changes the book when the catalogues now give an exact number (or the book had none).
const keepsOwn = recheck && !!cur.callNumber && (!res.callNumber || res.confidence !== 'exact');
if (cur.manualOverride) {
emit(id, { dewey, lookedUpAt, ...(cur.hierarchyTail === null ? { hierarchyTail: [] } : {}), ...(tail.edition !== undefined ? { edition: tail.edition } : {}) });
log(`[lookup] ${label}: kept the hand-entered call number (${took()})`);
} else if (keepsOwn) {
emit(id, { lookedUpAt });
log(`[lookup] ${label}: looked up again, nothing better than ${cur.callNumber} (${took()})`);
} else if (res.callNumber) {
emit(id, {
callNumber: res.callNumber, sortKey: res.sortKey, confidence: res.confidence,
source: res.source, dewey, status: 'resolved', attentionReason: null, lookedUpAt, ...tail,
});
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.
let reason = res.reason ?? 'No Library of Congress number found';
if (!res.meta && cur.isbn13) {
// No catalogue has this ISBN at all: a book already here with nearly the same digits is the likely original.
let best: { book: Book; d: number } | null = null;
for (const o of db.listBooks()) {
const d = o.id !== id && o.isbn13 ? isbnDistance(cur.isbn13, o.isbn13) : null;
if (d !== null && d <= MISREAD_MAX_DIFF && (!best || d < best.d)) best = { book: o, d };
}
if (best) reason = `No catalogue has this ISBN. It may be a misread of ${best.book.title} (${best.book.isbn13}), which is already here.`;
}
emit(id, { dewey, status: 'needs_attention', attentionReason: reason, lookedUpAt, ...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)) {
// 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 = 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()})`);
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;
}
forget(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 });
}
}
}
async function backfillTail(id: number): Promise<void> {
const book = db.getBook(id);
if (!book || book.hierarchyTail !== null || book.status === 'pending') { tailAttempts.delete(id); return; }
const label = book.isbn13 ?? book.lccn ?? book.title;
// Only the tail column is ever written here: the number, sort key, confidence, source, status, queue flag and
// printed date stay as they are.
if (book.manualOverride || book.source === 'manual') {
tailAttempts.delete(id);
emit(id, { hierarchyTail: [] });
return;
}
const n = tailAttempts.get(id) ?? 0;
try {
const tail = await resolver.tail({
...(book.isbn13 ? { isbn13: book.isbn13 } : {}), ...(book.lccn ? { lccn: book.lccn } : {}),
title: book.title, ...(book.authors[0] ? { author: book.authors[0] } : {}),
...(book.subtitle ? { subtitle: book.subtitle } : {}), subjects: book.subjects, callNumber: book.callNumber,
});
tailAttempts.delete(id);
emit(id, { hierarchyTail: tail });
log(`[tail] ${label}: ${tail.length ? tail.join(' / ') : 'no usable subject heading'}`);
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
if (isTemporary(e) && n < delays.length) {
tailAttempts.set(id, n + 1);
const delay = delays[n]!;
log(`[tail] ${label}: ${message}; trying again in ${Math.round(delay / 1000)} s`);
const t = setTimeout(() => { waiting.delete(-id); tailQueue.push(id); start(); notify(); }, delay);
if (idlers === 0) t.unref();
waiting.set(-id, t); // a negative key keeps tail retries apart from lookup retries
return;
}
tailAttempts.delete(id);
log(`[tail] ${label}: left for the next start, ${message}`); // NULL stays: the next start tries again
}
}
async function backfillEdition(id: number): Promise<void> {
const book = db.getBook(id);
if (!book || book.edition !== null || book.status === 'pending') { editionAttempts.delete(id); return; }
const label = book.isbn13 ?? book.lccn ?? book.title;
// Only the edition column is ever written here.
if (!book.isbn13 && !book.lccn) { editionAttempts.delete(id); emit(id, { edition: '' }); return; }
const n = editionAttempts.get(id) ?? 0;
try {
const edition = await resolver.edition({ isbn13: book.isbn13, lccn: book.lccn });
editionAttempts.delete(id);
// The row may have been edited by hand while the catalogue was asked: only fill it if it is still NULL.
if (db.getBook(id)?.edition === null) emit(id, { edition });
log(`[edition] ${label}: ${edition || 'none'}`);
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
if (isTemporary(e) && n < delays.length) {
editionAttempts.set(id, n + 1);
const delay = delays[n]!;
log(`[edition] ${label}: ${message}; trying again in ${Math.round(delay / 1000)} s`);
const t = setTimeout(() => { waiting.delete(-1_000_000_000 - id); editionQueue.push(id); start(); notify(); }, delay);
if (idlers === 0) t.unref();
waiting.set(-1_000_000_000 - id, t);
return;
}
editionAttempts.delete(id);
log(`[edition] ${label}: left for the next start, ${message}`); // NULL stays: the next start tries again
}
}
async function drain(): Promise<void> {
while (queue.length || tailQueue.length || editionQueue.length) {
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 */ }
} else {
const id = editionQueue.shift()!;
try { await backfillEdition(id); } catch { /* ditto */ }
}
}
}
function start(): void {
if (running) return;
running = drain().finally(() => { running = null; if (queue.length || tailQueue.length || editionQueue.length) start(); notify(); });
}
return {
enqueue(id, opts) {
if (opts?.recheck) rechecks.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); 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();
},
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);
const stale = db.listRecheckIds(new Date(now() - RECHECK_AFTER_MS).toISOString());
if (stale.length > 0) log(`[lookup] ${stale.length} book(s) with no number or an approximate one will be looked up again`);
for (const id of stale) this.enqueue(id, { recheck: true });
},
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`);
for (const id of db.listTailMissingIds()) if (!tailQueue.includes(id)) tailQueue.push(id);
start();
},
resumeEditions() {
for (const id of db.listEditionMissingIds()) if (!editionQueue.includes(id)) editionQueue.push(id);
start();
},
async idle() {
idlers++;
for (const t of waiting.values()) t.ref();
try {
while (running || queue.length || tailQueue.length || editionQueue.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();
}
},
};
}