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 } /** * 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, retryDelaysMs: number[] = [], ): Promise { let signal = AbortSignal.timeout(timeoutMs); const timedOut = (e: unknown) => signal.aborted || (e as Error)?.name === 'TimeoutError'; 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; 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}: ${describeError(e)}`); } return { status: res.status, body }; } export function trimPunct(s: string): string { return s.replace(/[\s\/,:;.]+$/, '').trim(); }