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

instant(): Only render shell, unless prefetch prop is set (#95150)

When using the instant() API, or the Navigation Inspector, the
prefetched state should match what a user is most likely to see in
production with a warm cache. So, when Partial Prefetching is enabled,
and the Link does not have a prefetch prop, only the shell should be
allowed to render.

Before this PR, the _entire_ prefetched state would display, regardless
of the prefetch configuration of the route and the link.

This is essential to prevent false negatives in tests that assert on the
prefetched state: the test must not depend on data that wouldn't be
prefetched in a real production environment.

As part of the fix, I also updated the logic to ignore any cache entries
that were already present before the `instant()` lock was acquired, to
ensure the test is not "polluted" by earlier prefetches or navigations.
Theoretically we could optimize this in the future but this is the
cleanest way to ensure this property for now.

<!-- NEXT_JS_LLM_PR -->
parent d3324057
...@@ -18,7 +18,7 @@ export const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const ...@@ -18,7 +18,7 @@ export const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const
// Cookie for the Instant Navigation Testing API. Sent automatically with all // Cookie for the Instant Navigation Testing API. Sent automatically with all
// requests while a navigation lock is held; the server uses its presence to // requests while a navigation lock is held; the server uses its presence to
// render only the static shell. Not exposed in production builds by default. // render only the shell. Not exposed in production builds by default.
export const NEXT_INSTANT_TEST_COOKIE = export const NEXT_INSTANT_TEST_COOKIE =
'next-instant-navigation-testing' as const 'next-instant-navigation-testing' as const
......
...@@ -335,7 +335,8 @@ function rescheduleLinkPrefetch( ...@@ -335,7 +335,8 @@ function rescheduleLinkPrefetch(
treeAtTimeOfPrefetch, treeAtTimeOfPrefetch,
instance.fetchStrategy, instance.fetchStrategy,
priority, priority,
null null,
null // navigationLockPrefetch
) )
} else { } else {
// We already have an old task object that we can reschedule. This is // We already have an old task object that we can reschedule. This is
...@@ -380,7 +381,8 @@ export function pingVisibleLinks( ...@@ -380,7 +381,8 @@ export function pingVisibleLinks(
tree, tree,
instance.fetchStrategy, instance.fetchStrategy,
PrefetchPriority.Default, PrefetchPriority.Default,
null null,
null // navigationLockPrefetch
) )
} }
} }
...@@ -12,6 +12,7 @@ import { ...@@ -12,6 +12,7 @@ import {
NOT_FOUND_SEGMENT_KEY, NOT_FOUND_SEGMENT_KEY,
} from '../../../shared/lib/segment' } from '../../../shared/lib/segment'
import { matchSegment } from '../match-segments' import { matchSegment } from '../match-segments'
import type { NavigationLockState } from '../segment-cache/navigation-testing-lock'
import { createHrefFromUrl } from './create-href-from-url' import { createHrefFromUrl } from './create-href-from-url'
import { fetchServerResponse } from './fetch-server-response' import { fetchServerResponse } from './fetch-server-response'
import { dispatchAppRouterAction } from '../use-action-queue' import { dispatchAppRouterAction } from '../use-action-queue'
...@@ -127,7 +128,7 @@ export type NavigationRequestAccumulation = { ...@@ -127,7 +128,7 @@ export type NavigationRequestAccumulation = {
scrollRef: ScrollRef | null scrollRef: ScrollRef | null
} }
export type NavigationLock = Promise<void> | null export type NavigationLock = NavigationLockState | null
const noop = () => {} const noop = () => {}
...@@ -144,6 +145,7 @@ export function createInitialCacheNodeForHydration( ...@@ -144,6 +145,7 @@ export function createInitialCacheNodeForHydration(
separateRefreshUrls: null, separateRefreshUrls: null,
scrollRef: null, scrollRef: null,
} }
const restrictToShell = false
const task = createCacheNodeOnNavigation( const task = createCacheNodeOnNavigation(
navigatedAt, navigatedAt,
initialTree, initialTree,
...@@ -153,7 +155,8 @@ export function createInitialCacheNodeForHydration( ...@@ -153,7 +155,8 @@ export function createInitialCacheNodeForHydration(
seedHead, seedHead,
seedDynamicStaleAt, seedDynamicStaleAt,
false, false,
accumulation accumulation,
restrictToShell
) )
return task return task
} }
...@@ -200,7 +203,10 @@ export function startPPRNavigation( ...@@ -200,7 +203,10 @@ export function startPPRNavigation(
seedHead: HeadData | null, seedHead: HeadData | null,
seedDynamicStaleAt: number, seedDynamicStaleAt: number,
isSamePageNavigation: boolean, isSamePageNavigation: boolean,
accumulation: NavigationRequestAccumulation accumulation: NavigationRequestAccumulation,
// Instant Navigation Testing API only — restricts segment reads to shell
// entries. Always false outside the testing API. See navigation-testing-lock.
restrictToShell: boolean
): NavigationTask | null { ): NavigationTask | null {
const parentNeedsDynamicRequest = false const parentNeedsDynamicRequest = false
const parentRefreshState = null const parentRefreshState = null
...@@ -223,7 +229,8 @@ export function startPPRNavigation( ...@@ -223,7 +229,8 @@ export function startPPRNavigation(
parentNeedsDynamicRequest, parentNeedsDynamicRequest,
oldRootRefreshState, oldRootRefreshState,
parentRefreshState, parentRefreshState,
accumulation accumulation,
restrictToShell
) )
} }
...@@ -242,7 +249,10 @@ function updateCacheNodeOnNavigation( ...@@ -242,7 +249,10 @@ function updateCacheNodeOnNavigation(
parentNeedsDynamicRequest: boolean, parentNeedsDynamicRequest: boolean,
oldRootRefreshState: RefreshState, oldRootRefreshState: RefreshState,
parentRefreshState: RefreshState | null, parentRefreshState: RefreshState | null,
accumulation: NavigationRequestAccumulation accumulation: NavigationRequestAccumulation,
// Instant Navigation Testing API only — restricts segment reads to shell
// entries. Always false outside the testing API. See navigation-testing-lock.
restrictToShell: boolean
): NavigationTask | null { ): NavigationTask | null {
// Check if this segment matches the one in the previous route. A // Check if this segment matches the one in the previous route. A
// search-param-only difference at a page segment falls through to the // search-param-only difference at a page segment falls through to the
...@@ -302,7 +312,8 @@ function updateCacheNodeOnNavigation( ...@@ -302,7 +312,8 @@ function updateCacheNodeOnNavigation(
seedHead, seedHead,
seedDynamicStaleAt, seedDynamicStaleAt,
parentNeedsDynamicRequest, parentNeedsDynamicRequest,
accumulation accumulation,
restrictToShell
) )
} }
...@@ -371,7 +382,8 @@ function updateCacheNodeOnNavigation( ...@@ -371,7 +382,8 @@ function updateCacheNodeOnNavigation(
// route hasn't changed. Otherwise (no prior node) mint a fresh one. // route hasn't changed. Otherwise (no prior node) mint a fresh one.
oldCacheNode !== undefined oldCacheNode !== undefined
? oldCacheNode.bfcacheId ? oldCacheNode.bfcacheId
: generateBFCacheId(freshness) : generateBFCacheId(freshness),
restrictToShell
) )
newCacheNode = result.cacheNode newCacheNode = result.cacheNode
needsDynamicRequest = result.needsDynamicRequest needsDynamicRequest = result.needsDynamicRequest
...@@ -515,7 +527,8 @@ function updateCacheNodeOnNavigation( ...@@ -515,7 +527,8 @@ function updateCacheNodeOnNavigation(
parentNeedsDynamicRequest || needsDynamicRequest, parentNeedsDynamicRequest || needsDynamicRequest,
oldRootRefreshState, oldRootRefreshState,
refreshState, refreshState,
accumulation accumulation,
restrictToShell
) )
if (taskChild === null) { if (taskChild === null) {
...@@ -627,7 +640,10 @@ function createCacheNodeOnNavigation( ...@@ -627,7 +640,10 @@ function createCacheNodeOnNavigation(
seedHead: HeadData | null, seedHead: HeadData | null,
seedDynamicStaleAt: number, seedDynamicStaleAt: number,
parentNeedsDynamicRequest: boolean, parentNeedsDynamicRequest: boolean,
accumulation: NavigationRequestAccumulation accumulation: NavigationRequestAccumulation,
// Instant Navigation Testing API only — restricts segment reads to shell
// entries. Always false outside the testing API. See navigation-testing-lock.
restrictToShell: boolean
): NavigationTask { ): NavigationTask {
// Same traversal as updateCacheNodeNavigation, but simpler. We switch to this // Same traversal as updateCacheNodeNavigation, but simpler. We switch to this
// path once we reach the part of the tree that was not in the previous route. // path once we reach the part of the tree that was not in the previous route.
...@@ -655,7 +671,8 @@ function createCacheNodeOnNavigation( ...@@ -655,7 +671,8 @@ function createCacheNodeOnNavigation(
seedDynamicStaleAt, seedDynamicStaleAt,
// This segment was not part of the previous route, so mint a fresh // This segment was not part of the previous route, so mint a fresh
// bfcacheId. // bfcacheId.
generateBFCacheId(freshness) generateBFCacheId(freshness),
restrictToShell
) )
const newCacheNode = result.cacheNode const newCacheNode = result.cacheNode
const needsDynamicRequest = result.needsDynamicRequest const needsDynamicRequest = result.needsDynamicRequest
...@@ -693,7 +710,8 @@ function createCacheNodeOnNavigation( ...@@ -693,7 +710,8 @@ function createCacheNodeOnNavigation(
seedHead, seedHead,
seedDynamicStaleAt, seedDynamicStaleAt,
parentNeedsDynamicRequest || needsDynamicRequest, parentNeedsDynamicRequest || needsDynamicRequest,
accumulation accumulation,
restrictToShell
) )
taskChildren.set(parallelRouteKey, taskChild) taskChildren.set(parallelRouteKey, taskChild)
...@@ -918,7 +936,10 @@ function createCacheNodeForSegment( ...@@ -918,7 +936,10 @@ function createCacheNodeForSegment(
seedHead: HeadData | null, seedHead: HeadData | null,
freshness: FreshnessPolicy, freshness: FreshnessPolicy,
dynamicStaleAt: number, dynamicStaleAt: number,
bfcacheId: number bfcacheId: number,
// Instant Navigation Testing API only — restricts segment reads to shell
// entries. Always false outside the testing API. See navigation-testing-lock.
restrictToShell: boolean
): { cacheNode: CacheNode; needsDynamicRequest: boolean } { ): { cacheNode: CacheNode; needsDynamicRequest: boolean } {
// Construct a new CacheNode using data from the BFCache, the client's // Construct a new CacheNode using data from the BFCache, the client's
// Segment Cache, or seeded from a server response. // Segment Cache, or seeded from a server response.
...@@ -1064,7 +1085,11 @@ function createCacheNodeForSegment( ...@@ -1064,7 +1085,11 @@ function createCacheNodeForSegment(
let cachedRsc: React.ReactNode | null = null let cachedRsc: React.ReactNode | null = null
let isCachedRscPartial: boolean = true let isCachedRscPartial: boolean = true
const segmentEntry = readSegmentCacheEntryForNavigation(now, tree.varyPath) const segmentEntry = readSegmentCacheEntryForNavigation(
now,
tree.varyPath,
restrictToShell
)
if (segmentEntry !== null) { if (segmentEntry !== null) {
switch (segmentEntry.status) { switch (segmentEntry.status) {
case EntryStatus.Fulfilled: { case EntryStatus.Fulfilled: {
...@@ -1169,7 +1194,8 @@ function createCacheNodeForSegment( ...@@ -1169,7 +1194,8 @@ function createCacheNodeForSegment(
if (metadataVaryPath !== null) { if (metadataVaryPath !== null) {
const metadataEntry = readSegmentCacheEntryForNavigation( const metadataEntry = readSegmentCacheEntryForNavigation(
now, now,
metadataVaryPath metadataVaryPath,
restrictToShell
) )
if (metadataEntry !== null) { if (metadataEntry !== null) {
switch (metadataEntry.status) { switch (metadataEntry.status) {
......
...@@ -73,7 +73,9 @@ export function restoreReducer( ...@@ -73,7 +73,9 @@ export function restoreReducer(
null, null,
restoreSeed.dynamicStaleAt, restoreSeed.dynamicStaleAt,
false, false,
accumulation accumulation,
// A history-traversal restore never restricts to the shell.
false
) )
if (task === null) { if (task === null) {
......
...@@ -38,6 +38,7 @@ import { ...@@ -38,6 +38,7 @@ import {
type PrefetchTask, type PrefetchTask,
type PrefetchSubtaskResult, type PrefetchSubtaskResult,
} from './scheduler' } from './scheduler'
import type { NavigationLockPrefetch } from './navigation-testing-lock'
import { import {
type RouteVaryPath, type RouteVaryPath,
type SegmentVaryPath, type SegmentVaryPath,
...@@ -513,9 +514,65 @@ export function readSegmentCacheEntry( ...@@ -513,9 +514,65 @@ export function readSegmentCacheEntry(
*/ */
export function readSegmentCacheEntryForNavigation( export function readSegmentCacheEntryForNavigation(
now: number, now: number,
varyPath: SegmentVaryPath varyPath: SegmentVaryPath,
restrictToShell: boolean = false
): SegmentCacheEntry | null { ): SegmentCacheEntry | null {
const isRevalidation = false const isRevalidation = false
if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { getCurrentNavigationLock } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
const lock = getCurrentNavigationLock()
if (lock !== null) {
// Instant Navigation Testing API
//
// Modify the lookup logic to simulate the behavior that we would expect
// to mostly realistically happen in a production environment with a
// warm prefetch cache.
// If restrictToShell is true, it means we're navigating to a link that
// 1) has Partial Prefetching enabled, and 2) does not have a prefetch
// prop set. We should only allow the shell to render, not anything that
// varies on concrete route params.
const lookupVaryPath = restrictToShell
? getShellSegmentVaryPath(varyPath)
: varyPath
// To prevent the test navigation from being "polluted" by earlier
// prefetches, we'll also only match entries that were created during
// the current lock scope. This is tracked by the `ownedEntries` set.
const ownedEntries = lock.ownedEntries
// Besides that, the rest of the logic is the same as production.
const fulfilled = getFromCacheMap(
now,
getCurrentSegmentCacheVersion(),
segmentCacheMap,
lookupVaryPath,
isRevalidation,
true
)
if (fulfilled !== null && ownedEntries.has(fulfilled)) {
return fulfilled
}
const entry = getFromCacheMap(
now,
getCurrentSegmentCacheVersion(),
segmentCacheMap,
lookupVaryPath,
isRevalidation,
false
)
if (entry !== null && ownedEntries.has(entry)) {
return entry
}
return null
}
}
// Prefer a Fulfilled entry (e.g. a cached shell) over a more-specific
// Pending/Rejected one so it renders immediately instead of blocking on an
// in-flight entry.
const fulfilled = getFromCacheMap( const fulfilled = getFromCacheMap(
now, now,
getCurrentSegmentCacheVersion(), getCurrentSegmentCacheVersion(),
...@@ -807,12 +864,34 @@ function deprecated_createOptimisticRouteTree( ...@@ -807,12 +864,34 @@ function deprecated_createOptimisticRouteTree(
export function readOrCreateSegmentCacheEntry( export function readOrCreateSegmentCacheEntry(
now: number, now: number,
fetchStrategy: FetchStrategy, fetchStrategy: FetchStrategy,
tree: RouteTree tree: RouteTree,
// Non-null when this read is part of a locked navigation's prefetch (Instant
// Navigation Testing API only; always null in production). See below.
navigationLockPrefetch: NavigationLockPrefetch | null
): SegmentCacheEntry { ): SegmentCacheEntry {
const existingEntry = readSegmentCacheEntry(now, tree.varyPath) const existingEntry = readSegmentCacheEntry(now, tree.varyPath)
if (existingEntry !== null) { if (existingEntry !== null) {
if (
process.env.__NEXT_EXPOSE_TESTING_API &&
navigationLockPrefetch !== null
) {
// Locked navigation: ignore entries that predate the lock so each
// navigation reads only data (re)fetched within the lock scope — a
// "clean read." But an entry we already created within this scope is
// reused like normal; otherwise the prefetch would discard the entry it
// just fetched on every scheduler pass and refetch forever. See
// navigation-testing-lock.ts.
const { getCurrentNavigationLock } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
const lock = getCurrentNavigationLock()
if (lock !== null && lock.ownedEntries.has(existingEntry)) {
return existingEntry return existingEntry
} }
} else {
return existingEntry
}
}
// No reusable entry, or a locked navigation discarding a pre-lock entry.
// Create a pending entry and add it to the cache. The stale time is set to a // Create a pending entry and add it to the cache. The stale time is set to a
// default value; the actual stale time will be set when the entry is // default value; the actual stale time will be set when the entry is
// fulfilled with data from the server response. // fulfilled with data from the server response.
...@@ -981,12 +1060,21 @@ export function createDetachedSegmentCacheEntry( ...@@ -981,12 +1060,21 @@ export function createDetachedSegmentCacheEntry(
staleAt, staleAt,
version: 0, version: 0,
} }
if (process.env.__NEXT_EXPOSE_TESTING_API) {
// Instant Navigation Testing API: mark entries created during a lock scope
// as owned, so locked navigations match only data (re)fetched within the
// scope. No-op when no lock is held (always in production).
const { recordNavigationLockOwnedEntry } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
recordNavigationLockOwnedEntry(emptyEntry)
}
return emptyEntry return emptyEntry
} }
export function upgradeToPendingSegment( export function upgradeToPendingSegment(
emptyEntry: EmptySegmentCacheEntry, emptyEntry: EmptySegmentCacheEntry,
fetchStrategy: FetchStrategy fetchStrategy: FetchStrategy,
navigationLockPrefetch: NavigationLockPrefetch | null
): PendingSegmentCacheEntry { ): PendingSegmentCacheEntry {
const pendingEntry: PendingSegmentCacheEntry = emptyEntry as any const pendingEntry: PendingSegmentCacheEntry = emptyEntry as any
pendingEntry.status = EntryStatus.Pending pendingEntry.status = EntryStatus.Pending
...@@ -1005,6 +1093,23 @@ export function upgradeToPendingSegment( ...@@ -1005,6 +1093,23 @@ export function upgradeToPendingSegment(
// than when receiving the response, because it's guaranteed to happen // than when receiving the response, because it's guaranteed to happen
// before the data is read on the server. // before the data is read on the server.
pendingEntry.version = getCurrentSegmentCacheVersion() pendingEntry.version = getCurrentSegmentCacheVersion()
if (
process.env.__NEXT_EXPOSE_TESTING_API &&
// Instant Navigation Testing API only. Non-null when the requesting
// prefetch is driving a locked navigation, in which case the
// freshly-spawned pending entry is tracked against that navigation's
// prefetch state so the navigation waits for it to fulfill before reading
// it. Null at non-scheduler call sites (BFCache fulfillment, response
// processing), which don't spawn an in-flight request to wait on, and
// always in production.
navigationLockPrefetch !== null
) {
const { trackNavigationLockPrefetchEntry } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
trackNavigationLockPrefetchEntry(navigationLockPrefetch, pendingEntry)
}
return pendingEntry return pendingEntry
} }
...@@ -1038,7 +1143,13 @@ export function attemptToFulfillDynamicSegmentFromBFCache( ...@@ -1038,7 +1143,13 @@ export function attemptToFulfillDynamicSegmentFromBFCache(
return null return null
} }
const pendingSegment = upgradeToPendingSegment(segment, FetchStrategy.Full) const pendingSegment = upgradeToPendingSegment(
segment,
FetchStrategy.Full,
// Fulfilled synchronously from the BFCache; nothing for a locked
// navigation to wait on.
null
)
const isPartial = false const isPartial = false
return fulfillSegmentCacheEntry( return fulfillSegmentCacheEntry(
pendingSegment, pendingSegment,
...@@ -1072,7 +1183,10 @@ export function attemptToUpgradeSegmentFromBFCache( ...@@ -1072,7 +1183,10 @@ export function attemptToUpgradeSegmentFromBFCache(
} }
const pendingSegment = upgradeToPendingSegment( const pendingSegment = upgradeToPendingSegment(
createDetachedSegmentCacheEntry(now), createDetachedSegmentCacheEntry(now),
FetchStrategy.Full FetchStrategy.Full,
// Fulfilled synchronously from the BFCache; nothing for a locked
// navigation to wait on.
null
) )
const isPartial = false const isPartial = false
const newEntry = fulfillSegmentCacheEntry( const newEntry = fulfillSegmentCacheEntry(
...@@ -2250,7 +2364,8 @@ function writeSegmentBundleResponse( ...@@ -2250,7 +2364,8 @@ function writeSegmentBundleResponse(
// to upsert it into the canonical slot. // to upsert it into the canonical slot.
const detachedEntry = createDetachedSegmentCacheEntry(now) const detachedEntry = createDetachedSegmentCacheEntry(now)
fulfilled = fulfillSegmentCacheEntry( fulfilled = fulfillSegmentCacheEntry(
upgradeToPendingSegment(detachedEntry, FetchStrategy.PPR), // Response-write path, not a locked-navigation prefetch.
upgradeToPendingSegment(detachedEntry, FetchStrategy.PPR, null),
data.rsc, data.rsc,
entryStaleAt, entryStaleAt,
data.isPartial, data.isPartial,
...@@ -3036,17 +3151,20 @@ function fulfillEntrySpawnedByRuntimePrefetch( ...@@ -3036,17 +3151,20 @@ function fulfillEntrySpawnedByRuntimePrefetch(
) )
} }
} else { } else {
// There's no matching entry. Attempt to create a new one. // There's no matching entry. Attempt to create a new one. This is a
// response-write path, not a locked-navigation prefetch.
const possiblyNewEntry = readOrCreateSegmentCacheEntry( const possiblyNewEntry = readOrCreateSegmentCacheEntry(
now, now,
fetchStrategy, fetchStrategy,
tree tree,
null
) )
if (possiblyNewEntry.status === EntryStatus.Empty) { if (possiblyNewEntry.status === EntryStatus.Empty) {
// Confirmed this is a new entry. We can fulfill it. // Confirmed this is a new entry. We can fulfill it.
const newEntry = possiblyNewEntry const newEntry = possiblyNewEntry
const fulfilledEntry = fulfillSegmentCacheEntry( const fulfilledEntry = fulfillSegmentCacheEntry(
upgradeToPendingSegment(newEntry, fetchStrategy), // Response-write path, not a locked-navigation prefetch.
upgradeToPendingSegment(newEntry, fetchStrategy, null),
rsc, rsc,
staleAt, staleAt,
isPartial, isPartial,
...@@ -3068,7 +3186,9 @@ function fulfillEntrySpawnedByRuntimePrefetch( ...@@ -3068,7 +3186,9 @@ function fulfillEntrySpawnedByRuntimePrefetch(
const newEntry = fulfillSegmentCacheEntry( const newEntry = fulfillSegmentCacheEntry(
upgradeToPendingSegment( upgradeToPendingSegment(
createDetachedSegmentCacheEntry(now), createDetachedSegmentCacheEntry(now),
fetchStrategy fetchStrategy,
// Response-write path, not a locked-navigation prefetch.
null
), ),
rsc, rsc,
staleAt, staleAt,
......
...@@ -74,7 +74,7 @@ export function navigate( ...@@ -74,7 +74,7 @@ export function navigate(
// prefetch task has been initiated before proceeding with the navigation. // prefetch task has been initiated before proceeding with the navigation.
// This guarantees that segment data requests are at least pending, even // This guarantees that segment data requests are at least pending, even
// for routes that already have a cached route tree. Without this, the // for routes that already have a cached route tree. Without this, the
// static shell might be incomplete because some segments were never // shell might be incomplete because some segments were never
// requested. // requested.
if (process.env.__NEXT_EXPOSE_TESTING_API) { if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { isNavigationLocked } = const { isNavigationLocked } =
...@@ -288,6 +288,21 @@ export function navigateToKnownRoute( ...@@ -288,6 +288,21 @@ export function navigateToKnownRoute(
console.error(error) console.error(error)
} }
} }
// Instant Navigation Testing API: when the lock is held, restrict segment
// reads to shell entries if the target route would only have prefetched
// its shell.
let restrictToShell = false
if (process.env.__NEXT_EXPOSE_TESTING_API) {
const { shouldRestrictNavigationToShell } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
const link = getLinkForCurrentNavigation()
restrictToShell = shouldRestrictNavigationToShell(
navigationSeed.routeTree.prefetchHints,
link !== null ? link.fetchStrategy : FetchStrategy.PPR
)
}
const accumulation: NavigationRequestAccumulation = { const accumulation: NavigationRequestAccumulation = {
separateRefreshUrls: null, separateRefreshUrls: null,
scrollRef: null, scrollRef: null,
...@@ -324,7 +339,8 @@ export function navigateToKnownRoute( ...@@ -324,7 +339,8 @@ export function navigateToKnownRoute(
navigationSeed.head, navigationSeed.head,
navigationSeed.dynamicStaleAt, navigationSeed.dynamicStaleAt,
isSamePageNavigation, isSamePageNavigation,
accumulation accumulation,
restrictToShell
) )
if (task !== null) { if (task !== null) {
if (freshnessPolicy !== FreshnessPolicy.Gesture) { if (freshnessPolicy !== FreshnessPolicy.Gesture) {
...@@ -1055,16 +1071,25 @@ async function ensurePrefetchThenNavigate( ...@@ -1055,16 +1071,25 @@ async function ensurePrefetchThenNavigate(
const cacheKey = createCacheKey(url.href, nextUrl) const cacheKey = createCacheKey(url.href, nextUrl)
await new Promise<void>((resolve) => { // Create this navigation's "wait for prefetch to fulfill" state and schedule
// the prefetch as a locked-navigation prefetch. The prefetch's promise
// resolves once it has spawned every request and all of them have fulfilled,
// so the navigation below reads present data rather than a still-in-flight
// entry.
const { beginNavigationLockPrefetch } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
const navigationLockPrefetch = beginNavigationLockPrefetch()
schedulePrefetchTask( schedulePrefetchTask(
cacheKey, cacheKey,
currentFlightRouterState, currentFlightRouterState,
fetchStrategy, fetchStrategy,
PrefetchPriority.Default, PrefetchPriority.Default,
null, // onInvalidate null, // onInvalidate
resolve // _onComplete callback navigationLockPrefetch
) )
}) if (navigationLockPrefetch !== null) {
await navigationLockPrefetch.promise
}
// Prefetch is complete. Proceed with the normal navigation flow, which // Prefetch is complete. Proceed with the normal navigation flow, which
// will now find the route in the cache. // will now find the route in the cache.
......
...@@ -42,6 +42,7 @@ export function prefetch( ...@@ -42,6 +42,7 @@ export function prefetch(
treeAtTimeOfPrefetch, treeAtTimeOfPrefetch,
fetchStrategy, fetchStrategy,
PrefetchPriority.Default, PrefetchPriority.Default,
onInvalidate onInvalidate,
null // navigationLockPrefetch
) )
} }
export default function Loading() {
return <div data-testid="route-loading">Loading route...</div>
}
import { Suspense } from 'react'
export function generateStaticParams() {
return [{ slug: 'hello' }]
}
export default function DynamicParamsPage({
params,
}: {
params: Promise<{ slug: string }>
}) {
return (
<div>
<h1 data-testid="dynamic-params-title">Dynamic Params Page</h1>
<Suspense
fallback={<div data-testid="params-fallback">Loading params...</div>}
>
<ParamContent params={params} />
</Suspense>
</div>
)
}
async function ParamContent({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
return <div data-testid="param-value">slug: {slug}</div>
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function HomePage() {
return (
<div>
<h1 data-testid="home-title">Partial Prefetch Shell Test</h1>
{/* Default (partial) prefetch — only the shell is prefetched. */}
<Link href="/dynamic-params/hello" id="partial-link">
Partial link
</Link>
{/* Full prefetch — a speculative (whole-route) prefetch that warms the
concrete-param entry too. */}
<Link href="/dynamic-params/hello" prefetch={true} id="full-link">
Full prefetch link
</Link>
</div>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
// Opt every segment into Partial Prefetching, so an auto prefetch only warms
// the shell (params -> Fallback) unless the link forces a full
// prefetch. This is what makes the navigation lock restrict reads to the
// shell.
partialPrefetching: true,
experimental: {
// App Shells must be enabled for the shell restriction to apply — with it
// off, every prefetch implicitly includes the speculative (non-shell) part
// of the target, so there is nothing to restrict.
appShells: true,
// Enable the testing API in production builds for these tests.
exposeTestingApiInProductionBuild: true,
prefetchInlining: false,
},
}
module.exports = nextConfig
...@@ -167,7 +167,7 @@ describe('instant-navigation-testing-api', () => { ...@@ -167,7 +167,7 @@ describe('instant-navigation-testing-api', () => {
}) })
}) })
it('renders static shell on page reload', async () => { it('renders shell on page reload', async () => {
const page = await openPage(next, '/target-page') const page = await openPage(next, '/target-page')
// Wait for the page to fully load with dynamic content // Wait for the page to fully load with dynamic content
...@@ -196,7 +196,7 @@ describe('instant-navigation-testing-api', () => { ...@@ -196,7 +196,7 @@ describe('instant-navigation-testing-api', () => {
) )
}) })
it('renders static shell on MPA navigation via plain anchor', async () => { it('renders shell on MPA navigation via plain anchor', async () => {
const page = await openPage(next, '/') const page = await openPage(next, '/')
await instant(page, async () => { await instant(page, async () => {
...@@ -281,7 +281,7 @@ describe('instant-navigation-testing-api', () => { ...@@ -281,7 +281,7 @@ describe('instant-navigation-testing-api', () => {
// Fourth MPA navigation: go to target page again // Fourth MPA navigation: go to target page again
await page.click('#plain-link-to-target') await page.click('#plain-link-to-target')
// Still shows static shell, dynamic content still blocked // Still shows shell, dynamic content still blocked
await loadingShell.waitFor({ state: 'visible' }) await loadingShell.waitFor({ state: 'visible' })
expect(await dynamicContent.count()).toBe(0) expect(await dynamicContent.count()).toBe(0)
}) })
...@@ -859,3 +859,78 @@ describe('instant-navigation-testing-api - root params', () => { ...@@ -859,3 +859,78 @@ describe('instant-navigation-testing-api - root params', () => {
}) })
}) })
}) })
describe('instant-navigation-testing-api - partial prefetching (App Shells)', () => {
const { next } = nextTestSetup({
files: join(__dirname, 'fixtures', 'partial-prefetch'),
skipDeployment: true,
// Skew protection (deployment-id asset versioning) is orthogonal to the
// shell-restriction behavior under test. Disable it so the suite exercises
// only the navigation-lock behavior.
disableAutoSkewProtection: true,
})
// Under Partial Prefetching with App Shells, an auto (partial) prefetch only
// warms the shell — the concrete-param entry is not speculatively
// prefetched. The testing lock simulates that warm cache: a navigation may
// only match the shell entry, never an entry that varies on concrete route
// params, even if such an entry happens to be warm in the cache (here, from a
// sibling prefetch={true} link). Without the restriction, the navigation
// would match the warm `slug: hello` entry and show it instantly.
it('restricts navigation to the shell even when a concrete-param entry is warm', async () => {
const page = await openPage(next, '/')
// Warm both entries for /dynamic-params/hello:
// - the prefetch={true} sibling link does a speculative (whole-route)
// prefetch, warming the concrete slug=hello segment entry, and
// - the default link does a partial prefetch, warming the shell entry
// (params -> Fallback) that the restricted navigation should render.
await page.hover('#full-link')
await page.hover('#partial-link')
await page.waitForTimeout(3000)
await instant(page, async () => {
// Navigate via the default (partial) link. Even though the concrete
// slug=hello entry is warm, the lock restricts the read to the shell.
await page.click('#partial-link')
// A shell boundary is shown — either the route-level loading.tsx or the
// page's inner Suspense fallback — proving the navigation rendered the
// shell rather than the warm concrete entry.
const shell = page.locator(
'[data-testid="route-loading"], [data-testid="params-fallback"]'
)
await shell.first().waitFor({ state: 'visible' })
// The concrete param value is NOT matched.
const paramValue = page.locator('[data-testid="param-value"]')
expect(await paramValue.count()).toBe(0)
})
// After the instant scope exits, the concrete value streams in normally.
const paramValue = page.locator('[data-testid="param-value"]')
await paramValue.waitFor({ state: 'visible' })
expect(await paramValue.textContent()).toContain('slug: hello')
})
// A prefetch={true} link triggers a speculative (whole-route) prefetch, so
// the concrete-param entry IS prefetched. In that case the lock must NOT
// restrict to the shell — the navigation is allowed to match the concrete
// entry, since that's what a warm cache would actually contain.
it('allows matching concrete params when the link uses prefetch={true}', async () => {
const page = await openPage(next, '/')
await instant(page, async () => {
await page.click('#full-link')
// The concrete param value is matched and shown instantly.
const paramValue = page.locator('[data-testid="param-value"]')
await paramValue.waitFor({ state: 'visible' })
expect(await paramValue.textContent()).toContain('slug: hello')
// The Suspense fallback (shell) is NOT shown.
const fallback = page.locator('[data-testid="params-fallback"]')
expect(await fallback.count()).toBe(0)
})
})
})
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