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