feat: persist Open Library responses across restarts #5

Merged
chris-paganon merged 8 commits from feat/persistent-caching into master 2026-11-14 18:31:04 +00:00

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_cache table (migration 0008): 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-memory defineCachedFunction (1 h LRU, cleared on restart):
    1. Fresh row → return it. No throttle slot is used.
    2. Otherwise fetch (same throttle, timeout and errors as before) and upsert the raw JSON.
    3. On a transient failure (429, 5xx, timeout or network) with an expired row ≤ 7 days past expiry → serve it and log a warning (stale-if-error). 404 and other errors behave as before.
    • Concurrent identical requests share one in-flight promise.
  • Unreadable payloads are dropped, not pinned: if search, bibliography or import normalization fails, the row is deleted (forgetOpenLibraryResponse), so retrying refetches.
  • Import ISBN reuse (lookupImportIsbns in import-matching.ts, used by processLibraryImport):
    • Before: deferred ISBN misses were re-sent in every following step's ISBN query.
    • Now each ISBN's matched works, or a confirmed empty result, are stored as isbn:<fields-hash>:<isbn>.
    • Misses are recorded only when the response wasn't truncated (numFound ≤ 100). Otherwise only hits count as conclusive.
  • Daily purge task open-library:purge-cache (04:30) deletes rows more than 7 days past expiry.
  • README caching paragraph updated.

Decisions

Storage One PostgreSQL table. No Redis or extra container. Kirkus pages keep the existing in-memory Nitro cache (out of scope).
Key request:sha256([path, query]). The query includes fields, so changing OPEN_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.
What is stored Raw upstream JSON for requests, normalized on read, so parser fixes such as the recent rating-average fix apply to cached data immediately. ISBN entries store validated {book, isbns} matches; any that fail the current saveBookPayloadSchema are ignored and refetched.
TTL /search* 24 h (they carry rating snapshots, so ratings are at most a day old, which is fine for an aggregate). /trending/weekly.json 6 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.
Stale use Only when Open Library fails, up to 7 days past expiry, then purged. With ratings, this means a slightly older snapshot rather than an error. mergeImportedBook still keeps an existing rating when the new one is null.
Invalidation TTL, field-list keys, deletion on unreadable payloads, and the daily purge. No manual invalidation UI.
Batching Import ISBN rows still use one batched query per step, now limited to unseen ISBNs. Recommendation resolution already had its own persistent table (recommendation_resolution) and is unchanged.

Verification

  • pnpm lint-full passes (typecheck + eslint) on every commit.
  • Migration applied to a cloned dev DB.
  • Search: becky chambers took 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.
  • Stale-if-error: temporarily pointed the fetch at openlibrary.invalid (reverted, not committed) and manually expired a row:
    • expired query → 200 from cache, with the warning Open Library request to /search.json failed; serving an expired cached response.
    • fresh query → 200
    • uncached query → 503 as before
  • Import (via API, 4-row CSVs):
    • Run 1 queried 5 ISBNs in one batch and stored per-ISBN entries.
    • Run 2 reused the 2 Le Guin ISBNs from cache and queried only the 3 unseen ones. Both unknown ISBNs were stored as empty. Step 2 resolved the deferred miss with only a title query (no repeated ISBN query).
    • All 4 imported correctly.
  • Browser demo (below): search ann leckie (upstream fetch, slow), then stop the dev server (the reload shows connection refused) and restart it. Reloading ann leckie and opening martha wells (cached before earlier restarts) both render immediately; the table's newest fetched_at stays the same, so no upstream request was made.

Demo

demo

persistent-caching-demo.mp4

## 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_cache` table** (migration `0008`): `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-memory `defineCachedFunction` (1 h LRU, cleared on restart): 1. Fresh row → return it. No throttle slot is used. 2. Otherwise fetch (same throttle, timeout and errors as before) and upsert the raw JSON. 3. On a transient failure (429, 5xx, timeout or network) with an expired row ≤ 7 days past expiry → serve it and log a warning (stale-if-error). 404 and other errors behave as before. - Concurrent identical requests share one in-flight promise. - **Unreadable payloads are dropped, not pinned**: if search, bibliography or import normalization fails, the row is deleted (`forgetOpenLibraryResponse`), so retrying refetches. - **Import ISBN reuse** (`lookupImportIsbns` in `import-matching.ts`, used by `processLibraryImport`): - Before: deferred ISBN misses were re-sent in every following step's ISBN query. - Now each ISBN's matched works, or a confirmed empty result, are stored as `isbn:<fields-hash>:<isbn>`. - Misses are recorded only when the response wasn't truncated (`numFound ≤ 100`). Otherwise only hits count as conclusive. - **Daily purge task** `open-library:purge-cache` (04:30) deletes rows more than 7 days past expiry. - README caching paragraph updated. ## Decisions | | | |---|---| | Storage | One PostgreSQL table. No Redis or extra container. Kirkus pages keep the existing in-memory Nitro cache (out of scope). | | Key | `request:sha256([path, query])`. The query includes `fields`, so changing `OPEN_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. | | What is stored | Raw upstream JSON for requests, **normalized on read**, so parser fixes such as the recent rating-average fix apply to cached data immediately. ISBN entries store validated `{book, isbns}` matches; any that fail the current `saveBookPayloadSchema` are ignored and refetched. | | TTL | `/search*` 24 h (they carry rating snapshots, so ratings are at most a day old, which is fine for an aggregate). `/trending/weekly.json` 6 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. | | Stale use | Only when Open Library fails, up to 7 days past expiry, then purged. With ratings, this means a slightly older snapshot rather than an error. `mergeImportedBook` still keeps an existing rating when the new one is null. | | Invalidation | TTL, field-list keys, deletion on unreadable payloads, and the daily purge. No manual invalidation UI. | | Batching | Import ISBN rows still use one batched query per step, now limited to unseen ISBNs. Recommendation resolution already had its own persistent table (`recommendation_resolution`) and is unchanged. | ## Verification - `pnpm lint-full` passes (typecheck + eslint) on every commit. - Migration applied to a cloned dev DB. - Search: `becky chambers` took 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. - Stale-if-error: temporarily pointed the fetch at `openlibrary.invalid` (reverted, not committed) and manually expired a row: - expired query → 200 from cache, with the warning `Open Library request to /search.json failed; serving an expired cached response.` - fresh query → 200 - uncached query → 503 as before - Import (via API, 4-row CSVs): - Run 1 queried 5 ISBNs in one batch and stored per-ISBN entries. - Run 2 reused the 2 Le Guin ISBNs from cache and queried only the 3 unseen ones. Both unknown ISBNs were stored as empty. Step 2 resolved the deferred miss with only a title query (no repeated ISBN query). - All 4 imported correctly. - Browser demo (below): search `ann leckie` (upstream fetch, slow), then stop the dev server (the reload shows connection refused) and restart it. Reloading `ann leckie` and opening `martha wells` (cached before earlier restarts) both render immediately; the table's newest `fetched_at` stays the same, so no upstream request was made. ## Demo ![demo](https://forgejo.chrispaganon.com/attachments/5328fb4b-86b6-4c59-9750-670990c91885) [persistent-caching-demo.mp4](https://forgejo.chrispaganon.com/attachments/5328fb4b-86b6-4c59-9750-670990c91885)
Author
Owner

Review of master...feat/persistent-caching (5 commits), using the full-code-review skill.

Important

  1. [P2] Evict invalid responses for every cached endpoint — must fix before merge. server/utils/open-library-request.ts:47–49 persists the raw response before callers validate it. Search, bibliography and import callers now call forgetOpenLibraryResponse on failure, but server/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 in server/utils/recommendation-sources.ts:106 do 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.

  2. [P2] Do not negative-cache ISBNs after a partially parsed response — must fix before merge. server/utils/import-matching.ts:39–43 treats result.total <= 100 as 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 produces total: 2 with 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-full passed; git diff --check master...HEAD passed. The generated Nitro task registry includes open-library:purge-cache with the configured daily schedule. No code, tests, migrations or database data were changed; no dev server or containers were started.

Review of `master...feat/persistent-caching` (5 commits), using the full-code-review skill. ### Important 1. **[P2] Evict invalid responses for every cached endpoint — must fix before merge.** `server/utils/open-library-request.ts:47–49` persists the raw response before callers validate it. Search, bibliography and import callers now call `forgetOpenLibraryResponse` on failure, but `server/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 in `server/utils/recommendation-sources.ts:106` do 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. 2. **[P2] Do not negative-cache ISBNs after a partially parsed response — must fix before merge.** `server/utils/import-matching.ts:39–43` treats `result.total <= 100` as 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 produces `total: 2` with 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-full` passed; `git diff --check master...HEAD` passed. The generated Nitro task registry includes `open-library:purge-cache` with the configured daily schedule. No code, tests, migrations or database data were changed; no dev server or containers were started.
chris-paganon force-pushed feat/persistent-caching from 073458c95d to bfc1d8082f 2026-11-14 18:28:18 +00:00 Compare
chris-paganon force-pushed feat/persistent-caching from bfc1d8082f to f99e3eaa76 2026-11-14 18:30:54 +00:00 Compare
Author
Owner

Both 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:

  • A fetched payload is stored only after parse succeeds.
  • A cached payload is served only if it still parses; otherwise it is refetched. This also covers entries written by older parsers.
  • Stale-if-error only falls back to entries that parse.
  • Parser failures become a 502 with the caller's message.

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). forgetOpenLibraryResponse is 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")
ImportSearchResult has a new complete flag. normalizeImportSearch sets it to matches.length === total, which means every reported record was returned (not truncated by the limit) and every one parsed. lookupImportIsbns writes empty (miss) entries only when complete is 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-full passes. Smoke-tested search, author pages and a 4-row import against the rebased code. The README no longer pins a migration number.

Both 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: - A fetched payload is stored only after `parse` succeeds. - A cached payload is served only if it still parses; otherwise it is refetched. This also covers entries written by older parsers. - Stale-if-error only falls back to entries that parse. - Parser failures become a 502 with the caller's message. 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). `forgetOpenLibraryResponse` is 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") `ImportSearchResult` has a new `complete` flag. `normalizeImportSearch` sets it to `matches.length === total`, which means every reported record was returned (not truncated by the limit) and every one parsed. `lookupImportIsbns` writes empty (miss) entries only when `complete` is 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-full` passes. Smoke-tested search, author pages and a 4-row import against the rebased code. The README no longer pins a migration number.
chris-paganon deleted branch feat/persistent-caching 2026-11-14 18:31:04 +00:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
chris-paganon/chrisp-books!5
No description provided.