A network error, timeout, 5xx or 429 no longer ends a lookup or sends a book to Needs attention. Lookups back off exponentially with jitter (2 s doubling to 5 min, honouring Retry-After) for as long as the book is pending, keep each definitive answer so a retry only asks for what is missing, and limit requests to two at a time per host. Once a call number is in hand, a step that still fails after six tries is left for the backfills. Books an earlier version failed for a temporary reason are queued again at startup. The cards show which source is not answering and when the next try is, title search waits for Open Library with a Cancel button, and Look up again sits next to Fix. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
101 lines
4.3 KiB
TypeScript
101 lines
4.3 KiB
TypeScript
import { useEffect, useState } from 'preact/hooks';
|
|
import type { Book } from '../shared/types.ts';
|
|
import { api } from './api.ts';
|
|
import { emptyState, reduce, shelfOrder } from './store.ts';
|
|
import type { BookAction, BookState } from './store.ts';
|
|
import { emptyPending, queueVisible, visible } from './pending.ts';
|
|
import { queueOrder } from './bookstate.ts';
|
|
import type { PendingState } from './pending.ts';
|
|
|
|
let state: BookState = emptyState;
|
|
/** Books removed from view whose real delete has not been sent yet (see removal.ts). */
|
|
let pending: PendingState = emptyPending;
|
|
/** The book most recently scanned or added, for the Last scan card. `existed` means it was in the library already. */
|
|
export interface LastScan { id: number; existed: boolean }
|
|
let lastScan: LastScan | null = null;
|
|
const listeners = new Set<() => void>();
|
|
|
|
/** When each book was first seen waiting for its lookup, for the elapsed-seconds display. */
|
|
const pendingSince = new Map<number, number>();
|
|
function trackPending(action: BookAction): void {
|
|
const note = (b: Book, fromServerTime: boolean) => {
|
|
if (b.status !== 'pending') { pendingSince.delete(b.id); return; }
|
|
if (pendingSince.has(b.id)) return;
|
|
const created = Date.parse(b.createdAt);
|
|
pendingSince.set(b.id, fromServerTime && Number.isFinite(created) ? Math.min(created, Date.now()) : Date.now());
|
|
};
|
|
const now = Date.now();
|
|
if (action.type === 'upsert') { receivedAt.set(action.book.id, now); note(action.book, false); }
|
|
else if (action.type === 'replace') { pendingSince.clear(); receivedAt.clear(); action.books.forEach(b => { receivedAt.set(b.id, now); note(b, true); }); }
|
|
else { pendingSince.delete(action.id); receivedAt.delete(action.id); }
|
|
}
|
|
/** When the page last received each book, so a retry's remaining wait can be counted down locally. */
|
|
const receivedAt = new Map<number, number>();
|
|
export function retryReceivedAt(book: Book): number { return receivedAt.get(book.id) ?? Date.now(); }
|
|
|
|
export function lookupStartedAt(book: Book): number { return pendingSince.get(book.id) ?? Date.now(); }
|
|
|
|
/** Re-renders once a second while `active`, and returns the current time. */
|
|
export function useNow(active: boolean): number {
|
|
const [now, setNow] = useState(Date.now());
|
|
useEffect(() => {
|
|
if (!active) return;
|
|
setNow(Date.now());
|
|
const t = setInterval(() => setNow(Date.now()), 1000);
|
|
return () => clearInterval(t);
|
|
}, [active]);
|
|
return now;
|
|
}
|
|
|
|
function notify(): void { listeners.forEach(l => l()); }
|
|
|
|
export function dispatch(action: BookAction): void {
|
|
trackPending(action);
|
|
state = reduce(state, action);
|
|
if (action.type === 'delete' && action.id in pending.items) { // the real delete is done
|
|
const items = { ...pending.items };
|
|
delete items[action.id];
|
|
pending = { items };
|
|
}
|
|
notify();
|
|
}
|
|
export const getPending = () => pending;
|
|
export function setPending(next: PendingState): void { pending = next; notify(); }
|
|
export function setLastScan(id: number, existed: boolean): void { lastScan = { id, existed }; notify(); }
|
|
export function useLastScan(): LastScan | null { useBooks(); return lastScan; }
|
|
export const upsertBook = (book: Book) => dispatch({ type: 'upsert', book });
|
|
|
|
export function useBooks(): Book[] {
|
|
const [, force] = useState(0);
|
|
useEffect(() => {
|
|
const l = () => force(n => n + 1);
|
|
listeners.add(l);
|
|
return () => { listeners.delete(l); };
|
|
}, []);
|
|
return visible(shelfOrder(state), pending);
|
|
}
|
|
|
|
/** The queued books for "Cards to print": attention first, then newest first. */
|
|
export function useQueue(): Book[] {
|
|
const books = useBooks();
|
|
return queueOrder(queueVisible(books, pending));
|
|
}
|
|
|
|
export function getBook(id: number): Book | undefined { return state.byId[id]; }
|
|
|
|
async function refetch(): Promise<void> {
|
|
try { dispatch({ type: 'replace', books: await api.listBooks('all') }); } catch { /* retried on next open */ }
|
|
}
|
|
|
|
/** One EventSource for the whole app. Every (re)connect refetches the full list. */
|
|
export function startLive(): void {
|
|
const es = new EventSource('/api/events');
|
|
es.onopen = () => { void refetch(); };
|
|
es.addEventListener('book', e => {
|
|
try { upsertBook(JSON.parse((e as MessageEvent).data) as Book); } catch { /* ignore */ }
|
|
});
|
|
es.addEventListener('deleted', e => {
|
|
try { dispatch({ type: 'delete', id: (JSON.parse((e as MessageEvent).data) as { id: number }).id }); } catch { /* ignore */ }
|
|
});
|
|
}
|