Unverified Commit 2f19ae8e authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Record which params a CacheNode's data depends on (#98972)

Adds a `varyParams` field to CacheNode. When present, they represent the
set of params that the data for that segment varies by. (When null, the
set is unknown.)

Currently, the vary params are only known when the data is fully cached;
vary params are not recorded during a dynamic render. However, this will
change in a future PR once we've integrated with the experimental
Ledgers feature in React.
parent 9937a54a
......@@ -52,9 +52,10 @@ import {
readFromBFCacheDuringRegularNavigation,
writeToBFCache,
writeHeadToBFCache,
updateBFCacheEntryStaleAt,
updateBFCacheEntryFromDynamicResponse,
computeDynamicStaleAt,
} from './segment-cache/bfcache'
import type { VaryParams } from '../../shared/lib/segment-cache/vary-params-decoding'
// This is yet another tree type that is used to track pending promises that
// need to be fulfilled once the dynamic data is received. The terminal nodes of
......@@ -389,10 +390,12 @@ function updateRenderTreeOnNavigation(
// new one.
const data = newRouteTree.data
const seedRsc = data !== null ? data.rsc : null
const seedVaryParams = data !== null ? data.varyParams : null
const result = createRenderTreeForSegment(
navigatedAt,
newRouteTree,
seedRsc,
seedVaryParams,
newMetadataVaryPath,
seedHead,
freshness,
......@@ -662,10 +665,12 @@ function createRenderTreeOnNavigation(
const data = newRouteTree.data
const seedRsc = data !== null ? data.rsc : null
const seedVaryParams = data !== null ? data.varyParams : null
const result = createRenderTreeForSegment(
navigatedAt,
newRouteTree,
seedRsc,
seedVaryParams,
newMetadataVaryPath,
seedHead,
freshness,
......@@ -916,6 +921,7 @@ function createRenderTreeForSegment(
now: number,
tree: RouteTree<RSCSegmentData | null>,
seedRsc: React.ReactNode | null,
seedVaryParams: VaryParams | null,
metadataVaryPath: VaryPath | null,
seedHead: HeadData | null,
freshness: FreshnessPolicy,
......@@ -966,6 +972,7 @@ function createRenderTreeForSegment(
createCacheNode(
bfcacheEntry.rsc,
bfcacheEntry.prefetchRsc,
bfcacheEntry.varyParams,
bfcacheEntry.head,
bfcacheEntry.prefetchHead,
bfcacheId
......@@ -996,6 +1003,7 @@ function createRenderTreeForSegment(
const cacheNode = createCacheNode(
seedRsc,
null,
seedVaryParams,
isPage ? seedHead : null,
null,
bfcacheId
......@@ -1035,6 +1043,7 @@ function createRenderTreeForSegment(
createCacheNode(
bfcacheEntry.rsc,
dropPrefetchRsc ? null : bfcacheEntry.prefetchRsc,
bfcacheEntry.varyParams,
bfcacheEntry.head,
dropPrefetchRsc ? null : bfcacheEntry.prefetchHead,
bfcacheEntry.bfcacheId
......@@ -1056,6 +1065,7 @@ function createRenderTreeForSegment(
let cachedRsc: React.ReactNode | null = null
let isCachedRscPartial: boolean = true
let cachedVaryParams: VaryParams | null = null
const segmentEntry = readSegmentCacheEntryForNavigation(
now,
......@@ -1069,6 +1079,7 @@ function createRenderTreeForSegment(
// Happy path: a cache hit
cachedRsc = segmentEntry.rsc
isCachedRscPartial = segmentEntry.isPartial
cachedVaryParams = segmentEntry.varyParams
break
}
case EntryStatus.Pending: {
......@@ -1079,6 +1090,8 @@ function createRenderTreeForSegment(
cachedRsc = promiseForFulfilledEntry.then((entry) =>
entry !== null ? entry.rsc : null
)
// The entry's data hasn't arrived, and neither has the source of the
// params it depends on; `cachedVaryParams` stays null.
// Because the request is still pending, we typically don't know yet
// whether the response will be partial. We shouldn't skip this segment
// during the dynamic navigation request. Otherwise, we might need to
......@@ -1115,6 +1128,10 @@ function createRenderTreeForSegment(
// means the data failed to load; the LayoutRouter will suspend indefinitely
// until the router updates again (refer to finishNavigationTask).
let rsc: React.ReactNode | null
// The source of the params `rsc` depends on. A server response or a
// fulfilled segment cache entry carries one; a deferred `rsc` gets its
// source when the response arrives (finishPendingCacheNode).
let varyParams: VaryParams | null
let doesSegmentNeedDynamicRequest: boolean
if (seedRsc !== null) {
......@@ -1124,6 +1141,7 @@ function createRenderTreeForSegment(
// partial cached state in the meantime.
prefetchRsc = cachedRsc
rsc = seedRsc
varyParams = seedVaryParams
} else {
// We already have a completely cached segment. Ignore the seed data,
// which may still be streaming in. This shouldn't happen in the normal
......@@ -1131,6 +1149,7 @@ function createRenderTreeForSegment(
// already fully cached, and the server will skip rendering them.
prefetchRsc = null
rsc = cachedRsc
varyParams = cachedVaryParams
}
doesSegmentNeedDynamicRequest = false
} else {
......@@ -1143,10 +1162,12 @@ function createRenderTreeForSegment(
// data arrives from the server.
prefetchRsc = cachedRsc
rsc = createDeferredRsc()
varyParams = null
} else {
// The data is fully cached.
prefetchRsc = null
rsc = cachedRsc
varyParams = cachedVaryParams
}
doesSegmentNeedDynamicRequest = isCachedRscPartial
}
......@@ -1246,6 +1267,7 @@ function createRenderTreeForSegment(
const cacheNode = createCacheNode(
rsc,
prefetchRsc,
varyParams,
head,
prefetchHead,
bfcacheId
......@@ -1270,6 +1292,7 @@ function createRenderTreeForSegment(
function createCacheNode(
rsc: React.ReactNode | null,
prefetchRsc: React.ReactNode | null,
varyParams: VaryParams | null,
head: React.ReactNode | null,
prefetchHead: HeadData | null,
bfcacheId: number,
......@@ -1278,6 +1301,7 @@ function createCacheNode(
return {
rsc,
prefetchRsc,
varyParams,
head,
prefetchHead,
scrollRef,
......@@ -1769,9 +1793,7 @@ async function fetchMissingDynamicData(
task.route,
result.transportData,
// Navigation responses stream in incrementally, so their vary params
// can't be drained here — and nothing consumes them from a navigation
// seed (only segment-cache writes read vary params, and those decode
// their own, buffered, payloads).
// can't be drained here; they decode as null.
null,
result.isResponsePartial,
// Navigation responses always include the param values in the tree, so
......@@ -1911,12 +1933,17 @@ function writeDynamicDataIntoNavigationTask(
revealAfter
)
// Update the BFCache entry's staleAt for this segment with the value
// from the dynamic response. This applies the per-page
// unstable_dynamicStaleTime if set, or the default DYNAMIC_STALETIME_MS.
// We only update segments that received dynamic data — static segments
// are unaffected.
updateBFCacheEntryStaleAt(serverRouteTree.varyPath, dynamicStaleAt)
// The BFCache entry for this segment was written before the response
// arrived. Bring it up to date with what the response filled in: its
// staleAt (the per-page unstable_dynamicStaleTime if set, or the default
// DYNAMIC_STALETIME_MS) and the source of the params its data depends
// on. We only update segments that received dynamic data — static
// segments are unaffected.
updateBFCacheEntryFromDynamicResponse(
serverRouteTree.varyPath,
cacheNode,
dynamicStaleAt
)
}
const taskChildren = task.children
......@@ -2008,20 +2035,27 @@ function finishPendingCacheNode(
return
}
// TODO: `varyParams` must always describe the render that produced `rsc`,
// but nothing in the CacheNode type ties the two fields together; this
// function keeps them in lockstep by writing both at once. Eventually the
// whole CacheNode should be a thenable whose fields are populated through
// dedicated helpers that own the state transition.
if (rsc === null) {
// This is a lazy cache node. We can overwrite it. This is only safe
// because we know that the LayoutRouter suspends if `rsc` is `null`.
cacheNode.rsc = dynamicSegmentData
} else if (isDeferredRsc(rsc)) {
cacheNode.varyParams = dynamicData.varyParams
} else if (isDeferredRsc(rsc) && rsc.status === 'pending') {
// This is a deferred RSC promise. We can fulfill it with the data we just
// received from the server. If it was already resolved by a different
// navigation, then this does nothing because we can't overwrite data.
// received from the server. The source of the params that data depends
// on travels with it.
//
// In the streaming dev render, defer the fill until `revealAfter` settles,
// so React doesn't render the boundary's children before their row has been
// decoded (otherwise it suspends on the still-pending children and commits
// a premature fallback). Outside that render `revealAfter` is null and we
// resolve immediately.
cacheNode.varyParams = dynamicData.varyParams
if (revealAfter !== null) {
const resolveRsc = () => rsc.resolve(dynamicSegmentData, debugInfo)
// Use the same callback for both outcomes: we don't expect `revealAfter`
......@@ -2032,8 +2066,9 @@ function finishPendingCacheNode(
rsc.resolve(dynamicSegmentData, debugInfo)
}
} else {
// This is not a deferred RSC promise, nor is it empty, so it must have
// been populated by a different navigation. We must not overwrite it.
// This is not a deferred RSC promise that's still pending, nor is it
// empty, so it must have been populated by a different navigation. We
// must not overwrite it (nor its dependency source).
}
// Check if this is a leaf segment. If so, it will have a `head` property with
......
......@@ -87,9 +87,9 @@ export function createInitialRouterState({
// render from the root.
null,
// The initial payload may still be streaming in while we hydrate, so its
// vary params can't be drained here — and nothing consumes them from
// this tree. The segment-cache write below re-decodes the transport data
// with the payload's root params once the stale time has resolved.
// vary params can't be drained here; they decode as null. The
// segment-cache write below re-decodes the transport data with the
// payload's root params once the stale time has resolved.
null,
// Same for partiality: only segment-cache writes consume it, and the
// write below re-decodes with the payload's actual response-level value.
......
import { DYNAMIC_STALETIME_MS } from '../router-reducer/reducers/navigate-reducer'
import type { CacheNode } from '../../../shared/lib/app-router-types'
import type { VaryParams } from '../../../shared/lib/segment-cache/vary-params-decoding'
import type { VaryPath } from './vary-path'
/**
......@@ -36,6 +37,11 @@ export type BFCacheEntry = {
head: React.ReactNode | null
prefetchHead: React.ReactNode | null
// The source of the params `rsc` depends on, copied from the CacheNode that
// wrote this entry (see CacheNode.varyParams). A restored node reads it to
// decide whether a later navigation can keep its data.
varyParams: VaryParams | null
// The bfcacheId of the CacheNode that wrote this entry. Restored on
// history-traversal navigations so that `useRouter().bfcacheId` is stable
// across back/forward, even without `cacheComponents` Activity preservation.
......@@ -79,6 +85,7 @@ export function writeToBFCache(
varyPath,
cacheNode.rsc,
cacheNode.prefetchRsc,
cacheNode.varyParams,
cacheNode.head,
cacheNode.prefetchHead,
dynamicStaleAt,
......@@ -91,6 +98,7 @@ function writeEntryToBFCache(
varyPath: VaryPath,
rsc: React.ReactNode,
prefetchRsc: React.ReactNode,
varyParams: VaryParams | null,
head: React.ReactNode,
prefetchHead: React.ReactNode,
dynamicStaleAt: number,
......@@ -109,6 +117,8 @@ function writeEntryToBFCache(
head,
prefetchHead,
varyParams,
bfcacheId,
ref: null,
......@@ -139,7 +149,9 @@ export function writeHeadToBFCache(
dynamicStaleAt: number
): void {
// Write the special "segment" that represents the head data. The page
// node's head fields take the place of the entry's segment fields.
// node's head fields take the place of the entry's segment fields. The
// head's dependency source isn't tracked on the node, so the entry has
// none.
writeEntryToBFCache(
now,
varyPath,
......@@ -147,19 +159,33 @@ export function writeHeadToBFCache(
cacheNode.prefetchHead,
null,
null,
null,
dynamicStaleAt,
cacheNode.bfcacheId
)
}
/**
* Update the staleAt of an existing BFCache entry. Used after a dynamic
* response arrives with a per-page stale time from `unstable_dynamicStaleTime`.
* The per-page value is authoritative — it overrides whatever staleAt was set
* by the default DYNAMIC_STALETIME_MS.
* Patches the entry written for a segment before its dynamic response
* arrived, with what the response filled in on the segment's CacheNode: the
* per-page stale time from `unstable_dynamicStaleTime` (authoritative over
* the default DYNAMIC_STALETIME_MS the entry was written with) and the
* source of the params its data depends on. The entry shares the node's
* deferred `rsc` promise, which the response resolves in place. Only the entry
* that shares the node's `rsc` is updated; a refresh may have replaced the
* entry at the same vary path, and that entry belongs to the newer node.
*
* TODO: This function exists because the entry gets `rsc` when it is written
* but the stale time and vary params only later, through a second write that
* has to find the entry again. The response should fill in all three as one
* unit: make the pending CacheNode itself the thenable (like DeferredRsc, but
* for the whole node) with an explicit pending → fulfilled/rejected
* transition, so the entry holds the node and observes its resolution
* directly, with nothing to look up or patch afterwards.
*/
export function updateBFCacheEntryStaleAt(
export function updateBFCacheEntryFromDynamicResponse(
varyPath: VaryPath,
cacheNode: CacheNode,
newStaleAt: number
): void {
if (typeof window === 'undefined') {
......@@ -175,8 +201,9 @@ export function updateBFCacheEntryStaleAt(
isRevalidation,
false
)
if (entry !== null) {
if (entry !== null && entry.rsc === cacheNode.rsc) {
entry.staleAt = newStaleAt
entry.varyParams = cacheNode.varyParams
}
}
......
......@@ -5,6 +5,8 @@ import {
StaticAttemptHints,
} from '../../../shared/lib/app-router-types'
import {
createVaryParams,
readVaryParams,
SEARCH_PARAMS_VARY_ID,
type VaryParams,
} from '../../../shared/lib/segment-cache/vary-params-decoding'
......@@ -185,10 +187,9 @@ export type RSCSegmentData = {
*/
isPartial: boolean
/**
* The params this segment's output depends on (root params already
* unioned in), drained from the response's wire iterables at decode. Null
* means unknown — tracking wasn't enabled, or the decode had no root
* params to union in — so consumers key on all params.
* The source of the params this segment's output depends on (root params
* included). Null means unknown — tracking wasn't enabled, or the decode
* had no root params to union in — so consumers key on all params.
*/
varyParams: VaryParams | null
/**
......@@ -361,6 +362,12 @@ export type FulfilledSegmentCacheEntry = SegmentCacheEntryShared & {
blockedTasks: null
rsc: React.ReactNode | null
isPartial: boolean
// The source of the params `rsc` depends on, recorded under exactly the
// condition the entry's key trusts it (see the re-key derivation in
// writeSegmentDataIntoCache). Null means unknown: consumers assume the
// output depends on every param. A navigation that renders this entry's
// `rsc` as its final data carries it onto the CacheNode.
varyParams: VaryParams | null
promise: null
}
......@@ -1314,6 +1321,7 @@ export function attemptToFulfillDynamicSegmentFromBFCache(
bfcacheEntry.rsc,
dynamicPrefetchStaleAt,
isPartial,
bfcacheEntry.varyParams,
// bfcache data is concrete, never an ISR fallback.
false,
FetchStrategy.Full
......@@ -1352,6 +1360,7 @@ export function attemptToUpgradeSegmentFromBFCache(
bfcacheEntry.rsc,
dynamicPrefetchStaleAt,
isPartial,
bfcacheEntry.varyParams,
// bfcache data is concrete, never an ISR fallback.
false,
FetchStrategy.Full
......@@ -1548,6 +1557,7 @@ function fulfillSegmentCacheEntry(
rsc: React.ReactNode,
staleAt: number,
isPartial: boolean,
varyParams: VaryParams | null,
// Only static (per-segment PPR) responses can be ISR fallbacks; all other
// callers pass false. Always assigned (even when false) so that re-fulfilling
// a previously-fallback entry with a concrete response clears the flag and
......@@ -1570,6 +1580,7 @@ function fulfillSegmentCacheEntry(
fulfilledEntry.rsc = rsc
fulfilledEntry.staleAt = staleAt
fulfilledEntry.isPartial = isPartial
fulfilledEntry.varyParams = varyParams
fulfilledEntry.isUpgradeableISRFallback = isUpgradeableISRFallback
fulfilledEntry.fetchStrategy = fetchStrategy
// Resolve any listeners that were waiting for this data.
......@@ -3430,46 +3441,59 @@ function writeSegmentDataIntoCache(
// vary path).
const payloadStrategy = contentFetchStrategy ?? fetchStrategy
let fulfilledVaryPath: VaryPath | null = null
// The dependency source the entry records, so a navigation that renders
// its content can tell which params that content read. It is the same
// evidence the key derivation below trusts, under the same condition, with
// the same correction; otherwise null, and consumers assume every param.
let recordedVaryParams: VaryParams | null = null
if (
process.env.__NEXT_VARY_PARAMS &&
payloadStrategy !== FetchStrategy.Full &&
segmentVaryParams !== null
) {
let varyParams = segmentVaryParams
if (
payloadStrategy === FetchStrategy.RuntimeShell &&
varyParams.has(SEARCH_PARAMS_VARY_ID)
) {
// SPECIAL CASE: for a RuntimeShell payload, the search params entry
// is dropped from the server's vary evidence before deriving the
// key, so the search component of the resulting path is marked as
// the fallback. This exists ONLY because of a known compromise in
// how the server reports search params: accessing `searchParams`
// records a dependency on them at access time, even when the render
// suspends on that access and cuts the content at the param
// fallback. A shell render's page and head segments therefore report
// the search params while the emitted bytes contain no
// search-dependent content.
// Trusting that report would key shell-grade content at a concrete
// search value, where shell-restricted reads (which generalize every
// non-root param — see getShellSegmentVaryPath) can never find it. A
// RuntimeShell payload's search-dependent content is reduced to
// fallbacks by construction, so its key must not vary on search
// regardless of the over-reported evidence. Every other component of
// the evidence is still honored as-is.
//
// Nothing else should rely on this branch; for every other payload
// grade — and every other param — the server's evidence
// is authoritative.
//
// TODO: Reconsider special-casing this on the server instead: don't
// report a param access that never resolved past the fallback cut in
// the emitted stage. A shell payload's evidence would then be
// accurate, and this branch could be deleted.
varyParams = new Set(varyParams)
varyParams.delete(SEARCH_PARAMS_VARY_ID)
// Read the reported set now, when the key is chosen. The payload is fully
// buffered by the time it's written, so the source has settled; a read of
// null means the report is unavailable and every param varies.
let varyParams = readVaryParams(segmentVaryParams)
if (varyParams !== null) {
if (
payloadStrategy === FetchStrategy.RuntimeShell &&
varyParams.has(SEARCH_PARAMS_VARY_ID)
) {
// SPECIAL CASE: for a RuntimeShell payload, the search params entry
// is dropped from the server's vary evidence before deriving the
// key, so the search component of the resulting path is marked as
// the fallback. This exists ONLY because of a known compromise in
// how the server reports search params: accessing `searchParams`
// records a dependency on them at access time, even when the render
// suspends on that access and cuts the content at the param
// fallback. A shell render's page and head segments therefore report
// the search params while the emitted bytes contain no
// search-dependent content.
// Trusting that report would key shell-grade content at a concrete
// search value, where shell-restricted reads (which generalize every
// non-root param — see getShellSegmentVaryPath) can never find it. A
// RuntimeShell payload's search-dependent content is reduced to
// fallbacks by construction, so its key must not vary on search
// regardless of the over-reported evidence. Every other component of
// the evidence is still honored as-is.
//
// Nothing else should rely on this branch; for every other payload
// grade — and every other param — the server's evidence
// is authoritative.
//
// TODO: Reconsider special-casing this on the server instead: don't
// report a param access that never resolved past the fallback cut in
// the emitted stage. A shell payload's evidence would then be
// accurate, and this branch could be deleted.
varyParams = new Set(varyParams)
varyParams.delete(SEARCH_PARAMS_VARY_ID)
recordedVaryParams = createVaryParams(varyParams)
} else {
recordedVaryParams = segmentVaryParams
}
fulfilledVaryPath = getFulfilledSegmentVaryPath(tree.varyPath, varyParams)
}
fulfilledVaryPath = getFulfilledSegmentVaryPath(tree.varyPath, varyParams)
}
// The canonical path to (re-)key the entry at. When the derivation above
......@@ -3508,6 +3532,7 @@ function writeSegmentDataIntoCache(
rsc,
staleAt,
isPartial,
recordedVaryParams,
isUpgradeableISRFallback,
recordedFetchStrategy
)
......@@ -3527,6 +3552,7 @@ function writeSegmentDataIntoCache(
rsc,
staleAt,
isPartial,
recordedVaryParams,
isUpgradeableISRFallback,
recordedFetchStrategy
)
......
......@@ -25,7 +25,7 @@ import type {
VaryParams,
VaryParamsIterable,
} from '../../../shared/lib/segment-cache/vary-params-decoding'
import { readVaryParams } from '../../../shared/lib/segment-cache/vary-params-decoding'
import { decodeVaryParams } from '../../../shared/lib/segment-cache/vary-params-decoding'
import {
type SegmentRequestKey,
ROOT_SEGMENT_REQUEST_KEY,
......@@ -70,10 +70,9 @@ export type NavigationSeed = {
head: HeadData | null
isHeadPartial: boolean
/**
* The params the head's output depends on (root params already unioned
* in), drained from the response's wire iterables at decode. Null means
* unknown — tracking wasn't enabled, or the decode had no root params to
* union in — so consumers key on all params.
* The source of the params the head's output depends on (root params
* included). Null means unknown — tracking wasn't enabled, or the decode
* had no root params to union in — so consumers key on all params.
*/
headVaryParams: VaryParams | null
/**
......@@ -118,13 +117,11 @@ export function createNavigationSeed(
// The response's root vary params (its `r` field): the root params
// accessed anywhere in the response, emitted once at the response level
// and unioned into the head's and every segment's own drained set here at
// the decode boundary. Pass null when vary params are unavailable or
// unwanted: navigation and reducer flows, whose responses stream in
// incrementally (the wire iterables can only be drained completely from a
// fully-buffered response) and whose seeds' vary params nothing consumes —
// only segment-cache writes read them, and those decode their own,
// buffered, payloads. Null decodes every set as null ("unknown; key on
// all params") without touching the wire iterables.
// the decode boundary. Pass null when the response streams in
// incrementally (navigation and reducer flows): the wire iterables can
// only be drained completely from a fully-buffered response, so their sets
// decode as null ("unknown; key on all params") without touching the wire
// iterables.
rootVaryParams: VaryParamsIterable | null,
// Whether anything in the response is not fully resolved: dynamic holes, runtime holes, anything suspended.
// Boolean-form nodes resolve their partiality to this value (their wire
......@@ -192,7 +189,7 @@ export function createNavigationSeed(
? isResponsePartial
: transportHead.p
: readFulfilledIsPartial(transportHead.p)
headVaryParams = readVaryParams(transportHead.v, rootVaryParams)
headVaryParams = decodeVaryParams(transportHead.v, rootVaryParams)
headStaleTimeSeconds =
transportHead.s !== undefined
? readFulfilledStaleTimeSeconds(transportHead.s)
......@@ -636,11 +633,12 @@ function decodeTransportNode(
typeof nodeData.p === 'boolean'
? isResponsePartial
: readFulfilledIsPartial(nodeData.p),
// Drain the segment's wire iterable into a plain set, unioning in the
// response-level root params. Same buffered-read reasoning as `p`
// above; skipped entirely (decoded as null, "unknown") when the caller
// passed no root params — see createNavigationSeed.
varyParams: readVaryParams(nodeData.v, rootVaryParams),
// The source of the params this segment's output depends on: the
// segment's wire iterable, drained here, unioning in the response-level
// root params (same buffered-read reasoning as `p` above), or decoded
// as null ("unknown") when the caller passed no root params — see
// createNavigationSeed.
varyParams: decodeVaryParams(nodeData.v, rootVaryParams),
// Per-node staleTime, only present in per-segment prefetch responses
// (same buffered-read reasoning as `p` above).
staleTimeSeconds:
......
......@@ -11,7 +11,10 @@ export type LoadingModuleData =
| [React.JSX.Element, React.ReactNode, React.ReactNode]
| null
import type { VaryParamsIterable } from './segment-cache/vary-params-decoding'
import type {
VaryParams,
VaryParamsIterable,
} from './segment-cache/vary-params-decoding'
import type { FullTransportData, PartialTransportData } from './rsc-transport'
/** viewport metadata node */
......@@ -45,6 +48,15 @@ export type CacheNode = {
*/
prefetchRsc: React.ReactNode
/**
* The source of the params `rsc` depends on, from the response that
* produced it. Null when unknown: the data came from the segment cache, or
* from a render that didn't track params, or `rsc` is still pending — it
* is set alongside `rsc` when the response arrives. A navigation that only
* changes params this output did not depend on can keep rendering it.
*/
varyParams: VaryParams | null
prefetchHead: HeadData | null
head: HeadData
......
......@@ -20,7 +20,16 @@ export const SEARCH_PARAMS_VARY_ID = 0
// Path param names, and SEARCH_PARAMS_VARY_ID for the search params.
export type VaryParamId = string | number
export type VaryParams = Set<VaryParamId>
/**
* The params a piece of rendered output depends on — the ids of the vary path
* nodes it read: path param names, and SEARCH_PARAMS_VARY_ID for the search
* params — as the source that reports them rather than a snapshot of it.
*
* The wire iterables can only be drained from a fully-buffered response; they
* are drained once at decode into an already-settled thenable, and read at the
* point a decision needs the set (readVaryParams).
*/
export type VaryParams = PromiseLike<Set<VaryParamId>>
/**
* Vary params are serialized into the Flight stream as an
......@@ -33,9 +42,9 @@ export type VaryParams = Set<VaryParamId>
*
* Root params are NOT included in a segment's own iterable. They're emitted
* once at the top level of the response (as a separate iterable) and unioned in
* by `readVaryParams`, because root params can be accessed at any point during
* the render — folding them into every segment would otherwise require a merge
* once the whole render is complete.
* by `decodeVaryParams`, because root params can be accessed at any point
* during the render — folding them into every segment would otherwise require
* a merge once the whole render is complete.
*/
export type VaryParamsIterable = AsyncIterable<VaryParamId>
......@@ -59,7 +68,7 @@ export type VaryParamsIterable = AsyncIterable<VaryParamId>
*/
function drainVaryParams(
iterable: VaryParamsIterable,
target: VaryParams
target: Set<VaryParamId>
): void {
const iterator = iterable[Symbol.asyncIterator]()
while (true) {
......@@ -74,13 +83,13 @@ function drainVaryParams(
}
/**
* Reads a segment's (or the head's) vary params, unioning in the response-level
* root params.
* Converts a segment's (or the head's) vary params off the wire, at the
* decode boundary, unioning in the response-level root params.
*
* Root params are emitted once at the top level rather than folded into every
* segment by the server, so every read recombines them here — building the
* merge into the read means a caller can't forget it, and it's done in a single
* pass with no intermediate set.
* segment by the server, so every decode recombines them here — building the
* merge into the decode means a caller can't forget it, and it's done in a
* single pass with no intermediate set.
*
* Returns null ("unknown", key on all params) unless BOTH iterables are
* present. A null/absent `iterable` means the segment's own tracking wasn't
......@@ -94,7 +103,7 @@ function drainVaryParams(
* set — a tracked segment that read no params, with no root params accessed,
* can be shared across all param values.
*/
export function readVaryParams(
export function decodeVaryParams(
iterable: VaryParamsIterable | null | undefined,
rootIterable: VaryParamsIterable | null | undefined
): VaryParams | null {
......@@ -106,8 +115,34 @@ export function readVaryParams(
) {
return null
}
const varyParams: VaryParams = new Set()
drainVaryParams(iterable, varyParams)
drainVaryParams(rootIterable, varyParams)
return varyParams
const total: Set<VaryParamId> = new Set()
drainVaryParams(iterable, total)
drainVaryParams(rootIterable, total)
return createVaryParams(total)
}
/**
* Wraps an already-known set as a vary params source. Shaped like a settled
* Flight promise so readVaryParams can read it off the thenable's status.
*/
export function createVaryParams(total: Set<VaryParamId>): VaryParams {
// TODO: Don't need to use a native promise. Just inline a thenable that
// immediately calls its listener.
const settled = Promise.resolve(total) as Promise<Set<VaryParamId>> & {
status: 'fulfilled'
value: Set<VaryParamId>
}
settled.status = 'fulfilled'
settled.value = total
return settled
}
/**
* Reads the set from a vary params source. Null when it is not available;
* the reader assumes every param varies.
*/
export function readVaryParams(
varyParams: VaryParams
): Set<VaryParamId> | null {
return readFulfilledValue(varyParams, null)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment