Skip to content

Commit f63db7c

Browse files
authored
feat(ppr): producer B — emit the shell entry at build time for prerendered routes (#699) (#701)
A Prerender route that also declares the ppr path option now gets its complete ShellCacheEntry (HTML prelude + postponed state + tag union) produced at vite build and served from the very first request after deploy — x-rango-shell: HIT with zero runtime capture. One entry format, two producers, one consumer: the build's shell prerender phase (buildApp post) reuses the discovery temp server and runs producer A's capture core (deriveShellCaptureContext + captureAndStoreShell) over the just-collected prerender payloads; entries stage as __ps-*.js assets behind a lazy __shell-manifest.js read through on a shell-store MISS. ppr.ttl is staleness-only (runtime recapture is the SWR upgrade path), the buildVersion gate retires entries per deploy, and updateTag evicts the immutable baked entries via tag-marker comparison (new optional store method isTagsInvalidatedSince on memory/CF/Vercel — no tombstones). Dev parity via the /__rsc_shell on-demand endpoint (memoized per HMR generation). Also fixes handlerLiveHoles being dropped by the KV/Vercel shell envelopes (pre-existing #695 bug, red-before-green). Closes #699.
1 parent 65ace1c commit f63db7c

34 files changed

Lines changed: 2328 additions & 126 deletions

‎docs/design/shell-fast-path.md‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -181,11 +181,18 @@ consumer:
181181

182182
- **Producer A (runtime)**: the background capture, triggered by traffic,
183183
TTL-bound.
184-
- **Producer B (build time)**: Prerender runs the same capture under
185-
`BuildContext`. Build-time production is the SAFER producer: there is no
186-
ambient user identity at build, so the identity guard is trivially
187-
satisfied and the capture-credential defense-in-depth concern vanishes for
188-
build-time entries.
184+
- **Producer B (build time)**: SHIPPED (#699). The build's shell prerender
185+
phase (`vite/discovery/shell-prerender-phase.ts`, buildApp post) runs the
186+
SAME capture core (`deriveShellCaptureContext` + `captureAndStoreShell`,
187+
driven by `prerender/build-shell-capture.ts`) over the just-collected
188+
prerender payloads, and the serve path reads the resulting manifest through
189+
`rsc/shell-build-manifest.ts` on a store MISS — first request after deploy
190+
is a HIT. Build-time production is the SAFER producer: there is no ambient
191+
user identity at build, so the identity guard is trivially satisfied and
192+
the capture-credential defense-in-depth concern vanishes for build-time
193+
entries. In dev the same producer runs on demand via `/__rsc_shell`.
194+
Details: `packages/rangojs-router/docs/prerender-api-design.md`
195+
("Build-time PPR shells").
189196
- **Consumer**: the fast path above. The worker cannot tell whether an entry
190197
came from a capture or from the build — extending the existing hard rule
191198
("the browser can't tell a route was pre-rendered") one layer deeper, into
@@ -242,9 +249,9 @@ basket badge still streams live; the homepage is a runtime capture with a
242249
(their records already fast-path the covered subtree today).
243250
- **Prefetch renders and partial navigations** — unchanged; the fast path is
244251
document-HIT-tail only. The PDP-prefetch starvation lever is follow-up.
245-
- **Prerender unification (producer B)** — the entry format now carries
246-
everything a build-time producer needs; wiring `matchForPrerender` to emit
247-
shell entries is its own PR.
252+
- **Prerender unification (producer B)** — shipped since as #699 (see the
253+
Unification section above); it was out of the v1 scope this section
254+
records.
248255
- **Loader-pushed plain handle values consumed in shell content** drift on
249256
HITs (fresh push vs frozen prelude) exactly as they do today — the shape
250257
rule is the contract; not a fast-path regression.

‎packages/rangojs-router/docs/internal/feature-file-map.md‎

Lines changed: 42 additions & 41 deletions
Large diffs are not rendered by default.

‎packages/rangojs-router/docs/internal/feature-map.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,7 @@ Route-local schema definitions (`search` option), typed route param types (`Rout
212212
- SWR background revalidation re-establishes the request-context ALS (so a cached body reading `getRequestContext()` resolves off the request's I/O context on workerd); profile opt-in `foregroundOnAction` re-executes a stale entry in the foreground during a server action's revalidation render (fresh action response) instead of serving stale + background-revalidating
213213
- Tag-based invalidation: `cacheTag()` (runtime) + `cache({ tags })` (static/dynamic); `updateTag()` (awaitable, read-your-own-writes) and `revalidateTag()` (background, non-blocking — both hard-purge; the only difference is awaitability) fan out to the store-level `invalidateTags()` (the whole tag batch in one call). `cacheTag()` is render-callable: outside a `"use cache"` scope but during a request render it records onto the request's document artifact (`_requestTags`) instead of throwing, so a plain server component tags the PPR shell / document it renders into — PPR's DERIVATIVE invalidation, no first-class ppr tag API (`cacheTag`/`cache-tag.ts`). Built-in stores index tags; the CF store keeps markers in its own KV (single-store, no companion tag store), and the tag-marker reads inherit the L1/L2 latency budgets and fail open. Explicit `cache({ store })` stores are registered for invalidation via a handler-owned, LRU-bounded registry. Document-cache and PPR shell entries are tagged with the request's tag union so they are tag-invalidatable too.
214214
- PPR shell caching (the `ppr` path option; `PartialPrerenderProps` exported from the root) — an opt-in second render axis, integral to the router (no middleware). It caches the rendered HTML shell (React `prerender`'s prelude bytes plus the `postponed` resume state, one coupled `ShellCacheEntry`) and, on a hit, commits the composed response after the WHOLE middleware chain: prelude bytes flush first, then fizz resumes only the holes; the browser sees one ordinary streamed document. Holes are render-defined — `loading()` subtrees (structural; loaders masked at capture), pending promises in handed-over data under the consumer's Suspense (physics), everything else shell (top-level pushed handle promises are awaited pre-SSR and baked; the capture gate holds for that await). The background capture is mixed-chain (cached segments replay, uncached handlers execute — the cookies()/headers() capture guard is load-bearing) and never re-runs middleware (the derived context inherits post-middleware state). Backed by the optional `getShell`/`putShell` store family (memory/CF/Vercel), reactVersion+buildVersion-gated (isValidShellHit; a redeploy invalidates like a React upgrade, hasIntactShellPayload rejects corrupt payloads pre-commit, a failed HIT tail schedules a healing recapture) and tag-invalidatable. Shell/payload PARITY on a HIT is guaranteed by the CAPTURE DATA SNAPSHOT (`cache/shell-snapshot.ts`, internal): a pre-render write barrier settles the foreground's deferred cache writes so the capture replays the foreground's cache generation (never clobbers it); the capture render records its cache-store read-hits + writes (`RecordingShellStore`, excluding the shell family; `captureAndStoreShell` fires the capture's isolated `onResponse` so the ring-3 segment write runs and is recorded), stores them on `ShellCacheEntry.snapshot` (carried through the CF/Vercel envelopes), and `serveShellHit`'s tail render replays them AS FRESH (`SeededShellStore`) so a shell-baked cached value that DRIFTED (shorter-ttl `cache()`, tag-invalidated item) still matches the frozen prelude — parity beats freshness inside the shell; freshness comes from holes, the shell ttl/swr, and `ppr.tags`. Actions, progressive enhancement, per-request nonce, and `streamMode: "allReady"` (the SEO/bot story) always take axis 1. See [PPR shell caching design](../design/ppr-shell-resume.md).
215+
- Build-time PPR shells (producer B, #699): a `Prerender` route that also declares `ppr` gets its complete `ShellCacheEntry` produced at `vite build` and served from the FIRST request after deploy (`x-rango-shell: HIT`, zero runtime capture) — one entry format, two producers, one consumer. The build's shell prerender phase (buildApp post; the prelude embeds the BUILT client bootstrap URL) reuses the discovery temp server and runs producer A's capture core over the just-collected prerender payloads; entries stage as `__ps-*.js` assets + a lazy `__shell-manifest.js` (pathname-only keys) read through on a shell-store MISS. `ppr.ttl` is staleness-only (recapture = the SWR upgrade path); the buildVersion gate retires entries per deploy; `updateTag` evicts by tag-marker comparison (`isTagsInvalidatedSince`, new optional store method on all three stores) against the entry's build-time `createdAt` — no tombstones. Dev parity: the read-through fetches the `/__rsc_shell` dev endpoint (on-demand capture, memoized per HMR generation) for trie `pr`-flagged routes. See prerender-api-design.md (Build-time PPR shells).
215216

216217
### Error and Control Flow
217218

‎packages/rangojs-router/docs/prerender-api-design.md‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ route was pre-rendered.
3232
- **Render-error handling** - a build-time render throw surfaces to the build (fail
3333
by default, or `prerender.onError: "warn"` to skip the URL); `throw new Skip()`
3434
in a render fn skips one URL. See [Render Errors](#render-errors).
35+
- **Build-time PPR shells (producer B, #699)** - a `Prerender` route that also
36+
declares the `ppr` path option gets its complete PPR shell entry (HTML prelude +
37+
postponed state) produced at `vite build` and served from the very first
38+
request. See [Build-time PPR shells](#build-time-ppr-shells-producer-b).
3539

3640
### Remaining
3741

@@ -306,6 +310,87 @@ render rather than serving a frozen error page.
306310

307311
---
308312

313+
## Build-time PPR shells (producer B)
314+
315+
Pre-rendering is caching at build time — and for a route that ALSO declares the
316+
`ppr` path option, that now extends one layer up: the build additionally
317+
produces the route's complete PPR shell entry (`ShellCacheEntry`: HTML prelude,
318+
postponed resume state, snapshot, tag union), so the FIRST request after a
319+
deploy serves `x-rango-shell: HIT` with zero runtime capture. One entry format,
320+
two producers (runtime capture / build), one consumer — the worker cannot tell
321+
where an entry came from. Design: `docs/design/shell-fast-path.md`.
322+
323+
### Build flow
324+
325+
1. `expandPrerenderRoutes` records each Prerender+ppr URL as a shell candidate
326+
(`matchForPrerender` now surfaces the matched route entry's `ppr` option)
327+
and retains the Flight payload JSON in memory.
328+
2. The shell prerender phase (`vite/discovery/shell-prerender-phase.ts`, a
329+
`buildApp` post hook) runs AFTER every environment bundle is written — the
330+
prelude embeds the BUILT client bootstrap URL, which does not exist at
331+
buildStart. It reuses the buildStart temp server (kept alive on discovery
332+
state), seeds an in-realm prerender store from the retained payloads, and
333+
runs producer A's capture core (`prerender/build-shell-capture.ts`, built on
334+
`deriveShellCaptureContext` + `captureAndStoreShell`) per URL: the capture's
335+
`match()` HITs the prerender store and REPLAYS the build-time segments — no
336+
handler execution — with live-lane loaders masked into holes, identical to
337+
runtime capture. The fizz half runs in the temp server's SSR environment
338+
runner; production-hashed client references bridge to dev refKeys through a
339+
wrapped `__vite_rsc_client_require__` (same `computeProductionHash`).
340+
3. Entries are stamped with the MAIN build's version (the version plugin's
341+
value folded into the shipped worker) and staged as `__ps-*.js` asset
342+
modules under `dist/rsc/assets/`, with a lazy `__shell-manifest.js` and a
343+
`globalThis.__loadShellManifestModule` injection into the RSC entry —
344+
mirroring the prerender payload manifest. No static file serving; the
345+
worker handles every request.
346+
4. A capture that is refused (identity guard, rejected bake-lane loader),
347+
produces no shell, or never consulted the prerender store is SKIPPED with a
348+
loud `SHELL SKIP` build line — the route keeps runtime-capture semantics,
349+
never a wrong-lane bake. Manifest keys are pathname-only (router ids hash
350+
transformed source positions and differ across realms); pathname collisions
351+
across routers are declined at build.
352+
353+
### Runtime flow
354+
355+
On a runtime shell-store MISS, the serve path consults the build manifest
356+
(`rsc/shell-build-manifest.ts` `lookupBuildShell`) and serves a valid entry
357+
through the SAME `serveShellHit`. Gates: search-less requests only (the build
358+
captured the bare pathname; a search-bearing URL has its own shell identity,
359+
owned by runtime capture), `reactVersion`/`buildVersion` validity, payload
360+
integrity, and tag markers (below). The runtime store is always read FIRST, so
361+
a captured entry supersedes the baked one as soon as it lands.
362+
363+
### Lifecycle semantics
364+
365+
| Event | Effect on the baked entry |
366+
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
367+
| deploy (new build) | retired: buildVersion gate + a fresh manifest replace it |
368+
| `ppr.ttl` elapses | STALENESS only: still serves, but a runtime recapture is scheduled — SWR is the upgrade path from baked entry to fresher runtime entry, never the bootstrap path |
369+
| `updateTag()` on its tag | evicted WITHOUT tombstones: the manifest is immutable, so `isTagsInvalidatedSince(tags, entry.createdAt)` (new optional store method) compares the store's tag markers |
370+
| store lacks the method | TAGGED baked entries are not served (warned once — updateTag could never evict them); untagged entries are unaffected |
371+
372+
`isTagsInvalidatedSince` implementations: CFCacheStore wraps its existing KV
373+
tag-marker check; MemorySegmentCacheStore records per-tag invalidation
374+
instants; VercelCacheStore writes its own `tm`-family markers on
375+
`invalidateTags` (the platform's `expireTag` deletes entries and keeps no
376+
queryable history).
377+
378+
### Dev mode
379+
380+
No build manifest exists in dev, so producer B runs ON DEMAND: the
381+
read-through's dev branch fetches `/__rsc_shell` (a dev-server endpoint
382+
mirroring `/__rsc_prerender`), which runs the same capture core in the dev
383+
realms — main-server environments on the Node preset, the shared temp Node
384+
server on Cloudflare (whose `virtual:entry-ssr` now resolves to the REAL
385+
rango SSR entry, lazily) — memoized per router HMR generation and per caller
386+
version. The endpoint is policy-free: the serve gate sends the resolved
387+
`ttl`/`swr`/`tags`/version. Only trie `pr`-flagged routes arm the dev branch
388+
(production's exact candidate set), and a `/__rsc_prerender` pre-flight
389+
refuses non-prerenderable routes so a live-handler render can never be served
390+
as a baked shell. First dev request: `x-rango-shell: HIT`, same as production.
391+
392+
---
393+
309394
## Handler Eviction
310395

311396
In production builds, `Prerender` exports are replaced with stubs:
@@ -516,3 +601,5 @@ At runtime, the cache-lookup middleware uses these flags:
516601
| `src/cache/cache-scope.ts` | RSC serialize/deserialize for segments |
517602
| `src/vite/router-discovery.ts` (`closeBundle`) + `src/vite/discovery/prerender-collection.ts` (`expandPrerenderRoutes`) + `src/vite/discovery/bundle-postprocess.ts` | Collects prerender data, stages assets, writes manifest + injects `__loadPrerenderManifestModule` (`src/vite/index.ts` is only the public-API barrel) |
518603
| `src/router/match-middleware/intercept-resolution.ts` | Runtime intercept handling (`handleCacheHitIntercept`) |
604+
| `src/vite/discovery/shell-prerender-phase.ts` (buildApp post) + `src/prerender/build-shell-capture.ts` (`captureShellForBuild`) | Producer B: build-time PPR shell capture + `__ps` asset/manifest staging (#699) |
605+
| `src/rsc/shell-build-manifest.ts` (`lookupBuildShell`) + `src/prerender/shell-manifest-key.ts` | Runtime read-through for baked shell entries (production manifest / dev `/__rsc_shell` on-demand) |

‎packages/rangojs-router/e2e/prerender-ppr.test.ts‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,80 @@ function runPrerenderPprSpec(f: Fixture): void {
8888
expect(seq2).toBe(seq1 + 1);
8989
});
9090

91+
// ---------------------------------------------------------------------
92+
// Producer B (#699): the shell entry is produced at BUILD time (dev: on
93+
// demand via /__rsc_shell), so the FIRST request already HITs. Build
94+
// entries cover the BARE pathname only — the ?probe= URLs above carry a
95+
// search string and keep exercising the runtime-capture lanes untouched.
96+
// Bare-path usage is partitioned across tests (fullyParallel-safe):
97+
// beta = first-request assertion, alpha = liveness; eviction has its own
98+
// route + tag (/pp-evict/gamma) so its updateTag cannot blast these; the
99+
// "warm" slug below absorbs the cold-graph cost (dev: the on-demand
100+
// capture compiles the temp SSR graph on first use) so the strict
101+
// first-request assertions never race CI cold-start physics.
102+
// ---------------------------------------------------------------------
103+
104+
test.beforeAll(async ({ playwright }) => {
105+
const ctx = await playwright.request.newContext();
106+
try {
107+
await warmToHit(ctx as unknown as Page["request"], f.url("/pp/warm"));
108+
} finally {
109+
await ctx.dispose();
110+
}
111+
});
112+
113+
test("build-time shell: the FIRST request serves x-rango-shell: HIT with the frozen prelude", async ({
114+
request,
115+
}) => {
116+
const res = await request.get(f.url("/pp/beta"), {
117+
headers: HTML_HEADERS,
118+
});
119+
expect(res.status()).toBe(200);
120+
expect(res.headers()["x-rango-shell"]).toBe("HIT");
121+
const { prelude, resumed } = splitPrelude(await res.text());
122+
expect(prelude).toContain("Prerendered shell content for beta");
123+
expect(prelude).toContain("Loading pp seq...");
124+
expect(prelude).not.toContain("pp-seq:");
125+
expect(resumed).toContain("pp-seq:");
126+
});
127+
128+
test("build-time shell: loaders stay live across baked-entry HITs (seq advances)", async ({
129+
request,
130+
}) => {
131+
const url = f.url("/pp/alpha");
132+
const first = await request.get(url, { headers: HTML_HEADERS });
133+
expect(first.headers()["x-rango-shell"]).toBe("HIT");
134+
const seq1 = readSeq(await first.text());
135+
136+
const second = await request.get(url, { headers: HTML_HEADERS });
137+
expect(second.headers()["x-rango-shell"]).toBe("HIT");
138+
expect(readSeq(await second.text())).toBe(seq1 + 1);
139+
});
140+
141+
test("updateTag evicts the build-time shell; the runtime capture then owns the route", async ({
142+
request,
143+
}) => {
144+
const url = f.url("/pp-evict/gamma");
145+
const baked = await request.get(url, { headers: HTML_HEADERS });
146+
expect(baked.headers()["x-rango-shell"]).toBe("HIT");
147+
expect(await baked.text()).toContain("Evictable shell content for gamma");
148+
149+
// Awaitable invalidation (cache-tag fixture endpoint): the tag marker
150+
// lands before the response, so the next read is deterministically MISS —
151+
// the baked entry is immutable, but the marker comparison rejects it.
152+
const invalidate = await request.get(
153+
f.url("/cache-tag-test/invalidate/pp-evict-shell"),
154+
);
155+
expect(invalidate.status()).toBe(200);
156+
157+
const evicted = await request.get(url, { headers: HTML_HEADERS });
158+
expect(evicted.headers()["x-rango-shell"]).toBe("MISS");
159+
160+
// Producer A takes over: the MISS scheduled a runtime capture that
161+
// stores a runtime entry (the runtime store is read before the manifest).
162+
await warmToHit(request, url);
163+
});
164+
91165
test("per-param shells: both prerendered slugs HIT independently with their own content", async ({
92166
request,
93167
}) => {

‎packages/rangojs-router/e2e/test-app/src/router.named-routes.gen.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,7 @@ export const NamedRoutes = {
263263
plpMeta: "/plp-meta",
264264
plpMetaTx: "/plp-meta-tx",
265265
"pp.article": "/pp/:slug",
266+
"pp.evict": "/pp-evict/:slug",
266267
"prerender-handle": "/prerender-handle",
267268
"prerender-reverse": "/prerender-reverse",
268269
"prerenderComplex.detail": "/prerender-complex/:slug",

0 commit comments

Comments
 (0)