Unverified Commit 03383c3d authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Remove the page/layout distinction from RouteTree (#98970)

Part of a series of internal refactors to improve param tracking on the
client.

A route tree node used to come in two variants, a layout and a page,
distinguished by an isPage flag that every constructor had to keep
consistent with the VaryPath it built. The variants only differed in
whether the vary path carried a search params entry, and the code that
needed to know either checked the flag or read the vary path's shape
positionally.

Collapse them into one RouteTree type with one VaryPath type. The few
places that still care whether a node is a page derive it from the
segment. When something needs to read the search params, they can be
accessed from the RouteTree or VaryPath like we do for other params.

This is a pure refactor of the existing code. It reads more naturally
with a single tree type and a single vary path type, which the rest of
this stack builds on.
parent cb95ca37
......@@ -45,7 +45,7 @@ import type { NormalizedSearch } from './segment-cache/cache-key'
import type { CacheMap } from './segment-cache/cache-map'
import {
getRenderedSearchFromVaryPath,
type PageVaryPath,
type VaryPath,
} from './segment-cache/vary-path'
import {
readFromBFCache,
......@@ -219,7 +219,7 @@ export function startPPRNavigation(
oldCacheNode: CacheNode | null,
oldRouterState: FlightRouterState,
newRouteTree: RouteTree<RSCSegmentData | null>,
newMetadataVaryPath: PageVaryPath | null,
newMetadataVaryPath: VaryPath | null,
freshness: FreshnessPolicy,
seedHead: HeadData | null,
seedDynamicStaleAt: number,
......@@ -264,7 +264,7 @@ function updateCacheNodeOnNavigation(
oldCacheNode: CacheNode | void,
oldRouterState: FlightRouterState,
newRouteTree: RouteTree<RSCSegmentData | null>,
newMetadataVaryPath: PageVaryPath | null,
newMetadataVaryPath: VaryPath | null,
freshness: FreshnessPolicy,
seedHead: HeadData | null,
seedDynamicStaleAt: number,
......@@ -656,7 +656,7 @@ function accumulateScrollRef(
function createCacheNodeOnNavigation(
navigatedAt: number,
newRouteTree: RouteTree<RSCSegmentData | null>,
newMetadataVaryPath: PageVaryPath | null,
newMetadataVaryPath: VaryPath | null,
freshness: FreshnessPolicy,
seedHead: HeadData | null,
seedDynamicStaleAt: number,
......@@ -780,7 +780,7 @@ function createCacheNodeOnNavigation(
function createSegmentFromRouteTree(
newRouteTree: RouteTree<RSCSegmentData | null>
): Segment {
if (newRouteTree.isPage) {
if (newRouteTree.segment === PAGE_SEGMENT_KEY) {
// In a dynamic server response, the server embeds the search params into
// the segment key, but in a static one it's omitted. The client handles
// this inconsistency by adding the search params back right at the end.
......@@ -953,7 +953,7 @@ function createCacheNodeForSegment(
now: number,
tree: RouteTree<RSCSegmentData | null>,
seedRsc: React.ReactNode | null,
metadataVaryPath: PageVaryPath | null,
metadataVaryPath: VaryPath | null,
seedHead: HeadData | null,
freshness: FreshnessPolicy,
dynamicStaleAt: number,
......@@ -978,7 +978,7 @@ function createCacheNodeForSegment(
// also be able to use that data without spawning a new request. (This is
// referred to as the "seed" data.)
const isPage = tree.isPage
const isPage = tree.segment === PAGE_SEGMENT_KEY
// During certain kinds of navigations, we may be able to render from
// the BFCache.
......
import { DYNAMIC_STALETIME_MS } from '../router-reducer/reducers/navigate-reducer'
import type { SegmentVaryPath } from './vary-path'
import type { VaryPath } from './vary-path'
/**
* Sentinel value indicating that no per-page dynamic stale time was provided.
......@@ -69,7 +69,7 @@ export function invalidateBfCache(): void {
export function writeToBFCache(
now: number,
varyPath: SegmentVaryPath,
varyPath: VaryPath,
rsc: React.ReactNode,
prefetchRsc: React.ReactNode,
head: React.ReactNode,
......@@ -115,7 +115,7 @@ export function writeToBFCache(
export function writeHeadToBFCache(
now: number,
varyPath: SegmentVaryPath,
varyPath: VaryPath,
head: React.ReactNode,
prefetchHead: React.ReactNode,
dynamicStaleAt: number,
......@@ -141,7 +141,7 @@ export function writeHeadToBFCache(
* by the default DYNAMIC_STALETIME_MS.
*/
export function updateBFCacheEntryStaleAt(
varyPath: SegmentVaryPath,
varyPath: VaryPath,
newStaleAt: number
): void {
if (typeof window === 'undefined') {
......@@ -162,9 +162,7 @@ export function updateBFCacheEntryStaleAt(
}
}
export function readFromBFCache(
varyPath: SegmentVaryPath
): BFCacheEntry | null {
export function readFromBFCache(varyPath: VaryPath): BFCacheEntry | null {
if (typeof window === 'undefined') {
return null
}
......@@ -184,7 +182,7 @@ export function readFromBFCache(
export function readFromBFCacheDuringRegularNavigation(
now: number,
varyPath: SegmentVaryPath
varyPath: VaryPath
): BFCacheEntry | null {
if (typeof window === 'undefined') {
return null
......
import type { VaryPath } from './vary-path'
import type { VaryPathNode } from './vary-path'
import { lruPut, updateLruSize, deleteFromLru } from './lru'
/**
......@@ -160,7 +160,7 @@ export function createCacheMap<V extends MapValue>(): CacheMap<V> {
function getOrInitialize<V extends MapValue>(
cacheMap: CacheMap<V>,
keys: VaryPath,
keys: VaryPathNode,
isRevalidation: boolean
): MapEntry<V> {
// Go through each level of keys until we find the entry that matches, or
......@@ -170,7 +170,7 @@ function getOrInitialize<V extends MapValue>(
// Unlike getWithFallback, it will not access fallback entries unless it's
// explicitly part of the keypath.
let entry = cacheMap
let remainingKeys: VaryPath | null = keys
let remainingKeys: VaryPathNode | null = keys
let key: unknown | null = null
while (true) {
const previousKey = key
......@@ -230,7 +230,7 @@ export function getFromCacheMap<V extends MapValue>(
now: number,
currentCacheVersion: number,
rootEntry: CacheMap<V>,
keys: VaryPath,
keys: VaryPathNode,
isRevalidation: boolean,
// When true, terminal entries whose status is not Fulfilled are skipped, so
// the lookup falls through to a less-specific Fallback entry. Use this
......@@ -301,7 +301,7 @@ function getEntryWithFallbackImpl<V extends MapValue>(
now: number,
currentCacheVersion: number,
entry: MapEntry<V>,
keys: VaryPath | null,
keys: VaryPathNode | null,
isRevalidation: boolean,
previousKey: unknown | null,
onlyMatchFulfilled: boolean
......@@ -317,7 +317,7 @@ function getEntryWithFallbackImpl<V extends MapValue>(
// are treated as non-matches, so the recursion will continue searching for
// a Fallback match. See getFromCacheMap for the rationale.
let key
let remainingKeys: VaryPath | null
let remainingKeys: VaryPathNode | null
if (keys !== null) {
key = keys.value
remainingKeys = keys.parent
......@@ -373,7 +373,7 @@ function getEntryWithFallbackImpl<V extends MapValue>(
export function setInCacheMap<V extends MapValue>(
cacheMap: CacheMap<V>,
keys: VaryPath,
keys: VaryPathNode,
value: V,
isRevalidation: boolean
): void {
......
......@@ -4,7 +4,10 @@ import {
PrefetchHint,
StaticAttemptHints,
} from '../../../shared/lib/app-router-types'
import type { VaryParams } from '../../../shared/lib/segment-cache/vary-params-decoding'
import {
SEARCH_PARAMS_VARY_ID,
type VaryParams,
} from '../../../shared/lib/segment-cache/vary-params-decoding'
import { readFulfilledValue } from '../../../shared/lib/rsc-transport'
import {
NEXT_DID_POSTPONE_HEADER,
......@@ -33,18 +36,15 @@ import {
} from './scheduler'
import {
type RouteVaryPath,
type SegmentVaryPath,
type PartialSegmentVaryPath,
type VaryPath,
type PartialVaryPath,
getRouteVaryPath,
getFulfilledRouteVaryPath,
getFulfilledSegmentVaryPath,
getSegmentVaryPathForRequest,
getShellSegmentVaryPath,
clonePageVaryPathWithNewSearchParams,
type PageVaryPath,
type LayoutVaryPath,
getPartialPageVaryPath,
getPartialLayoutVaryPath,
cloneVaryPathWithNewSearchParams,
getPartialVaryPath,
getRenderedSearchFromVaryPath,
} from './vary-path'
import { createHrefFromUrl } from '../router-reducer/create-href-from-url'
......@@ -199,17 +199,18 @@ export type RSCSegmentData = {
staleTimeSeconds: number | null
}
type RouteTreeShared<TData> = {
export type RouteTree<TData> = {
requestKey: SegmentRequestKey
// TODO: Remove the `segment` field, now that it can be reconstructed
// from `param`.
segment: FlightRouterStateSegment
varyPath: VaryPath
// The vary path used for shell-scoped keying of this segment: the
// segment's vary path with every non-root param replaced with Fallback
// (see getShellSegmentVaryPath), so one shell-tier entry serves all param
// values below the root. Precomputed once during tree construction so we
// don't have to recompute it on every shell request.
shellVaryPath: SegmentVaryPath
shellVaryPath: VaryPath
refreshState: RefreshState | null
// Render output for this segment, when the tree was created from a server
// response that rendered it. The type parameter encodes a lifecycle
......@@ -236,18 +237,6 @@ export type RefreshState = {
renderedSearch: NormalizedSearch
}
type LayoutRouteTree<TData> = RouteTreeShared<TData> & {
isPage: false
varyPath: LayoutVaryPath
}
type PageRouteTree<TData> = RouteTreeShared<TData> & {
isPage: true
varyPath: PageVaryPath
}
export type RouteTree<TData> = LayoutRouteTree<TData> | PageRouteTree<TData>
type RouteCacheEntryShared = {
// This is false only if we're certain the route cannot be intercepted. It's
// true in all other cases, including on initialization when we haven't yet
......@@ -612,7 +601,7 @@ export function readSegmentCacheEntryForNavigation(
// The map the navigation is bound to: a locked navigation's driving-task
// map, or the shared map otherwise.
map: CacheMap<SegmentCacheEntry>,
varyPath: SegmentVaryPath,
varyPath: VaryPath,
restrictToShell: boolean = false
): SegmentCacheEntry | null {
const isRevalidation = false
......@@ -653,7 +642,7 @@ export function readSegmentCacheEntryForNavigation(
function readRevalidatingSegmentCacheEntry(
now: number,
map: CacheMap<SegmentCacheEntry>,
varyPath: SegmentVaryPath
varyPath: VaryPath
): SegmentCacheEntry | null {
const isRevalidation = true
return getFromCacheMap(
......@@ -882,37 +871,20 @@ function deprecated_createOptimisticRouteTree(
}
}
// We only need to clone the vary path if the route is a page.
if (tree.isPage) {
// The shell vary path Fallbacks search params, so it's unaffected by the
// new rendered search and can be reused as-is.
return {
requestKey: tree.requestKey,
segment: tree.segment,
shellVaryPath: tree.shellVaryPath,
refreshState: tree.refreshState,
// Optimistic trees are structure-only. (The input tree comes from the
// route cache, which never carries render output.)
data: null,
varyPath: clonePageVaryPathWithNewSearchParams(
tree.varyPath,
newRenderedSearch
),
isPage: true,
slots: clonedSlots,
prefetchHints: tree.prefetchHints,
}
}
// The shell vary path Fallbacks search params, so it's unaffected by the
// new rendered search and can be reused as-is.
return {
requestKey: tree.requestKey,
segment: tree.segment,
shellVaryPath: tree.shellVaryPath,
refreshState: tree.refreshState,
// Optimistic trees are structure-only. (The input tree comes from the
// route cache, which never carries render output.)
data: null,
varyPath: tree.varyPath,
isPage: false,
varyPath: cloneVaryPathWithNewSearchParams(
tree.varyPath,
newRenderedSearch
),
slots: clonedSlots,
prefetchHints: tree.prefetchHints,
}
......@@ -1082,7 +1054,7 @@ export function upsertSegmentEntry(
// testing-lock scope boundary still writes into the map its entries
// live in.
map: CacheMap<SegmentCacheEntry>,
varyPath: SegmentVaryPath,
varyPath: VaryPath,
candidateEntry: SegmentCacheEntry,
// The fully concrete vary path a read for this segment position resolves
// against (all concrete param values, i.e. `tree.varyPath`) — the most
......@@ -1091,7 +1063,7 @@ export function upsertSegmentEntry(
// Used to detect and evict stale entries at more specific keypaths that
// would otherwise shadow the candidate. Pass null when there's no request
// context; the shadow check is skipped.
lookupVaryPath: SegmentVaryPath | null
lookupVaryPath: VaryPath | null
): SegmentCacheEntry | null {
// We have a new entry that has not yet been inserted into the cache. Before
// we do so, we need to confirm whether it takes precedence over the existing
......@@ -1208,7 +1180,7 @@ export function upsertSegmentEntry(
function evictShadowingSegmentEntries(
now: number,
map: CacheMap<SegmentCacheEntry>,
lookupVaryPath: SegmentVaryPath,
lookupVaryPath: VaryPath,
candidateEntry: SegmentCacheEntry
): void {
// There can in principle be multiple shadowing entries at successively less
......@@ -1428,7 +1400,7 @@ function pingBlockedTasks(entry: {
}
export function createMetadataRouteTree(
metadataVaryPath: PageVaryPath,
metadataVaryPath: VaryPath,
// The route root's prefetch hints. The head has no node of its own on the
// wire, so route-level hints are read from the root on its behalf — the
// same convention as pingStaticHead in scheduler.ts.
......@@ -1445,10 +1417,6 @@ export function createMetadataRouteTree(
refreshState: null,
data: null,
varyPath: metadataVaryPath,
// The metadata isn't really a "page" (though it isn't really a "segment"
// either) but for the purposes of how this field is used, it behaves like
// one. If this logic ever gets more complex we can change this to an enum.
isPage: true,
slots: null,
// Only the static-attempt bits apply to the head: it's a route-level
// fact ("static per-segment responses may exist for this route"), and
......@@ -1466,7 +1434,7 @@ export function createMetadataRouteTree(
* the subtrees that carry data. Called when a tree is stored in the route
* cache: route cache entries live indefinitely, so retaining render output
* there would pin RSC payloads in memory outside the segment cache's eviction
* control. See the lifecycle note on RouteTreeShared.
* control. See the lifecycle note on RouteTree.
*/
function stripDataFromRouteTree(
tree: RouteTree<RSCSegmentData | null>
......@@ -1499,19 +1467,6 @@ function stripDataFromRouteTree(
string,
RouteTree<null>
> | null
if (tree.isPage) {
return {
requestKey: tree.requestKey,
segment: tree.segment,
shellVaryPath: tree.shellVaryPath,
refreshState: tree.refreshState,
data: null,
varyPath: tree.varyPath,
isPage: true,
slots: strippedSlots,
prefetchHints: tree.prefetchHints,
}
}
return {
requestKey: tree.requestKey,
segment: tree.segment,
......@@ -1519,7 +1474,6 @@ function stripDataFromRouteTree(
refreshState: tree.refreshState,
data: null,
varyPath: tree.varyPath,
isPage: false,
slots: strippedSlots,
prefetchHints: tree.prefetchHints,
}
......@@ -1529,7 +1483,7 @@ export function fulfillRouteCacheEntry(
now: number,
entry: PendingRouteCacheEntry,
tree: RouteTree<RSCSegmentData | null>,
metadataVaryPath: PageVaryPath,
metadataVaryPath: VaryPath,
couldBeIntercepted: boolean,
canonicalUrl: string,
supportsPerSegmentPrefetching: boolean
......@@ -1573,7 +1527,7 @@ export function writeRouteIntoCache(
search: NormalizedSearch,
nextUrl: string | null,
tree: RouteTree<RSCSegmentData | null>,
metadataVaryPath: PageVaryPath,
metadataVaryPath: VaryPath,
couldBeIntercepted: boolean,
canonicalUrl: string,
supportsPerSegmentPrefetching: boolean
......@@ -1665,7 +1619,7 @@ function rejectSegmentCacheEntry(
}
export type RouteTreeAccumulator = {
metadataVaryPath: PageVaryPath | null
metadataVaryPath: VaryPath | null
// Whether the decoded tree's segment identities diverged from the base
// tree it was overlaid onto. See NavigationSeed.treeDivergedFromBase.
treeDivergedFromBase: boolean
......@@ -1698,9 +1652,7 @@ export function convertReusedFlightRouterStateToRouteTree(
// Unlike a FlightRouterState, the RouteTree type contains backreferences to
// the parent segments. Append the vary path to the parent's vary path.
const parentPartialVaryPath = parentRouteTree.isPage
? getPartialPageVaryPath(parentRouteTree.varyPath)
: getPartialLayoutVaryPath(parentRouteTree.varyPath)
const parentPartialVaryPath = getPartialVaryPath(parentRouteTree.varyPath)
const segment = flightRouterState[0]
// And the request key.
const parentRequestKey = parentRouteTree.requestKey
......@@ -1722,7 +1674,7 @@ export function convertReusedFlightRouterStateToRouteTree(
export function convertFlightRouterStateToRouteTree(
flightRouterState: FlightRouterState,
requestKey: SegmentRequestKey,
parentPartialVaryPath: PartialSegmentVaryPath | null,
parentPartialVaryPath: PartialVaryPath | null,
parentRenderedSearch: NormalizedSearch,
acc: RouteTreeAccumulator
): RouteTree<null> {
......@@ -1757,9 +1709,7 @@ export function convertFlightRouterStateToRouteTree(
acc
)
tree.refreshState = refreshState
const partialVaryPath = tree.isPage
? getPartialPageVaryPath(tree.varyPath)
: getPartialLayoutVaryPath(tree.varyPath)
const partialVaryPath = getPartialVaryPath(tree.varyPath)
let slots: Map<string, RouteTree<null>> | null = null
......@@ -2369,10 +2319,8 @@ async function fetchAndWritePerSegmentPrefetchResponse(
// no tree position, so the decode could only derive a vary path for it
// from a page node in the payload's own tree, which a standalone head
// response (a bare root identity) doesn't have.
// (createMetadataRouteTree stores a PageVaryPath in `varyPath`, so the
// cast is sound.)
const now = Date.now()
const metadataVaryPath = route.metadata.varyPath as PageVaryPath
const metadataVaryPath = route.metadata.varyPath
writeResponsePayloadsIntoCache(
now,
fetchStrategy,
......@@ -2776,7 +2724,7 @@ function writeResponsePayloadsIntoCache(
// (Per-segment payloads encode partiality per node and ignore the
// response-level value entirely.)
isFullResponsePartial: boolean,
metadataVaryPath: PageVaryPath | null,
metadataVaryPath: VaryPath | null,
// The pending entries this response fulfills. Null when the caller owns
// none (the embedded runtime prefetch stream), in which case every write
// is a detached upsert.
......@@ -3099,7 +3047,7 @@ function writeServerResponseIntoCache(
// Where to key the head. Null derives it from the decoded tree's first
// page node; per-segment payloads pass the route's own metadata vary path
// instead, since a standalone head response's tree has no page node.
metadataVaryPath: PageVaryPath | null,
metadataVaryPath: VaryPath | null,
spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null,
// The strategy tier describing the CONTENT of the payload being written,
// when it differs from `fetchStrategy` (which drives matching and
......@@ -3384,7 +3332,7 @@ function writeSegmentDataIntoCache(
rsc: React.ReactNode,
isPartial: boolean,
staleAt: number,
segmentVaryParams: Set<string> | null,
segmentVaryParams: VaryParams | null,
tree: RouteTree<RSCSegmentData | null>,
spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null,
// The strategy tier describing the CONTENT of the payload this write came
......@@ -3496,26 +3444,30 @@ function writeSegmentDataIntoCache(
// is good for any value of them (its request path below IS the shell
// vary path).
const payloadStrategy = contentFetchStrategy ?? fetchStrategy
let fulfilledVaryPath: SegmentVaryPath | null = null
let fulfilledVaryPath: VaryPath | null = null
if (
process.env.__NEXT_VARY_PARAMS &&
payloadStrategy !== FetchStrategy.Full &&
segmentVaryParams !== null
) {
let varyParams = segmentVaryParams
if (payloadStrategy === FetchStrategy.RuntimeShell && varyParams.has('?')) {
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 '?' 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 '?' 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
// 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
......@@ -3530,7 +3482,7 @@ function writeSegmentDataIntoCache(
// the emitted stage. A shell payload's evidence would then be
// accurate, and this branch could be deleted.
varyParams = new Set(varyParams)
varyParams.delete('?')
varyParams.delete(SEARCH_PARAMS_VARY_ID)
}
fulfilledVaryPath = getFulfilledSegmentVaryPath(tree.varyPath, varyParams)
}
......@@ -3563,7 +3515,7 @@ function writeSegmentDataIntoCache(
const isOwned =
ownedEntry !== undefined && ownedEntry.status === EntryStatus.Pending
let fulfilledEntry: FulfilledSegmentCacheEntry
let insertVaryPath: SegmentVaryPath | null
let insertVaryPath: VaryPath | null
if (isOwned) {
// We own this entry — fulfill it directly.
fulfilledEntry = fulfillSegmentCacheEntry(
......
......@@ -45,18 +45,12 @@ import {
} from '../../route-params'
import type { NormalizedSearch } from './cache-key'
import { splitPathnameIntoParts } from './cache-key'
import type {
PageVaryPath,
PartialSegmentVaryPath,
SegmentVaryPath,
} from './vary-path'
import type { PartialVaryPath, VaryPath } from './vary-path'
import {
appendLayoutVaryPath,
finalizeLayoutVaryPath,
finalizeMetadataVaryPath,
finalizePageVaryPath,
getPartialLayoutVaryPath,
getPartialPageVaryPath,
finalizeVaryPath,
getPartialVaryPath,
getShellSegmentVaryPath,
} from './vary-path'
import {
......@@ -72,7 +66,7 @@ import { computeDynamicStaleAt } from './bfcache'
export type NavigationSeed = {
renderedSearch: string
routeTree: RouteTree<RSCSegmentData | null>
metadataVaryPath: PageVaryPath | null
metadataVaryPath: VaryPath | null
head: HeadData | null
isHeadPartial: boolean
/**
......@@ -233,7 +227,7 @@ export function createNavigationSeed(
/**
* Creates a RouteTree node for a segment, with its identity and cache-key
* information (vary paths, page-ness, the normalized segment value)
* information (vary paths, the normalized segment value)
* initialized, and the remaining fields set to their defaults. The caller
* finishes initializing those in place after recursing into the children.
* Shared by the FlightRouterState converter and the transport decoder so the
......@@ -244,16 +238,14 @@ export function createRouteTreeNode<TData>(
originalSegment: FlightRouterStateSegment,
isRootParam: boolean,
requestKey: SegmentRequestKey,
parentPartialVaryPath: PartialSegmentVaryPath | null,
parentPartialVaryPath: PartialVaryPath | null,
renderedSearch: NormalizedSearch,
acc: RouteTreeAccumulator
): RouteTree<TData | null> {
let segment: FlightRouterStateSegment
let partialVaryPath: PartialSegmentVaryPath | null
let isPage: boolean
let varyPath: SegmentVaryPath
let partialVaryPath: PartialVaryPath | null
let varyPath: VaryPath
if (Array.isArray(originalSegment)) {
isPage = false
const paramCacheKey = originalSegment[1]
const paramName = originalSegment[0]
partialVaryPath = appendLayoutVaryPath(
......@@ -262,7 +254,7 @@ export function createRouteTreeNode<TData>(
paramName,
isRootParam
)
varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)
varyPath = finalizeVaryPath(requestKey, null, partialVaryPath)
segment = originalSegment
} else {
// This segment does not have a param. Inherit the partial vary path of
......@@ -270,7 +262,6 @@ export function createRouteTreeNode<TData>(
partialVaryPath = parentPartialVaryPath
if (requestKey.endsWith(PAGE_SEGMENT_KEY)) {
// This is a page segment.
isPage = true
// The navigation implementation expects the search params to be included
// in the segment. However, in the case of a static response, the search
......@@ -282,11 +273,7 @@ export function createRouteTreeNode<TData>(
// TODO: We should move search params out of FlightRouterState and handle
// them entirely on the client, similar to our plan for dynamic params.
segment = PAGE_SEGMENT_KEY
varyPath = finalizePageVaryPath(
requestKey,
renderedSearch,
partialVaryPath
)
varyPath = finalizeVaryPath(requestKey, renderedSearch, partialVaryPath)
// The metadata "segment" is not part the route tree, but it has the same
// conceptual params as a page segment. Write the vary path into the
// accumulator object. If there are multiple parallel pages, we use the
......@@ -302,9 +289,8 @@ export function createRouteTreeNode<TData>(
}
} else {
// This is a layout segment.
isPage = false
segment = originalSegment
varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)
varyPath = finalizeVaryPath(requestKey, null, partialVaryPath)
}
}
return {
......@@ -313,11 +299,7 @@ export function createRouteTreeNode<TData>(
shellVaryPath: getShellSegmentVaryPath(varyPath),
refreshState: null,
data: null,
// TODO: Cheating the type system here a bit because TypeScript can't tell
// that the type of isPage and varyPath are consistent. If isPage were
// wrong it would break the behavior and we'd catch it quickly.
varyPath: varyPath as any,
isPage: isPage as boolean as any,
varyPath,
slots: null,
prefetchHints: 0,
}
......@@ -446,7 +428,7 @@ function decodeTransportNode(
rootVaryParams: VaryParamsIterable | null,
isResponsePartial: boolean,
requestKey: SegmentRequestKey,
parentPartialVaryPath: PartialSegmentVaryPath | null,
parentPartialVaryPath: PartialVaryPath | null,
parentRenderedSearch: NormalizedSearch,
pathnameParts: Array<string> | null,
// The URL position this node's children read from.
......@@ -517,9 +499,7 @@ function decodeTransportNode(
acc
)
tree.refreshState = refreshState
const partialVaryPath = tree.isPage
? getPartialPageVaryPath(tree.varyPath)
: getPartialLayoutVaryPath(tree.varyPath)
const partialVaryPath = getPartialVaryPath(tree.varyPath)
let slots: Map<string, RouteTree<RSCSegmentData | null>> | null = null
const transportChildren = node.c
......
......@@ -45,6 +45,7 @@
import type { DynamicParamTypesShort } from '../../../shared/lib/app-router-types'
import { PrefetchHint } from '../../../shared/lib/app-router-types'
import { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'
import type {
RouteTree,
RSCSegmentData,
......@@ -67,12 +68,11 @@ import type { NormalizedPathname, NormalizedSearch } from './cache-key'
import { splitPathnameIntoParts } from './cache-key'
import {
appendLayoutVaryPath,
finalizeLayoutVaryPath,
finalizePageVaryPath,
finalizeMetadataVaryPath,
finalizeVaryPath,
getShellSegmentVaryPath,
type PartialSegmentVaryPath,
type PageVaryPath,
type PartialVaryPath,
type VaryPath,
} from './vary-path'
/**
......@@ -239,7 +239,7 @@ export function discoverKnownRoute(
nextUrl: string | null,
pendingEntry: PendingRouteCacheEntry | null,
routeTree: RouteTree<RSCSegmentData | null>,
metadataVaryPath: PageVaryPath,
metadataVaryPath: VaryPath,
couldBeIntercepted: boolean,
canonicalUrl: string,
supportsPerSegmentPrefetching: boolean,
......@@ -317,7 +317,7 @@ function handleMismatchDueToRewrite(
search: NormalizedSearch,
nextUrl: string | null,
fullTree: RouteTree<RSCSegmentData | null>,
metadataVaryPath: PageVaryPath,
metadataVaryPath: VaryPath,
couldBeIntercepted: boolean,
canonicalUrl: string,
supportsPerSegmentPrefetching: boolean
......@@ -389,7 +389,7 @@ function discoverKnownRoutePart(
search: NormalizedSearch,
nextUrl: string | null,
fullTree: RouteTree<RSCSegmentData | null>,
metadataVaryPath: PageVaryPath,
metadataVaryPath: VaryPath,
couldBeIntercepted: boolean,
canonicalUrl: string,
supportsPerSegmentPrefetching: boolean,
......@@ -1010,7 +1010,7 @@ function matchKnownRoutePart(
* (parallel routes may have multiple pages, but metadata uses the first).
*/
type ReifyAccumulator = {
metadataVaryPath: PageVaryPath | null
metadataVaryPath: VaryPath | null
}
/**
......@@ -1028,7 +1028,7 @@ function reifyRouteTree(
pattern: RouteTree<null>,
resolvedParams: ResolvedParams,
search: NormalizedSearch,
parentPartialVaryPath: PartialSegmentVaryPath | null,
parentPartialVaryPath: PartialVaryPath | null,
acc: ReifyAccumulator
): RouteTree<null> {
const originalSegment = pattern.segment
......@@ -1039,7 +1039,7 @@ function reifyRouteTree(
(pattern.prefetchHints & PrefetchHint.IsRootLayoutOrAbove) !== 0
let newSegment = originalSegment
let partialVaryPath: PartialSegmentVaryPath | null
let partialVaryPath: PartialVaryPath | null
if (typeof originalSegment !== 'string') {
// Dynamic segment: compute new cache key and append to partial vary path
......@@ -1087,13 +1087,10 @@ function reifyRouteTree(
}
}
if (pattern.isPage) {
let newVaryPath: VaryPath
if (originalSegment === PAGE_SEGMENT_KEY) {
// Page segment: finalize with search params
const newVaryPath = finalizePageVaryPath(
pattern.requestKey,
search,
partialVaryPath
)
newVaryPath = finalizeVaryPath(pattern.requestKey, search, partialVaryPath)
// Collect metadata vary path (first page wins, same as original algorithm)
if (acc.metadataVaryPath === null) {
acc.metadataVaryPath = finalizeMetadataVaryPath(
......@@ -1102,36 +1099,21 @@ function reifyRouteTree(
partialVaryPath
)
}
return {
requestKey: pattern.requestKey,
segment: newSegment,
shellVaryPath: getShellSegmentVaryPath(newVaryPath),
refreshState: pattern.refreshState,
// Route cache patterns never carry seed data (see
// stripDataFromRouteTree), so neither do trees reified from them.
data: null,
varyPath: newVaryPath,
isPage: true,
slots: newSlots,
prefetchHints: pattern.prefetchHints,
}
} else {
// Layout segment: finalize without search params
const newVaryPath = finalizeLayoutVaryPath(
pattern.requestKey,
partialVaryPath
)
return {
requestKey: pattern.requestKey,
segment: newSegment,
shellVaryPath: getShellSegmentVaryPath(newVaryPath),
refreshState: pattern.refreshState,
data: null,
varyPath: newVaryPath,
isPage: false,
slots: newSlots,
prefetchHints: pattern.prefetchHints,
}
newVaryPath = finalizeVaryPath(pattern.requestKey, null, partialVaryPath)
}
return {
requestKey: pattern.requestKey,
segment: newSegment,
shellVaryPath: getShellSegmentVaryPath(newVaryPath),
refreshState: pattern.refreshState,
// Route cache patterns never carry seed data (see
// stripDataFromRouteTree), so neither do trees reified from them.
data: null,
varyPath: newVaryPath,
slots: newSlots,
prefetchHints: pattern.prefetchHints,
}
}
......
......@@ -6,7 +6,14 @@ import type {
} from './cache-key'
import type { RouteTree, RSCSegmentData } from './cache'
import { Fallback, type FallbackType } from './cache-map'
import { HEAD_REQUEST_KEY } from '../../../shared/lib/segment-cache/segment-value-encoding'
import {
HEAD_REQUEST_KEY,
type SegmentRequestKey,
} from '../../../shared/lib/segment-cache/segment-value-encoding'
import {
SEARCH_PARAMS_VARY_ID,
type VaryParamId,
} from '../../../shared/lib/segment-cache/vary-params-decoding'
type Opaque<T, K> = T & { __brand: K }
......@@ -25,17 +32,17 @@ type Opaque<T, K> = T & { __brand: K }
* A route's vary path is simpler: it's comprised of the pathname, search
* string, and Next-URL header.
*/
export type VaryPath = {
export type VaryPathNode = {
/**
* Identifies which param this vary path node corresponds to. Used by
* getFulfilledSegmentVaryPath to determine which params to replace with
* Fallback based on the varyParams set from the server.
*
* - For path params: the param name (e.g., 'slug')
* - For search params: '?'
* - For search params: SEARCH_PARAMS_VARY_ID
* - For non-param nodes (request keys, etc.): null
*/
id: string | null
id: VaryParamId | null
value: string | null | FallbackType
/**
* Whether this node corresponds to a root param — a path param at or above
......@@ -44,11 +51,11 @@ export type VaryPath = {
* Fallback. See getShellSegmentVaryPath. Only ever true on path param nodes;
* false for structural and search param nodes.
*
* Always a boolean (never undefined) so that every VaryPath node shares a
* Always a boolean (never undefined) so that every VaryPathNode shares a
* single hidden class, keeping the cache hot paths monomorphic.
*/
isRootParam: boolean
parent: VaryPath | null
parent: VaryPathNode | null
}
// Because it's so important for vary paths to line up across cache accesses,
......@@ -62,7 +69,7 @@ export type RouteVaryPath = Opaque<
value: NormalizedPathname
isRootParam: false
parent: {
id: '?'
id: typeof SEARCH_PARAMS_VARY_ID
value: NormalizedSearch
isRootParam: false
parent: {
......@@ -76,38 +83,25 @@ export type RouteVaryPath = Opaque<
'RouteVaryPath'
>
// requestKey -> pathParams
export type LayoutVaryPath = Opaque<
// requestKey -> [searchParams] -> pathParams
//
// The first entry is the request key (id: null). It is followed by the search
// params entry (id: SEARCH_PARAMS_VARY_ID) when the segment varies on search
// params, and then by the path params (id: param name), one entry per param,
// nearest first.
export type VaryPath = Opaque<
{
id: null
value: string
value: SegmentRequestKey
isRootParam: false
parent: PartialSegmentVaryPath | null
parent: VaryPathNode | null
},
'LayoutVaryPath'
'VaryPath'
>
// requestKey -> searchParams -> pathParams
export type PageVaryPath = Opaque<
{
id: null
value: string
isRootParam: false
parent: {
id: '?'
value: NormalizedSearch | FallbackType
isRootParam: false
parent: PartialSegmentVaryPath | null
}
},
'PageVaryPath'
>
export type SegmentVaryPath = LayoutVaryPath | PageVaryPath
// Intermediate type used when building a vary path during a recursive traversal
// of the route tree.
export type PartialSegmentVaryPath = Opaque<VaryPath, 'PartialSegmentVaryPath'>
export type PartialVaryPath = Opaque<VaryPathNode, 'PartialVaryPath'>
export function getRouteVaryPath(
pathname: NormalizedPathname,
......@@ -115,12 +109,12 @@ export function getRouteVaryPath(
nextUrl: NormalizedNextUrl | null
): RouteVaryPath {
// requestKey -> searchParams -> nextUrl
const varyPath: VaryPath = {
const varyPath: VaryPathNode = {
id: null,
value: pathname,
isRootParam: false,
parent: {
id: '?',
id: SEARCH_PARAMS_VARY_ID,
value: search,
isRootParam: false,
parent: {
......@@ -143,12 +137,12 @@ export function getFulfilledRouteVaryPath(
// This is called when a route's data is fulfilled. The cache entry will be
// re-keyed based on which inputs the response varies by.
// requestKey -> searchParams -> nextUrl
const varyPath: VaryPath = {
const varyPath: VaryPathNode = {
id: null,
value: pathname,
isRootParam: false,
parent: {
id: '?',
id: SEARCH_PARAMS_VARY_ID,
value: search,
isRootParam: false,
parent: {
......@@ -163,73 +157,64 @@ export function getFulfilledRouteVaryPath(
}
export function appendLayoutVaryPath(
parentPath: PartialSegmentVaryPath | null,
parentPath: PartialVaryPath | null,
cacheKey: string,
paramName: string,
isRootParam: boolean
): PartialSegmentVaryPath {
const varyPathPart: VaryPath = {
): PartialVaryPath {
const varyPathPart: VaryPathNode = {
id: paramName,
value: cacheKey,
isRootParam,
parent: parentPath,
}
return varyPathPart as PartialSegmentVaryPath
return varyPathPart as PartialVaryPath
}
export function finalizeLayoutVaryPath(
requestKey: string,
varyPath: PartialSegmentVaryPath | null
): LayoutVaryPath {
const layoutVaryPath: VaryPath = {
id: null,
value: requestKey,
isRootParam: false,
parent: varyPath,
export function finalizeVaryPath(
requestKey: SegmentRequestKey,
// Non-null when the segment varies on search params: the search entry is
// spliced in between the request key and the path params. Fallback keys an
// entry that is reusable across all search strings.
searchParams: NormalizedSearch | FallbackType | null,
partialVaryPath: PartialVaryPath | null
): VaryPath {
// requestKey -> [searchParams] -> pathParams
let parent: VaryPathNode | null = partialVaryPath
if (searchParams !== null) {
parent = {
id: SEARCH_PARAMS_VARY_ID,
value: searchParams,
isRootParam: false,
parent: partialVaryPath,
}
}
return layoutVaryPath as LayoutVaryPath
}
export function getPartialLayoutVaryPath(
finalizedVaryPath: LayoutVaryPath
): PartialSegmentVaryPath | null {
// This is the inverse of finalizeLayoutVaryPath.
return finalizedVaryPath.parent
}
export function finalizePageVaryPath(
requestKey: string,
renderedSearch: NormalizedSearch,
varyPath: PartialSegmentVaryPath | null
): PageVaryPath {
// Unlike layouts, a page segment's vary path also includes the search string.
// requestKey -> searchParams -> pathParams
const pageVaryPath: VaryPath = {
const varyPath: VaryPathNode = {
id: null,
value: requestKey,
isRootParam: false,
parent: {
id: '?',
value: renderedSearch,
isRootParam: false,
parent: varyPath,
},
parent,
}
return pageVaryPath as PageVaryPath
return varyPath as VaryPath
}
export function getPartialPageVaryPath(
finalizedVaryPath: PageVaryPath
): PartialSegmentVaryPath | null {
// This is the inverse of finalizePageVaryPath.
return finalizedVaryPath.parent.parent
export function getPartialVaryPath(
finalizedVaryPath: VaryPath
): PartialVaryPath | null {
// This is the inverse of finalizeVaryPath: strip the request key, and the
// search params entry if there is one.
const parent = finalizedVaryPath.parent
if (parent !== null && parent.id === SEARCH_PARAMS_VARY_ID) {
return parent.parent as PartialVaryPath | null
}
return parent as PartialVaryPath | null
}
export function finalizeMetadataVaryPath(
pageRequestKey: string,
pageRequestKey: SegmentRequestKey,
renderedSearch: NormalizedSearch,
varyPath: PartialSegmentVaryPath | null
): PageVaryPath {
varyPath: PartialVaryPath | null
): VaryPath {
// The metadata "segment" is not a real segment because it doesn't exist in
// the normal structure of the route tree, but in terms of caching, it
// behaves like a page segment because it varies by all the same params as
......@@ -255,27 +240,21 @@ export function finalizeMetadataVaryPath(
// This is fine because the only difference between request keys for
// different parallel pages are things like route groups and parallel
// route slots. As long as it's always the same one, it doesn't matter.
const pageVaryPath: VaryPath = {
id: null,
// Append the actual metadata request key to the page request key. Note
// that we're not using a separate vary path part; it's unnecessary because
// these are not conceptually separate inputs.
value: pageRequestKey + HEAD_REQUEST_KEY,
isRootParam: false,
parent: {
id: '?',
value: renderedSearch,
isRootParam: false,
parent: varyPath,
},
}
return pageVaryPath as PageVaryPath
//
// Append the actual metadata request key to the page request key. Note
// that we're not using a separate vary path part; it's unnecessary because
// these are not conceptually separate inputs.
return finalizeVaryPath(
(pageRequestKey + HEAD_REQUEST_KEY) as SegmentRequestKey,
renderedSearch,
varyPath
)
}
export function getSegmentVaryPathForRequest(
fetchStrategy: FetchStrategy,
tree: RouteTree<RSCSegmentData | null>
): SegmentVaryPath {
): VaryPath {
// This is used for storing pending requests in the cache. We want to choose
// the most generic vary path based on the strategy used to fetch it, i.e.
// static/PPR versus runtime prefetching, so that it can be reused as much
......@@ -313,10 +292,13 @@ export function getSegmentVaryPathForRequest(
return tree.shellVaryPath
}
// Only page segments (and the special "metadata" segment, which is treated
// like a page segment for the purposes of caching) may contain search
// params. There's no reason to include them in the vary path otherwise.
if (tree.isPage) {
// The vary path includes a search params entry only when the segment varies
// on search params.
const searchParamsVaryPath = originalVaryPath.parent
if (
searchParamsVaryPath !== null &&
searchParamsVaryPath.id === SEARCH_PARAMS_VARY_ID
) {
// Only a runtime prefetch will include search params in the vary path.
// Static prefetches never include search params, so they can be reused
// across all possible search param values.
......@@ -325,67 +307,71 @@ export function getSegmentVaryPathForRequest(
fetchStrategy === FetchStrategy.PPRRuntime
if (!doesVaryOnSearchParams) {
// The response from the the server will not vary on search params. Clone
// the end of the original vary path to replace the search params
// with Fallback.
// The response from the the server will not vary on search params.
// Rebuild the vary path with the search params replaced by Fallback.
//
// requestKey -> searchParams -> pathParams
// ^ This part gets replaced with Fallback
const searchParamsVaryPath = (originalVaryPath as PageVaryPath).parent
const pathParamsVaryPath = searchParamsVaryPath.parent
const patchedVaryPath: VaryPath = {
id: null,
value: originalVaryPath.value,
isRootParam: false,
parent: {
id: '?',
value: Fallback,
isRootParam: false,
parent: pathParamsVaryPath,
},
}
return patchedVaryPath as SegmentVaryPath
return finalizeVaryPath(
originalVaryPath.value,
Fallback,
getPartialVaryPath(originalVaryPath)
)
}
}
// The request does vary on search params. We don't need to modify anything.
return originalVaryPath as SegmentVaryPath
return originalVaryPath
}
export function clonePageVaryPathWithNewSearchParams(
originalVaryPath: PageVaryPath,
export function cloneVaryPathWithNewSearchParams(
originalVaryPath: VaryPath,
newSearch: NormalizedSearch
): PageVaryPath {
): VaryPath {
// requestKey -> searchParams -> pathParams
// ^ This part gets replaced with newSearch
const searchParamsVaryPath = originalVaryPath.parent
const clonedVaryPath: VaryPath = {
id: null,
value: originalVaryPath.value,
isRootParam: false,
parent: {
id: '?',
value: newSearch,
isRootParam: false,
parent: searchParamsVaryPath.parent,
},
if (
searchParamsVaryPath === null ||
searchParamsVaryPath.id !== SEARCH_PARAMS_VARY_ID
) {
// No search params entry; nothing to replace.
return originalVaryPath
}
return clonedVaryPath as PageVaryPath
return finalizeVaryPath(
originalVaryPath.value,
newSearch,
getPartialVaryPath(originalVaryPath)
)
}
/**
* Returns the rendered value of the vary path's search params entry when the
* vary path has one with a concrete value, null otherwise. Only a segment that
* varies on search params carries the entry; on every other vary path, and on
* one whose search params entry is Fallback, this is null.
*/
export function getRenderedSearchFromVaryPath(
varyPath: PageVaryPath
varyPath: VaryPath
): NormalizedSearch | null {
const searchParams = varyPath.parent.value
return typeof searchParams === 'string'
? (searchParams as NormalizedSearch)
: null
let node: VaryPathNode | null = varyPath
while (node !== null) {
if (node.id === SEARCH_PARAMS_VARY_ID) {
const search = node.value
if (typeof search === 'string') {
return search as NormalizedSearch
}
return null
}
node = node.parent
}
return null
}
export function getFulfilledSegmentVaryPath(
original: VaryPath,
varyParams: Set<string>
): SegmentVaryPath {
original: VaryPathNode,
varyParams: Set<VaryParamId>
): VaryPath {
// Re-keys a segment's vary path based on which params the segment actually
// depends on. Params that are NOT in the varyParams set are replaced with
// Fallback, allowing the cache entry to be reused across different values of
......@@ -394,7 +380,7 @@ export function getFulfilledSegmentVaryPath(
// This is called when a segment is fulfilled with data from the server. The
// varyParams set comes from the server and indicates which params were
// accessed during rendering.
const clone: VaryPath = {
const clone: VaryPathNode = {
id: original.id,
// If the id is null, this node is not a param (e.g., it's a request key).
// If the id is in the varyParams set, keep the original value.
......@@ -409,10 +395,10 @@ export function getFulfilledSegmentVaryPath(
? null
: getFulfilledSegmentVaryPath(original.parent, varyParams),
}
return clone as SegmentVaryPath
return clone as VaryPath
}
export function getShellSegmentVaryPath(original: VaryPath): SegmentVaryPath {
export function getShellSegmentVaryPath(original: VaryPathNode): VaryPath {
// Re-keys a segment's vary path to identify the "App Shell" entry for this
// segment position — a reusable loading state that can be served for any
// concrete navigation to this segment. The shell is rendered with params
......@@ -421,7 +407,7 @@ export function getShellSegmentVaryPath(original: VaryPath): SegmentVaryPath {
// them. Accordingly, we keep the concrete value of structural nodes (request
// keys, etc.) and root param nodes, and replace every other param node (non-
// root path params and search params) with Fallback.
const clone: VaryPath = {
const clone: VaryPathNode = {
id: original.id,
value:
original.id === null || original.isRootParam === true
......@@ -433,5 +419,5 @@ export function getShellSegmentVaryPath(original: VaryPath): SegmentVaryPath {
? null
: getShellSegmentVaryPath(original.parent),
}
return clone as SegmentVaryPath
return clone as VaryPath
}
......@@ -4,11 +4,15 @@ import {
getVaryParamsAccumulator,
workUnitAsyncStorage,
} from './work-unit-async-storage.external'
import {
SEARCH_PARAMS_VARY_ID,
type VaryParamId,
} from '../../shared/lib/segment-cache/vary-params-decoding'
/**
* Accumulates vary params for a single segment (or for metadata/rootParams).
*
* A VaryParamsAccumulator is an `AsyncIterable<string>` that can be serialized
* A VaryParamsAccumulator is an `AsyncIterable<VaryParamId>` that can be serialized
* by React Flight. As params are accessed during render, each newly-seen param
* name is `add`ed, which yields it into the Flight stream immediately. After
* rendering, call `close()` (via `finishAccumulatingVaryParams`) to end the
......@@ -29,28 +33,29 @@ import {
* only instance referenced by more than one segment, and it only ever yields
* "done", so concurrent iteration of it is safe.
*/
export class VaryParamsAccumulator implements AsyncIterable<string> {
private _resolve: ((result: IteratorResult<string>) => void) | null = null
export class VaryParamsAccumulator implements AsyncIterable<VaryParamId> {
private _resolve: ((result: IteratorResult<VaryParamId>) => void) | null =
null
private _done = false
private _buffer: string[] = []
private _buffer: VaryParamId[] = []
// The set of param names already yielded. Doubles as the dedupe guard so the
// same name is never emitted twice.
private _seen: Set<string> = new Set()
private _seen: Set<VaryParamId> = new Set()
/**
* Records that a param was accessed. Yields the name into the stream the
* first time it's seen; subsequent accesses of the same name are no-ops.
*/
add(paramName: string): void {
if (this._done || this._seen.has(paramName)) {
add(id: VaryParamId): void {
if (this._done || this._seen.has(id)) {
return
}
this._seen.add(paramName)
this._seen.add(id)
if (this._resolve !== null) {
this._resolve({ value: paramName, done: false })
this._resolve({ value: id, done: false })
this._resolve = null
} else {
this._buffer.push(paramName)
this._buffer.push(id)
}
}
......@@ -67,7 +72,7 @@ export class VaryParamsAccumulator implements AsyncIterable<string> {
}
}
[Symbol.asyncIterator](): AsyncIterator<string> {
[Symbol.asyncIterator](): AsyncIterator<VaryParamId> {
return {
next: () => {
if (this._buffer.length > 0) {
......@@ -76,7 +81,7 @@ export class VaryParamsAccumulator implements AsyncIterable<string> {
if (this._done) {
return Promise.resolve({ value: undefined, done: true })
}
return new Promise<IteratorResult<string>>((resolve) => {
return new Promise<IteratorResult<VaryParamId>>((resolve) => {
this._resolve = resolve
})
},
......@@ -182,9 +187,9 @@ export function getRootParamsVaryParamsAccumulator(): VaryParamsAccumulator | nu
*/
export function accumulateVaryParam(
accumulator: VaryParamsAccumulator,
paramName: string
id: VaryParamId
): void {
accumulator.add(paramName)
accumulator.add(id)
}
/**
......@@ -261,23 +266,23 @@ export function createVaryingSearchParams(
// checks, or enumeration — must register as varying. A Proxy is required
// (rather than per-property getters) so that enumeration of an empty
// searchParams object still triggers a vary. All accesses bucket into the
// single sentinel '?'; the segment is keyed by the whole query string.
// single search params id; the segment is keyed by the whole query string.
// TODO: Split into per-param tracking if the cache key evolves.
return new Proxy(originalSearchParamsObject, {
get(target, prop, receiver) {
if (typeof prop === 'string') {
accumulateVaryParam(accumulator, '?')
accumulateVaryParam(accumulator, SEARCH_PARAMS_VARY_ID)
}
return Reflect.get(target, prop, receiver)
},
has(target, prop) {
if (typeof prop === 'string') {
accumulateVaryParam(accumulator, '?')
accumulateVaryParam(accumulator, SEARCH_PARAMS_VARY_ID)
}
return Reflect.has(target, prop)
},
ownKeys(target) {
accumulateVaryParam(accumulator, '?')
accumulateVaryParam(accumulator, SEARCH_PARAMS_VARY_ID)
return Reflect.ownKeys(target)
},
})
......
......@@ -6,11 +6,25 @@
import { readFulfilledValue } from '../rsc-transport'
export type VaryParams = Set<string>
/**
* The vary path id for search params. Path params are identified by their
* name. Search params don't have a fixed set of names, so any access to them
* is reported under this one id, and the segment is keyed by the whole search
* string (see createVaryingSearchParams in app-render/vary-params.ts).
*
* It's a number so it can't collide with a param name. `app/[?]/page.tsx` is a
* valid route.
*/
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>
/**
* Vary params are serialized into the Flight stream as an
* `AsyncIterable<string>` that yields each accessed param name exactly once
* `AsyncIterable<VaryParamId>` that yields each accessed param id exactly once
* (the server dedupes before emitting). Because each access is flushed into the
* stream as it happens, there's no step at the end of the render that has to
* run for the client to read anything. If a prerender is aborted by sync I/O,
......@@ -23,7 +37,7 @@ export type VaryParams = Set<string>
* the render — folding them into every segment would otherwise require a merge
* once the whole render is complete.
*/
export type VaryParamsIterable = AsyncIterable<string>
export type VaryParamsIterable = AsyncIterable<VaryParamId>
/**
* Synchronously drains a vary params `AsyncIterable`, adding each yielded name
......
import { nextTestSetup, FileRef } from 'e2e-utils'
import { join } from 'path'
import { retry } from '../../../../lib/next-test-utils'
// `[?]` is a valid param name, so a vary path node whose id is `?` must not
// be taken for the search params entry. The `[?]` route is written at
// runtime rather than checked in: git refuses a path containing `?` on
// Windows, and webpack's `next build` rejects the emitted filename as a
// query string, so the fixture is turbopack-only.
// @force-gate turbopack && !deploy
describe('segment cache (param named "?")', () => {
const { next } = nextTestSetup({
files: {
'app/layout.tsx': new FileRef(join(__dirname, 'app/layout.tsx')),
'next.config.js': new FileRef(join(__dirname, 'next.config.js')),
'app/[?]/layout.tsx': `
export default function QuestionMarkLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<div>
<p>Layout under [?]</p>
{children}
</div>
)
}
`,
'app/[?]/page.tsx': `
import Link from 'next/link'
import { Suspense } from 'react'
async function Param({ params }: { params: Promise<{ '?': string }> }) {
const { '?': value } = await params
return <div id="question-mark-param">Param: {value}</div>
}
export default async function QuestionMarkPage({
params,
}: {
params: Promise<{ '?': string }>
}) {
return (
<>
<Suspense fallback="Loading...">
<Param params={params} />
</Suspense>
<Link id="link-param-a" href="/param-a">
param-a
</Link>
<Link id="link-param-b" href="/param-b">
param-b
</Link>
</>
)
}
`,
},
})
// The layout matters: the page's vary path derives from the layout's, which
// ends at the `?` param node.
it('keys segments under a param literally named "?" by its value', async () => {
const browser = await next.browser('/param-a')
expect(await browser.elementById('question-mark-param').text()).toBe(
'Param: param-a'
)
await browser.elementById('link-param-b').click()
await retry(async () => {
expect(await browser.elementById('question-mark-param').text()).toBe(
'Param: param-b'
)
expect(await browser.url()).toMatch(/\/param-b$/)
})
await browser.elementById('link-param-a').click()
await retry(async () => {
expect(await browser.elementById('question-mark-param').text()).toBe(
'Param: param-a'
)
})
})
})
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