Unverified Commit aa8e252f authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Store the head as its own CacheNode (#98973)

Throughout most of the client router implementation, the head is treated
as if it belongs to the page segment. For example, CacheNode has
separate `rsc` and `headRsc` fields, and the page's CacheNode owns both.
This had led to a bunch of special cases related to the head.

The Segment Cache largely (though not entirely) avoids this by instead
modeling the head as a special kind of segment. It has its own vary
path, its own SegmentCacheEntry, etc. There are still a few places where
treatment of the head is special, because it doesn't exist inside the
normal route tree structure. But we treat it like segment wherever
possible.

This PR updates the navigation implementation to use the same model:
treat the head as a segment that is a sibling to the route segment tree.

This is a large diff but the changes are almost entirely mechanical.
Although the added/removed balance is about even, that includes a new
test case. The net number of implementation lines has gone down.
parent 2f19ae8e
......@@ -299,7 +299,7 @@ function gesturePush(href: string, options?: NavigateOptions): void {
url,
currentUrl,
state.renderedSearch,
state.cache,
state.root,
state.tree,
state.nextUrl,
freshnessPolicy,
......
......@@ -16,6 +16,7 @@ import type {
AppRouterState,
} from './router-reducer/router-reducer-types'
import { createHrefFromUrl } from './router-reducer/create-href-from-url'
import { createHeadKey } from './router-reducer/create-segment-key'
import {
SearchParamsContext,
PathnameContext,
......@@ -27,7 +28,6 @@ import { useActionQueue } from './use-action-queue'
import { setLastCommittedTree } from './router-reducer/reducers/committed-state'
import { AppRouterAnnouncer } from './app-router-announcer'
import { RedirectBoundary } from './redirect-boundary'
import { findHeadInCache } from './router-reducer/reducers/find-head-in-cache'
import { unresolvedThenable } from './unresolved-thenable'
import { removeBasePath } from '../remove-base-path'
import { hasBasePath } from '../has-base-path'
......@@ -160,8 +160,8 @@ function HistoryUpdater({
// task. Re-prefetch all visible links with the updated values. In most
// cases, this will not result in any new network requests, only if
// the prefetch result actually varies on one of these inputs.
pingVisibleLinks(appRouterState.nextUrl, appRouterState.cache)
}, [appRouterState.nextUrl, appRouterState.cache])
pingVisibleLinks(appRouterState.nextUrl, appRouterState.root)
}, [appRouterState.nextUrl, appRouterState.root])
return null
}
......@@ -185,14 +185,13 @@ function copyNextJsInternalHistoryState(data: any) {
function Head({
headRenderTree,
}: {
headRenderTree: RouteTree<CacheNode> | null
headRenderTree: RouteTree<CacheNode>
}): React.ReactNode {
// If this segment has a `prefetchHead`, it's the statically prefetched data.
// We should use that on initial render instead of `head`. Then we'll switch
// to `head` when the dynamic response streams in.
const head = headRenderTree !== null ? headRenderTree.data.head : null
const prefetchHead =
headRenderTree !== null ? headRenderTree.data.prefetchHead : null
// If the head has a `prefetchRsc`, it's the statically prefetched data. We
// should use that on initial render instead of `rsc`. Then we'll switch to
// `rsc` when the dynamic response streams in.
const head = headRenderTree.data.rsc
const prefetchHead = headRenderTree.data.prefetchRsc
// If no prefetch data is available, then we go straight to rendering `head`.
const resolvedPrefetchRsc = prefetchHead !== null ? prefetchHead : head
......@@ -236,7 +235,7 @@ function Router({
}, [canonicalUrl])
if (process.env.NODE_ENV !== 'production') {
const { cache, tree } = state
const { root, tree } = state
// This hook is in a conditional but that is ok because `process.env.NODE_ENV` never changes
// eslint-disable-next-line react-hooks/rules-of-hooks
......@@ -246,10 +245,10 @@ function Router({
// @ts-ignore this is for debugging
window.nd = {
router: publicAppRouterInstance,
cache,
root,
tree,
}
}, [cache, tree])
}, [root, tree])
}
useEffect(() => {
......@@ -437,11 +436,7 @@ function Router({
}
}, [])
const { cache, tree, nextUrl, scrollRef, previousNextUrl } = state
const matchingHead = useMemo(() => {
return findHeadInCache(cache, tree[1])
}, [cache, tree])
const { root, tree, nextUrl, scrollRef, previousNextUrl } = state
// Add memoized pathParams for useParams.
const pathParams = useMemo(() => {
......@@ -467,7 +462,7 @@ function Router({
const layoutRouterContext = useMemo(() => {
return {
parentTree: tree,
parentRenderTree: cache,
parentRenderTree: root.tree,
parentSegmentPath: null,
parentParams: {},
parentLoadingData: null,
......@@ -480,7 +475,7 @@ function Router({
// Root segment is always active
isActive: true,
}
}, [tree, cache, canonicalUrl])
}, [tree, root, canonicalUrl])
const globalLayoutRouterContext = useMemo(() => {
return {
......@@ -491,20 +486,17 @@ function Router({
}
}, [tree, scrollRef, nextUrl, previousNextUrl])
let head
if (matchingHead !== null) {
// The head is wrapped in an extra component so we can use
// `useDeferredValue` to swap between the prefetched and final versions of
// the head. (This is what LayoutRouter does for segment data, too.)
//
// The `key` is used to remount the component whenever the head moves to
// a different segment.
const [headRenderTree, headKey] = matchingHead
head = <Head key={headKey} headRenderTree={headRenderTree} />
} else {
head = null
}
// The head is wrapped in an extra component so we can use
// `useDeferredValue` to swap between the prefetched and final versions of
// the head. (This is what LayoutRouter does for segment data, too.)
//
// The `key` is used to remount the component whenever the head moves to a
// different page, one of its path param values changes (the same inputs as
// LayoutRouter's keys), or its search params change. These are the entries
// of the head's vary path (see getHeadRequestKey).
const head = (
<Head key={createHeadKey(root.head.varyPath)} headRenderTree={root.head} />
)
let content = (
<RedirectBoundary>
......@@ -512,7 +504,7 @@ function Router({
{/* RootLayoutBoundary enables detection of Suspense boundaries around the root layout.
When users wrap their layout in <Suspense>, this creates the component stack pattern
"Suspense -> RootLayoutBoundary" which dynamic-rendering.ts uses to allow dynamic rendering. */}
<RootLayoutBoundary>{cache.data.rsc}</RootLayoutBoundary>
<RootLayoutBoundary>{root.tree.data.rsc}</RootLayoutBoundary>
<AppRouterAnnouncer tree={tree} />
</RedirectBoundary>
)
......
import type { RouteTree } from './segment-cache/cache'
import type { RootRouteTree } from './segment-cache/cache'
import type { CacheNode } from '../../shared/lib/app-router-types'
import type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime'
import {
......@@ -345,7 +345,7 @@ function rescheduleLinkPrefetch(
const cacheKey = createCacheKey(instance.prefetchHref, nextUrl)
instance.prefetchTask = scheduleSegmentPrefetchTask(
cacheKey,
appRouterState.cache,
appRouterState.root,
instance.fetchStrategy,
priority,
null,
......@@ -356,7 +356,7 @@ function rescheduleLinkPrefetch(
// effectively the same as canceling the old task and creating a new one.
reschedulePrefetchTask(
existingPrefetchTask,
appRouterState.cache,
appRouterState.root,
instance.fetchStrategy,
priority
)
......@@ -367,7 +367,7 @@ function rescheduleLinkPrefetch(
export function pingVisibleLinks(
nextUrl: string | null,
cache: RouteTree<CacheNode>
root: RootRouteTree<CacheNode>
) {
// For each currently visible link, cancel the existing prefetch task (if it
// exists) and schedule a new one. This is effectively the same as if all the
......@@ -378,7 +378,7 @@ export function pingVisibleLinks(
// cache invalidation.
for (const instance of prefetchableAndVisible) {
const task = instance.prefetchTask
if (task !== null && !isPrefetchTaskDirty(task, nextUrl, cache)) {
if (task !== null && !isPrefetchTaskDirty(task, nextUrl, root)) {
// The cache has not been invalidated, and none of the inputs have
// changed. Bail out.
continue
......@@ -391,7 +391,7 @@ export function pingVisibleLinks(
const cacheKey = createCacheKey(instance.prefetchHref, nextUrl)
instance.prefetchTask = scheduleSegmentPrefetchTask(
cacheKey,
cache,
root,
instance.fetchStrategy,
PrefetchPriority.Default,
null,
......
import type { RouteTree } from './segment-cache/cache'
import type { RootRouteTree } from './segment-cache/cache'
import type { CacheNode } from '../../shared/lib/app-router-types'
import type { PrefetchOptions } from '../../shared/lib/app-router-context.shared-runtime'
import { PrefetchKind } from './router-reducer/router-reducer-types'
......@@ -62,7 +62,7 @@ export function prefetchRoute(href: string, options?: PrefetchOptions): void {
prefetch(
href,
state.nextUrl,
state.cache,
state.root,
fetchStrategy,
options?.onInvalidate ?? null
)
......@@ -74,7 +74,8 @@ export function prefetchRoute(href: string, options?: PrefetchOptions): void {
* or router.prefetch. It must be validated before we attempt to prefetch it.
* @param nextUrl - A special header used by the server for interception routes.
* Roughly corresponds to the current URL.
* @param renderTreeAtTimeOfPrefetch - The active data and its vary paths.
* @param renderTreeAtTimeOfPrefetch - The active render tree and head, and
* their vary paths.
* @param fetchStrategy - Whether to prefetch dynamic data, in addition to
* static data. This is used by `<Link prefetch={true}>`.
* @param onInvalidate - A callback that will be called when the prefetch cache
......@@ -90,7 +91,7 @@ export function prefetchRoute(href: string, options?: PrefetchOptions): void {
export function prefetch(
href: string,
nextUrl: string | null,
renderTreeAtTimeOfPrefetch: RouteTree<CacheNode>,
renderTreeAtTimeOfPrefetch: RootRouteTree<CacheNode>,
fetchStrategy: PrefetchTaskFetchStrategy,
onInvalidate: null | (() => void)
) {
......
......@@ -10,12 +10,10 @@ import {
writeRuntimePrefetchStreamIntoCache,
spawnStaticStageCacheWrite,
segmentCacheMap,
createRootRouteTree,
} from '../segment-cache/cache'
import { decodeTransportTreeIntoRouteTree } from '../segment-cache/decode-server-response'
import {
UnknownDynamicStaleTime,
computeDynamicStaleAt,
} from '../segment-cache/bfcache'
import { createNavigationSeed } from '../segment-cache/decode-server-response'
import { UnknownDynamicStaleTime } from '../segment-cache/bfcache'
import { decodeStageUntilBoundary } from './fetch-server-response'
import { discoverKnownRoute } from '../segment-cache/optimistic-routes'
import type { NormalizedSearch } from '../segment-cache/cache-key'
......@@ -51,8 +49,6 @@ export function createInitialRouterState({
// as a URL that should be crawled.
const initialCanonicalUrl = initialCanonicalUrlParts.join('/')
const initialHead = initialTransportData.h.r
// The initial router state tree, derived from the transport tree. Page
// segments keep their search params, which travel inside the segment
// string.
......@@ -66,13 +62,10 @@ export function createInitialRouterState({
createHrefFromUrl(location)
: initialCanonicalUrl
// Decode the initial transport tree into the RouteTree type, with the
// payload's render output embedded on each node. (discoverKnownRoute below
// stores this tree in the route cache, which strips the data on write —
// see stripDataFromRouteTree.)
// NOTE: The metadataVaryPath isn't used for anything currently because the
// head is embedded into the render tree, but eventually we'll lift it out
// and store it on the top-level state object.
// Decode the initial transport data into the RouteTree type, with the
// payload's render output embedded on each node and the head as its own
// one-node tree. (discoverKnownRoute below stores the route tree in the
// route cache, which strips the data on write — see stripDataFromRouteTree.)
//
// For statically-generated-at-build-time HTML pages, the tree baked into
// the initial RSC payload won't have the correct segment inlining hints
......@@ -80,12 +73,12 @@ export function createInitialRouterState({
// trees with InliningHintsStale, which causes the route cache entry to be
// immediately expired. The next prefetch will re-fetch the tree with
// correct hints from the /_tree response.
const acc = { metadataVaryPath: null, treeDivergedFromBase: false }
const initialRouteTree = decodeTransportTreeIntoRouteTree(
initialTransportData.t,
const initialSeed = createNavigationSeed(
navigatedAt,
// There's no base tree to overlay onto; the initial payload is a full
// render from the root.
null,
initialTransportData,
// The initial payload may still be streaming in while we hydrate, so its
// vary params can't be drained here; they decode as null. The
// segment-cache write below re-decodes the transport data with the
......@@ -100,23 +93,20 @@ export function createInitialRouterState({
// see createInitialRSCPayloadFromFallbackPrerender), so there's no
// pathname to parse them from.
null,
initialRenderedSearch as NormalizedSearch,
acc
initialRenderedSearch,
null,
initialDynamicStaleTimeSeconds ?? UnknownDynamicStaleTime
)
const metadataVaryPath = acc.metadataVaryPath
const initialTask = createInitialRenderTreeForHydration(
const initialRoot = initialSeed.root
const initialNavigation = createInitialRenderTreeForHydration(
navigatedAt,
initialRouteTree,
initialHead,
computeDynamicStaleAt(
navigatedAt,
initialDynamicStaleTimeSeconds ?? UnknownDynamicStaleTime
)
initialRoot,
initialSeed.dynamicStaleAt
)
// The following only applies in the browser (location !== null) since neither
// route learning nor segment cache state persists from SSR to client.
if (location !== null && metadataVaryPath !== null) {
if (location !== null) {
// Learn the route pattern so we can predict it for future navigations.
discoverKnownRoute(
Date.now(),
......@@ -124,10 +114,10 @@ export function createInitialRouterState({
location.search as NormalizedSearch,
null, // nextUrl — initial render is never an interception
null, // No pending entry
initialRouteTree,
metadataVaryPath,
initialRoot,
initialCouldBeIntercepted,
canonicalUrl,
initialSeed.renderedSearch,
initialSupportsPerSegmentPrefetching,
false // hasDynamicRewrite
)
......@@ -245,8 +235,11 @@ export function createInitialRouterState({
// complete tree.)
const initialState = {
tree: initialTask.route,
cache: initialTask.node,
tree: initialNavigation.tree.route,
root: createRootRouteTree(
initialNavigation.tree.node,
initialNavigation.head.node
),
pushRef: {
pendingPush: false,
mpaNavigation: false,
......
import type { VaryPath, VaryPathNode } from '../segment-cache/vary-path'
// In the browser, React keys include concrete params so navigation preserves
// or resets component state according to the segment's actual identity.
export { createRouterCacheKey as createSegmentKey } from './create-router-cache-key'
// The head's key also includes the search params. Otherwise, inside a
// transition, `useDeferredValue` returns the new (still pending) head instead
// of the prefetched one, and the whole navigation suspends.
export function createHeadKey(varyPath: VaryPath): string {
// Encode the parts as a JSON array rather than joining them. A catch-all
// value and a search string can both contain `/`, so joined strings from
// different params could be the same.
const parts: Array<string> = [varyPath.value]
let params: VaryPathNode | null = varyPath.parent
while (params !== null) {
const value = params.value
if (typeof value === 'string') {
parts.push(value)
}
params = params.parent
}
return JSON.stringify(parts)
}
import type { Segment } from '../../../shared/lib/app-router-types'
import type { VaryPath } from '../segment-cache/vary-path'
import { createRouterCacheKey } from './create-router-cache-key'
// React uses these keys to find suspended subtrees when resuming HTML. They
......@@ -17,3 +18,13 @@ export function createSegmentKey(
return createRouterCacheKey(segment, true)
}
// TODO: To model this more accurately, we should use React.optimisticKey
// instead. Perhaps a separate Fragment that wraps around the Head:
// <Fragment key={headKey}> where headKey is React.optimisticKey during
// SSR. We should do this for all fallback param values.
export function createHeadKey(varyPath: VaryPath): string {
// The head's vary path starts with its request key: the route structure,
// with param names but no values.
return varyPath.value
}
import type { RouteTree } from '../../segment-cache/cache'
import type {
FlightRouterState,
CacheNode,
} from '../../../../shared/lib/app-router-types'
import { DEFAULT_SEGMENT_KEY } from '../../../../shared/lib/segment'
import { createSegmentKey } from '../create-segment-key'
export function findHeadInCache(
cache: RouteTree<CacheNode>,
parallelRoutes: FlightRouterState[1]
): [RouteTree<CacheNode>, string] | null {
return findHeadInCacheImpl(cache, parallelRoutes, '')
}
function findHeadInCacheImpl(
cache: RouteTree<CacheNode>,
parallelRoutes: FlightRouterState[1],
keyPrefix: string
): [RouteTree<CacheNode>, string] | null {
const isLastItem = Object.keys(parallelRoutes).length === 0
if (isLastItem) {
// Returns the render tree of the segment whose head we will render.
return [cache, keyPrefix]
}
// First try the 'children' parallel route if it exists
// when starting from the "root", this corresponds with the main page component
const parallelRoutesKeys = Object.keys(parallelRoutes).filter(
(key) => key !== 'children'
)
// if we are at the root, we need to check the children slot first
if ('children' in parallelRoutes) {
parallelRoutesKeys.unshift('children')
}
const slots = cache.slots
if (slots !== null) {
for (const key of parallelRoutesKeys) {
const [segment, childParallelRoutes] = parallelRoutes[key]
// If the parallel is not matched and using the default segment,
// skip searching the head from it.
if (segment === DEFAULT_SEGMENT_KEY) {
continue
}
const childRenderTree = slots.get(key)
if (!childRenderTree) {
continue
}
// This key identifies the Head component, not a cache entry. On the
// server it must match even when resuming with previously unknown params.
const segmentKey = createSegmentKey(segment)
const item = findHeadInCacheImpl(
childRenderTree,
childParallelRoutes,
keyPrefix + '/' + segmentKey
)
if (item) {
return item
}
}
}
return null
}
......@@ -46,7 +46,7 @@ export function navigateReducer(
url,
currentUrl,
currentRenderedSearch,
state.cache,
state.root,
state.tree,
state.nextUrl,
FreshnessPolicy.Default,
......
......@@ -33,8 +33,8 @@ export function refreshReducer(
process.env.__NEXT_EXPOSE_TESTING_API && action.bypassCacheInvalidation
if (!bypassCacheInvalidation) {
const currentNextUrl = state.nextUrl
const currentRenderTree = state.cache
invalidateSegmentCacheEntries(currentNextUrl, currentRenderTree)
const currentRoot = state.root
invalidateSegmentCacheEntries(currentNextUrl, currentRoot)
}
// A full refresh has no HMR generation to cancel.
return refreshDynamicData(state, FreshnessPolicy.RefreshAll, undefined)
......@@ -83,6 +83,7 @@ export function refreshDynamicData(
true,
null,
currentRenderedSearch,
null,
UnknownDynamicStaleTime
)
......@@ -99,7 +100,7 @@ export function refreshDynamicData(
refreshSeed,
currentUrl,
currentRenderedSearch,
state.cache,
state.root,
freshnessPolicy,
nextUrlForRefresh,
scrollBehavior,
......
......@@ -63,17 +63,16 @@ export function restoreReducer(
true,
null,
renderedSearch,
null,
UnknownDynamicStaleTime
)
const task = startPPRNavigation(
const navigation = startPPRNavigation(
now,
currentUrl,
state.renderedSearch,
state.cache,
restoreSeed.routeTree,
restoreSeed.metadataVaryPath,
state.root,
restoreSeed.root,
FreshnessPolicy.HistoryTraversal,
null,
restoreSeed.dynamicStaleAt,
false,
accumulation,
......@@ -83,11 +82,11 @@ export function restoreReducer(
false
)
if (task === null) {
if (navigation === null) {
return completeHardNavigation(state, restoredUrl, 'replace')
}
spawnDynamicRequests(
task,
navigation,
restoredUrl,
restoredNextUrl,
FreshnessPolicy.HistoryTraversal,
......@@ -117,8 +116,7 @@ export function restoreReducer(
state,
restoredUrl,
renderedSearch,
task.node,
task.route,
navigation,
restoredNextUrl
)
}
......@@ -365,7 +365,7 @@ export function serverActionReducer(
// invalidate both caches until we have a way to detect cookie
// mutations on the client.
if (revalidationKind === ActionDidRevalidateStaticAndDynamic) {
invalidateEntirePrefetchCache(nextUrl, state.cache)
invalidateEntirePrefetchCache(nextUrl, state.root)
}
// Start a cooldown before re-prefetching to allow CDN cache
......@@ -494,26 +494,24 @@ export function serverActionReducer(
// tree, so there's no pathname to parse them from (nor a need to).
null,
flightDataRenderedSearch,
null,
UnknownDynamicStaleTime
)
// Learn the route pattern so we can predict it for future navigations.
const metadataVaryPath = redirectSeed.metadataVaryPath
if (metadataVaryPath !== null) {
discoverKnownRoute(
now,
redirectUrl.pathname,
redirectUrl.search as NormalizedSearch,
nextUrl,
null, // No pending entry
redirectSeed.routeTree,
metadataVaryPath,
couldBeIntercepted,
redirectCanonicalUrl,
isPrerender,
false // hasDynamicRewrite
)
}
discoverKnownRoute(
now,
redirectUrl.pathname,
redirectUrl.search as NormalizedSearch,
nextUrl,
null, // No pending entry
redirectSeed.root,
couldBeIntercepted,
redirectCanonicalUrl,
redirectSeed.renderedSearch,
isPrerender,
false // hasDynamicRewrite
)
const navigationLock = getCurrentNavigationLock()
return navigateToKnownRoute(
......@@ -524,7 +522,7 @@ export function serverActionReducer(
redirectSeed,
currentUrl,
currentRenderedSearch,
state.cache,
state.root,
freshnessPolicy,
nextUrl,
scrollBehavior,
......@@ -550,7 +548,7 @@ export function serverActionReducer(
redirectUrl,
currentUrl,
currentRenderedSearch,
state.cache,
state.root,
currentFlightRouterState,
nextUrl,
freshnessPolicy,
......
......@@ -59,7 +59,7 @@ export function serverPatchReducer(
retrySeed,
currentUrl,
currentRenderedSearch,
state.cache,
state.root,
action.freshnessPolicy,
retryNextUrl,
scrollBehavior,
......
import type { RouteTree } from '../segment-cache/cache'
import type { RootRouteTree } from '../segment-cache/cache'
import type { CacheNode, ScrollRef } from '../../../shared/lib/app-router-types'
import type { FlightRouterState } from '../../../shared/lib/app-router-types'
import type { NavigationSeed } from '../segment-cache/decode-server-response'
......@@ -211,10 +211,15 @@ export type AppRouterState = {
*/
tree: FlightRouterState
/**
* The cache holds React nodes for every segment that is shown on screen as well as previously shown segments.
* It also holds in-progress data requests.
* The render tree and the document head (see RootRouteTree). The tree holds
* React nodes for every segment that is shown on screen as well as
* previously shown segments, and in-progress data requests. The head is a
* one-node render tree keyed at the metadata vary path.
*
* One object per committed navigation; the prefetch scheduler compares it by
* identity (see PrefetchTask.renderTreeAtTimeOfPrefetch).
*/
cache: RouteTree<CacheNode>
root: RootRouteTree<CacheNode>
/**
* Decides if the update should create a new history entry and if the navigation has to trigger a browser navigation.
*/
......
......@@ -34,8 +34,6 @@ import {
export type BFCacheEntry = {
rsc: React.ReactNode | null
prefetchRsc: React.ReactNode | null
head: React.ReactNode | null
prefetchHead: React.ReactNode | null
// The source of the params `rsc` depends on, copied from the CacheNode that
// wrote this entry (see CacheNode.varyParams). A restored node reads it to
......@@ -79,47 +77,18 @@ export function writeToBFCache(
varyPath: VaryPath,
cacheNode: CacheNode,
dynamicStaleAt: number
): void {
writeEntryToBFCache(
now,
varyPath,
cacheNode.rsc,
cacheNode.prefetchRsc,
cacheNode.varyParams,
cacheNode.head,
cacheNode.prefetchHead,
dynamicStaleAt,
cacheNode.bfcacheId
)
}
function writeEntryToBFCache(
now: number,
varyPath: VaryPath,
rsc: React.ReactNode,
prefetchRsc: React.ReactNode,
varyParams: VaryParams | null,
head: React.ReactNode,
prefetchHead: React.ReactNode,
dynamicStaleAt: number,
bfcacheId: number
): void {
if (typeof window === 'undefined') {
return
}
const entry: BFCacheEntry = {
rsc,
prefetchRsc,
// TODO: These fields will be removed from both BFCacheEntry and
// SegmentCacheEntry. The head has its own separate cache entry.
head,
prefetchHead,
rsc: cacheNode.rsc,
prefetchRsc: cacheNode.prefetchRsc,
varyParams,
varyParams: cacheNode.varyParams,
bfcacheId,
bfcacheId: cacheNode.bfcacheId,
ref: null,
// TODO: This is just a heuristic. Getting the actual size of the segment
......@@ -142,29 +111,6 @@ function writeEntryToBFCache(
setInCacheMap(bfcacheMap, varyPath, entry, isRevalidation)
}
export function writeHeadToBFCache(
now: number,
varyPath: VaryPath,
cacheNode: CacheNode,
dynamicStaleAt: number
): void {
// Write the special "segment" that represents the head data. The page
// node's head fields take the place of the entry's segment fields. The
// head's dependency source isn't tracked on the node, so the entry has
// none.
writeEntryToBFCache(
now,
varyPath,
cacheNode.head,
cacheNode.prefetchHead,
null,
null,
null,
dynamicStaleAt,
cacheNode.bfcacheId
)
}
/**
* Patches the entry written for a segment before its dynamic response
* arrived, with what the response filled in on the segment's CacheNode: the
......
......@@ -7,7 +7,6 @@
import type {
FlightRouterState,
HeadData,
Segment as FlightRouterStateSegment,
} from '../../../shared/lib/app-router-types'
import {
......@@ -21,10 +20,7 @@ import type {
TransportSegment,
} from '../../../shared/lib/rsc-transport'
import { readFulfilledValue } from '../../../shared/lib/rsc-transport'
import type {
VaryParams,
VaryParamsIterable,
} from '../../../shared/lib/segment-cache/vary-params-decoding'
import type { VaryParamsIterable } from '../../../shared/lib/segment-cache/vary-params-decoding'
import { decodeVaryParams } from '../../../shared/lib/segment-cache/vary-params-decoding'
import {
type SegmentRequestKey,
......@@ -48,39 +44,31 @@ import { splitPathnameIntoParts } from './cache-key'
import type { PartialVaryPath, VaryPath } from './vary-path'
import {
appendLayoutVaryPath,
finalizeMetadataVaryPath,
finalizeVaryPath,
getPartialVaryPath,
getShellSegmentVaryPath,
} from './vary-path'
import {
type RouteTree,
type RootRouteTree,
type RSCSegmentData,
type RefreshState,
type RouteTreeAccumulator,
convertFlightRouterStateToRouteTree,
convertRootFlightRouterStateToRouteTree,
createMetadataRouteTree,
createRootRouteTree,
getHeadRequestKey,
} from './cache'
import { computeDynamicStaleAt } from './bfcache'
export type NavigationSeed = {
renderedSearch: string
routeTree: RouteTree<RSCSegmentData | null>
metadataVaryPath: VaryPath | null
head: HeadData | null
isHeadPartial: boolean
/**
* The source of the params the head's output depends on (root params
* included). Null means unknown — tracking wasn't enabled, or the decode
* had no root params to union in — so consumers key on all params.
*/
headVaryParams: VaryParams | null
renderedSearch: NormalizedSearch
/**
* The head's own staleTime in seconds, when the response carries one
* (per-segment prefetch responses only — see TransportSegmentData['s']).
* Null means the response-level staleness governs the head.
* The decoded response. The head's `data` is decoded exactly like a segment
* node's: null when the response carries no head.
*/
headStaleTimeSeconds: number | null
root: RootRouteTree<RSCSegmentData | null>
dynamicStaleAt: number
// Whether the response rendered a segment whose identity differs from the
// base tree's at the same position (inactive parallel route branches are
......@@ -137,18 +125,23 @@ export function createNavigationSeed(
// decodeTransportTreeIntoRouteTree. Callers whose responses always carry
// concrete values (navigation responses) may pass null.
renderedPathname: string | null,
// Already normalized by the response reader (see getRenderedSearch); the
// router state stores it as a plain string, so it is re-branded here.
renderedSearch: string,
// Where to key the head. Null derives it from the route's own first page
// node (see createRouteTreeNode). Per-segment prefetch payloads pass the
// route's own metadata vary path instead: a standalone head response's tree
// is a bare root identity with no page node.
metadataVaryPath: VaryPath | null,
dynamicStaleTimeSeconds: number
): NavigationSeed {
const normalizedRenderedSearch = renderedSearch as NormalizedSearch
const acc: RouteTreeAccumulator = {
metadataVaryPath: null,
treeDivergedFromBase: false,
}
let routeTree: RouteTree<RSCSegmentData | null>
let head: HeadData | null = null
let isHeadPartial = true
let headVaryParams: VaryParams | null = null
let headStaleTimeSeconds: number | null = null
let headData: RSCSegmentData | null = null
if (transportData !== null) {
routeTree = decodeTransportTreeIntoRouteTree(
transportData.t,
......@@ -156,12 +149,11 @@ export function createNavigationSeed(
rootVaryParams,
isResponsePartial,
renderedPathname,
renderedSearch as NormalizedSearch,
normalizedRenderedSearch,
acc
)
const transportHead = transportData.h
if (transportHead !== undefined) {
head = transportHead.r
// The wire form of `p` determines which signal is authoritative for
// the head's partiality, mirroring the per-node rule in
// decodeTransportNode:
......@@ -183,17 +175,20 @@ export function createNavigationSeed(
// carries a complete head; a partial (postponed) one does not.
// Without Cache Components, the server sends the correct
// isHeadPartial, so the wire boolean is used as-is.
isHeadPartial =
typeof transportHead.p === 'boolean'
? process.env.__NEXT_CACHE_COMPONENTS
? isResponsePartial
: transportHead.p
: readFulfilledIsPartial(transportHead.p)
headVaryParams = decodeVaryParams(transportHead.v, rootVaryParams)
headStaleTimeSeconds =
transportHead.s !== undefined
? readFulfilledStaleTimeSeconds(transportHead.s)
: null
headData = {
rsc: transportHead.r,
isPartial:
typeof transportHead.p === 'boolean'
? process.env.__NEXT_CACHE_COMPONENTS
? isResponsePartial
: transportHead.p
: readFulfilledIsPartial(transportHead.p),
varyParams: decodeVaryParams(transportHead.v, rootVaryParams),
staleTimeSeconds:
transportHead.s !== undefined
? readFulfilledStaleTimeSeconds(transportHead.s)
: null,
}
}
} else {
if (currentTree === null) {
......@@ -204,19 +199,33 @@ export function createNavigationSeed(
}
routeTree = convertRootFlightRouterStateToRouteTree(
currentTree,
renderedSearch as NormalizedSearch,
normalizedRenderedSearch,
acc
)
}
if (metadataVaryPath === null) {
metadataVaryPath = acc.metadataVaryPath
if (metadataVaryPath === null) {
// Every route renders a page, so a rendered tree always has a node to
// key the head under.
throw new InvariantError(
'Cannot key the head of a server response: its tree has no page ' +
'segment.'
)
}
}
return {
routeTree,
metadataVaryPath: acc.metadataVaryPath,
renderedSearch,
head,
isHeadPartial,
headVaryParams,
headStaleTimeSeconds,
root: createRootRouteTree(
routeTree,
createMetadataRouteTree(
metadataVaryPath,
routeTree.prefetchHints,
headData
)
),
renderedSearch: normalizedRenderedSearch,
dynamicStaleAt: computeDynamicStaleAt(now, dynamicStaleTimeSeconds),
treeDivergedFromBase: acc.treeDivergedFromBase,
}
......@@ -224,7 +233,7 @@ export function createNavigationSeed(
/**
* Creates a RouteTree node for a segment, with its identity and cache-key
* information (vary paths, the normalized segment value)
* information (vary paths, the normalized segment value, the refresh state)
* initialized, and the remaining fields set to their defaults. The caller
* finishes initializing those in place after recursing into the children.
* Shared by FlightRouterState conversion, transport decoding, and subtree
......@@ -236,6 +245,7 @@ export function createRouteTreeNode<TData>(
requestKey: SegmentRequestKey,
parentPartialVaryPath: PartialVaryPath | null,
renderedSearch: NormalizedSearch,
refreshState: RefreshState | null,
acc: RouteTreeAccumulator
): RouteTree<TData | null> {
let segment: FlightRouterStateSegment
......@@ -270,15 +280,12 @@ export function createRouteTreeNode<TData>(
// them entirely on the client, similar to our plan for dynamic params.
segment = PAGE_SEGMENT_KEY
varyPath = finalizeVaryPath(requestKey, renderedSearch, partialVaryPath)
// The metadata "segment" is not part the route tree, but it has the same
// conceptual params as a page segment. Write the vary path into the
// accumulator object. If there are multiple parallel pages, we use the
// first one. Which page we choose is arbitrary as long as it's
// consistently the same one every time every time. See
// finalizeMetadataVaryPath for more details.
if (acc.metadataVaryPath === null) {
acc.metadataVaryPath = finalizeMetadataVaryPath(
requestKey,
// The head is keyed under the route's own first page and varies on the
// same params as that page (see getHeadRequestKey). A page reused from
// another URL carries a refresh state and never keys it.
if (refreshState === null && acc.metadataVaryPath === null) {
acc.metadataVaryPath = finalizeVaryPath(
getHeadRequestKey(requestKey),
renderedSearch,
partialVaryPath
)
......@@ -293,7 +300,7 @@ export function createRouteTreeNode<TData>(
requestKey,
segment,
shellVaryPath: getShellSegmentVaryPath(varyPath),
refreshState: null,
refreshState,
data: null,
varyPath,
slots: null,
......@@ -492,9 +499,9 @@ function decodeTransportNode(
requestKey,
parentPartialVaryPath,
renderedSearch,
refreshState,
acc
)
tree.refreshState = refreshState
const partialVaryPath = getPartialVaryPath(tree.varyPath)
let slots: Map<string, RouteTree<RSCSegmentData | null>> | null = null
......
......@@ -48,6 +48,7 @@ import { PrefetchHint } from '../../../shared/lib/app-router-types'
import { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'
import type {
RouteTree,
RootRouteTree,
RSCSegmentData,
FulfilledRouteCacheEntry,
} from './cache'
......@@ -58,6 +59,8 @@ import {
getCurrentRouteCacheVersion,
type PendingRouteCacheEntry,
createMetadataRouteTree,
createRootRouteTree,
getHeadRequestKey,
} from './cache'
import { isValueExpired } from './cache-map'
import {
......@@ -68,7 +71,6 @@ import type { NormalizedPathname, NormalizedSearch } from './cache-key'
import { splitPathnameIntoParts } from './cache-key'
import {
appendLayoutVaryPath,
finalizeMetadataVaryPath,
finalizeVaryPath,
getShellSegmentVaryPath,
type PartialVaryPath,
......@@ -238,14 +240,14 @@ export function discoverKnownRoute(
search: NormalizedSearch,
nextUrl: string | null,
pendingEntry: PendingRouteCacheEntry | null,
routeTree: RouteTree<RSCSegmentData | null>,
metadataVaryPath: VaryPath,
root: RootRouteTree<RSCSegmentData | null>,
couldBeIntercepted: boolean,
canonicalUrl: string,
renderedSearch: NormalizedSearch,
supportsPerSegmentPrefetching: boolean,
hasDynamicRewrite: boolean
): FulfilledRouteCacheEntry {
const tree = routeTree
const tree = root.tree
const pathnameParts = splitPathnameIntoParts(pathname)
......@@ -254,10 +256,10 @@ export function discoverKnownRoute(
const fulfilledEntry = fulfillRouteCacheEntry(
now,
pendingEntry,
tree,
metadataVaryPath,
root,
couldBeIntercepted,
canonicalUrl,
renderedSearch,
supportsPerSegmentPrefetching
)
// Populate the known route tree (handles rewrite detection internally).
......@@ -273,10 +275,10 @@ export function discoverKnownRoute(
pathname,
search,
nextUrl,
tree,
metadataVaryPath,
root,
couldBeIntercepted,
canonicalUrl,
renderedSearch,
supportsPerSegmentPrefetching,
hasDynamicRewrite
)
......@@ -295,10 +297,10 @@ export function discoverKnownRoute(
pathname,
search,
nextUrl,
tree,
metadataVaryPath,
root,
couldBeIntercepted,
canonicalUrl,
renderedSearch,
supportsPerSegmentPrefetching,
hasDynamicRewrite
)
......@@ -316,10 +318,10 @@ function handleMismatchDueToRewrite(
pathname: string,
search: NormalizedSearch,
nextUrl: string | null,
fullTree: RouteTree<RSCSegmentData | null>,
metadataVaryPath: VaryPath,
root: RootRouteTree<RSCSegmentData | null>,
couldBeIntercepted: boolean,
canonicalUrl: string,
renderedSearch: NormalizedSearch,
supportsPerSegmentPrefetching: boolean
): FulfilledRouteCacheEntry {
if (existingEntry !== null) {
......@@ -330,10 +332,10 @@ function handleMismatchDueToRewrite(
pathname as NormalizedPathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
root,
couldBeIntercepted,
canonicalUrl,
renderedSearch,
supportsPerSegmentPrefetching
)
}
......@@ -388,10 +390,10 @@ function discoverKnownRoutePart(
pathname: string,
search: NormalizedSearch,
nextUrl: string | null,
fullTree: RouteTree<RSCSegmentData | null>,
metadataVaryPath: VaryPath,
root: RootRouteTree<RSCSegmentData | null>,
couldBeIntercepted: boolean,
canonicalUrl: string,
renderedSearch: NormalizedSearch,
supportsPerSegmentPrefetching: boolean,
hasDynamicRewrite: boolean
): FulfilledRouteCacheEntry {
......@@ -415,10 +417,10 @@ function discoverKnownRoutePart(
pathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
root,
couldBeIntercepted,
canonicalUrl,
renderedSearch,
supportsPerSegmentPrefetching
)
}
......@@ -456,10 +458,10 @@ function discoverKnownRoutePart(
pathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
root,
couldBeIntercepted,
canonicalUrl,
renderedSearch,
supportsPerSegmentPrefetching
)
}
......@@ -477,10 +479,10 @@ function discoverKnownRoutePart(
pathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
root,
couldBeIntercepted,
canonicalUrl,
renderedSearch,
supportsPerSegmentPrefetching
)
}
......@@ -506,10 +508,10 @@ function discoverKnownRoutePart(
pathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
root,
couldBeIntercepted,
canonicalUrl,
renderedSearch,
supportsPerSegmentPrefetching
)
}
......@@ -532,10 +534,10 @@ function discoverKnownRoutePart(
pathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
root,
couldBeIntercepted,
canonicalUrl,
renderedSearch,
supportsPerSegmentPrefetching
)
}
......@@ -573,10 +575,10 @@ function discoverKnownRoutePart(
pathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
root,
couldBeIntercepted,
canonicalUrl,
renderedSearch,
supportsPerSegmentPrefetching
)
}
......@@ -640,10 +642,10 @@ function discoverKnownRoutePart(
pathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
root,
couldBeIntercepted,
canonicalUrl,
renderedSearch,
supportsPerSegmentPrefetching,
hasDynamicRewrite
)
......@@ -662,10 +664,10 @@ function discoverKnownRoutePart(
pathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
root,
couldBeIntercepted,
canonicalUrl,
renderedSearch,
supportsPerSegmentPrefetching
)
}
......@@ -680,10 +682,10 @@ function discoverKnownRoutePart(
pathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
root,
couldBeIntercepted,
canonicalUrl,
renderedSearch,
supportsPerSegmentPrefetching
)
}
......@@ -713,10 +715,10 @@ function discoverKnownRoutePart(
pathname as NormalizedPathname,
search,
nextUrl,
fullTree,
metadataVaryPath,
root,
couldBeIntercepted,
canonicalUrl,
renderedSearch,
supportsPerSegmentPrefetching
)
}
......@@ -774,7 +776,7 @@ export function matchKnownRoute(
// components read them. Resolve the target URL on the server instead of
// combining a predicted tree with UI cached for an allowed parameter value.
if (
pattern.tree.prefetchHints &
pattern.root.tree.prefetchHints &
(PrefetchHint.IsClosedParam | PrefetchHint.SubtreeHasClosedParams)
) {
return null
......@@ -785,7 +787,7 @@ export function matchKnownRoute(
// segments and recomputes vary paths for correct segment cache keying.
const acc: ReifyAccumulator = { metadataVaryPath: null }
const reifiedTree = reifyRouteTree(
pattern.tree,
pattern.root.tree,
resolvedParams,
search,
null, // Start with null partial vary path at the root
......@@ -802,7 +804,8 @@ export function matchKnownRoute(
}
const reifiedMetadata = createMetadataRouteTree(
metadataVaryPath,
reifiedTree.prefetchHints
reifiedTree.prefetchHints,
null
)
// Create a synthetic (predicted) entry. It's not inserted into the route
......@@ -815,8 +818,7 @@ export function matchKnownRoute(
canonicalUrl: pathname + search,
status: EntryStatus.Fulfilled,
blockedTasks: null,
tree: reifiedTree,
metadata: reifiedMetadata,
root: createRootRouteTree(reifiedTree, reifiedMetadata),
couldBeIntercepted: pattern.couldBeIntercepted,
supportsPerSegmentPrefetching: pattern.supportsPerSegmentPrefetching,
predictedFrom: matchedPart,
......@@ -1091,10 +1093,10 @@ function reifyRouteTree(
if (originalSegment === PAGE_SEGMENT_KEY) {
// Page segment: finalize with search params
newVaryPath = finalizeVaryPath(pattern.requestKey, search, partialVaryPath)
// Collect metadata vary path (first page wins, same as original algorithm)
// Collect metadata vary path (first page wins; see getHeadRequestKey)
if (acc.metadataVaryPath === null) {
acc.metadataVaryPath = finalizeMetadataVaryPath(
pattern.requestKey,
acc.metadataVaryPath = finalizeVaryPath(
getHeadRequestKey(pattern.requestKey),
search,
partialVaryPath
)
......
......@@ -18,6 +18,7 @@ import {
type FulfilledRouteCacheEntry,
type RouteCacheEntry,
type RouteTree,
type RootRouteTree,
fetchSegmentPrefetchesUsingRuntimeRequest,
type PendingSegmentCacheEntry,
type SegmentCacheEntry,
......@@ -44,7 +45,10 @@ import {
import type { CacheMap } from './cache-map'
import type { NavigationLockPrefetch } from './navigation-testing-lock'
import { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'
import type { SegmentRequestKey } from '../../../shared/lib/segment-cache/segment-value-encoding'
import {
HEAD_REQUEST_KEY,
type SegmentRequestKey,
} from '../../../shared/lib/segment-cache/segment-value-encoding'
import { cleanup } from './lru'
const scheduleMicrotask =
......@@ -62,8 +66,12 @@ const scheduleMicrotask =
export type PrefetchTask = {
key: RouteCacheKey
// The active render tree when this task was scheduled.
renderTreeAtTimeOfPrefetch: RouteTree<CacheNode>
// The active render tree and head when this task was scheduled. The walks
// compare the target route against these to decide which segments the
// navigation would keep and which it would fetch. Compared by identity in
// isPrefetchTaskDirty, which relies on the router state holding one
// RootRouteTree object per committed navigation (see AppRouterState.root).
renderTreeAtTimeOfPrefetch: RootRouteTree<CacheNode>
/**
* The cache versions at the time the task was initiated. Used to determine
......@@ -300,7 +308,8 @@ export type IncludeDynamicData = null | 'full' | 'dynamic'
* expected to be validated and normalized.
*
* @param key The RouteCacheKey to prefetch.
* @param renderTreeAtTimeOfPrefetch The active render tree and its vary paths
* @param renderTreeAtTimeOfPrefetch The active render tree and head, and
* their vary paths
* @param fetchStrategy Whether to prefetch dynamic data, in addition to
* static data. This is used by `<Link prefetch={true}>`.
* @param navigationLockPrefetch Testing API only. Non-null when this prefetch
......@@ -309,7 +318,7 @@ export type IncludeDynamicData = null | 'full' | 'dynamic'
*/
export function schedulePrefetchTask(
key: RouteCacheKey,
renderTreeAtTimeOfPrefetch: RouteTree<CacheNode>,
renderTreeAtTimeOfPrefetch: RootRouteTree<CacheNode>,
fetchStrategy: PrefetchTaskFetchStrategy,
priority: PrefetchPriority,
onInvalidate: null | (() => void),
......@@ -383,7 +392,7 @@ export function cancelPrefetchTask(task: PrefetchTask): void {
export function reschedulePrefetchTask(
task: PrefetchTask,
renderTreeAtTimeOfPrefetch: RouteTree<CacheNode>,
renderTreeAtTimeOfPrefetch: RootRouteTree<CacheNode>,
fetchStrategy: PrefetchTaskFetchStrategy,
priority: PrefetchPriority
): void {
......@@ -428,7 +437,7 @@ export function reschedulePrefetchTask(
export function isPrefetchTaskDirty(
task: PrefetchTask,
nextUrl: string | null,
cache: RouteTree<CacheNode>
root: RootRouteTree<CacheNode>
): boolean {
// This is used to quickly bail out of a prefetch task if the result is
// guaranteed to not have changed since the task was initiated. This is
......@@ -438,7 +447,7 @@ export function isPrefetchTaskDirty(
return (
task.routeCacheVersion !== getCurrentRouteCacheVersion() ||
task.segmentCacheVersion !== getCurrentSegmentCacheVersion() ||
task.renderTreeAtTimeOfPrefetch !== cache ||
task.renderTreeAtTimeOfPrefetch !== root ||
task.key.nextUrl !== nextUrl
)
}
......@@ -626,7 +635,7 @@ function processQueueInMicrotask() {
const routeHasPartialPrefetching =
route !== null &&
route.status === EntryStatus.Fulfilled &&
(route.tree.prefetchHints &
(route.root.tree.prefetchHints &
PrefetchHint.SubtreeHasPartialPrefetching) !==
0
task.phase = routeHasPartialPrefetching
......@@ -846,7 +855,7 @@ function pingRootRouteTree(
// Stop prefetching segments until there's more bandwidth.
return PrefetchTaskExitStatus.InProgress
}
const tree = route.tree
const tree = route.root.tree
// A task's fetch strategy gets set to `PPR` for any "auto" prefetch.
// If it turned out that the route isn't PPR-enabled, we need to use `LoadingBoundary` instead.
......@@ -903,7 +912,7 @@ function pingRootRouteTree(
staticWalkStrategy === FetchStrategy.PPR &&
!needsSpeculativePrefetch(
task.fetchStrategy,
route.tree.prefetchHints
route.root.tree.prefetchHints
)
) {
return PrefetchTaskExitStatus.Done
......@@ -915,7 +924,7 @@ function pingRootRouteTree(
now,
task,
route,
task.renderTreeAtTimeOfPrefetch,
task.renderTreeAtTimeOfPrefetch.tree,
tree,
null,
staticWalkStrategy
......@@ -999,7 +1008,7 @@ function pingRootRouteTree(
now,
task,
route,
task.renderTreeAtTimeOfPrefetch,
task.renderTreeAtTimeOfPrefetch.tree,
tree,
spawnedEntries,
fetchStrategy
......@@ -1061,7 +1070,7 @@ type SegmentBundle = {
* path either when it requires runtime completeness and no static attempt is
* happening, or when a fulfilled static head entry reported that a runtime
* request would return more content than the entry contains. Deopting
* registers the head under its metadata request key, which makes the runtime
* registers the head under its wire request key, which makes the runtime
* gate in pingRootRouteTree fire even when every tree segment was
* sufficient; pingRuntimeHead performs the actual head work.
*/
......@@ -1082,10 +1091,10 @@ function pingStaticHead(
// The head is not a tree node — it hangs off the route root — so the
// static-attempt hints are read from the root's node. (Segments read the
// hints from their own node; see `pingNewPartOfCacheComponentsTree.`)
!shouldSegmentAttemptStaticRequest(fetchStrategy, route.tree)
!shouldSegmentAttemptStaticRequest(fetchStrategy, route.root.tree)
) {
// No static attempt: the head arrives via the runtime request instead.
addSpawnedRuntimePrefetch(task, route.metadata.requestKey)
addSpawnedRuntimePrefetch(task, HEAD_REQUEST_KEY)
return
}
......@@ -1095,18 +1104,18 @@ function pingStaticHead(
// as part of that page's response, and its runtime-completeness signal
// is carried by that page's own entries.
process.env.__NEXT_PREFETCH_INLINING &&
!(route.tree.prefetchHints & PrefetchHint.HeadOutlined)
!(route.root.tree.prefetchHints & PrefetchHint.HeadOutlined)
) {
return
}
const segments: SegmentBundle = {
tree: route.metadata,
tree: route.root.head,
entry: readOrCreateSegmentCacheEntry(
now,
task.segmentCacheMap,
fetchStrategy,
route.metadata
route.root.head
),
parent: null,
}
......@@ -1115,7 +1124,7 @@ function pingStaticHead(
task,
route,
task.key,
route.metadata,
route.root.head,
segments,
fetchStrategy,
true
......@@ -1125,7 +1134,7 @@ function pingStaticHead(
// runtime prefetch. (Outside of runtime-completeness contexts the
// head's signal is unused — a partial static head is filled in by the
// navigation-time request, as with any other static segment.)
addSpawnedRuntimePrefetch(task, route.metadata.requestKey)
addSpawnedRuntimePrefetch(task, HEAD_REQUEST_KEY)
}
}
......@@ -1155,7 +1164,9 @@ function walkCanUseRuntimeRequests(
}
// `FetchStrategy.PPR` can only use runtime requests if PPF is enabled on the route.
return (
(route.tree.prefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) !== 0
(route.root.tree.prefetchHints &
PrefetchHint.SubtreeHasPartialPrefetching) !==
0
)
}
......@@ -1270,7 +1281,7 @@ function isShellEntryEligibleForStaticAttempt(
}
/**
* Register a subtree root (or the head's metadata key) for the batched
* Register a subtree root (or the head's wire key) for the batched
* runtime request issued by the gate at the end of pingRootRouteTree.
*/
function addSpawnedRuntimePrefetch(
......@@ -1299,7 +1310,7 @@ function pingRuntimeHead(
now,
task,
route,
route.metadata,
route.root.head,
false,
spawnedEntries,
// When prefetching the head, there's no difference between Full
......@@ -1455,7 +1466,7 @@ function pingNewPartOfCacheComponentsTree(
// In PPF, links may skip speculative prefetching if they only need a shell.
if (
fetchStrategy === FetchStrategy.PPR &&
!needsSpeculativePrefetch(task.fetchStrategy, route.tree.prefetchHints)
!needsSpeculativePrefetch(task.fetchStrategy, route.root.tree.prefetchHints)
) {
return PrefetchTaskExitStatus.Done
}
......@@ -2453,12 +2464,12 @@ function accumulateSegmentBundle(
tree.prefetchHints & PrefetchHint.HeadInlinedIntoSelf
) {
effectiveParent = {
tree: route.metadata,
tree: route.root.head,
entry: readOrCreateSegmentCacheEntry(
now,
task.segmentCacheMap,
fetchStrategy,
route.metadata
route.root.head
),
parent: parentBundle,
}
......
......@@ -6,10 +6,7 @@ import type {
} from './cache-key'
import type { RouteTree } from './cache'
import { Fallback, type FallbackType } from './cache-map'
import {
HEAD_REQUEST_KEY,
type SegmentRequestKey,
} from '../../../shared/lib/segment-cache/segment-value-encoding'
import type { SegmentRequestKey } from '../../../shared/lib/segment-cache/segment-value-encoding'
import {
SEARCH_PARAMS_VARY_ID,
type VaryParamId,
......@@ -210,47 +207,6 @@ export function getPartialVaryPath(
return parent as PartialVaryPath | null
}
export function finalizeMetadataVaryPath(
pageRequestKey: SegmentRequestKey,
renderedSearch: NormalizedSearch,
varyPath: PartialVaryPath | null
): VaryPath {
// The metadata "segment" is not a real segment because it doesn't exist in
// the normal structure of the route tree, but in terms of caching, it
// behaves like a page segment because it varies by all the same params as
// a page.
//
// To keep the protocol for querying the server simple, the request key for
// the metadata does not include any path information. It's unnecessary from
// the server's perspective, because unlike page segments, there's only one
// metadata response per URL, i.e. there's no need to distinguish multiple
// parallel pages.
//
// However, this means the metadata request key is insufficient for
// caching the the metadata in the client cache, because on the client we
// use the request key to distinguish the metadata entry from all other
// page's metadata entries.
//
// So instead we create a simulated request key based on the page segment.
// Conceptually this is equivalent to the request key the server would have
// assigned the metadata segment if it treated it as part of the actual
// route structure.
// If there are multiple parallel pages, we use whichever is the first one.
// This is fine because the only difference between request keys for
// different parallel pages are things like route groups and parallel
// route slots. As long as it's always the same one, it doesn't matter.
//
// Append the actual metadata request key to the page request key. Note
// that we're not using a separate vary path part; it's unnecessary because
// these are not conceptually separate inputs.
return finalizeVaryPath(
(pageRequestKey + HEAD_REQUEST_KEY) as SegmentRequestKey,
renderedSearch,
varyPath
)
}
export function getSegmentVaryPathForRequest<TData>(
fetchStrategy: FetchStrategy,
tree: RouteTree<TData>
......
......@@ -57,10 +57,6 @@ export type CacheNode = {
*/
varyParams: VaryParams | null
prefetchHead: HeadData | null
head: HeadData
/**
* A shared mutable ref that tracks whether this segment should be scrolled
* to. All new segments created during a single navigation share the same
......
import { Metadata } from 'next'
type Params = { locale: string; tenant: string }
// Only one tenant is prerendered. Any other tenant is rendered on demand, so
// its head is missing from the cache while the body, which reads only the
// locale, can be reused from the prerendered one.
export function generateStaticParams(): Params[] {
return [{ locale: 'en', tenant: 'acme' }]
}
export async function generateMetadata({
params,
}: {
params: Promise<Params>
}): Promise<Metadata> {
const { tenant } = await params
return {
title: `Tenant: ${tenant}`,
}
}
export default async function PageWithPerTenantHead({
params,
}: {
params: Promise<Params>
}) {
const { locale } = await params
return <div id="target-page">{`Locale: ${locale}`}</div>
}
......@@ -37,6 +37,22 @@ export default function Page() {
</LinkAccordion>
</li>
</ul>
<hr />
<ul>
<li>
<LinkAccordion href="/page-with-per-tenant-head/en/acme">
Page with per-tenant head (en/acme)
</LinkAccordion>
</li>
<li>
<LinkAccordion
prefetch={false}
href="/page-with-per-tenant-head/en/initech"
>
Page with per-tenant head (en/initech, prefetch=false)
</LinkAccordion>
</li>
</ul>
</>
)
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { createRouterAct } from 'router-act'
import type * as Playwright from 'playwright'
const NEXT_ROUTER_STATE_TREE_HEADER = 'next-router-state-tree'
const NEXT_ROUTER_PREFETCH_HEADER = 'next-router-prefetch'
// The request tree the client sends when every segment is cached and only the
// head is missing. Mirrors MetadataOnlyRequestTree in the segment cache.
const METADATA_ONLY_REQUEST_TREE = JSON.stringify([
'',
{},
null,
'metadata-only',
])
describe('segment cache (metadata)', () => {
const { next, isNextDev } = nextTestSetup({
......@@ -129,4 +143,72 @@ describe('segment cache (metadata)', () => {
}, 'no-requests')
})
})
// On the platform a cold ISR path is served from a completed static
// prerender that cannot vary on the request tree, so the page body is sent
// along with the head.
// @gate !deploy
it('requests only the head when the page segments are cached', async () => {
let act: ReturnType<typeof createRouterAct>
// The request tree of every navigation request (RSC requests that are
// not prefetches), decoded from its header.
const navigationRequestTrees: Array<string | null> = []
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
p.on('request', (request) => {
const headers = request.headers()
if (
headers['rsc'] === '1' &&
headers[NEXT_ROUTER_PREFETCH_HEADER] === undefined
) {
const encoded = headers[NEXT_ROUTER_STATE_TREE_HEADER]
navigationRequestTrees.push(
encoded === undefined ? null : decodeURIComponent(encoded)
)
}
})
},
})
// Prefetch the prerendered tenant. The body reads only the locale, so
// this caches it for every tenant in "en"; the head reads the tenant, so
// only acme's head is cached.
await act(async () => {
const checkbox = await browser.elementByCss(
'input[data-link-accordion="/page-with-per-tenant-head/en/acme"]'
)
await checkbox.click()
}, [{ includes: 'Locale: en' }, { includes: 'Tenant: acme' }])
// Reveal a link to a tenant that is not prerendered, without prefetching
// it. Its head is the only thing missing from the cache.
await act(async () => {
const checkbox = await browser.elementByCss(
'input[data-link-accordion="/page-with-per-tenant-head/en/initech"]'
)
await checkbox.click()
}, 'no-requests')
// The navigation asks the server for the head alone. The response carries
// the new tenant's title and no page body.
await act(async () => {
const link = await browser.elementByCss(
'a[href="/page-with-per-tenant-head/en/initech"]'
)
await link.click()
}, [
{ includes: 'Tenant: initech' },
{ includes: 'Locale: en', block: 'reject' },
])
expect(navigationRequestTrees).toEqual([METADATA_ONLY_REQUEST_TREE])
// The body is the cached one, rendered under the new tenant's title.
const pageContent = await browser.elementById('target-page')
expect(await pageContent.text()).toBe('Locale: en')
await retry(async () => {
const title = await browser.eval(() => document.title)
expect(title).toBe('Tenant: initech')
})
})
})
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