Skip to content

perf: batch image signed URLs + cache seeded catalog fetches (round 2, phase 2)#479

Merged
BigSimmo merged 1 commit into
claude/perf-r2-bundle-hygienefrom
claude/perf-r2-network-caching
Jul 11, 2026
Merged

perf: batch image signed URLs + cache seeded catalog fetches (round 2, phase 2)#479
BigSimmo merged 1 commit into
claude/perf-r2-bundle-hygienefrom
claude/perf-r2-network-caching

Conversation

@BigSimmo

Copy link
Copy Markdown
Owner

Summary

Phase 2 of the round-2 performance initiative (stacked on #475). Collapses per-image and per-component fetch storms and adds HTTP caching to rarely-changing owner-scoped catalog content.

Image signed URLs (high impact on image-heavy documents)

  • New POST /api/images/signed-urls (≤50 ids): one rate-limit consume + one document_images read + one owner-scoped documents read + one createSignedUrls batch call — previously each image cost its own API call with 3 DB round trips.
  • Fail-closed per item: every id starts null; only images whose parent document passes withOwnerReadScope and whose generation metadata matches the committed index generation resolve to URLs. Unknown / unauthorized / uncommitted ids are indistinguishable (all null). Tests: mixed ownership, uncommitted replacement generation, anonymous public-only scope.
  • Client coalescing in signed-url-cache.ts: 25 ms batching window, queues keyed by authorization header so sessions never mix in one batch. DocumentImage (viewer) + SourceImage (answer surface) both fetch through it.
  • Proof: headless Playwright probe on the demo document — image renders via exactly one POST /api/images/signed-urls, zero per-image GETs.
  • Single-image GET now sends Cache-Control: private, max-age=540 + Vary: Authorization (URLs live 600 s), so reloads reuse it.

Catalog fetch dedup + HTTP caching

  • client-fetch-cache.ts: short-TTL + in-flight dedup for useRegistryRecords / useMedicationCatalog (several surfaces mount them concurrently and previously issued identical GETs). Non-OK responses are never cached, so the auth-loading 401 race still re-resolves correctly.
  • Seven seeded content routes (registry records, medications, differentials, presentations — lists + slugs): no-storeprivate, max-age=300, stale-while-revalidate=600 + Vary: Authorization, 200 responses only (the shared slug-route helpers are status-aware; 404s/errors stay no-store). Verified live via curl.

Tenancy review note

The batch endpoint is a new owner-scoped read surface. It reuses enforceDocumentReadRateLimit, withOwnerReadScope, and isCommittedGenerationMetadata unchanged from the single route and fails closed per item; please review with the tenancy defense-in-depth lens.

Verification

  • tsc, eslint, prettier clean
  • Full vitest: 1429 passed (the site-map coverage test caught the undocumented new route — docs/site-map.md regenerated)
  • New tests: 3 batch-route owner-scoping, 4 client-coalescing, 6 fetch-cache
  • Live demo-mode checks: batch endpoint (known/unknown/invalid ids), seeded-route headers, headless image-render probe

🤖 Generated with Claude Code

Round-2 phase 2 (client network & caching).

- New POST /api/images/signed-urls resolves up to 50 images with one
  rate-limit consume, one document_images read, one owner-scoped documents
  read, and one batch storage signing call — replacing N API calls of 3 DB
  round trips each on image-heavy document views. Authorization is fail-closed
  per item (unknown, unauthorized, and uncommitted-generation ids all resolve
  null), mirroring the single route's checks; covered by mixed-ownership,
  uncommitted-generation, and anonymous-scope tests.
- signed-url-cache.ts gains a 25 ms batching window keyed by authorization
  header (sessions never share a batch); DocumentImage (viewer) and
  SourceImage (answer surface) fetch through it. Headless Playwright probe:
  the document page renders its image via exactly one batch POST.
- The single-image GET now sends Cache-Control: private, max-age=540 +
  Vary: Authorization so reloads reuse the 10-minute signed URL.
- client-fetch-cache.ts adds short-TTL + in-flight dedup for the registry and
  medication catalog hooks, which several surfaces mount concurrently; 401s
  and errors are never cached so auth loading re-resolves.
- Seven seeded content routes (registry records, medications, differentials,
  presentations — lists and slugs) move from no-store to
  private, max-age=300, stale-while-revalidate=600 + Vary: Authorization,
  200 responses only (404s/errors stay no-store). Verified live via curl.
- docs/site-map.md regenerated for the new route.

Verified: tsc, eslint, prettier, full vitest 1429 passed (site-map test
caught the missing route doc — fixed), targeted suites green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f3c2b6f4-ba7f-4a28-85f7-fbece5009354

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/perf-r2-network-caching
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch claude/perf-r2-network-caching

Comment @coderabbitai help to get the list of available commands.

@supabase

supabase Bot commented Jul 11, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project sjrfecxgysukkwxsowpy because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

function cacheKey(url: string, headers?: Record<string, string>) {
return `${url}${JSON.stringify(headers ?? {})}`;

P1 Badge Avoid caching cookie-scoped catalog responses

fetchJsonCached keys entries only by the explicit headers object, but these same-origin fetches still carry Supabase cookies while useAuthSession() is loading or after auth state changes, and the catalog routes resolve those cookies via publicAccessContext. A 200 owner-scoped response fetched with {} headers is cached under the same key as any later cookie/no-header request, so signing out or switching users in the same tab can show the previous user's registry/medication data for up to 60s. Skip caching when no bearer header is present or include a stable session key in the cache key.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/lib/http.ts
// 200 responses only — errors and 404s must never be cached.
export const seededContentCacheHeaders = {
"Cache-Control": "private, max-age=300, stale-while-revalidate=600",
Vary: "Authorization",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Vary private cached API responses on Cookie

The new cache header varies only on Authorization, but these routes also treat Supabase session cookies as an auth signal (shouldResolvePublicCatalogAccess/publicAccessContext). When an owner-scoped 200 is produced from a cookie-only request, for example before the client has a bearer token, the browser's private HTTP cache may reuse it for a later cookie/no-header request by a signed-out or different user because the Cookie value is not part of the cache key. Include Cookie in Vary or keep cookie-authenticated responses no-store; the same issue applies to the new image signed-url GET cache header.

Useful? React with 👍 / 👎.

@BigSimmo
BigSimmo merged commit 95ce39f into claude/perf-r2-bundle-hygiene Jul 11, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant