feat: persist Open Library responses across restarts #5
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "feat/persistent-caching"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
Open Library responses now persist in PostgreSQL. Restarts no longer drop them, and all users share them. Import ISBN lookups are now cached per ISBN, so deferred rows, retries and later imports only query identifiers that Open Library hasn't answered recently, still batched into a single
isbn:(a OR b …)query. Nothing here adds upstream requests or bulk harvesting.Changes
open_library_cachetable (migration0008):key(PK),payload jsonb,fetched_at,expires_at(indexed). It lives in the existing database, so the deployment stays at 2 containers.openLibraryRequest(server/utils/open-library-request.ts) replaces the in-memorydefineCachedFunction(1 h LRU, cleared on restart):forgetOpenLibraryResponse), so retrying refetches.lookupImportIsbnsinimport-matching.ts, used byprocessLibraryImport):isbn:<fields-hash>:<isbn>.numFound ≤ 100). Otherwise only hits count as conclusive.open-library:purge-cache(04:30) deletes rows more than 7 days past expiry.Decisions
request:sha256([path, query]). The query includesfields, so changingOPEN_LIBRARY_SEARCH_FIELDS(e.g. adding subtitle or ratings) automatically misses the old entries. ISBN keys include a hash of the import field list for the same reason.{book, isbns}matches; any that fail the currentsaveBookPayloadSchemaare ignored and refetched./search*24 h (they carry rating snapshots, so ratings are at most a day old, which is fine for an aggregate)./trending/weekly.json6 h (recommendation refresh is hourly). Authors and series 7 days. ISBN matches 24 h, same as search, so an import can't write a rating older than a normal search would.mergeImportedBookstill keeps an existing rating when the new one is null.recommendation_resolution) and is unchanged.Verification
pnpm lint-fullpasses (typecheck + eslint) on every commit.becky chamberstook 3537 ms uncached and 14 ms on repeat. After a dev-server restart the first request was 133 ms, with no new cache row written.openlibrary.invalid(reverted, not committed) and manually expired a row:Open Library request to /search.json failed; serving an expired cached response.ann leckie(upstream fetch, slow), then stop the dev server (the reload shows connection refused) and restart it. Reloadingann leckieand openingmartha wells(cached before earlier restarts) both render immediately; the table's newestfetched_atstays the same, so no upstream request was made.Demo
persistent-caching-demo.mp4
Review of
master...feat/persistent-caching(5 commits), using the full-code-review skill.Important
[P2] Evict invalid responses for every cached endpoint — must fix before merge.
server/utils/open-library-request.ts:47–49persists the raw response before callers validate it. Search, bibliography and import callers now callforgetOpenLibraryResponseon failure, butserver/api/authors/index.get.ts:10–11,server/api/authors/[id].get.ts:9–10,server/api/series/[id].get.ts:13–14, and the trending source inserver/utils/recommendation-sources.ts:106do not. A single HTTP-success response with an invalid shape consequently makes subsequent attempts fail from the persistent cache even after upstream recovers: author/series profiles for 7 days, author search for 24 hours, trending for 6 hours, including across restarts. Previously these responses expired after one hour or disappeared on restart. Apply the same discard-on-validation-failure handling to these callers (or validate before storing), so retries can recover.[P2] Do not negative-cache ISBNs after a partially parsed response — must fix before merge.
server/utils/import-matching.ts:39–43treatsresult.total <= 100as proof that every absent ISBN has no match. However,normalizeImportSearch(:71–85) deliberately drops individual malformed/unusable records and succeeds whenever at least one usable record remains. For example, a two-ISBN batch returning one valid work and one work whose metadata fails validation producestotal: 2with one match; the second ISBN is then cached as[]for 24 hours. Later imports and retries skip that ISBN lookup and take the title fallback even if a narrower lookup or corrected upstream response would return its exact match. The 100-result guard prevents pagination-related false negatives but does not prevent parsing-related ones. Propagate whether any records were skipped (and whether all reported records were returned), and only write negative entries when the response was fully received and parsed; retain positive caching otherwise.Nit picks
None.
Pre-existing
None reported separately.
Security
No actionable security findings.
Validation:
pnpm lint-fullpassed;git diff --check master...HEADpassed. The generated Nitro task registry includesopen-library:purge-cachewith the configured daily schedule. No code, tests, migrations or database data were changed; no dev server or containers were started.073458c95dtobfc1d8082fbfc1d8082ftof99e3eaa76Both findings accepted and fixed.
1. Invalid responses stayed cached ("fix: cache Open Library responses only after the caller's parser accepts them")
I made validation part of the request rather than adding more discard calls.
requestOpenLibraryData(path, query, contact, parse, unreadableMessage)now requires a parser:parsesucceeds.Every caller now passes its parser: book search, bibliography, import lookup, author search, author profile, series, trending, and master's new author bibliography (whose parser returns both the raw payload and the normalized books).
forgetOpenLibraryResponseis gone. Because the parameter is required, typecheck catches any new caller without one.Verified by temporarily breaking
authorProfileSchema: two requests returned 502, both went upstream, and no row was written. After reverting, the endpoint cached normally.2. False-negative ISBN entries from partly parsed responses ("fix(import): cache ISBN misses only from fully parsed responses")
ImportSearchResulthas a newcompleteflag.normalizeImportSearchsets it tomatches.length === total, which means every reported record was returned (not truncated by the limit) and every one parsed.lookupImportIsbnswrites empty (miss) entries only whencompleteis true. Hits are still cached in every case.Also rebased onto master twice (PR #3/#4/#6). The cache migration was regenerated each time and is now
0011_redundant_midnight.sql, chained to master's 0010 snapshot. All 12 migrations apply to a fresh DB clone.pnpm lint-fullpasses. Smoke-tested search, author pages and a 4-row import against the rebased code. The README no longer pins a migration number.