Skip to content

Commit e697989

Browse files
committed
docs(router): trim render-pass.ts comments to the invariants
Cut the comments from 167 of 300 lines to 62 of 195: one line per field where its fresh-or-shared reason is not obvious, with the ticket or issue reference kept (#684, #700, #1035, #1109). The background row now points at rango-t160, and the #1109 note names the trigger: an Object.assign that takes the object to 20 own properties. Comment-only: both versions print identically through the TypeScript printer with comments removed, and their token streams match.
1 parent de99338 commit e697989

1 file changed

Lines changed: 53 additions & 158 deletions

File tree

‎packages/rangojs-router/src/server/render-pass.ts‎

Lines changed: 53 additions & 158 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,9 @@
11
/**
2-
* Derived render passes: a second render over a request that has already
3-
* passed its middleware. A PPR shell capture, a PPR HIT tail and a background
4-
* re-render of a stale route record each run on `Object.create(base)`, so
5-
* every field the pass does not own reads the request's value through the
6-
* prototype (variables, env, request identity, cache store, waitUntil).
7-
*
8-
* RENDER_PASS_FIELDS is the one table of what each pass owns. A field missing
9-
* from a row reads the foreground request's value (#684, the shell-capture
10-
* row). derived-context-shape.rsc-test.tsx pins each row's own-key set.
2+
* Derived render passes over a request past its middleware (PPR shell
3+
* capture, PPR HIT tail, background re-render), each `Object.create(base)`.
4+
* A field missing from a RENDER_PASS_FIELDS row reads the foreground
5+
* request's value (#684). derived-context-shape.rsc-test.tsx pins each row's
6+
* own keys.
117
*/
128
import type { RecordingShellStore } from "../cache/shell-snapshot.js";
139
import type { HandleStore } from "./handle-store.js";
@@ -19,54 +15,44 @@ import {
1915

2016
type ShellImplicitCache = NonNullable<RequestContext["_shellImplicitCache"]>;
2117

22-
/** The pass while its row writes it: _handleStore, readonly elsewhere, is set here. */
18+
/** _handleStore, readonly on RequestContext, is written by the rows. */
2319
type PassUnderConstruction = RequestContext<any> & {
2420
_handleStore: HandleStore;
2521
};
2622

27-
/** What each purpose's caller builds and the pass's own fields read. */
23+
/** What each purpose's caller builds for its row. */
2824
export interface RenderPassInit {
2925
"shell-capture": {
30-
/** The capture's handle store, its push funnel wired (deriveShellCaptureContext). */
3126
handleStore: HandleStore;
3227
/** A navigation-only capture renders this URL instead of the request's. */
3328
identity: { request: Request; url: URL } | undefined;
34-
/**
35-
* Only with a cache store on the request: the recording wrapper over it
36-
* and the capture's implicit doc scope over the recording.
37-
*/
29+
/** Only with a cache store on the request. */
3830
recording:
3931
| { store: RecordingShellStore; implicitCache: ShellImplicitCache }
4032
| undefined;
4133
};
4234
"ppr-tail": {
43-
/** The request's handle store: the tail renders into it. */
35+
/** The request's store, shared: the tail's handles are this response's. */
4436
handleStore: HandleStore;
45-
/** The entry's bake-lane loader pins, when it has records. */
4637
loaderSeed: RequestContext["_shellLoaderSeed"];
47-
/** The doc record replay over the entry's snapshot (docTail). */
4838
implicitCache: ShellImplicitCache;
4939
};
5040
"background-revalidation": {
5141
handleStore: HandleStore;
52-
/** A throwaway context nothing merges or drains: the pass's response writes land on it. */
42+
/** Throwaway: the pass's response writes land here and are dropped. */
5343
sink: RequestContext<any>;
5444
};
5545
}
5646

5747
export type RenderPurpose = keyof RenderPassInit;
5848

5949
interface PassFieldPolicy<I> {
60-
/**
61-
* "own": a fresh barrier family wired to `init.handleStore` and
62-
* closure-bound to the pass (wireRenderBarrier), before `own` runs.
63-
* "inherited": the base's, read through the prototype.
64-
*/
50+
/** "own": wireRenderBarrier(pass, init.handleStore) before `own` runs. */
6551
readonly renderBarrier: "own" | "inherited";
6652
/**
67-
* Writes the pass's own fields. Named stores, not Object.assign of one
68-
* literal: on Node 24 an Object.assign of 20 properties leaves the object
69-
* in V8 dictionary mode (#1109), and the capture owns over 30.
53+
* Named stores, not one Object.assign: on Node 24 an Object.assign that
54+
* takes the object to 20 own properties leaves it in V8 dictionary mode
55+
* (#1109).
7056
*/
7157
readonly own: (
7258
pass: PassUnderConstruction,
@@ -78,193 +64,104 @@ interface PassFieldPolicy<I> {
7864
export const RENDER_PASS_FIELDS: {
7965
readonly [P in RenderPurpose]: PassFieldPolicy<RenderPassInit[P]>;
8066
} = {
81-
/**
82-
* rsc/shell-capture.ts deriveShellCaptureContext. The capture inherits the
83-
* foreground's post-middleware state and owns the render-scoped
84-
* accumulators: its match() behaves like a normal render (cache()'d
85-
* segments replay, uncached handlers run fresh) while the foreground's
86-
* response is already sent.
87-
*/
67+
/** rsc/shell-capture.ts deriveShellCaptureContext. */
8868
"shell-capture": {
89-
// Own render barrier, closure-bound to the derived ctx and the fresh store
90-
// (issue #684, plan 009). Without this every _renderBarrier* read fell
91-
// through the prototype to the foreground's ALREADY-RESOLVED barrier: a
92-
// bake-lane loader's `await ctx.rendered()` resolved instantly and
93-
// ctx.use(handle) read the FOREGROUND handle snapshot — foreground
94-
// per-request handle data could bake into the shared shell.
95-
// wireRenderBarrier also resets _treeHasStreaming (recomputed for the
96-
// capture's tree) and the deadlock-guard fields as own properties.
69+
// #684: an inherited barrier is the foreground's, already resolved:
70+
// ctx.rendered() returns at once and ctx.use(handle) bakes the
71+
// foreground's handles into the shell.
9772
renderBarrier: "own",
9873
own(pass, { handleStore, identity, recording }, base) {
99-
// A fresh store. The foreground store is already drained to completion
100-
// (its stream() flipped `completed` on settle) and would throw
101-
// LateHandlePushError on any re-push. Every downstream reader resolves
102-
// the store off the ambient context (setupLoaderAccess captures
103-
// _getRequestContext()._handleStore; trackHandler reads it), so the
104-
// fresh store on the derived context is what the capture match()
105-
// writes handles to.
74+
// Fresh: the foreground's is drained and throws LateHandlePushError.
10675
pass._handleStore = handleStore;
107-
// The capture notes the route records it reads or writes itself; the
108-
// foreground's (a partial request's `partial:` record, say) are not the
109-
// ones this shell is captured from.
76+
// The capture notes its own route records, not the foreground's.
11077
pass._routeRecordWindow = undefined;
111-
// A navigation-only capture renders another URL than its request's.
11278
if (identity) {
11379
pass.request = identity.request;
11480
pass.url = identity.url;
11581
pass.originalUrl = new URL(identity.url);
11682
pass.pathname = identity.url.pathname;
11783
pass.searchParams = identity.url.searchParams;
11884
}
119-
// The capture collects its OWN shell tags here — non-loader tags only,
120-
// since loaders are masked — which is exactly the tag set a shell entry
121-
// should be invalidatable by (loader tags belong to holes).
85+
// The shell entry's invalidation tags (loader tags belong to holes).
12286
pass._requestTags = new Set<string>();
123-
// Own explicit-store registry: cache-store resolutions during the
124-
// capture (the implicit scope's SnapshotOnlySegmentStore, any
125-
// per-capture explicit store instance) must NOT register into the
126-
// handler-lifetime _explicitTaggedStores set — a capture-ephemeral
127-
// store pinned there would trip the partial-tag-store warning on every
128-
// later updateTag() and retain the whole capture snapshot in memory.
129-
// Capture registrations die with this context; module-singleton stores
130-
// stay registered by normal renders.
87+
// A capture-ephemeral store in the handler-lifetime set would warn on
88+
// every later updateTag() and retain the snapshot.
13189
pass._explicitTaggedStores = new Set();
132-
// Own lists: the capture's render errors refuse the capture only, and
133-
// the foreground's never reach it.
90+
// The capture's render errors refuse the capture only.
13491
pass._renderErrors = [];
13592
pass._recoveredHandlerErrors = undefined;
136-
// The switch the loader, cookies() and headers() capture guards read.
93+
// Read by the loader, cookies() and headers() capture guards.
13794
pass._shellCaptureRun = true;
138-
// Own dynamic() latch. The inherited method writes the FOREGROUND
139-
// context (its closure), which already served, and nothing read it for
140-
// a runtime capture: handler code that opts out after an await (a
141-
// handler promise the capture now waits for) must refuse THIS capture
142-
// instead (settleCaptureRecord and captureAndStoreShell read _dynamic).
143-
// The ppr header latch is left alone: a capture's response is never
144-
// sent.
95+
// The inherited dynamic() writes the foreground, which already served;
96+
// settleCaptureRecord and captureAndStoreShell read this latch.
14597
pass._dynamic = false;
14698
pass.dynamic = (): void => {
14799
pass._dynamic = true;
148100
};
149-
// Own-property reset: an inherited flag would make serializeSegments
150-
// store a double-encoded fragment. No current arming site reaches a
151-
// capture render (kept as defense-in-depth for a future one).
101+
// An inherited true makes serializeSegments double-encode a fragment.
152102
pass._shellFragmentPayload = false;
153-
// The capture never appends to the foreground's (already-finalized)
154-
// metrics.
103+
// Metrics and spans are foreground surfaces, already ended.
155104
pass._metricsStore = undefined;
156-
// Spans, like perf metrics above, are a FOREGROUND surface: the capture
157-
// re-render must not emit a second rango.render/loader/ssr set after
158-
// the foreground rango.request span ended (orphan spans in the trace).
159105
pass._tracing = undefined;
160-
// Bake-lane (`ssr: false`) loader containers, which execute during
161-
// capture (docs/design/loader-container-bake.md). resolveLoaderData
162-
// registers each container promise here; settleCaptureRecord waits for
163-
// them, and the drain in captureAndStoreShell elides + pins them into
164-
// the snapshot's loader family.
106+
// Bake-lane loader containers: settleCaptureRecord awaits them, the
107+
// drain pins them into the snapshot.
165108
pass._shellCaptureLoaderRecords = new Map();
166-
// Own onResponse list so the capture's match-middleware callbacks (the
167-
// doc record registers here) are ISOLATED from the foreground's shared
168-
// array AND can be fired by settleCaptureRecord. The segment write is
169-
// gated behind onResponse, which the capture never triggers (it builds
170-
// no Response): without the synthetic fire, no doc record is written.
109+
// Fired by settleCaptureRecord: the capture builds no Response, and the
110+
// doc record's write is gated on onResponse.
171111
pass._onResponseCallbacks = [];
172-
// Capture data snapshot: the capture's cache-store calls go through a
173-
// recording wrapper on the DERIVED context's store (own property, so
174-
// the request's _cacheStore is untouched — the snapshot is
175-
// per-capture). It records the doc segment record, which rides inside
176-
// the ShellCacheEntry with the bake-lane loader pins; no cache read is
177-
// recorded. See cache/shell-snapshot.ts and the design doc.
178112
if (recording) {
113+
// Own, so the request's _cacheStore is untouched.
179114
pass._cacheStore = recording.store;
180-
// Cache writes are deferred (waitUntil): the doc record's write would
181-
// otherwise land after the match returns. The own waitUntil COLLECTS
182-
// those write promises (still forwarding to the request's so the
183-
// write persists and the worker stays alive), then
184-
// settleCaptureRecord and captureAndStoreShell await them before
185-
// reading the record and draining.
115+
// Collects deferred cache writes (settleCaptureRecord awaits them)
116+
// and still forwards each to the request's waitUntil.
186117
pass.waitUntil = (fn: () => Promise<void>): void => {
187118
const p = Promise.resolve().then(fn);
188119
recording.store.trackWrite(p);
189120
base.waitUntil(() => p);
190121
};
191-
// The doc record (capture side): the implicit doc-cache scope makes
192-
// the capture's match write ALL matched non-loader segments as one
193-
// doc-keyed segment record — into the snapshot only
194-
// (SnapshotOnlySegmentStore), so the record dies with the shell entry
195-
// and the next capture's lookup still misses (handlers re-run on
196-
// recapture). A route deriving its own cache() scope keeps it, and
197-
// recordShellCaptureDocRecord (cache-store.ts) writes the same record
198-
// for it.
122+
// The doc record goes into the snapshot only, so a recapture misses
123+
// and handlers re-run.
199124
pass._shellImplicitCache = recording.implicitCache;
200125
}
201126
},
202127
},
203128

204-
/**
205-
* rsc/rsc-rendering.ts serveShellHit: the live tail behind a committed
206-
* shell prelude. It replays the entry's doc record and serves its loader
207-
* pins, and shares the request's handle store (not an own field): the
208-
* tail's handles are this response's.
209-
*/
129+
/** rsc/rsc-rendering.ts serveShellHit. */
210130
"ppr-tail": {
211-
// Matching writes render state onto the derived context. Its barrier must
212-
// close over that same context or a streaming tail inherits the base
213-
// context's premature non-streaming handle snapshot.
131+
// An inherited barrier carries the base's premature non-streaming handle
132+
// snapshot into a streaming tail.
214133
renderBarrier: "own",
215134
own(pass, { handleStore, loaderSeed, implicitCache }) {
216-
// The tail's render barrier resolves once its record is replayed and
217-
// before a loader runs (cache-lookup.ts withCacheLookup,
218-
// yieldFromStore). The store then holds what the prelude was rendered
219-
// from, so that is the snapshot the document hydrates with; what this
220-
// request's loaders do to it afterwards reaches the client after
221-
// hydration (HandleStore.freezeDocumentSnapshot, issue #1035).
135+
// #1035: the document hydrates with the handles as of the record
136+
// replay, before any loader runs.
222137
const resolveRenderBarrier = pass._resolveRenderBarrier;
223138
pass._resolveRenderBarrier = (segments) => {
224139
handleStore.freezeDocumentSnapshot();
225140
resolveRenderBarrier(segments);
226141
};
227142
if (loaderSeed) pass._shellLoaderSeed = loaderSeed;
228143
pass._shellImplicitCache = implicitCache;
229-
// Fragment splice (issue #700): store hits in THIS tail emit their
230-
// stored segment fragments verbatim (expanded by segment-fragments.ts).
231-
// The flag lives on the derived context so it can never leak into a
232-
// capture render, which serializes segments and must see real
233-
// elements.
144+
// #700 fragment splice: own, so it never reaches a capture render.
234145
pass._shellFragmentPayload = true;
235146
},
236147
},
237148

238149
/**
239-
* router/match-middleware/background-revalidation.ts rerenderAndCacheRoute:
240-
* a stale HIT's refresh and proactive caching. It owns the per-render
241-
* state the foreground reads while it is still producing the page (a stale
242-
* HIT re-runs its loaders; a proactive render starts once the Response
243-
* exists, while its body streams).
150+
* router/match-middleware/background-revalidation.ts rerenderAndCacheRoute.
244151
*/
245152
"background-revalidation": {
246-
// The request's barrier, read through the prototype: unlike the two rows
247-
// above, this pass wires none of its own. Whether it should is the open
248-
// question rango-t135-q1.
153+
// The request's barrier; whether this pass needs its own is rango-t160.
249154
renderBarrier: "inherited",
250155
own(pass, { handleStore, sink }) {
251-
// Read late (loader pushes and aux-lane tracking in
252-
// loader-resolution.ts, nested cache restores and captures in
253-
// cache-scope.ts), so a swap sent live pushes into this render.
254-
// setupLoaderAccess binds the store at setup, so it runs inside the
255-
// derived context too.
156+
// Read late by loader pushes and cache-scope.ts; setupLoaderAccess
157+
// binds it at setup, so that also runs inside this pass.
256158
pass._handleStore = handleStore;
257-
// Nothing lands on the foreground's perf timeline (the DSL store's
258-
// `metrics` is unset too, rerenderAndCacheRoute).
159+
// Nothing lands on the foreground's perf timeline.
259160
pass._metricsStore = undefined;
260161
pass._renderErrors = [];
261162
pass._recoveredHandlerErrors = undefined;
262-
// Response writes (headers, cookies, status, onResponse callbacks) go
263-
// to the throwaway sink (whose status gates the write) and are dropped:
264-
// a layout above the cache() boundary is outside the header guard and
265-
// an error boundary sets a status, so they would otherwise reach the
266-
// live response. The sink's mutators are closures over its own stub,
267-
// and they keep the same guards.
163+
// Response writes go to the sink: a layout above the cache() boundary
164+
// or an error boundary's status would otherwise reach the live response.
268165
pass._onResponseCallbacks = [];
269166
pass.header = sink.header;
270167
pass.setCookie = sink.setCookie;
@@ -274,16 +171,14 @@ export const RENDER_PASS_FIELDS: {
274171
pass.setTheme = sink.setTheme;
275172
pass._rotateStateCookie = sink._rotateStateCookie;
276173
pass._setKeepCacheDirective = sink._setKeepCacheDirective;
277-
// ctx.res reads the sink's stub, not the live request's.
278174
bindRes(pass, () => sink.res);
279175
},
280176
},
281177
};
282178

283179
/**
284-
* Derive a render pass over `base` for `purpose`: `Object.create(base)` with
285-
* the own fields RENDER_PASS_FIELDS[purpose] declares. The only place a
286-
* request context is derived (tools/check-internals.mjs).
180+
* `Object.create(base)` with RENDER_PASS_FIELDS[purpose]'s own fields. The only
181+
* place a request context is derived (tools/check-internals.mjs).
287182
*/
288183
export function deriveRenderPass<P extends RenderPurpose, TEnv>(
289184
base: RequestContext<TEnv>,

0 commit comments

Comments
 (0)