Ride out Open Library's dropped connections

Open Library resets or times out a share of connections. Retry a failed
connection quickly inside the Open Library client, name the real cause
(ECONNRESET and the like) in the error, and have title search retry and
then answer 503 with a plain message instead of an unhandled exception.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-22 11:20:01 -07:00
1 parent bb46d343a8
commit ee10e00ccd
5 files changed
+96 -16

No files matched your search

+21
View File
@@ -325,3 +325,24 @@ test('PATCH edition: typed text is kept, clearing it means "none" (not "look up
assert.equal(b.book.edition, '');
assert.equal(db.getBook(book.id)!.edition, '');
});
test('a title search that hits a temporary failure is retried, then answers 503 with a plain message', async () => {
const { TemporaryError } = await import('./sources/http.ts');
let calls = 0;
const mk = (failures: number) => {
calls = 0;
const resolver = { resolve: async () => found, tail: async () => [], edition: async () => '', search: async () => { if (++calls <= failures) throw new TemporaryError('boom'); return [{ title: 'Hit', authors: [], lcc: [] }]; } };
const db = openDb(':memory:');
return createApp({
db, jobs: createJobs({ db, resolver, onChange: () => {}, log: () => {} }), resolver, searchRetryDelaysMs: [0, 0],
renderCardsPdf: async () => new Uint8Array(), renderCalibrationPdf: async () => new Uint8Array(),
classNames: () => ({ className: '', subclassName: '' }),
});
};
const ok = await mk(2).request('/api/search?title=a');
assert.equal(ok.status, 200);
assert.equal(calls, 3);
const bad = await mk(99).request('/api/search?title=a');
assert.equal(bad.status, 503);
assert.match(((await bad.json()) as any).error, /Open Library did not answer/);
});
+20 -4
View File
@@ -8,6 +8,7 @@ import { OFFSET_LIMIT_MM, ROTATION_LIMIT_DEG } from '../shared/sheet.ts';
import type { Book, CardData, Hierarchy, SearchResult, Settings } from '../shared/types.ts';
import { normalizeIsbn } from '../shared/isbn.ts';
import { formatCallNumber, parseCallNumber, sortKeyOfRaw } from '../shared/callnumber.ts';
import { TemporaryError } from './sources/http.ts';
import type { Db, Filter, NewBook } from './db.ts';
import type { Jobs, ResolverLike } from './jobs.ts';
import type { renderCalibrationPdf, renderCardsPdf } from './pdf/render.ts';
@@ -48,11 +49,13 @@ export interface AppDeps {
events?: EventBus;
/** Where pictures the scanner failed to read are kept for tuning (the newest 30). */
capturesDir?: string;
/** Waits between tries of a title search that hit a temporary failure (default 1 s, 3 s). */
searchRetryDelaysMs?: number[];
}
class HttpError extends Error {
status: 400 | 404;
constructor(status: 400 | 404, message: string) { super(message); this.status = status; }
status: 400 | 404 | 503;
constructor(status: 400 | 404 | 503, message: string) { super(message); this.status = status; }
}
const str = (v: unknown): string | null => (typeof v === 'string' && v.trim() ? v.trim() : null);
@@ -169,8 +172,21 @@ export function createApp(deps: AppDeps): Hono {
const title = c.req.query('title')?.trim() ?? '';
const author = c.req.query('author')?.trim() ?? '';
if (!title && !author) throw new HttpError(400, 'Enter a title or an author');
const results: SearchResult[] = await resolver.search(title, author);
return c.json(results);
// Open Library drops connections now and then: ask again a couple of times, then say so plainly.
const delays = deps.searchRetryDelaysMs ?? [1_000, 3_000];
for (let n = 0; ; n++) {
try {
const results: SearchResult[] = await resolver.search(title, author);
return c.json(results);
} catch (e) {
if (!(e instanceof TemporaryError)) throw e;
if (n >= delays.length) {
console.error(`[search] ${e.message}`);
throw new HttpError(503, 'Open Library did not answer. Try the search again in a moment.');
}
await new Promise((r) => setTimeout(r, delays[n]));
}
}
});
app.post('/api/books/from-search', async (c) => {
+18 -1
View File
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { getText, REQUEST_TIMEOUT_MS, TemporaryError } from './http.ts';
import { describeError, 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);
@@ -25,3 +25,20 @@ test('a body that stalls past the timeout is a TemporaryError too', async () =>
}) as typeof fetch;
await assert.rejects(getText(slowBody, 'http://x/', 20), TemporaryError);
});
test('a connection reset is tried again, and the cause is named when it keeps failing', async () => {
let calls = 0;
const reset = () => Object.assign(new TypeError('fetch failed'), { cause: Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' }) });
const flaky = (async () => { if (++calls < 3) throw reset(); return new Response('ok'); }) as unknown as typeof fetch;
assert.equal((await getText(flaky, 'http://x/', 1000, [0, 0])).body, 'ok');
assert.equal(calls, 3);
calls = 0;
const dead = (async () => { calls++; throw reset(); }) as unknown as typeof fetch;
await assert.rejects(getText(dead, 'http://x/', 1000, [0, 0]), (e: Error) => e instanceof TemporaryError && /ECONNRESET/.test(e.message));
assert.equal(calls, 3);
});
test('describeError lists every address of an aggregate failure once', () => {
const e = Object.assign(new TypeError('fetch failed'), { cause: Object.assign(new Error(''), { errors: [{ code: 'ETIMEDOUT' }, { code: 'ENETUNREACH' }, { code: 'ETIMEDOUT' }] }) });
assert.equal(describeError(e), 'fetch failed (ETIMEDOUT; ENETUNREACH)');
});
+35 -9
View File
@@ -14,16 +14,42 @@ export const USER_AGENT = 'booksorter/0.1 (personal library tool)';
export interface HttpResult { status: number; body: string }
/**
* Open Library (archive.org) often resets or drops a connection, then answers the very next try: so a failure to
* connect is tried again a couple of times here, quickly, before it counts as a failed lookup (opt-in per caller: the
* Library of Congress client has its own fallback endpoint instead).
*/
export const CONNECT_RETRY_DELAYS_MS = [400, 1_200];
/** node's fetch says only "fetch failed"; the reason (ECONNRESET, UND_ERR_CONNECT_TIMEOUT, ...) is in `cause`. */
export function describeError(e: unknown): string {
const err = e as { message?: string; cause?: unknown } | null;
const parts = [err?.message ?? String(e)];
const cause = err?.cause as { code?: string; message?: string; errors?: { code?: string; message?: string }[] } | undefined;
if (cause) {
const list = cause.errors?.length ? cause.errors : [cause];
const why = [...new Set(list.map((c) => [c.code, c.message].filter(Boolean).join(' ')).filter(Boolean))];
if (why.length) parts.push(`(${why.join('; ')})`);
}
return parts.join(' ');
}
/** One GET. Network errors and 5xx/429 become TemporaryError; other statuses are returned. */
export async function getText(f: typeof fetch, url: string, timeoutMs = REQUEST_TIMEOUT_MS): Promise<HttpResult> {
const signal = AbortSignal.timeout(timeoutMs);
export async function getText(
f: typeof fetch, url: string, timeoutMs = REQUEST_TIMEOUT_MS, retryDelaysMs: number[] = [],
): Promise<HttpResult> {
let 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 }, 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}`);
let res: Response | undefined;
for (let n = 0; !res; n++) {
try {
res = await f(url, { headers: { 'User-Agent': USER_AGENT }, signal });
} catch (e) {
if (timedOut(e)) throw new TemporaryError(`Timed out after ${Math.round(timeoutMs / 1000)} s waiting for ${url}`);
if (n >= retryDelaysMs.length) throw new TemporaryError(`Network error for ${url}: ${describeError(e)}`);
await new Promise((r) => setTimeout(r, retryDelaysMs[n]));
signal = AbortSignal.timeout(timeoutMs);
}
}
if (res.status >= 500 || res.status === 429) throw new TemporaryError(`HTTP ${res.status} from ${url}`);
let body: string;
@@ -31,7 +57,7 @@ export async function getText(f: typeof fetch, url: string, timeoutMs = REQUEST_
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}`);
throw new TemporaryError(`Network error reading ${url}: ${describeError(e)}`);
}
return { status: res.status, body };
}
+2 -2
View File
@@ -1,7 +1,7 @@
import type { BookMeta, Candidate, SearchResult } from '../../shared/types.ts';
import { formatCallNumber, parseCallNumber } from '../../shared/callnumber.ts';
import { cleanEdition } from './marc.ts';
import { getText, trimPunct, TemporaryError } from './http.ts';
import { getText, trimPunct, TemporaryError, CONNECT_RETRY_DELAYS_MS } from './http.ts';
import type { SourceCache } from './http.ts';
export interface OlInfo {
@@ -155,7 +155,7 @@ export function createOpenLibrary(deps: { fetch: typeof fetch; cache: SourceCach
const hit = deps.cache.get(key);
if (hit !== null) return hit;
}
const res = await getText(deps.fetch, url);
const res = await getText(deps.fetch, url, undefined, CONNECT_RETRY_DELAYS_MS);
// Other 4xx: treat as an empty answer rather than an error.
const text = res.status >= 400 ? '{}' : res.body;
parseJson(text); // reject HTML overload pages before they reach the cache