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 {
......
...@@ -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,37 +1099,22 @@ function reifyRouteTree( ...@@ -1102,37 +1099,22 @@ 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 { return {
requestKey: pattern.requestKey, requestKey: pattern.requestKey,
segment: newSegment, segment: newSegment,
shellVaryPath: getShellSegmentVaryPath(newVaryPath), shellVaryPath: getShellSegmentVaryPath(newVaryPath),
refreshState: pattern.refreshState, refreshState: pattern.refreshState,
// Route cache patterns never carry seed data (see
// 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,
} }
}
} }
/** /**
......
...@@ -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