diff --git a/scripts/browser-check.ts b/scripts/browser-check.ts index 1d2a987..1722bfc 100644 --- a/scripts/browser-check.ts +++ b/scripts/browser-check.ts @@ -1,155 +1,424 @@ -// Drives Firefox against a running Booksorter server. Usage: node scripts/browser-check.ts [baseUrl] -// Env: SHOTS= to save screenshots, ISBN= to use another already-resolved ISBN. -import { firefox } from 'playwright'; +// Drives Chromium (the browser the app is used in) and Firefox against a running Booksorter server. +// Usage: node scripts/browser-check.ts [baseUrl] (point the server at a scratch database) +// npx playwright install chromium firefox # once +// PORT=4323 BOOKSORTER_DB=/tmp/scratch.db npm start # in another terminal +// Env: SHOTS= saves 1280px dark-mode screenshots; ISBN= uses another already-resolved book. +// The camera is Chromium's fake camera playing a .y4m video of an EAN-13 barcode that this script renders. +// It adds, removes and re-adds the test book, and invents a few books in the page (never on the server) to +// hold the "looking up" and "needs attention" states still. +import { chromium, firefox } from 'playwright'; +import type { Browser, BrowserContext, Page } from 'playwright'; import { build } from 'esbuild'; -import { mkdirSync } from 'node:fs'; +import { mkdirSync, mkdtempSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { makeBarcodeY4m } from './browser-media.ts'; const base = process.argv[2] ?? 'http://localhost:4321'; +if (new URL(base).port === '4321' && !process.env.ALLOW_4321) { console.error('Refusing to run against port 4321 (the real database). Use a scratch server.'); process.exit(2); } const shots = process.env.SHOTS; if (shots) mkdirSync(shots, { recursive: true }); const ISBN = process.env.ISBN ?? '9781593278281'; +const ISBN2 = '9780201835953'; // used only for invented books, never looked up const root = fileURLToPath(new URL('..', import.meta.url)); +const work = mkdtempSync(join(tmpdir(), 'booksorter-check-')); const failures: string[] = []; const check = (name: string, ok: boolean, detail = '') => { console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ' ' + detail : ''}`); if (!ok) failures.push(name); }; +const norm = (s: string) => s.replace(/\s+/g, ' ').trim(); -// EAN-13 module pattern (95 modules) for a 13-digit string. -function ean13Modules(code: string): string { - const L = ['0001101', '0011001', '0010011', '0111101', '0100011', '0110001', '0101111', '0111011', '0110111', '0001011']; - const R = L.map((p) => [...p].map((b) => (b === '0' ? '1' : '0')).join('')); - const G = R.map((p) => [...p].reverse().join('')); - const parity = ['LLLLLL', 'LLGLGG', 'LLGGLG', 'LLGGGL', 'LGLLGG', 'LGGLLG', 'LGGGLL', 'LGLGLG', 'LGLGGL', 'LGGLGL']; - const d = [...code].map(Number); - let out = '101'; - for (let i = 0; i < 6; i++) out += parity[d[0]][i] === 'L' ? L[d[i + 1]] : G[d[i + 1]]; - out += '01010'; - for (let i = 7; i < 13; i++) out += R[d[i]]; - return out + '101'; +const consoleErrors: string[] = []; +const badRequests: string[] = []; +const foreign: string[] = []; +function watch(page: Page, label: string) { + page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(`${label}: ${m.text()}`); }); + page.on('pageerror', (e) => consoleErrors.push(`${label}: ${e}`)); + page.on('requestfailed', (r) => badRequests.push(`${label}: ${r.url()} ${r.failure()?.errorText}`)); + page.on('response', (r) => { if (r.status() >= 400) badRequests.push(`${label}: ${r.url()} ${r.status()}`); }); + page.on('request', (r) => { + const u = new URL(r.url()); + if (!['localhost', '127.0.0.1'].includes(u.hostname) && !['blob:', 'data:', 'about:'].includes(u.protocol)) foreign.push(r.url()); + }); +} +const shot = async (page: Page, name: string) => { if (shots) await page.screenshot({ path: `${shots}/${name}.png`, fullPage: true }); }; +const section = async (name: string, fn: () => Promise) => { + console.log(`\n# ${name}`); + try { await fn(); } catch (e) { check(`${name}: ran to completion`, false, String(e).split('\n')[0]); } +}; + +const api = (page: Page, path: string, init?: { method?: string; body?: unknown }): Promise => + page.evaluate(async ({ path, init }) => { + const r = await fetch(path, { method: init?.method ?? 'GET', headers: init?.body ? { 'Content-Type': 'application/json' } : undefined, body: init?.body ? JSON.stringify(init.body) : undefined }); + const t = await r.text(); + return t ? JSON.parse(t) : null; + }, { path, init }); + +const removeBook = (page: Page, isbn: string) => page.evaluate(async (isbn) => { + const books = await (await fetch('/api/books?filter=all')).json(); + for (const b of books.filter((x: any) => x.isbn13 === isbn)) await fetch(`/api/books/${b.id}`, { method: 'DELETE' }); +}, isbn); + +const fakeBook = (id: number, over: Record) => ({ + id, isbn13: null, lccn: null, title: `Book ${id}`, subtitle: null, authors: ['A. Writer'], publisher: null, year: null, subjects: [], + callNumber: null, sortKey: null, confidence: null, source: null, dewey: null, status: 'pending', attentionReason: null, + manualOverride: false, inQueue: true, printedAt: null, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), ...over, +}); + +/** Answer POST /api/scan for one ISBN with an invented book instead of asking the server. */ +async function inventScan(page: Page, isbn: string, book: Record) { + await page.route('**/api/scan', async (route) => { + const sent = route.request().postDataJSON(); + if (sent?.isbn === isbn) await route.fulfill({ json: { book, duplicate: false } }); + else await route.fallback(); + }); } -// Bundle scanner.ts (the production module) so the page can call its detector. +const rows = (page: Page) => page.locator('.scan .right li.book'); +const statusLine = (page: Page) => page.getByRole('status').filter({ hasText: /\S/ }).first(); + +// Bundle the production scanner so a page can call its decode functions directly. const bundled = await build({ - stdin: { contents: "export { makeDetector } from './src/web/scanner.ts';", resolveDir: root, loader: 'ts' }, + stdin: { contents: "export * from './src/web/scanner.ts';", resolveDir: root, loader: 'ts' }, bundle: true, format: 'esm', write: false, target: 'es2022', logLevel: 'silent', }); const scannerJs = bundled.outputFiles[0].text.replaceAll('https://fastly.jsdelivr.net/npm/', '/local-only/'); -const browser = await firefox.launch({ +// Videos for the fake camera: a barcode on white at a readable size, a hard (small, soft) one, and an empty page. +const videoOk = join(work, 'barcode.y4m'); +const videoHard = join(work, 'barcode-small.y4m'); +const videoBlank = join(work, 'blank.y4m'); +makeBarcodeY4m(videoOk, { isbn: ISBN, moduleScale: 2.0, frames: 24 }); +makeBarcodeY4m(videoHard, { isbn: ISBN, moduleScale: 1.6, frames: 24 }); +makeBarcodeY4m(videoBlank, { isbn: ISBN, moduleScale: 0.01, frames: 4 }); + +const chromiumFor = (video: string) => chromium.launch({ headless: true, - firefoxUserPrefs: { 'media.navigator.streams.fake': true, 'media.navigator.permission.disabled': true }, + args: ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', `--use-file-for-fake-video-capture=${video}`], }); -const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } }); -const page = await ctx.newPage(); -const consoleErrors: string[] = []; -const badRequests: string[] = []; -const foreign: string[] = []; -page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()); }); -page.on('pageerror', (e) => consoleErrors.push(String(e))); -page.on('requestfailed', (r) => badRequests.push(`${r.url()} ${r.failure()?.errorText}`)); -page.on('response', (r) => { if (r.status() >= 400) badRequests.push(`${r.url()} ${r.status()}`); }); -page.on('request', (r) => { - const u = new URL(r.url()); - if (!['localhost', '127.0.0.1'].includes(u.hostname) && !['blob:', 'data:', 'about:'].includes(u.protocol)) foreign.push(r.url()); -}); -await page.route('**/__check/scanner.js', (route) => route.fulfill({ contentType: 'text/javascript', body: scannerJs })); +const darkContext = (b: Browser, extra: Parameters[0] = {}) => + b.newContext({ viewport: { width: 1280, height: 900 }, colorScheme: 'dark', permissions: ['camera'], ...extra }); -const shot = async (name: string) => { if (shots) await page.screenshot({ path: `${shots}/${name}.png`, fullPage: true }); }; -const tab = (name: RegExp) => page.getByRole('tab', { name }); +/** Records every stream the page opens, and every change of the status line, for later assertions. */ +const instrument = (ctx: BrowserContext, gumDelayMs = 0) => ctx.addInitScript((delay) => { + const w = window as any; + w.__streams = []; w.__statuses = []; w.__flashes = 0; + const md = navigator.mediaDevices; + const orig = md.getUserMedia.bind(md); + md.getUserMedia = async (c) => { + if (delay) await new Promise((r) => setTimeout(r, delay)); + const s = await orig(c); w.__streams.push(s); return s; + }; + new MutationObserver((list) => { + for (const m of list) { + const t = m.target as HTMLElement; + if (t.classList?.contains('video-wrap') && t.classList.contains('flash')) w.__flashes++; + } + const st = document.querySelector('p.status'); + if (st && st.textContent && w.__statuses[w.__statuses.length - 1] !== st.textContent) w.__statuses.push(st.textContent); + }).observe(document, { subtree: true, childList: true, attributes: true, characterData: true }); +}, gumDelayMs); +const liveTracks = (page: Page) => page.evaluate(() => (window as any).__streams.flatMap((s: MediaStream) => s.getTracks()).filter((t: MediaStreamTrack) => t.readyState === 'live').length); -try { +let server404 = false; +try { const r = await fetch(base); server404 = !r.ok; } catch { server404 = true; } +if (server404) { console.error(`No Booksorter server answering at ${base}`); process.exit(2); } + +// --------------------------------------------------------------------------------------------------- +// 1. Typed ISBNs: one Enter is one request and one row (Chromium and Firefox) +// --------------------------------------------------------------------------------------------------- +for (const [name, type] of [['chromium', chromium], ['firefox', firefox]] as const) { + await section(`${name}: typed ISBN`, async () => { + const browser = await type.launch({ headless: true }); + const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 }, colorScheme: 'dark' }); + const page = await ctx.newPage(); watch(page, name); + const posts: string[] = []; + page.on('request', (r) => { if (r.url().endsWith('/api/scan') && r.method() === 'POST') posts.push(r.postData() ?? ''); }); + await page.goto(base, { waitUntil: 'networkidle' }); + await removeBook(page, ISBN); // the lookup cache makes the re-add quick; a scratch database is assumed + const box = page.getByLabel('ISBN'); + check('ISBN box is focused on load', await box.evaluate((el) => el === document.activeElement)); + check('page loads, Scan tab renders', await page.getByRole('heading', { name: 'This session' }).isVisible()); + await box.fill(ISBN); + await box.press('Enter'); + await rows(page).first().waitFor(); + await page.waitForTimeout(700); + check('one typed ISBN + Enter sends exactly one POST /api/scan', posts.length === 1, `${posts.length} request(s)`); + check('one typed ISBN makes exactly one row', (await rows(page).count()) === 1); + await rows(page).first().locator('[data-state]').or(rows(page).first()).first().waitFor(); + await page.locator('.scan .right li.book:not(.looking)').first().waitFor({ timeout: 150_000 }); + const text = norm(await rows(page).first().innerText()); + check('the row shows one state', /Ready|Needs attention/.test(text) && !/Looking up/.test(text), text.slice(0, 120)); + + await box.fill(ISBN); + await box.press('Enter'); + await page.waitForTimeout(800); + check('typing the same ISBN again leaves one row', (await rows(page).count()) === 1, `${await rows(page).count()} row(s), ${posts.length} POSTs`); + check('the book already in this session is not marked "Already in catalog"', !/Already in catalog/.test(await rows(page).first().innerText())); + + // Two Enters while the first request is still in flight: still one request, one row. + await page.route('**/api/scan', async (route) => { await new Promise((r) => setTimeout(r, 600)); await route.fallback(); }); + const before = posts.length; + await box.fill(ISBN); await box.press('Enter'); + await box.fill(ISBN); await box.press('Enter'); + await page.waitForTimeout(1500); + check('two quick Enters for one ISBN send one request', posts.length - before === 1, `${posts.length - before} request(s)`); + check('and still one row', (await rows(page).count()) === 1); + + // Reload: the book is now an earlier one, so it is shown once with the note. + await page.reload({ waitUntil: 'networkidle' }); + await page.getByLabel('ISBN').fill(ISBN); await page.getByLabel('ISBN').press('Enter'); + await rows(page).first().waitFor(); + const earlier = norm(await rows(page).first().innerText()); + check('a book from an earlier session shows one row with "Already in catalog"', (await rows(page).count()) === 1 && /Already in catalog/.test(earlier), earlier.slice(0, 120)); + await browser.close(); + }); +} + +// --------------------------------------------------------------------------------------------------- +// 2. States, summary, queue (Chromium, invented books for the states that cannot be held still for real) +// --------------------------------------------------------------------------------------------------- +await section('session states, summary and print queue', async () => { + const browser = await chromium.launch({ headless: true }); + const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 }, colorScheme: 'dark' }); + const page = await ctx.newPage(); watch(page, 'states'); await page.goto(base, { waitUntil: 'networkidle' }); - await tab(/^Scan/).waitFor(); - check('page loads, Scan tab renders', await page.getByRole('heading', { name: 'This session' }).isVisible()); - await shot('scan-1280'); - await page.setViewportSize({ width: 380, height: 800 }); - await shot('scan-380'); - await page.setViewportSize({ width: 1280, height: 900 }); + await removeBook(page, ISBN); + const pendingBook = fakeBook(900001, { isbn13: ISBN2, title: 'The Mythical Man-Month', authors: ['Frederick P. Brooks'], attentionReason: 'Library of Congress did not answer. Trying again shortly.' }); + await inventScan(page, ISBN2, pendingBook); + const attentionBook = fakeBook(900002, { isbn13: null, title: 'A Book Nobody Catalogued', authors: ['Anon.'], status: 'needs_attention', attentionReason: 'No catalog record matched this ISBN.', inQueue: false }); + await page.route('**/api/books/lccn', (route) => route.fulfill({ json: { book: attentionBook } })); - // Typed ISBN. A book already in the catalog would only show "Already in catalog", so remove it first - // (it re-resolves from the lookup cache). Run this against a scratch database, not your real one. - await page.evaluate(async (isbn) => { - const books = await (await fetch('/api/books?filter=all')).json(); - for (const b of books.filter((x: any) => x.isbn13 === isbn)) await fetch(`/api/books/${b.id}`, { method: 'DELETE' }); - }, ISBN); + // Ready book 1: typed ISBN (resolved from cache). Ready book 2: entered by hand with a call number. const box = page.getByLabel('ISBN'); - check('ISBN box is focused on load', await box.evaluate((el) => el === document.activeElement)); - await box.fill(ISBN); - await box.press('Enter'); - await page.locator('.scan .right li.item .chip.ok').first().waitFor({ timeout: 120_000 }); - check('typed ISBN reaches Ready', true, (await page.locator('.scan .right li.item').first().innerText()).replace(/\s+/g, ' ')); - await shot('scan-after-1280'); + await box.fill(ISBN); await box.press('Enter'); + await page.locator('.scan .right li.book.ready').first().waitFor({ timeout: 150_000 }); + await page.locator('summary', { hasText: 'Enter by hand' }).click(); + const manual = page.locator('details', { hasText: 'Enter by hand' }); + await manual.getByLabel('Title').fill('Structure and Interpretation of Computer Programs'); + await manual.getByLabel('Authors (separate with ;)').fill('Harold Abelson; Gerald Jay Sussman'); + await manual.getByLabel('Call number (optional)').fill('QA76.6 .A24 1996'); + await manual.getByRole('button', { name: 'Add' }).click(); + await page.locator('.scan .right li.book.ready', { hasText: 'Structure and Interpretation' }).waitFor(); + // Looking-up book (invented scan), and a needs-attention book (invented LCCN answer). + await box.fill(ISBN2); await box.press('Enter'); + await rows(page).first().waitFor(); + await page.locator('summary', { hasText: 'Enter LCCN' }).click(); + const lccn = page.locator('details', { hasText: 'Enter LCCN' }); + await lccn.getByLabel('LCCN').fill('00000000'); + await lccn.getByRole('button', { name: 'Add' }).click(); + await page.locator('.scan .right li.book.attention').waitFor(); + await page.waitForTimeout(2200); // let the seconds count - // Barcode path, no camera - const modules = ean13Modules(ISBN); - const decoded = await page.evaluate(async ({ modules, src }) => { - const { makeDetector } = await import(/* @vite-ignore */ src); - const scale = 4, quiet = 12 * scale, h = 120; - const c = document.createElement('canvas'); - c.width = modules.length * scale + quiet * 2; c.height = h; - const g = c.getContext('2d')!; - g.fillStyle = '#fff'; g.fillRect(0, 0, c.width, h); - g.fillStyle = '#000'; - [...modules].forEach((m, i) => { if (m === '1') g.fillRect(quiet + i * scale, 10, scale, h - 20); }); - const found = await makeDetector().detect(c); - return found.map((f: { rawValue: string; format: string }) => `${f.format}:${f.rawValue}`); - }, { modules, src: '/__check/scanner.js' }); - check('wasm barcode decode', decoded.includes(`ean_13:${ISBN}`), JSON.stringify(decoded)); - - // Camera (Firefox fake stream) - await page.getByRole('button', { name: 'Start camera' }).click(); - await page.getByRole('button', { name: 'Stop camera' }).waitFor({ timeout: 15_000 }); - const playing = await page.waitForFunction(() => { - const v = document.querySelector('video') as HTMLVideoElement | null; - return !!v && !!v.srcObject && v.videoWidth > 0 && !v.paused; - }, null, { timeout: 15_000 }).then(() => true, () => false); - check('Start camera plays video', playing); - check('no camera error message', (await page.locator('.scan .warn[role=alert]').count()) === 0); - await page.waitForTimeout(1500); // let the scan loop run on the fake frames - await shot('scan-camera-1280'); - await page.getByRole('button', { name: 'Stop camera' }).click(); - await page.getByRole('button', { name: 'Start camera' }).waitFor(); - const stopped = await page.evaluate(() => !(document.querySelector('video') as HTMLVideoElement).srcObject); - check('Stop camera releases the stream', stopped); + const summary = norm(await page.locator('.scan .summary').innerText()); + check('summary counts all four rows', summary === '4 scanned · 2 ready · 1 looking up · 1 needs attention', summary); + const looking = rows(page).filter({ hasText: 'Looking up' }); + const lookingText = norm(await looking.innerText()); + check('a pending book shows Looking up with elapsed seconds', /Looking up… \d+ s/.test(lookingText), lookingText); + check('a pending book shows its retry note', lookingText.includes('Trying again shortly')); + check('a pending book never says "No call number"', !/No call number/.test(lookingText)); + check('a pending book has a spinner', (await looking.locator('.spinner').count()) === 1); + const secs = Number(/(\d+) s/.exec(lookingText)?.[1] ?? 0); + check('the elapsed seconds are counting', secs >= 2, `${secs} s`); + const attn = norm(await rows(page).filter({ hasText: 'Needs attention' }).innerText()); + check('a needs-attention row shows the reason and a Fix button', attn.includes('No catalog record matched') && attn.includes('Fix'), attn); + check('every row shows exactly one state label', + (await rows(page).evaluateAll((els) => els.map((e) => e.querySelectorAll('.state-label').length))).every((n) => n === 1)); + await rows(page).filter({ hasText: 'Needs attention' }).getByRole('button', { name: 'Fix' }).click(); + check('Fix opens the editor', await page.getByLabel('Call number', { exact: true }).isVisible()); + // The year field rejects text, never sends NaN. + let patched = false; + await page.route('**/api/books/900002', async (route) => { patched = true; await route.fulfill({ json: attentionBook }); }); + await page.locator('.editor').getByLabel('Year').fill('abc'); + await page.locator('.editor').getByRole('button', { name: 'Save' }).click(); + check('the editor shows an error for a non-numeric year and sends nothing', (await page.locator('.editor [role=alert]').first().isVisible()) && !patched); + await page.locator('.editor').getByLabel('Year').fill(''); + await page.locator('.editor').getByRole('button', { name: 'Save' }).click(); + await page.waitForTimeout(300); + check('an empty year is saved as null', patched); + await shot(page, 'scan-three-states'); // Print queue - await tab(/^Print queue/).click(); + const readyCount = (await api(page, '/api/books?filter=queue')).filter((b) => b.status === 'resolved' && b.callNumber).length; + await page.getByRole('tab', { name: /^Print queue/ }).click(); await page.getByRole('heading', { name: 'Print queue' }).waitFor(); - const rows = await page.locator('.queue section').first().locator('li.item').count(); - check('Print queue lists resolved books', rows >= 1, `${rows} rows`); - const keys: string[] = await page.evaluate(async () => { - const books = await (await fetch('/api/books?filter=queue')).json(); - return books.filter((b: any) => b.status === 'resolved' && b.callNumber).map((b: any) => b.sortKey ?? '~'); - }); - check('queue order matches shelf (sort key) order', JSON.stringify(keys) === JSON.stringify([...keys].sort()) && rows === keys.length); - await shot('queue-1280'); - const [pdfResp] = await Promise.all([ - page.waitForResponse((r) => r.url().includes('/api/print.pdf')), - page.getByRole('button', { name: 'Make PDF' }).click(), - ]); - const pdfBody = await pdfResp.body(); - check('Make PDF fetches a PDF', pdfResp.status() === 200 && pdfBody.subarray(0, 4).toString() === '%PDF', `${pdfBody.length} bytes`); - check('X-Book-Ids header present', /^\d+(,\d+)*$/.test(pdfResp.headers()['x-book-ids'] ?? '')); + const head = norm(await page.locator('.queue .summary').innerText()); + const want = `${readyCount} ${readyCount === 1 ? 'card' : 'cards'} ready · 1 still looking up`; + check('queue header counts ready and looking-up books', head === want, `${head} (expected ${want})`); + check('the pending book is listed in the queue, greyed, with the spinner', (await page.locator('.queue li.item.dim .spinner').count()) === 1); + check('the tab label counts queued books (ready + looking up)', norm(await page.getByRole('tab', { name: /^Print queue/ }).innerText()) === `Print queue (${readyCount + 1})`); + check('"Needs attention" does not claim every book has a call number', !/Every book has a call number/.test(await page.locator('.queue').innerText())); + const pdfBtn = page.getByRole('button', { name: /^Make PDF/ }); + check('Make PDF says how many cards', norm(await pdfBtn.innerText()) === `Make PDF (${readyCount} ${readyCount === 1 ? 'card' : 'cards'})`, norm(await pdfBtn.innerText())); + await shot(page, 'queue-ready-and-looking'); + const [pdfResp] = await Promise.all([page.waitForResponse((r) => r.url().includes('/api/print.pdf')), pdfBtn.click()]); + const body = await pdfResp.body(); + check('Make PDF fetches a PDF', pdfResp.status() === 200 && body.subarray(0, 4).toString() === '%PDF', `${body.length} bytes`); await page.getByText('Did the cards print correctly?').waitFor(); - await shot('queue-confirm-1280'); await page.getByRole('button', { name: 'Not yet' }).click(); - - // Catalog - await tab(/^Catalog/).click(); - await page.waitForTimeout(500); + await shot(page, 'queue-after-pdf'); + const catalog = page.getByRole('tab', { name: /^Catalog/ }); + await catalog.click(); + await page.waitForTimeout(400); check('Catalog tab renders', (await page.locator('main').innerText()).trim().length > 0); - await shot('catalog-1280'); + await browser.close(); +}); - check('no console errors', consoleErrors.length === 0, consoleErrors.join(' | ')); - check('no failed requests', badRequests.length === 0, badRequests.join(' | ')); - check('no request left localhost', foreign.length === 0, foreign.join(' | ')); -} catch (e) { - check('script ran to completion', false, String(e)); - await shot('failure').catch(() => {}); -} -await browser.close(); -console.log(failures.length ? `\n${failures.length} check(s) failed` : '\nAll checks passed'); +await section('print queue with nothing ready', async () => { + const browser = await chromium.launch({ headless: true }); + const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 }, colorScheme: 'dark' }); + const page = await ctx.newPage(); watch(page, 'empty-queue'); + // Show only a pending book: the server's list is answered by an invented one. + await page.route('**/api/books?*', (route) => route.fulfill({ json: [fakeBook(900003, { title: 'Still Looking' })] })); + await page.goto(base, { waitUntil: 'networkidle' }); + await page.getByRole('tab', { name: /^Print queue/ }).click(); + const head = norm(await page.locator('.queue .summary').innerText()); + check('queue with only a pending book reads "0 cards ready · 1 still looking up"', head === '0 cards ready · 1 still looking up', head); + const pdfBtn = page.getByRole('button', { name: /^Make PDF/ }); + check('Make PDF is disabled with an explanation', (await pdfBtn.isDisabled()) && (await page.locator('#pdf-why').innerText()).includes('No card is ready yet')); + check('the tab label says (1)', norm(await page.getByRole('tab', { name: /^Print queue/ }).innerText()) === 'Print queue (1)'); + await browser.close(); +}); + +// --------------------------------------------------------------------------------------------------- +// 3. The camera, in Chromium with a fake camera playing a video of a barcode +// --------------------------------------------------------------------------------------------------- +await section('camera: Start camera reads the barcode from video alone', async () => { + const browser = await chromiumFor(videoOk); + const ctx = await darkContext(browser); + await instrument(ctx); + const page = await ctx.newPage(); watch(page, 'camera'); + const posts: string[] = []; + page.on('request', (r) => { if (r.url().endsWith('/api/scan') && r.method() === 'POST') posts.push(r.postData() ?? ''); }); + await page.goto(base, { waitUntil: 'networkidle' }); + await removeBook(page, ISBN); + check('camera off: Start camera is in the middle of the video area', await page.locator('.video-empty').getByRole('button', { name: 'Start camera' }).isVisible()); + check('camera off: the status line says so', /camera is off/i.test(await statusLine(page).innerText())); + + await page.getByRole('button', { name: 'Start camera' }).dblclick(); // a double click must not open two streams + await page.getByText('Hold the barcode inside the box').waitFor({ timeout: 20_000 }); + check('the target box and instruction are shown', await page.locator('.target').isVisible()); + check('the Scanning indicator is shown', await page.locator('.scanning').isVisible()); + await page.waitForFunction(() => (window as any).__statuses.some((s: string) => /^Read \d{13}$/.test(s)), null, { timeout: 30_000 }); + const statuses: string[] = await page.evaluate(() => (window as any).__statuses); + check('status line went "Looking for a barcode…" then "Read "', statuses.includes('Looking for a barcode…') && statuses.includes(`Read ${ISBN}`), JSON.stringify(statuses)); + check('the video border flashed green on the read', (await page.evaluate(() => (window as any).__flashes)) >= 1); + await rows(page).first().waitFor({ timeout: 15_000 }); + await page.waitForTimeout(1500); + check('the book appeared in the session list from the camera alone, one row', (await rows(page).count()) === 1, norm(await rows(page).first().innerText()).slice(0, 100)); + check('a barcode held in view posts once, not once per frame', posts.length === 1, `${posts.length} POST(s)`); + check('a double click on Start camera opened one stream', (await page.evaluate(() => (window as any).__streams.length)) === 1); + check('the video has real size', await page.evaluate(() => { const v = document.querySelector('video')!; return v.videoWidth > 0; })); + await shot(page, 'scan-camera-read'); + + // Capture button and Space + await page.waitForFunction(() => document.querySelector('p.status')?.textContent === 'Looking for a barcode…', null, { timeout: 10_000 }); + const mark = await page.evaluate(() => (window as any).__statuses.length); + await page.getByRole('button', { name: 'Capture' }).click(); + await page.waitForFunction((m) => (window as any).__statuses.slice(m).some((s: string) => /^Read \d{13}$/.test(s)), mark, { timeout: 20_000 }); + const after: string[] = await page.evaluate((m) => (window as any).__statuses.slice(m), mark); + check('Capture takes a picture and reads the barcode', after[0] === 'Taking a picture and reading it…' && after.includes(`Read ${ISBN}`), JSON.stringify(after)); + await page.waitForFunction(() => document.querySelector('p.status')?.textContent === 'Looking for a barcode…', null, { timeout: 10_000 }); + const mark2 = await page.evaluate(() => (window as any).__statuses.length); + await page.locator('video').click({ force: true }); // focus leaves the text field + await page.evaluate(() => (document.activeElement as HTMLElement)?.blur?.()); + await page.keyboard.press('Space'); + await page.waitForFunction((m) => (window as any).__statuses.slice(m).includes('Taking a picture and reading it…'), mark2, { timeout: 10_000 }); + check('Space triggers Capture when focus is not in a text field', true); + await page.waitForFunction((m) => (window as any).__statuses.slice(m).some((s: string) => /^Read \d{13}$/.test(s)), mark2, { timeout: 20_000 }); + const box = page.getByLabel('ISBN'); + await box.focus(); await page.keyboard.press('Space'); + check('Space in the ISBN box also captures and types no space', (await box.inputValue()) === ''); + check('the Capture reads never added a second row', (await rows(page).count()) === 1); + + // Remembered: reload starts the camera by itself; Stop forgets it. + await page.reload({ waitUntil: 'networkidle' }); + await page.getByRole('button', { name: 'Stop camera' }).waitFor({ timeout: 20_000 }); + check('after a reload the camera starts by itself (permission already granted)', true); + await page.getByRole('button', { name: 'Stop camera' }).click(); + await page.getByRole('button', { name: 'Start camera' }).waitFor(); + check('Stop camera releases every stream', (await liveTracks(page)) === 0); + await page.reload({ waitUntil: 'networkidle' }); + await page.waitForTimeout(800); + check('after Stop and a reload the camera stays off, with the Start button in the video area', await page.locator('.video-empty').getByRole('button', { name: 'Start camera' }).isVisible()); + await browser.close(); +}); + +await section('camera: leaving the view while the permission prompt is open', async () => { + const browser = await chromiumFor(videoOk); + const ctx = await darkContext(browser); + await instrument(ctx, 1500); // getUserMedia answers 1.5 s late, like a person reading the prompt + const page = await ctx.newPage(); watch(page, 'prompt'); + await page.goto(base, { waitUntil: 'networkidle' }); + const btn = page.getByRole('button', { name: /^Start camera|^Starting camera/ }); + await btn.click(); + check('Start is disabled while starting', await page.getByRole('button', { name: 'Starting camera…' }).isDisabled()); + await page.getByRole('tab', { name: /^Print queue/ }).click(); // the Scan view unmounts mid-prompt + await page.waitForFunction(() => (window as any).__streams.length === 1, null, { timeout: 10_000 }); + await page.waitForTimeout(300); + check('the stream that arrives after leaving is stopped at once', (await liveTracks(page)) === 0); + await browser.close(); +}); + +await section('camera: nothing readable in view', async () => { + const browser = await chromiumFor(videoBlank); + const ctx = await darkContext(browser); + await instrument(ctx); + const page = await ctx.newPage(); watch(page, 'blank'); + await page.goto(base, { waitUntil: 'networkidle' }); + await page.getByRole('button', { name: 'Start camera' }).click(); + await page.getByText('Hold the barcode inside the box').waitFor({ timeout: 20_000 }); + await page.waitForTimeout(1000); + check('with no barcode the status stays "Looking for a barcode…"', (await statusLine(page).innerText()) === 'Looking for a barcode…'); + await page.getByRole('button', { name: 'Capture' }).click(); + await page.getByText('No barcode found in that picture. Move closer, add light, or type the ISBN below.').waitFor({ timeout: 20_000 }); + check('Capture says plainly when it finds nothing', true); + check('and no row was added', (await rows(page).count()) === 0); + await browser.close(); +}); + +await section('decoder: the thorough decode reads a small, soft barcode the live loop misses', async () => { + const browser = await chromiumFor(videoHard); + const ctx = await darkContext(browser); + const page = await ctx.newPage(); watch(page, 'decode'); + await page.route('**/__check/scanner.js', (route) => route.fulfill({ contentType: 'text/javascript', body: scannerJs })); + await page.goto(base, { waitUntil: 'networkidle' }); + const r = await page.evaluate(async (isbn) => { + const mod = await import(/* @vite-ignore */ ('/__check/' + 'scanner.js')); mod.prepare(); + const stream = await navigator.mediaDevices.getUserMedia({ video: { width: 1920, height: 1080 } }); + const v = document.createElement('video'); v.srcObject = stream; v.muted = true; await v.play(); + await new Promise((res) => setTimeout(res, 500)); + const live = await mod.decodeLive(v); const thorough = await mod.decodeThorough(v); + stream.getTracks().forEach((t: MediaStreamTrack) => t.stop()); + return { live, thorough, isbn }; + }, ISBN); + check('thorough decode reads the small barcode', r.thorough.isbn === ISBN, JSON.stringify(r)); + check('live decode never returns a wrong ISBN for it', r.live.isbn === null || r.live.isbn === ISBN, JSON.stringify(r.live)); + await browser.close(); +}); + +// --------------------------------------------------------------------------------------------------- +// 4. Firefox's fake camera starts and stops +// --------------------------------------------------------------------------------------------------- +await section('firefox: fake camera starts and stops', async () => { + const browser = await firefox.launch({ headless: true, firefoxUserPrefs: { 'media.navigator.streams.fake': true, 'media.navigator.permission.disabled': true } }); + const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 }, colorScheme: 'dark' }); + const page = await ctx.newPage(); watch(page, 'firefox-cam'); + await page.goto(base, { waitUntil: 'networkidle' }); + await page.getByRole('button', { name: 'Start camera' }).click(); + await page.getByRole('button', { name: 'Stop camera' }).waitFor({ timeout: 20_000 }); + check('Start camera plays video', await page.waitForFunction(() => { const v = document.querySelector('video') as HTMLVideoElement; return !!v.srcObject && v.videoWidth > 0 && !v.paused; }, null, { timeout: 15_000 }).then(() => true, () => false)); + await page.getByRole('button', { name: 'Stop camera' }).click(); + await page.getByRole('button', { name: 'Start camera' }).waitFor(); + check('Stop camera releases the stream', await page.evaluate(() => !(document.querySelector('video') as HTMLVideoElement).srcObject)); + await browser.close(); +}); + +check('no console errors', consoleErrors.length === 0, consoleErrors.join(' | ')); +check('no failed requests', badRequests.length === 0, badRequests.join(' | ')); +check('no request left localhost', foreign.length === 0, foreign.join(' | ')); +console.log(failures.length ? `\n${failures.length} check(s) failed: ${failures.join('; ')}` : '\nAll checks passed'); process.exit(failures.length ? 1 : 0); diff --git a/scripts/browser-media.ts b/scripts/browser-media.ts new file mode 100644 index 0000000..557a1c0 --- /dev/null +++ b/scripts/browser-media.ts @@ -0,0 +1,81 @@ +// Helpers for scripts/browser-check.ts: an EAN-13 bitmap, and a .y4m video of it for Chromium's fake camera. +import { writeFileSync } from 'node:fs'; + +/** EAN-13 module pattern (95 modules, 1 = bar) for a 13-digit string. */ +export function ean13Modules(code: string): string { + const L = ['0001101', '0011001', '0010011', '0111101', '0100011', '0110001', '0101111', '0111011', '0110111', '0001011']; + const R = L.map((p) => [...p].map((b) => (b === '0' ? '1' : '0')).join('')); + const G = R.map((p) => [...p].reverse().join('')); + const parity = ['LLLLLL', 'LLGLGG', 'LLGGLG', 'LLGGGL', 'LGLLGG', 'LGGLLG', 'LGGGLL', 'LGLGLG', 'LGLGGL', 'LGGLGL']; + const d = [...code].map(Number); + let out = '101'; + for (let i = 0; i < 6; i++) out += parity[d[0]][i] === 'L' ? L[d[i + 1]] : G[d[i + 1]]; + out += '01010'; + for (let i = 7; i < 13; i++) out += R[d[i]]; + return out + '101'; +} + +export interface VideoOptions { + isbn: string; + width?: number; height?: number; frames?: number; + /** Pixels per barcode module. A real book held about 30 cm from a 720p webcam is roughly 1.2 to 2 px per module. */ + moduleScale?: number; +} + +/** Deterministic noise so a run is repeatable. */ +function rng(seed: number) { let s = seed >>> 0; return () => ((s = (Math.imul(s, 1664525) + 1013904223) >>> 0) / 4294967296); } + +/** Gray frames (Uint8Array, width*height) of a barcode on a white page: soft focus, sensor noise, hand jitter. */ +export function barcodeFrames(o: VideoOptions): Uint8Array[] { + const W = o.width ?? 1280, H = o.height ?? 720, n = o.frames ?? 24, m = o.moduleScale ?? 2.6; + const mods = ean13Modules(o.isbn); + const bw = 95 * m, bh = Math.round(bw * 0.62); + const rand = rng(7); + const frames: Uint8Array[] = []; + for (let f = 0; f < n; f++) { + const jx = (rand() - 0.5) * 5, jy = (rand() - 0.5) * 5; + const x0 = W / 2 - bw / 2 + jx, y0 = H / 2 - bh / 2 + jy; + const raw = new Float32Array(W * H); + for (let y = 0; y < H; y++) { + for (let x = 0; x < W; x++) { + let v = 238 - 14 * (x / W) - 8 * (y / H); // a lit page, slightly uneven + if (y >= y0 && y < y0 + bh) { + let dark = 0; + for (let s = 0; s < 4; s++) { // 4 samples across the pixel + const mi = Math.floor((x + (s + 0.5) / 4 - x0) / m); + if (mi >= 0 && mi < 95 && mods[mi] === '1') dark++; + } + v = v * (1 - dark / 4) + 22 * (dark / 4); + } + raw[y * W + x] = v; + } + } + // Soft focus: a [1 2 1] blur both ways, then noise. + const out = new Uint8Array(W * H); + const tmp = new Float32Array(W * H); + for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { + const a = raw[y * W + Math.max(0, x - 1)], b = raw[y * W + x], c = raw[y * W + Math.min(W - 1, x + 1)]; + tmp[y * W + x] = (a + 2 * b + c) / 4; + } + for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { + const a = tmp[Math.max(0, y - 1) * W + x], b = tmp[y * W + x], c = tmp[Math.min(H - 1, y + 1) * W + x]; + out[y * W + x] = Math.max(0, Math.min(255, Math.round((a + 2 * b + c) / 4 + (rand() - 0.5) * 8))); + } + frames.push(out); + } + return frames; +} + +/** Write gray frames as a YUV4MPEG2 (4:2:0) file, the format Chromium's --use-file-for-fake-video-capture reads. */ +export function writeY4m(path: string, frames: Uint8Array[], width: number, height: number): void { + const header = Buffer.from(`YUV4MPEG2 W${width} H${height} F30:1 Ip A1:1 C420jpeg\n`); + const chroma = Buffer.alloc((width / 2) * (height / 2) * 2, 128); + const parts: Buffer[] = [header]; + for (const f of frames) parts.push(Buffer.from('FRAME\n'), Buffer.from(f), chroma); + writeFileSync(path, Buffer.concat(parts)); +} + +export function makeBarcodeY4m(path: string, o: VideoOptions): void { + const W = o.width ?? 1280, H = o.height ?? 720; + writeY4m(path, barcodeFrames(o), W, H); +} diff --git a/src/server/app.test.ts b/src/server/app.test.ts index ced4180..419d1f8 100644 --- a/src/server/app.test.ts +++ b/src/server/app.test.ts @@ -10,20 +10,20 @@ const found: Resolution = { callNumber: 'QA76.73.R87 K53 2018', sortKey: 'QA 76', confidence: 'exact', source: 'loc-isbn', dewey: null, reason: null, }; -function setup(resolve = async () => found) { +function setup(resolve = async () => found, port?: number) { const db = openDb(':memory:'); const events = createEventBus(); const resolver = { resolve, search: async () => [{ title: 'Hit', authors: [], lcc: [] }] }; - const jobs = createJobs({ db, resolver, onChange: (b) => events.emitBook(b), retryDelaysMs: [0] }); + const jobs = createJobs({ db, resolver, onChange: (b) => events.emitBook(b), retryDelaysMs: [0], log: () => {} }); const pdfCalls: { cards: CardData[]; opts: Settings & { startPosition: number } }[] = []; const app = createApp({ - db, jobs, resolver, events, + db, jobs, resolver, events, port, renderCardsPdf: async (cards, opts) => { pdfCalls.push({ cards, opts }); return new TextEncoder().encode('%PDF-stub'); }, renderCalibrationPdf: async () => new TextEncoder().encode('%PDF-cal'), classNames: (l) => ({ className: 'Class ' + l[0], subclassName: 'Sub ' + l }), }); - const req = (method: string, path: string, json?: unknown) => - app.request(path, { method, ...(json === undefined ? {} : { body: JSON.stringify(json), headers: { 'content-type': 'application/json' } }) }); + const req = (method: string, path: string, json?: unknown, extra: Record = {}) => + app.request(path, { method, headers: { ...(json === undefined ? {} : { 'content-type': 'application/json' }), ...extra }, ...(json === undefined ? {} : { body: JSON.stringify(json) }) }); return { db, jobs, app, req, pdfCalls, events }; } @@ -176,3 +176,49 @@ test('events stream delivers changes and cleans up on disconnect', async () => { await res2.body!.cancel(); assert.equal(events.listenerCount(), 0); }); + +test('state-changing requests from another origin are refused', async () => { + const { req, db } = setup(undefined, 4321); + const ok = ['http://localhost:4321', 'http://127.0.0.1:4321']; + const bad = ['http://evil.example', 'http://localhost:9999', 'http://localhost:4321.evil.com', 'null', 'https://localhost:4321']; + for (const origin of ok) assert.equal((await req('POST', '/api/books/manual', { title: 'T' }, { origin })).status, 200, origin); + for (const method of ['POST', 'PUT', 'PATCH', 'DELETE']) { + for (const origin of bad) { + const r = await req(method, '/api/books/1', method === 'DELETE' ? undefined : { title: 'x' }, { origin }); + assert.equal(r.status, 403, `${method} ${origin}`); + } + } + assert.equal(db.listBooks().length, 2); + assert.equal((await req('GET', '/api/books', undefined, { origin: 'http://evil.example' })).status, 200); + assert.equal((await req('POST', '/api/books/manual', { title: 'No origin header' })).status, 200); +}); + +test('PATCH year must be an integer or null', async () => { + const { req, db, jobs } = setup(); + const m = await (await req('POST', '/api/books/manual', { title: 'Foo', year: 2000 })).json() as any; + await jobs.idle(); + for (const year of ['abc', 1999.5, true, {}, -4]) { + assert.equal((await req('PATCH', `/api/books/${m.book.id}`, { year })).status, 400, JSON.stringify(year)); + } + assert.equal(db.getBook(m.book.id)!.year, 2000); + assert.equal((await req('PATCH', `/api/books/${m.book.id}`, { year: 2011 })).status, 200); + assert.equal(db.getBook(m.book.id)!.year, 2011); + assert.equal((await req('PATCH', `/api/books/${m.book.id}`, { year: null })).status, 200); + assert.equal(db.getBook(m.book.id)!.year, null); +}); + +test('retry forgets the book\'s cached source responses', async () => { + const { req, db, jobs } = setup(); + const s = await (await req('POST', '/api/scan', { isbn: '9781593278281' })).json() as any; + await jobs.idle(); + db.updateBook(s.book.id, { lccn: '2018012345', title: 'Rust Book' }); + for (const k of ['ol-data:9781593278281', 'ol-search:9781593278281', 'loc-isbn:9781593278281', 'loc-lccn:2018012345', + 'loc-title:Rust Book|Steve Klabnik', 'ol-data:9780201835953', 'loc-title:Other|X']) db.cache.set(k, 'body'); + assert.equal((await req('POST', `/api/books/${s.book.id}/retry`)).status, 200); + await jobs.idle(); + for (const k of ['ol-data:9781593278281', 'ol-search:9781593278281', 'loc-isbn:9781593278281', 'loc-lccn:2018012345', 'loc-title:Rust Book|Steve Klabnik']) { + assert.equal(db.cache.get(k), null, k); + } + assert.equal(db.cache.get('ol-data:9780201835953'), 'body'); + assert.equal(db.cache.get('loc-title:Other|X'), 'body'); +}); diff --git a/src/server/app.ts b/src/server/app.ts index 5388953..f2917dd 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -31,6 +31,8 @@ export function createEventBus(): EventBus { } export interface AppDeps { + /** The port the page is served from; the only Origin (on localhost / 127.0.0.1) allowed to change state. */ + port?: number; db: Db; jobs: Jobs; resolver: ResolverLike; renderCardsPdf: RenderCardsPdf; renderCalibrationPdf: RenderCalibrationPdf; classNames: ClassNames; @@ -58,6 +60,13 @@ function callNumberFields(raw: string): Partial { manualOverride: true, confidence: 'manual', source: 'manual' }; } +function cacheKeys(book: Book): string[] { + const keys: string[] = []; + if (book.isbn13) keys.push(`ol-data:${book.isbn13}`, `ol-search:${book.isbn13}`, `loc-isbn:${book.isbn13}`); + if (book.lccn) keys.push(`loc-lccn:${book.lccn}`); + return keys; +} + export function createApp(deps: AppDeps): Hono { const { db, jobs, resolver, classNames } = deps; const events = deps.events ?? createEventBus(); @@ -69,6 +78,20 @@ export function createApp(deps: AppDeps): Hono { return c.json({ error: 'Internal error' }, 500); }); + // A web page on another origin must not be able to drive this local app. Requests without an + // Origin header (curl, tests, same-origin GET-like navigations) are not browser cross-site requests. + app.use('*', async (c, next) => { + const method = c.req.method; + const origin = c.req.header('origin'); + if (origin !== undefined && (method === 'POST' || method === 'PUT' || method === 'PATCH' || method === 'DELETE')) { + const port = deps.port ?? (new URL(c.req.url).port || '80'); + if (origin !== `http://localhost:${port}` && origin !== `http://127.0.0.1:${port}`) { + return c.json({ error: 'Cross-origin request refused' }, 403); + } + } + await next(); + }); + async function body(c: Context): Promise> { try { const v = await c.req.json(); @@ -189,6 +212,9 @@ export function createApp(deps: AppDeps): Hono { app.post('/api/books/:id/retry', (c) => { const book = bookParam(c); if (book.manualOverride) throw new HttpError(400, 'This call number was entered by hand, so there is nothing to look up'); + // "Look up again" must really ask again, so forget what the sources told us for this book. + for (const key of cacheKeys(book)) db.cache.delete(key); + if (book.title) db.cache.deletePrefix(`loc-title:${book.title}|`); const updated = db.updateBook(book.id, { status: 'pending', attentionReason: null })!; events.emitBook(updated); jobs.enqueue(book.id); diff --git a/src/server/db.ts b/src/server/db.ts index 55cccfb..b42d6ab 100644 --- a/src/server/db.ts +++ b/src/server/db.ts @@ -3,7 +3,7 @@ import { mkdirSync } from 'node:fs'; import { dirname } from 'node:path'; import type { Book, Confidence, Settings, Source, Status } from '../shared/types.ts'; -import type { SourceCache } from './sources/http.ts'; +import type { ForgettableCache, SourceCache } from './sources/http.ts'; export type { SourceCache }; export interface NewBook { @@ -26,7 +26,7 @@ export interface Db { listPendingIds(): number[]; getSettings(): Settings; putSettings(s: Settings): void; - cache: SourceCache; + cache: ForgettableCache; close(): void; } @@ -169,6 +169,12 @@ export function openDb(path: string): Db { db.prepare('INSERT INTO source_cache (key, body) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET body = excluded.body') .run(key, body); }, + delete(key) { + db.prepare('DELETE FROM source_cache WHERE key = ?').run(key); + }, + deletePrefix(prefix) { + db.prepare('DELETE FROM source_cache WHERE substr(key, 1, length(?)) = ?').run(prefix, prefix); + }, }, close() { db.close(); }, }; diff --git a/src/server/jobs.test.ts b/src/server/jobs.test.ts index 55640bd..7bdfa50 100644 --- a/src/server/jobs.test.ts +++ b/src/server/jobs.test.ts @@ -1,7 +1,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { openDb } from './db.ts'; -import { createJobs } from './jobs.ts'; +import { createJobs, DEFAULT_RETRY_DELAYS_MS } from './jobs.ts'; import type { ResolverLike } from './jobs.ts'; import type { Book, Resolution } from '../shared/types.ts'; @@ -13,12 +13,13 @@ const found: Resolution = { reason: null, }; -function setup(resolve: ResolverLike['resolve']) { +function setup(resolve: ResolverLike['resolve'], delays = [0, 0, 0]) { const db = openDb(':memory:'); const changes: Book[] = []; + const logs: string[] = []; const resolver: ResolverLike = { resolve, search: async () => [] }; - const jobs = createJobs({ db, resolver, onChange: (b) => changes.push(b), retryDelaysMs: [0, 0, 0] }); - return { db, jobs, changes }; + 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 () => { @@ -37,7 +38,7 @@ test('success resolves the book and emits changes', async () => { 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: 'x' }); + const { book } = db.insertPending({ isbn13: '9781593278281', title: '9781593278281' }); jobs.enqueue(book.id); await jobs.idle(); const b = db.getBook(book.id)!; @@ -140,3 +141,120 @@ test('deleting a book mid-queue is harmless', async () => { 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'); +}); diff --git a/src/server/jobs.ts b/src/server/jobs.ts index ed098ac..f07ed34 100644 --- a/src/server/jobs.ts +++ b/src/server/jobs.ts @@ -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 } @@ -14,86 +16,118 @@ function defaultIsTemporary(e: unknown): boolean { return false; } -function sleep(ms: number): Promise { - 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(); + const attempts = new Map(); + // Books waiting for a retry: they hold no worker; a timer puts them back in the queue. + const waiting = new Map>(); let running: Promise | 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[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[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[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 { - 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 { + 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((r) => { wake.push(r); }); + } + } finally { + if (--idlers === 0) for (const t of waiting.values()) t.unref(); + } }, }; } diff --git a/src/server/main.ts b/src/server/main.ts index 3a3754b..d7d4460 100644 --- a/src/server/main.ts +++ b/src/server/main.ts @@ -1,5 +1,6 @@ import { existsSync, readFileSync, statSync } from 'node:fs'; -import { extname, join, normalize, resolve as resolvePath } from 'node:path'; +import { extname, join, resolve as resolvePath } from 'node:path'; +import { staticPath } from './static.ts'; import { serve } from '@hono/node-server'; import { openDb } from './db.ts'; import { createJobs } from './jobs.ts'; @@ -24,15 +25,14 @@ const resolver = createResolver({ fetch: globalThis.fetch, cache: db.cache }); const jobs = createJobs({ db, resolver, onChange: (b) => events.emitBook(b), isTemporary: (e) => e instanceof TemporaryError, }); -const app = createApp({ db, jobs, resolver, renderCardsPdf, renderCalibrationPdf, classNames, events }); +const app = createApp({ port, db, jobs, resolver, renderCardsPdf, renderCalibrationPdf, classNames, events }); app.get('*', (c) => { if (!existsSync(join(webRoot, 'index.html'))) { return c.text('The web app has not been built. Run `npm run build` and reload.', 503); } - const rel = normalize(decodeURIComponent(c.req.path)).replace(/^([/\\])+/, ''); - const file = resolvePath(webRoot, rel === '' ? 'index.html' : rel); - if (!file.startsWith(webRoot) || !existsSync(file) || !statSync(file).isFile()) return c.text('Not found', 404); + const file = staticPath(webRoot, c.req.path); + if (!file || !existsSync(file) || !statSync(file).isFile()) return c.text('Not found', 404); return c.body(readFileSync(file), 200, { 'Content-Type': MIME[extname(file)] ?? 'application/octet-stream' }); }); diff --git a/src/server/resolve/choose.test.ts b/src/server/resolve/choose.test.ts index e115606..c064c48 100644 --- a/src/server/resolve/choose.test.ts +++ b/src/server/resolve/choose.test.ts @@ -68,3 +68,15 @@ test('earlier tier wins over later tiers', () => { test('unparseable only -> null', () => { assert.equal(chooseCallNumber({ ...none, olEdition: raws('[E]', 'Fic') }, m), null); }); + +test('literature class-only number with the author cutter gets a title cutter', () => { + const r = chooseCallNumber({ ...none, olEdition: raws('PS3552.R89') }, { authors: ['Frank Herbert'], title: 'Dune', year: 2010 }); + assert.equal(r?.callNumber, 'PS3552.R89 D86 2010'); + const the = chooseCallNumber({ ...none, olEdition: raws('PS3552.R89') }, { authors: ['Frank Herbert'], title: 'The Dune' }); + assert.equal(the?.callNumber, 'PS3552.R89 D86'); +}); + +test('non-literature class-only numbers still get the author cutter', () => { + const r = chooseCallNumber({ ...none, olEdition: raws('QA76.73.R87') }, { authors: ['Klabnik, Steve'], title: 'The Rust Programming Language', year: 2018 }); + assert.equal(r?.callNumber, 'QA76.73.R87 K53 2018'); +}); diff --git a/src/server/resolve/choose.ts b/src/server/resolve/choose.ts index 0a6c0c4..01454d3 100644 --- a/src/server/resolve/choose.ts +++ b/src/server/resolve/choose.ts @@ -59,7 +59,9 @@ export function chooseCallNumber( const approximate = tier === 'locTitle' || tier === 'olWork'; let { cn, complete } = pickMostFrequent(ps); if (!complete && cn.cutters.length < 3) { - const c = cutterFor(mainEntry(meta.authors, meta.title)); + // Literature (P plus one letter) already carries the author as its first cutter; the next one is the title. + const literature = /^P[A-Z]$/.test(cn.letters) && cn.cutters.length >= 1; + const c = cutterFor(literature ? meta.title.trim().replace(/^(a|an|the)\s+/i, '') : mainEntry(meta.authors, meta.title)); cn = { ...cn, cutters: [...cn.cutters, { letter: c[0]!, digits: c.slice(1) }] }; if (meta.year) cn = withYear(cn, meta.year); } diff --git a/src/server/resolve/match.test.ts b/src/server/resolve/match.test.ts new file mode 100644 index 0000000..c33d194 --- /dev/null +++ b/src/server/resolve/match.test.ts @@ -0,0 +1,28 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { normalizeTitle, recordMatches, titlesMatch } from './match.ts'; +import type { MarcFields } from '../sources/marc.ts'; + +const rec = (title: string, names: string[]): MarcFields => ({ lccn: null, lcc: [], dewey: null, meta: { title, authors: [], subjects: [] }, names }); + +test('normalizeTitle', () => { + assert.equal(normalizeTitle('The Mythical Man-Month: Essays on Software'), 'mythical man month'); + assert.equal(normalizeTitle('An Introduction!'), 'introduction'); +}); + +test('titlesMatch: equal or prefix, nothing looser', () => { + assert.ok(titlesMatch('The mythical man-month :', 'Mythical Man-Month')); + assert.ok(titlesMatch('Dune', 'Dune Messiah')); + assert.ok(!titlesMatch('Dunes', 'Dune')); + assert.ok(!titlesMatch('', 'Dune')); + assert.ok(titlesMatch('Rust', 'The Rust Programming Language')); +}); + +test('recordMatches needs title and an author surname', () => { + const r = rec('The mythical man-month', ['Brooks, Frederick P.']); + assert.ok(recordMatches(r, 'The Mythical Man-Month: Essays', 'Frederick P. Brooks')); + assert.ok(recordMatches(r, 'Mythical Man-Month', 'Brooks, Frederick P.')); + assert.ok(!recordMatches(r, 'Mythical Man-Month', 'Tolkien')); + assert.ok(!recordMatches(r, 'Something Else', 'Brooks')); + assert.ok(recordMatches(rec('Dune', ['Smith, Bob', 'Herbert, Frank']), 'Dune', 'Frank Herbert')); +}); diff --git a/src/server/resolve/match.ts b/src/server/resolve/match.ts new file mode 100644 index 0000000..4a7259c --- /dev/null +++ b/src/server/resolve/match.ts @@ -0,0 +1,26 @@ +import { mainEntry } from '../../shared/cutter.ts'; +import type { MarcFields } from '../sources/marc.ts'; + +const plain = (s: string): string => + s.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim(); + +/** Lower-case, main title only (before any ":"), no punctuation, no leading article. */ +export function normalizeTitle(title: string): string { + return plain(title.split(':')[0]!).replace(/^(a|an|the) /, ''); +} + +/** Equal, or one is a prefix of the other (a record may carry a longer or shorter main title). */ +export function titlesMatch(a: string, b: string): boolean { + const x = normalizeTitle(a); + const y = normalizeTitle(b); + if (!x || !y) return false; + return x === y || x.startsWith(y + ' ') || y.startsWith(x + ' '); +} + +/** Does a LoC record plausibly describe this book? Title must match and a 100/700 name must contain the surname. */ +export function recordMatches(rec: MarcFields, title: string, author: string): boolean { + if (!rec.meta.title || !titlesMatch(rec.meta.title, title)) return false; + const surname = plain(mainEntry([author], title)); + if (!surname) return false; + return rec.names.some((n) => (' ' + plain(n) + ' ').includes(' ' + surname + ' ')); +} diff --git a/src/server/resolve/resolver.test.ts b/src/server/resolve/resolver.test.ts index c1ca56a..1f5a10e 100644 --- a/src/server/resolve/resolver.test.ts +++ b/src/server/resolve/resolver.test.ts @@ -2,6 +2,8 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { createResolver, TemporaryError } from './resolver.ts'; 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'; function memCache(): SourceCache & { map: Map } { @@ -102,22 +104,72 @@ test('cache hits are not delayed by the throttle', async () => { assert.equal(sleeps.length, before); }); -test('two uncached ISBNs are spaced by locIntervalMs', async () => { - const f = fixtureFetch(); +const emptyLoc = '0'; +const locSetup = (sleeps: number[]) => { + const urls: string[] = []; + const fetchStub = (async (u: string) => { urls.push(String(u)); return new Response(emptyLoc, { status: 200 }); }) as typeof fetch; + const loc = createLoc({ fetch: fetchStub, cache: memCache(), intervalMs: 6000, sleep: async (ms) => { sleeps.push(ms); } }); + return { loc, urls }; +}; + +test('token bucket: three LoC calls go out at once, the fourth waits one interval', async () => { const sleeps: number[] = []; - const r = createResolver({ fetch: f.fetch, cache: memCache(), locIntervalMs: 6000, sleep: async (ms) => { sleeps.push(ms); } }); - await r.resolve({ isbn13: '9781593278281' }); - await r.resolve({ isbn13: '9780201835953' }); + const { loc } = locSetup(sleeps); + for (const i of ['1', '2', '3']) await loc.byIsbn(i); + assert.deepEqual(sleeps, []); + await loc.byIsbn('4'); assert.equal(sleeps.length, 1); assert.ok(sleeps[0]! > 5000 && sleeps[0]! <= 6000, String(sleeps[0])); }); -test('concurrent resolves are also spaced', async () => { - const f = fixtureFetch(); +test('token bucket: concurrent callers beyond the burst are spaced one interval apart', async () => { const sleeps: number[] = []; - const r = createResolver({ fetch: f.fetch, cache: memCache(), locIntervalMs: 6000, sleep: async (ms) => { sleeps.push(ms); } }); - await Promise.all([r.resolve({ isbn13: '9781593278281' }), r.resolve({ isbn13: '9780201835953' })]); - assert.equal(sleeps.length, 1); + const { loc } = locSetup(sleeps); + await Promise.all(['1', '2', '3', '4', '5'].map((i) => loc.byIsbn(i))); + assert.equal(sleeps.length, 2); + assert.ok(sleeps[0]! > 5000 && sleeps[0]! <= 6000); + assert.ok(sleeps[1]! > 11000 && sleeps[1]! <= 12000); +}); + +test('LoC tries https first and the port-210 endpoint only as the fallback', async () => { + const { loc, urls } = locSetup([]); + await loc.byIsbn('1'); + assert.ok(urls[0]!.startsWith('https://lx2.loc.gov/sru/lcdb?'), urls[0]); + const urls2: string[] = []; + const failFirst = (async (u: string) => { + urls2.push(String(u)); + if (urls2.length === 1) throw new TypeError('down'); + return new Response(emptyLoc, { status: 200 }); + }) as typeof fetch; + await createLoc({ fetch: failFirst, cache: memCache(), intervalMs: 0, sleep: noSleep }).byIsbn('1'); + assert.equal(urls2.length, 2); + assert.ok(urls2[1]!.startsWith('http://lx2.loc.gov:210/lcdb?'), urls2[1]); +}); + +test('a LoC response with no record is not cached; one with a record is', async () => { + const cache = memCache(); + const loc = createLoc({ fetch: (async () => new Response(emptyLoc)) as typeof fetch, cache, intervalMs: 0, sleep: noSleep }); + assert.deepEqual(await loc.byIsbn('9780999999998'), []); + assert.equal(cache.map.size, 0); + const f = fixtureFetch(); + const loc2 = createLoc({ fetch: f.fetch, cache, intervalMs: 0, sleep: noSleep }); + assert.equal((await loc2.byIsbn('9781593278281')).length, 1); + assert.equal(cache.map.size, 1); +}); + +test('an Open Library miss is not cached, so the next lookup asks again', async () => { + const cache = memCache(); + let n = 0; + const miss = (async () => { n++; return new Response('{}'); }) as typeof fetch; + const ol = createOpenLibrary({ fetch: miss, cache }); + assert.equal(await ol.edition('9780999999998'), null); + assert.equal(await ol.work('9780999999998'), null); + assert.equal(cache.map.size, 0); + await ol.edition('9780999999998'); + assert.equal(n, 3); + const f = fixtureFetch(); + await createOpenLibrary({ fetch: f.fetch, cache }).edition('9781593278281'); + assert.deepEqual([...cache.map.keys()], ['ol-data:9781593278281']); }); test('LCCN only', async () => { @@ -138,10 +190,10 @@ test('title and author only uses the LoC title tier', async () => { assert.ok(res.meta); }); -test('falls back to the HTTPS SRU endpoint when the first refuses', async () => { +test('falls back to the port-210 SRU endpoint when https fails', async () => { const f = fixtureFetch(); const wrapped = (async (input: string | URL | Request, init?: RequestInit) => { - if (String(input).includes(':210')) throw new TypeError('connect ECONNREFUSED'); + if (String(input).startsWith('https://lx2.loc.gov')) throw new TypeError('connect ECONNREFUSED'); return f.fetch(input as string, init); }) as typeof fetch; const res = await createResolver({ fetch: wrapped, cache: memCache(), sleep: noSleep }).resolve({ isbn13: '9781593278281' }); @@ -156,8 +208,50 @@ test('search by title and author', async () => { }); test('lccn.loc.gov "Record not found" (HTTP 200) is an empty result, not a block page', async () => { - const { createLoc } = await import('../sources/loc.ts'); const fetchStub = (async () => new Response('Record not found for LCCN: 2003054578.', { status: 200 })) as typeof fetch; const loc = createLoc({ fetch: fetchStub, cache: memCache(), intervalMs: 0, sleep: noSleep }); assert.deepEqual(await loc.byLccn('2003054578'), []); }); + +test('title tier is skipped when the book has no author', async () => { + const f = fixtureFetch(); + const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }).resolve({ title: 'The Mythical Man-Month' }); + assert.equal(res.callNumber, null); + assert.equal(f.locCalls().length, 0); +}); + +test('title tier ignores records for a different author', async () => { + const f = fixtureFetch(); + const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }) + .resolve({ title: 'The Mythical Man-Month', author: 'Tolkien, J. R. R.' }); + assert.ok(f.locCalls().length > 0); + assert.equal(res.callNumber, null); +}); + +test('title tier ignores records for a different title', async () => { + const f = fixtureFetch(); + const res = await createResolver({ fetch: f.fetch, cache: memCache(), sleep: noSleep }) + .resolve({ title: 'The Mythical Dragon', author: 'Frederick Brooks' }); + assert.equal(res.callNumber, null); +}); + +function locDown(f: ReturnType): typeof fetch { + return (async (input: string | URL | Request, init?: RequestInit) => + /loc\.gov/.test(String(input)) ? new Response('down', { status: 503 }) : f.fetch(input as string, init)) as typeof fetch; +} + +test('tolerateLocFailure: Open Library numbers are used when the LoC is down', async () => { + const f = fixtureFetch(); + const r = createResolver({ fetch: locDown(f), cache: memCache(), sleep: noSleep }); + await assert.rejects(r.resolve({ isbn13: '9780441172719' }), TemporaryError); + const res = await r.resolve({ isbn13: '9780441172719' }, { tolerateLocFailure: true }); + assert.ok(res.callNumber, res.reason ?? ''); + assert.match(res.callNumber!, /^PS3558/); + assert.ok(res.source === 'ol-edition' || res.source === 'ol-work'); +}); + +test('tolerateLocFailure: nothing from Open Library either still fails', async () => { + const f = fixtureFetch(); + const r = createResolver({ fetch: locDown(f), cache: memCache(), sleep: noSleep }); + await assert.rejects(r.resolve({ isbn13: '9780999999998' }, { tolerateLocFailure: true }), TemporaryError); +}); diff --git a/src/server/resolve/resolver.ts b/src/server/resolve/resolver.ts index 24157d3..5a95769 100644 --- a/src/server/resolve/resolver.ts +++ b/src/server/resolve/resolver.ts @@ -6,13 +6,20 @@ import { createOpenLibrary } from '../sources/openlibrary.ts'; import type { OlInfo } from '../sources/openlibrary.ts'; import type { MarcFields } from '../sources/marc.ts'; import { TemporaryError } from '../sources/http.ts'; +import { recordMatches } from './match.ts'; import type { SourceCache } from '../sources/http.ts'; export { TemporaryError }; 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. */ + tolerateLocFailure?: boolean; +} + export interface Resolver { - resolve(input: ResolveInput, opts?: { onMeta?: (meta: BookMeta) => void }): Promise; + resolve(input: ResolveInput, opts?: ResolveOpts): Promise; search(title: string, author: string): Promise; } @@ -50,7 +57,16 @@ export function createResolver(deps: { sleep: deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))), }); - async function resolve(input: ResolveInput, opts?: { onMeta?: (meta: BookMeta) => void }): Promise { + async function resolve(input: ResolveInput, opts?: ResolveOpts): Promise { + // In tolerant mode the first LoC failure switches the LoC tiers off for the rest of this lookup. + let locError: unknown = null; + const locCall = async (fn: () => Promise): Promise => { + if (locError) return []; + try { return await fn(); } catch (e) { + if (opts?.tolerateLocFailure && e instanceof TemporaryError) { locError = e; return []; } + throw e; + } + }; const isbn = input.isbn13 ? (normalizeIsbn(input.isbn13) ?? input.isbn13) : undefined; let notified = false; const notify = (m: BookMeta | null) => { @@ -82,11 +98,11 @@ export function createResolver(deps: { let locRecs: MarcFields[] = []; let exactSource: 'loc-isbn' | 'loc-lccn' = 'loc-isbn'; if (lccn) { - locRecs = await loc.byLccn(lccn); + locRecs = await locCall(() => loc.byLccn(lccn)); if (locRecs.length > 0) exactSource = 'loc-lccn'; } if (isbn && lccOf(locRecs).length === 0) { - const recs = await loc.byIsbn(isbn); + const recs = await locCall(() => loc.byIsbn(isbn)); if (recs.length > 0) { locRecs = recs; exactSource = 'loc-isbn'; } } @@ -112,8 +128,11 @@ export function createResolver(deps: { work ??= await getWork(false); const m = metaOf([work?.meta]); const title = m?.title ?? input.title; - if (title) { - locTitleRecs = await loc.byTitle(title, m?.authors[0] ?? input.author ?? ''); + const author = m?.authors[0] ?? input.author ?? ''; + // Without an author a title search cannot be verified, so the tier is skipped. + if (title && author) { + const found = await locCall(() => loc.byTitle(title, author)); + locTitleRecs = found.filter((r) => recordMatches(r, title, author)); chosen = chooseCallNumber( { locExact: [], olEdition: [], locTitle: lccOf(locTitleRecs), olWork: [] }, forChoose(m), exactSource, @@ -141,6 +160,8 @@ export function createResolver(deps: { confidence: chosen.confidence, source: chosen.source, dewey, reason: null, }; } + // Open Library had nothing and the LoC could not be asked: report that, not "no number found". + if (locError) throw locError; return { meta, callNumber: null, sortKey: null, confidence: null, source: null, dewey, reason: meta ? 'No Library of Congress number found' : 'Not found in Open Library or the Library of Congress', diff --git a/src/server/sources/http.test.ts b/src/server/sources/http.test.ts new file mode 100644 index 0000000..6655ca8 --- /dev/null +++ b/src/server/sources/http.test.ts @@ -0,0 +1,27 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { getText, REQUEST_TIMEOUT_MS, TemporaryError } from './http.ts'; + +test('every request carries a 15 s abort signal', async () => { + assert.equal(REQUEST_TIMEOUT_MS, 15_000); + let signal: AbortSignal | undefined; + await getText((async (_u: string, init?: RequestInit) => { signal = init?.signal ?? undefined; return new Response('ok'); }) as typeof fetch, 'http://x/'); + assert.ok(signal instanceof AbortSignal); + assert.equal(signal.aborted, false); +}); + +test('a request that never answers becomes a TemporaryError', async () => { + const hang = ((_u: string, init?: RequestInit) => new Promise((_res, rej) => { + init!.signal!.addEventListener('abort', () => rej(init!.signal!.reason)); + })) as typeof fetch; + await assert.rejects(getText(hang, 'http://x/', 20), (e: Error) => e instanceof TemporaryError && /Timed out/.test(e.message)); +}); + +test('a body that stalls past the timeout is a TemporaryError too', async () => { + const slowBody = (async (_u: string, init?: RequestInit) => { + const res = new Response('x'); + res.text = () => new Promise((_a, rej) => { init!.signal!.addEventListener('abort', () => rej(init!.signal!.reason)); }); + return res; + }) as typeof fetch; + await assert.rejects(getText(slowBody, 'http://x/', 20), TemporaryError); +}); diff --git a/src/server/sources/http.ts b/src/server/sources/http.ts index 7ae7e8d..a0318b2 100644 --- a/src/server/sources/http.ts +++ b/src/server/sources/http.ts @@ -2,16 +2,27 @@ export class TemporaryError extends Error {} export interface SourceCache { get(key: string): string | null; set(key: string, body: string): void } +/** The database cache can also forget entries, so "Look up again" really asks again. */ +export interface ForgettableCache extends SourceCache { + delete(key: string): void; + deletePrefix(prefix: string): void; +} + +export const REQUEST_TIMEOUT_MS = 15_000; + export const USER_AGENT = 'booksorter/0.1 (personal library tool)'; export interface HttpResult { status: number; body: string } /** One GET. Network errors and 5xx/429 become TemporaryError; other statuses are returned. */ -export async function getText(f: typeof fetch, url: string): Promise { +export async function getText(f: typeof fetch, url: string, timeoutMs = REQUEST_TIMEOUT_MS): Promise { + const signal = AbortSignal.timeout(timeoutMs); + const timedOut = (e: unknown) => signal.aborted || (e as Error)?.name === 'TimeoutError'; let res: Response; try { - res = await f(url, { headers: { 'User-Agent': USER_AGENT } }); + 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}`); throw new TemporaryError(`Network error for ${url}: ${(e as Error).message}`); } if (res.status >= 500 || res.status === 429) throw new TemporaryError(`HTTP ${res.status} from ${url}`); @@ -19,6 +30,7 @@ export async function getText(f: typeof fetch, url: string): Promise 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}: ${(e as Error).message}`); } return { status: res.status, body }; diff --git a/src/server/sources/loc.ts b/src/server/sources/loc.ts index 8d6a66e..aa9da8e 100644 --- a/src/server/sources/loc.ts +++ b/src/server/sources/loc.ts @@ -4,7 +4,9 @@ import type { SourceCache } from './http.ts'; import { parseMarcXml } from './marc.ts'; import type { MarcFields } from './marc.ts'; -const SRU_URLS = ['http://lx2.loc.gov:210/lcdb', 'https://lx2.loc.gov/sru/lcdb']; +// https first; port 210 is blocked on some networks, so plain http on 210 is only the fallback. +export const SRU_URLS = ['https://lx2.loc.gov/sru/lcdb', 'http://lx2.loc.gov:210/lcdb']; +export const BURST = 3; const MAX_INTERVAL_MS = 60_000; export function isLocXml(body: string): boolean { @@ -22,19 +24,26 @@ export function createLoc(deps: { }): Loc { const baseInterval = deps.intervalMs; let interval = baseInterval; - let lastSlot: number | null = null; + // Token bucket: BURST tokens, one returns every `interval`. A book's two or three calls go out together; + // the long-run rate is one per interval. Tokens may go negative: that is a queue of reserved future slots. + let tokens = BURST; + let lastRefill = Date.now(); - /** Reserve the next request slot synchronously so concurrent callers are spaced too. */ + /** Take a token synchronously (so concurrent callers queue up too), then wait if it was not yet available. */ async function throttle(): Promise { + if (interval <= 0) return; const now = Date.now(); - const slot = lastSlot === null ? now : Math.max(now, lastSlot + interval); - lastSlot = slot; - if (slot > now) await deps.sleep(slot - now); + tokens = Math.min(BURST, tokens + (now - lastRefill) / interval); + lastRefill = now; + const wait = tokens >= 1 ? 0 : Math.ceil((1 - tokens) * interval); + tokens -= 1; + if (wait > 0) await deps.sleep(wait); } function blocked(): never { interval = Math.min(interval * 2, MAX_INTERVAL_MS); - lastSlot = Date.now(); + 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'); } @@ -63,8 +72,9 @@ export function createLoc(deps: { if (body === null) throw lastErr; if (!isLocXml(body)) blocked(); ok(); - deps.cache.set(cacheKey, body); - return parseMarcXml(body); + const recs = parseMarcXml(body); + if (recs.length > 0) deps.cache.set(cacheKey, body); // a miss is not cached: asking again may find it + return recs; } return { @@ -79,8 +89,9 @@ export function createLoc(deps: { if (res.status === 404 || /\s*Record not found/i.test(res.body)) { ok(); return []; } if (res.status >= 400 || !isLocXml(res.body)) blocked(); ok(); - deps.cache.set(key, res.body); - return parseMarcXml(res.body); + const recs = parseMarcXml(res.body); + if (recs.length > 0) deps.cache.set(key, res.body); + return recs; }, byTitle(title, author) { const t = title.replace(/"/g, ' ').trim(); diff --git a/src/server/sources/marc.test.ts b/src/server/sources/marc.test.ts index 86c8e04..b37aa61 100644 --- a/src/server/sources/marc.test.ts +++ b/src/server/sources/marc.test.ts @@ -10,7 +10,7 @@ test('SRU wrapped record', () => { const [r] = parseMarcXml(fx('loc-isbn-9781593278281.xml')); assert.deepEqual(r!.lcc, [{ raw: 'QA76.73.R87 K53 2018', complete: true }]); assert.match(r!.meta.title!, /Rust/); - assert.ok(r!.meta.authors!.some((a) => a.startsWith('Klabnik'))); + assert.ok(r!.meta.authors!.some((a) => a.endsWith('Klabnik'))); assert.equal(r!.meta.year, 2018); assert.ok(r!.lccn); }); @@ -53,3 +53,27 @@ test('non-text records (a DVD of the book) contribute no call number', () => { assert.equal(parseMarcXml(rec('g'))[0]!.meta.title, 'Harry Potter'); assert.equal(parseMarcXml(rec('a'))[0]!.lcc.length, 1); }); + +test('authors: 100 only, dates and commas stripped, shown as Forename Surname', () => { + const xml = ` + Herbert, Frank,1920-1986. + Dune / + Whelan, Michael,1950-`; + const [r] = parseMarcXml(xml); + assert.deepEqual(r!.meta.authors, ['Frank Herbert']); + assert.deepEqual(r!.names, ['Herbert, Frank', 'Whelan, Michael']); +}); + +test('authors: 700 only stands in when there is no 100; dates inside $a are removed', () => { + const xml = ` + Anthology + Brooks, Frederick P., 1931- + King, Martin Luther, Jr.,`; + const [r] = parseMarcXml(xml); + assert.deepEqual(r!.meta.authors, ['Frederick P. Brooks', 'Martin Luther King Jr.']); +}); + +test('the Rust fixture shows a plain author name', () => { + const [r] = parseMarcXml(fx('loc-isbn-9781593278281.xml')); + assert.ok(r!.meta.authors!.every((a) => !a.includes(',') && !/\d/.test(a)), String(r!.meta.authors)); +}); diff --git a/src/server/sources/marc.ts b/src/server/sources/marc.ts index 40885ec..4c6c191 100644 --- a/src/server/sources/marc.ts +++ b/src/server/sources/marc.ts @@ -7,6 +7,8 @@ export interface MarcFields { lcc: Candidate[]; dewey: string | null; meta: Partial; + /** Every 100/700 $a, cleaned but still in "Surname, Forename" form; used to verify title/author matches. */ + names: string[]; } type Node = Record; @@ -60,6 +62,25 @@ function sub(f: Field, code: string): string { function uniq(a: string[]): string[] { return [...new Set(a)]; } +/** Strip trailing punctuation and life dates from a MARC name: "Brooks, Frederick P., 1931-" -> "Brooks, Frederick P." */ +export function cleanName(raw: string): string { + let s = raw.trim(); + s = s.replace(/[,\s]*\(?\b(?:b\.\s*|d\.\s*|ca\.\s*)?\d{3,4}\??\s*-\s*(?:\d{3,4})?\)?[.,\s]*$/i, ''); + s = s.replace(/[\s,;:\/]+$/, ''); + // Keep the period of an initial or Jr./Sr.; drop the ISBD full stop after other words. + const last = /([^\s,]+)\.$/.exec(s)?.[1]; + if (last && last.length > 1 && !/^(jr|sr)$/i.test(last)) s = s.slice(0, -1); + return s.trim(); +} + +/** "Herbert, Frank" -> "Frank Herbert"; "King, Martin Luther, Jr." -> "Martin Luther King Jr."; names without a comma are left alone. */ +export function displayName(name: string): string { + const parts = name.split(',').map((p) => p.trim()).filter(Boolean); + if (parts.length < 2) return name.trim(); + const [surname, forenames, ...suffix] = parts as [string, string, ...string[]]; + return [forenames, surname, ...suffix].join(' '); +} + export function parseMarcRecord(rec: Node): MarcFields { const fields = fieldsOf(rec); const all = (tag: string) => fields.filter((f) => f.tag === tag); @@ -83,9 +104,10 @@ export function parseMarcRecord(rec: Node): MarcFields { const title = f245 ? trimPunct(sub(f245, 'a')) : ''; const subtitle = f245 ? trimPunct(sub(f245, 'b')) : ''; - const authors = uniq( - [...all('100'), ...all('700')].map((f) => trimPunct(sub(f, 'a'))).filter(Boolean), - ); + const f100 = all('100'); + const names = uniq([...f100, ...all('700')].map((f) => cleanName(sub(f, 'a'))).filter(Boolean)); + // The 100 is the author; 700s (editors, illustrators, co-authors) only stand in when there is none. + const authors = uniq((f100.length ? f100 : all('700')).map((f) => cleanName(sub(f, 'a'))).filter(Boolean).map(displayName)); const pub = all('260')[0] ?? all('264').find((f) => f.ind2 === '1') ?? all('264')[0]; const publisher = pub ? trimPunct(sub(pub, 'b')) : ''; @@ -101,7 +123,7 @@ export function parseMarcRecord(rec: Node): MarcFields { if (publisher) meta.publisher = publisher; if (ym) meta.year = Number(ym[1]); if (lccn) meta.lccn = lccn; - return { lccn, lcc, dewey, meta }; + return { lccn, lcc, dewey, meta, names }; } /** Parse every MARC record in an SRU response or a bare LCCN permalink record. */ diff --git a/src/server/sources/openlibrary.ts b/src/server/sources/openlibrary.ts index f9ccc82..1875707 100644 --- a/src/server/sources/openlibrary.ts +++ b/src/server/sources/openlibrary.ts @@ -102,7 +102,8 @@ export interface OpenLibrary { } export function createOpenLibrary(deps: { fetch: typeof fetch; cache: SourceCache }): OpenLibrary { - async function body(key: string | null, url: string): Promise { + /** Only a response that actually held a record (per `hasRecord`) is cached, so misses are asked again. */ + async function body(key: string | null, url: string, hasRecord: (text: string) => boolean = () => true): Promise { if (key) { const hit = deps.cache.get(key); if (hit !== null) return hit; @@ -111,17 +112,17 @@ export function createOpenLibrary(deps: { fetch: typeof fetch; cache: SourceCach // 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 - if (key && res.status < 400) deps.cache.set(key, text); + if (key && res.status < 400 && hasRecord(text)) deps.cache.set(key, text); return text; } return { async edition(isbn) { const url = `https://openlibrary.org/api/books?bibkeys=ISBN:${isbn}&jscmd=data&format=json`; - return parseEdition(await body(`ol-data:${isbn}`, url), isbn); + return parseEdition(await body(`ol-data:${isbn}`, url, (t) => parseEdition(t, isbn) !== null), isbn); }, async work(isbn) { const url = `https://openlibrary.org/search.json?isbn=${isbn}&fields=${FIELDS}`; - return parseWork(await body(`ol-search:${isbn}`, url)); + return parseWork(await body(`ol-search:${isbn}`, url, (t) => parseWork(t) !== null)); }, async search(title, author) { const q = new URLSearchParams(); diff --git a/src/server/static.test.ts b/src/server/static.test.ts new file mode 100644 index 0000000..c1c8d5e --- /dev/null +++ b/src/server/static.test.ts @@ -0,0 +1,14 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { staticPath } from './static.ts'; + +test('static paths stay inside the web root', () => { + const root = '/srv/dist/web'; + assert.equal(staticPath(root, '/'), '/srv/dist/web/index.html'); + assert.equal(staticPath(root, '/assets/app.js'), '/srv/dist/web/assets/app.js'); + assert.equal(staticPath(root, '/../webx/secret'), '/srv/dist/web/webx/secret'); + assert.equal(staticPath(root, '..%2Fwebx/secret'), null); + assert.equal(staticPath(root, '/%2e%2e/%2e%2e/etc/passwd'), '/srv/dist/web/etc/passwd'); + assert.equal(staticPath(root, '/bad%zz'), null); + assert.equal(staticPath(root, '/a%00b'), null); +}); diff --git a/src/server/static.ts b/src/server/static.ts new file mode 100644 index 0000000..84e0b36 --- /dev/null +++ b/src/server/static.ts @@ -0,0 +1,12 @@ +import { sep, normalize, resolve as resolvePath } from 'node:path'; + +/** Map a request path to a file under `root`, or null when it would leave the root. Does not check existence. */ +export function staticPath(root: string, urlPath: string): string | null { + let decoded: string; + try { decoded = decodeURIComponent(urlPath); } catch { return null; } + if (decoded.includes('\0')) return null; + const rel = normalize(decoded).replace(/^([/\\])+/, ''); + const file = resolvePath(root, rel === '' ? 'index.html' : rel); + // Compare with a trailing separator so a sibling like "x" cannot pass as inside "". + return file.startsWith(root.endsWith(sep) ? root : root + sep) ? file : null; +} diff --git a/src/shared/callnumber.test.ts b/src/shared/callnumber.test.ts index 36ab43b..9bc96ca 100644 --- a/src/shared/callnumber.test.ts +++ b/src/shared/callnumber.test.ts @@ -16,6 +16,7 @@ test('format', () => { ['PS-3558.00000000.E63 D8 2005', 'PS3558.E63 D8 2005'], ['PZ7.R79835 Har 1998', 'PZ7.R79835 Har 1998'], ['qa76.73.r87 k53 2018', 'QA76.73.R87 K53 2018'], + ['QA76.73.R87x K53 2018', 'QA76.73.R87x K53 2018'], ]; for (const [i, o] of cases) assert.equal(fmt(i), o, i); }); @@ -54,3 +55,19 @@ test('sort order', () => { shuffled.sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0)); assert.deepEqual(shuffled, want); }); + +test('cutter with one trailing lower-case letter', () => { + const cn = parseCallNumber('QA76.73.R87x K53 2018')!; + assert.deepEqual(cn.cutters, [{ letter: 'R', digits: '87x' }, { letter: 'K', digits: '53' }]); + assert.equal(cn.suffix, '2018'); + assert.deepEqual(parseCallNumber('QA76.73.C15K47 1988')!.cutters, [{ letter: 'C', digits: '15' }, { letter: 'K', digits: '47' }]); + assert.deepEqual(parseCallNumber('qa76.73.r87 k53 2018')!.cutters.map((c) => c.letter + c.digits), ['R87', 'K53']); +}); + +test('years with a trailing copy letter', () => { + const w = (raw: string, y: number) => formatCallNumber(withYear(parseCallNumber(raw)!, y)); + assert.equal(w('PS3562.E353 B3 1997c', 2005), 'PS3562.E353 B3 2005'); + assert.equal(w('PS3562.E353 B3 2005b', 2007), 'PS3562.E353 B3 2007'); + assert.equal(w('PZ7.R79835 Har 1998', 2001), 'PZ7.R79835 Har 2001'); + assert.equal(hasYear(parseCallNumber('PS3562.E353 B3 1997c')!), true); +}); diff --git a/src/shared/callnumber.ts b/src/shared/callnumber.ts index 9d56336..a745292 100644 --- a/src/shared/callnumber.ts +++ b/src/shared/callnumber.ts @@ -16,7 +16,8 @@ export function parseCallNumber(raw: string): CallNumber | null { let rest = m[4]!; const cutters: { letter: string; digits: string }[] = []; while (cutters.length < 3) { - const c = /^\s*\.?\s*([A-Za-z])(\d+)/.exec(rest); + // A cutter may carry one trailing lower-case letter ("R87x") when nothing alphanumeric follows it. + const c = /^\s*\.?\s*([A-Za-z])(\d+(?:[a-z](?![A-Za-z0-9]))?)/.exec(rest); if (!c) break; cutters.push({ letter: c[1]!.toUpperCase(), digits: c[2]! }); rest = rest.slice(c[0].length); @@ -58,7 +59,8 @@ export function cardLines(cn: CallNumber): [string, string] { return [line1, line2]; } -const YEAR = /\b(1[4-9]\d\d|20\d\d)\b/; +// A year may carry a copy-letter: 1997c. +const YEAR = /\b(1[4-9]\d\d|20\d\d)[a-z]?\b/; export function hasYear(cn: CallNumber): boolean { return YEAR.test(cn.suffix); } export function withYear(cn: CallNumber, year: number): CallNumber { diff --git a/src/shared/cutter.test.ts b/src/shared/cutter.test.ts index 6e0be5c..7b44ae7 100644 --- a/src/shared/cutter.test.ts +++ b/src/shared/cutter.test.ts @@ -16,3 +16,11 @@ test('mainEntry', () => { assert.equal(mainEntry(['Steve Klabnik'], 'x'), 'Klabnik'); assert.equal(mainEntry([], 'The Mythical Man-Month'), 'Mythical Man-Month'); }); + +test('mainEntry: both name forms and suffixes give the surname', () => { + assert.equal(mainEntry(['Herbert, Frank'], 'x'), 'Herbert'); + assert.equal(mainEntry(['Frank Herbert'], 'x'), 'Herbert'); + assert.equal(mainEntry(['Martin Luther King Jr.'], 'x'), 'King'); + assert.equal(mainEntry(['King, Martin Luther, Jr.'], 'x'), 'King'); + assert.equal(mainEntry(['Martin Luther King, Jr.'], 'x'), 'King'); +}); diff --git a/src/shared/cutter.ts b/src/shared/cutter.ts index 6269402..5d10a18 100644 --- a/src/shared/cutter.ts +++ b/src/shared/cutter.ts @@ -51,12 +51,21 @@ export function cutterFor(name: string): string { return out; } +const SUFFIX = /^(jr|sr|ii|iii|iv|esq|md|phd)\.?$/i; + export function mainEntry(authors: string[], title: string): string { - const a = authors[0]?.trim(); + const a = authors[0]?.trim().replace(/[\s,;]+$/, ''); if (a) { - if (a.includes(',')) return a.split(',')[0]!.trim(); + if (a.includes(',')) { + const head = a.split(',')[0]!.trim(); + // "Frank Herbert, Jr." has its suffix after the comma; "Herbert, Frank" has the forenames. + const words = head.split(/\s+/); + if (words.length > 1 && a.split(',').slice(1).every((p) => SUFFIX.test(p.trim()))) return words[words.length - 1]!; + return head; + } const words = a.split(/\s+/); - return words[words.length - 1]!; + while (words.length > 1 && SUFFIX.test(words[words.length - 1]!)) words.pop(); + return words[words.length - 1]!.replace(/\.$/, ''); } return title.trim().replace(/^(a|an|the)\s+/i, ''); } diff --git a/src/web/bookstate.test.ts b/src/web/bookstate.test.ts new file mode 100644 index 0000000..75520ed --- /dev/null +++ b/src/web/bookstate.test.ts @@ -0,0 +1,60 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import type { Book } from '../shared/types.ts'; +import { elapsedText, pdfLabel, queueHeader, queueSplit, queueTabLabel, rowState, sessionSummary } from './bookstate.ts'; + +function book(id: number, over: Partial): Book { + return { + id, isbn13: null, lccn: null, title: 'T' + id, subtitle: null, authors: [], publisher: null, year: null, + subjects: [], callNumber: null, sortKey: null, confidence: null, source: null, dewey: null, + status: 'pending', attentionReason: null, manualOverride: false, inQueue: true, + printedAt: null, createdAt: '', updatedAt: '', ...over, + }; +} +const ready = (id: number) => book(id, { status: 'resolved', callNumber: 'QA76.73 .R87 K53 2018', sortKey: 'k' + id }); +const looking = (id: number) => book(id, {}); +const attention = (id: number) => book(id, { status: 'needs_attention', attentionReason: 'No match' }); + +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.' }); +}); + +test('ready and attention states', () => { + assert.deepEqual(rowState(ready(1)), { kind: 'ready' }); + assert.deepEqual(rowState(attention(1)), { kind: 'attention', reason: 'No match' }); + assert.equal(rowState(book(1, { status: 'resolved' })).kind, 'attention'); +}); + +test('session summary', () => { + assert.equal(sessionSummary([ready(1), ready(2), ready(3), looking(4)]), '4 scanned · 3 ready · 1 looking up'); + assert.equal(sessionSummary([ready(1)]), '1 scanned · 1 ready'); + assert.equal(sessionSummary([attention(1), attention(2), looking(3)]), '3 scanned · 1 looking up · 2 need attention'); + assert.equal(sessionSummary([]), '0 scanned'); +}); + +test('queue split ignores books that are not queued or need attention', () => { + const printed = { ...ready(9), inQueue: false }; + const q = queueSplit([ready(1), looking(2), attention(3), printed, ready(4)]); + assert.deepEqual(q.ready.map(b => b.id), [1, 4]); + assert.deepEqual(q.looking.map(b => b.id), [2]); +}); + +test('queue labels', () => { + assert.equal(queueHeader(3, 1), '3 cards ready · 1 still looking up'); + assert.equal(queueHeader(1, 0), '1 card ready'); + assert.equal(queueHeader(0, 1), '0 cards ready · 1 still looking up'); + assert.equal(pdfLabel(3), 'Make PDF (3 cards)'); + assert.equal(pdfLabel(1), 'Make PDF (1 card)'); + assert.equal(pdfLabel(0), 'Make PDF'); + assert.equal(queueTabLabel(3, 1), 'Print queue (4)'); + assert.equal(queueTabLabel(0, 0), 'Print queue'); +}); + +test('elapsed text', () => { + assert.equal(elapsedText(0), '0 s'); + assert.equal(elapsedText(59_900), '59 s'); + assert.equal(elapsedText(65_000), '1 min 05 s'); + assert.equal(elapsedText(-5), '0 s'); +}); diff --git a/src/web/bookstate.ts b/src/web/bookstate.ts new file mode 100644 index 0000000..c4c5c42 --- /dev/null +++ b/src/web/bookstate.ts @@ -0,0 +1,62 @@ +import type { Book } from '../shared/types.ts'; + +/** The single state a book is shown in. */ +export type RowState = + | { kind: 'looking'; note: string | 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 === '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.' }; +} + +const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`; + +export function sessionSummary(books: Book[]): string { + let ready = 0, looking = 0, attention = 0; + for (const b of books) { + const s = rowState(b).kind; + if (s === 'ready') ready++; else if (s === 'looking') looking++; else attention++; + } + const parts = [`${books.length} scanned`]; + if (ready) parts.push(`${ready} ready`); + if (looking) parts.push(`${looking} looking up`); + if (attention) parts.push(`${attention} ${attention === 1 ? 'needs' : 'need'} attention`); + return parts.join(' · '); +} + +export interface QueueSplit { ready: Book[]; looking: Book[] } + +/** Queued books, split into the ones that can be printed now and the ones still being looked up. */ +export function queueSplit(books: Book[]): QueueSplit { + const ready: Book[] = [], looking: Book[] = []; + for (const b of books) { + if (!b.inQueue) continue; + const s = rowState(b).kind; + if (s === 'ready') ready.push(b); else if (s === 'looking') looking.push(b); + } + return { ready, looking }; +} + +export function queueHeader(ready: number, looking: number): string { + const head = plural(ready, 'card', 'cards') + ' ready'; + return looking ? `${head} · ${looking} still looking up` : head; +} + +export function pdfLabel(ready: number): string { + return ready ? `Make PDF (${plural(ready, 'card', 'cards')})` : 'Make PDF'; +} + +export function queueTabLabel(ready: number, looking: number): string { + const n = ready + looking; + return n ? `Print queue (${n})` : 'Print queue'; +} + +/** "12 s", "1 min 05 s" */ +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`; +} diff --git a/src/web/components/BookEditor.tsx b/src/web/components/BookEditor.tsx index 3d7ce82..0bcde1e 100644 --- a/src/web/components/BookEditor.tsx +++ b/src/web/components/BookEditor.tsx @@ -2,6 +2,7 @@ import { useState } from 'preact/hooks'; import type { Book } from '../../shared/types.ts'; import { api } from '../api.ts'; import { upsertBook, dispatch } from '../live.ts'; +import { parseYear } from '../year.ts'; export function BookEditor({ book, onClose }: { book: Book; onClose: () => void }) { const [title, setTitle] = useState(book.title); @@ -10,6 +11,7 @@ export function BookEditor({ book, onClose }: { book: Book; onClose: () => void const [year, setYear] = useState(book.year?.toString() ?? ''); const [callNumber, setCallNumber] = useState(book.callNumber ?? ''); const [msg, setMsg] = useState(''); + const [yearError, setYearError] = useState(''); const [busy, setBusy] = useState(false); async function run(fn: () => Promise) { @@ -18,17 +20,23 @@ export function BookEditor({ book, onClose }: { book: Book; onClose: () => void setBusy(false); } - const save = (ev: Event) => { ev.preventDefault(); void run(async () => { + const save = (ev: Event) => { + ev.preventDefault(); + const y = parseYear(year); + if (!y.ok) { setYearError('Enter the year as digits, for example 2018, or leave it empty.'); return; } + setYearError(''); + void run(async () => { const patch: Record = { title: title.trim(), authors: authors.split(/[;\n]/).map(a => a.trim()).filter(Boolean), publisher: publisher.trim() || null, - year: year.trim() ? Number(year) : null, + year: y.value, }; if (callNumber.trim() !== (book.callNumber ?? '')) patch.callNumber = callNumber.trim(); upsertBook(await api.patchBook(book.id, patch)); onClose(); - }); }; + }); + }; return (
@@ -36,8 +44,9 @@ export function BookEditor({ book, onClose }: { book: Book; onClose: () => void
- +
+ {yearError ? : null}