Unverified Commit 5dc3ae1f authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Fix Nav Inspector request loop on repeat captures (#97050)

## Summary

Repro (from #96692): enable the Nav Inspector, click a `<Link
prefetch={true}>`, close the inspector, navigate home, re-enable it, and
click the same link. The app hung in a pending "Compiling..." state
while firing prefetch requests in an infinite loop (~30/sec).

The Instant Navigation Testing lock restricted navigation reads to
entries created within the current lock scope (`ownedEntries`), enforced
as a post-hoc filter after the cache lookup. But the segment cache
resolves lookups by most-specific-match, so a previous scope's
runtime-prefetch entries at concrete param keypaths kept winning the
lookup, the filter kept rejecting them, and the locked prefetch created
its replacement at a more generic keypath that could never win — every
scheduler pass discarded and refetched forever.

Rather than patch the filter, this replaces the `ownedEntries`
mechanism:

- Each lock scope owns a private segment `CacheMap` that starts empty
and is discarded at release, so a captured navigation structurally
observes only data fetched under the lock — cross-scope shadowing
becomes impossible by construction.
- The map is an explicit capability bound when work is created: a
prefetch task captures its map when scheduled
(`PrefetchTask.segmentCacheMap` — the single place that consults lock
state), a locked navigation inherits its driving task's map, and
everything else — unlocked navigations, hydration, refreshes,
traversals, server actions and patches — binds to the shared map. Reads
and response writes receive the map explicitly, so a request that
straddles a scope boundary still writes into the map its entries live
in.

In production builds without the testing API this compiles down to the
previous single-map behavior.

Includes the failing test from #96692 (thanks @samselikoff), hardened to
use the retry-based panel-reopen helper the sibling tests use.

## Verification

- `pnpm test-dev-turbo
test/development/app-dir/instant-navs-devtools/instant-navs-devtools.test.ts`
(32/32, includes the new regression test)
- `pnpm test-dev-webpack
test/development/app-dir/instant-navs-devtools/instant-navs-devtools.test.ts
-t "repeat clicks"`
- `pnpm test-dev-turbo
test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts`
- `pnpm test-start-turbo
test/e2e/app-dir/instant-navigation-testing-api/instant-navigation-testing-api.test.ts`
- `pnpm test-start-turbo
test/e2e/app-dir/segment-cache/basic/segment-cache-basic.test.ts`
(production paths unregressed)

<!-- NEXT_JS_LLM -->

---------
Co-authored-by: 's avatarSam Selikoff <sam.selikoff@gmail.com>
parent 6bee42b2
......@@ -9,6 +9,7 @@ import { createInitialCacheNodeForHydration } from './ppr-navigations'
import {
resolveStaleAt,
processRuntimePrefetchStream,
segmentCacheMap,
writeDynamicRenderResponseIntoCache,
writePrerenderResponseIntoCache,
} from '../segment-cache/cache'
......@@ -155,7 +156,8 @@ export function createInitialRouterState({
staleAt,
initialTree,
initialRenderedSearch,
true // isResponsePartial
true, // isResponsePartial
segmentCacheMap // hydration writes are bound to the shared map
)
})
.catch(() => {
......@@ -181,7 +183,8 @@ export function createInitialRouterState({
staleAt,
initialTree,
initialRenderedSearch,
false // isResponsePartial
false, // isResponsePartial
segmentCacheMap // hydration writes are bound to the shared map
)
})
.catch(() => {
......@@ -219,7 +222,8 @@ export function createInitialRouterState({
processed.rootVaryParamsIterable,
processed.staleAt,
processed.navigationSeed,
null
null,
segmentCacheMap // hydration writes are bound to the shared map
)
}
})
......
......@@ -25,6 +25,8 @@ import {
type NavigationSeed,
} from '../segment-cache/decode-server-response'
import {
segmentCacheMap,
type SegmentCacheEntry,
type RouteTree,
type RSCSegmentData,
type RefreshState,
......@@ -45,6 +47,7 @@ import { discoverKnownRoute } from '../segment-cache/optimistic-routes'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
import { urlSearchParamsToParsedUrlQuery } from '../../route-params'
import type { NormalizedSearch } from '../segment-cache/cache-key'
import type { CacheMap } from '../segment-cache/cache-map'
import {
getRenderedSearchFromVaryPath,
type PageVaryPath,
......@@ -178,6 +181,8 @@ export function createInitialCacheNodeForHydration(
seedDynamicStaleAt,
false,
accumulation,
// Hydration is bound to the shared map.
segmentCacheMap,
restrictToShell
)
return task
......@@ -225,6 +230,9 @@ export function startPPRNavigation(
seedDynamicStaleAt: number,
isSamePageNavigation: boolean,
accumulation: NavigationRequestAccumulation,
// The segment cache map this navigation is bound to: a locked navigation's
// driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.
map: CacheMap<SegmentCacheEntry>,
// Instant Navigation Testing API only — restricts segment reads to shell
// entries. Always false outside the testing API. See navigation-testing-lock.
restrictToShell: boolean
......@@ -250,6 +258,7 @@ export function startPPRNavigation(
oldRootRefreshState,
parentRefreshState,
accumulation,
map,
restrictToShell
)
}
......@@ -269,6 +278,7 @@ function updateCacheNodeOnNavigation(
oldRootRefreshState: RefreshState,
parentRefreshState: RefreshState | null,
accumulation: NavigationRequestAccumulation,
map: CacheMap<SegmentCacheEntry>,
// Instant Navigation Testing API only — restricts segment reads to shell
// entries. Always false outside the testing API. See navigation-testing-lock.
restrictToShell: boolean
......@@ -331,6 +341,7 @@ function updateCacheNodeOnNavigation(
seedDynamicStaleAt,
parentNeedsDynamicRequest,
accumulation,
map,
restrictToShell
)
}
......@@ -401,6 +412,7 @@ function updateCacheNodeOnNavigation(
oldCacheNode !== undefined
? oldCacheNode.bfcacheId
: generateBFCacheId(freshness),
map,
restrictToShell
)
newCacheNode = result.cacheNode
......@@ -542,6 +554,7 @@ function updateCacheNodeOnNavigation(
oldRootRefreshState,
refreshState,
accumulation,
map,
restrictToShell
)
......@@ -654,6 +667,7 @@ function createCacheNodeOnNavigation(
seedDynamicStaleAt: number,
parentNeedsDynamicRequest: boolean,
accumulation: NavigationRequestAccumulation,
map: CacheMap<SegmentCacheEntry>,
// Instant Navigation Testing API only — restricts segment reads to shell
// entries. Always false outside the testing API. See navigation-testing-lock.
restrictToShell: boolean
......@@ -685,6 +699,7 @@ function createCacheNodeOnNavigation(
// This segment was not part of the previous route, so mint a fresh
// bfcacheId.
generateBFCacheId(freshness),
map,
restrictToShell
)
const newCacheNode = result.cacheNode
......@@ -719,6 +734,7 @@ function createCacheNodeOnNavigation(
seedDynamicStaleAt,
parentNeedsDynamicRequest || needsDynamicRequest,
accumulation,
map,
restrictToShell
)
......@@ -947,6 +963,7 @@ function createCacheNodeForSegment(
freshness: FreshnessPolicy,
dynamicStaleAt: number,
bfcacheId: number,
map: CacheMap<SegmentCacheEntry>,
// Instant Navigation Testing API only — restricts segment reads to shell
// entries. Always false outside the testing API. See navigation-testing-lock.
restrictToShell: boolean
......@@ -1097,6 +1114,7 @@ function createCacheNodeForSegment(
const segmentEntry = readSegmentCacheEntryForNavigation(
now,
map,
tree.varyPath,
restrictToShell
)
......@@ -1204,6 +1222,7 @@ function createCacheNodeForSegment(
if (metadataVaryPath !== null) {
const metadataEntry = readSegmentCacheEntryForNavigation(
now,
map,
metadataVaryPath,
restrictToShell
)
......@@ -1413,6 +1432,9 @@ export function spawnDynamicRequests(
// transition hasn't committed yet.
navigateType: 'push' | 'replace',
navigationLock: NavigationLock | null,
// The segment cache map this navigation is bound to. See `segmentCacheMap`
// in cache.ts.
map: CacheMap<SegmentCacheEntry>,
signal: AbortSignal | undefined
): void {
const dynamicRequestTree = task.dynamicRequestTree
......@@ -1439,6 +1461,7 @@ export function spawnDynamicRequests(
freshnessPolicy,
routeCacheEntry,
navigationLock,
map,
signal
)
......@@ -1493,6 +1516,7 @@ export function spawnDynamicRequests(
freshnessPolicy,
routeCacheEntry,
navigationLock,
map,
signal
)
)
......@@ -1771,6 +1795,7 @@ async function fetchMissingDynamicData(
freshnessPolicy: FreshnessPolicy,
routeCacheEntry: FulfilledRouteCacheEntry | null,
navigationLock: NavigationLock | null,
map: CacheMap<SegmentCacheEntry>,
signal: AbortSignal | undefined
): Promise<{
exitStatus: NavigationTaskExitStatus
......@@ -1834,7 +1859,8 @@ async function fetchMissingDynamicData(
staleAt,
dynamicRequestTree,
result.renderedSearch,
isResponsePartial
isResponsePartial,
map
)
})
.catch(() => {
......@@ -1861,7 +1887,8 @@ async function fetchMissingDynamicData(
processed.rootVaryParamsIterable,
processed.staleAt,
processed.navigationSeed,
null
null,
map
)
}
})
......
......@@ -6,7 +6,10 @@ import type {
import { ScrollBehavior } from '../router-reducer-types'
import { navigateToKnownRoute } from '../../segment-cache/navigation'
import { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'
import { invalidateSegmentCacheEntries } from '../../segment-cache/cache'
import {
invalidateSegmentCacheEntries,
segmentCacheMap,
} from '../../segment-cache/cache'
import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'
import { FreshnessPolicy, getCurrentNavigationLock } from '../ppr-navigations'
import {
......@@ -98,6 +101,8 @@ export function refreshDynamicData(
scrollBehavior,
navigateType,
navigationLock,
// A refresh is bound to the shared map.
segmentCacheMap,
null,
// Refresh navigations don't use route prediction, so there's no route
// cache entry to mark as having a dynamic rewrite on mismatch. If a
......
......@@ -17,6 +17,7 @@ import {
completeTraverseNavigation,
} from '../../segment-cache/navigation'
import { convertServerPatchToFullTree } from '../../segment-cache/decode-server-response'
import { segmentCacheMap } from '../../segment-cache/cache'
import { UnknownDynamicStaleTime } from '../../segment-cache/bfcache'
export function restoreReducer(
......@@ -72,6 +73,8 @@ export function restoreReducer(
restoreSeed.dynamicStaleAt,
false,
accumulation,
// A history-traversal restore is bound to the shared map.
segmentCacheMap,
// A history-traversal restore never restricts to the shell.
false
)
......@@ -96,6 +99,8 @@ export function restoreReducer(
// dynamic requests ungated (null lock) so they render from cache or fetch
// normally rather than being withheld behind the lock.
null,
// A history-traversal restore is bound to the shared map.
segmentCacheMap,
// Not an HMR refresh, so there's no request generation to cancel.
undefined
)
......
......@@ -44,7 +44,10 @@ import {
extractInfoFromServerReferenceId,
omitUnusedArgs,
} from '../../../../shared/lib/server-reference-info'
import { invalidateEntirePrefetchCache } from '../../segment-cache/cache'
import {
invalidateEntirePrefetchCache,
segmentCacheMap,
} from '../../segment-cache/cache'
import { startRevalidationCooldown } from '../../segment-cache/scheduler'
import { getDeploymentId } from '../../../../shared/lib/deployment-id'
import { getNavigationBuildId } from '../../../navigation-build-id'
......@@ -516,6 +519,8 @@ export function serverActionReducer(
scrollBehavior,
navigateType,
navigationLock,
// A server-action redirect navigation is bound to the shared map.
segmentCacheMap,
null,
// Server action redirects don't use route prediction - we already
// have the route tree from the server response. If a mismatch occurs
......
......@@ -10,6 +10,7 @@ import {
completeHardNavigation,
navigateToKnownRoute,
} from '../../segment-cache/navigation'
import { segmentCacheMap } from '../../segment-cache/cache'
import { refreshReducer } from './refresh-reducer'
import { getCurrentNavigationLock } from '../ppr-navigations'
......@@ -65,6 +66,8 @@ export function serverPatchReducer(
scrollBehavior,
navigateType,
navigationLock,
// A server-patch retry navigation is bound to the shared map.
segmentCacheMap,
null,
// Server patch (retry) navigations don't use route prediction. This is
// typically a retry after a previous mismatch, so the route was already
......
......@@ -13,12 +13,10 @@
*/
import type { FlightRouterState } from '../../../shared/lib/app-router-types'
import type { PendingSegmentCacheEntry, SegmentCacheEntry } from './cache'
import type { SegmentCacheEntry } from './cache'
import type { CacheMap } from './cache-map'
import type { FetchStrategy } from './types'
import type {
NavigationLockPrefetch,
NavigationLockState,
} from './navigation-testing-lock'
import type { NavigationLockPrefetch } from './navigation-testing-lock'
export type {
NavigationLockPrefetch,
......@@ -33,16 +31,11 @@ export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {
return null
}
export function recordNavigationLockOwnedEntry(
_entry: SegmentCacheEntry
): void {}
export function trackNavigationLockPrefetchEntry(
_prefetch: NavigationLockPrefetch,
_entry: PendingSegmentCacheEntry
): void {}
export function getNavigationLockSegmentCacheMap(): CacheMap<SegmentCacheEntry> | null {
return null
}
export function finishNavigationLockPrefetchSpawning(
export function resolveNavigationLockPrefetch(
_prefetch: NavigationLockPrefetch
): void {}
......@@ -57,10 +50,6 @@ export function isNavigationLocked(): boolean {
return false
}
export function getCurrentNavigationLock(): NavigationLockState | null {
return null
}
export function beginLockedNavigation(): Promise<void> | null {
return null
}
......
......@@ -26,11 +26,8 @@ import {
import { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers'
import { refreshOnInstantNavigationUnlock } from '../use-action-queue'
import { subtreeHasSpeculativePrefetch } from './scheduler'
import {
waitForSegmentCacheEntry,
type PendingSegmentCacheEntry,
type SegmentCacheEntry,
} from './cache'
import type { SegmentCacheEntry } from './cache'
import { createCacheMap, type CacheMap } from './cache-map'
import type { FetchStrategy } from './types'
type InstantNavCookieState = 'empty' | 'pending' | 'mpa' | 'spa'
......@@ -100,22 +97,18 @@ function writeCookieValue(value: InstantCookie): void {
/**
* The "wait for the locked navigation's prefetch to fulfill" state for a single
* locked navigation. `promise` resolves once that prefetch has spawned every
* request and all of them have fulfilled, so the navigation reads present data
* rather than a still-in-flight entry. Owned by the prefetch task (one per
* navigation, so successive navigations in a scope resolve independently) and
* also tracked in `NavigationLockState.activePrefetches` so the lock can
* force-resolve any that are still pending when it's released.
*
* `pendingCount` holds one reference for the scheduler while it is still
* spawning, plus one per in-flight entry; `promise` resolves when it drains to
* 0. `trackedEntries` dedupes entry registration.
* locked navigation. `promise` resolves when the driving prefetch task
* completes — which the scheduler only allows after a full pass has observed
* every segment response it cares about (see `blockTaskOnPendingResponse` in
* scheduler.ts) — so the navigation reads present data rather than a
* still-in-flight entry. Owned by the prefetch task (one per navigation, so
* successive navigations in a scope resolve independently) and also tracked
* in `NavigationLockState.activePrefetches` so the lock can force-resolve any
* that are still pending when it's released.
*/
export type NavigationLockPrefetch = {
promise: Promise<void>
resolve: () => void
pendingCount: number
trackedEntries: Set<PendingSegmentCacheEntry>
}
export type NavigationLockState = {
......@@ -131,16 +124,19 @@ export type NavigationLockState = {
// during a lock scope.
fetch: typeof fetch
// Every prefetch-completion state for this scope that hasn't resolved yet.
// A prefetch removes itself when it drains; on release, any still here are
// force-resolved so no navigation hangs waiting on a prefetch that the scope
// ended before it could finish.
// A prefetch removes itself when its driving task completes; on release, any
// still here are force-resolved so no navigation hangs waiting on a prefetch
// that the scope ended before it could finish.
activePrefetches: Set<NavigationLockPrefetch>
// Every segment entry that was (re)fetched within this lock scope. Navigation
// reads are restricted to these, so each instant() navigation observes only
// data fetched under the lock — a "clean read" — and never matches a stale
// entry left in the cache by an earlier navigation or prefetch. See
// `readSegmentCacheEntryForNavigation`.
ownedEntries: Set<SegmentCacheEntry>
// The scope's private segment cache. Prefetch tasks scheduled while the
// lock is held are bound to this map instead of the shared one, and a
// locked navigation inherits the map of the task that drives it (see
// `segmentCacheMap` in cache.ts). It starts empty, so each instant()
// navigation observes only data fetched under the lock — a "clean read" —
// and never matches a stale entry left in the shared cache by an earlier
// navigation, prefetch, or scope. Discarded when the lock is released; its
// entries are reclaimed by the LRU under memory pressure.
segmentCacheMap: CacheMap<SegmentCacheEntry>
// The withheld-data gate for the current locked navigation. A locked
// navigation's dynamic write waits on this rather than on the scope-wide
// `released`. Each navigation captures the promise when it begins (via
......@@ -167,12 +163,8 @@ export function getPreLockFetch(): typeof fetch | null {
* Creates the "wait for prefetch to fulfill" state for one locked navigation,
* registers it on the current lock, and returns it (the caller stores it on the
* prefetch task and awaits `.promise`). Returns null if no lock is held.
*
* `pendingCount` starts at 1, representing the scheduler itself while it is
* still spawning requests; that reference is released by
* `finishNavigationLockPrefetchSpawning`. Each spawned pending entry adds
* another (see `trackNavigationLockPrefetchEntry`). `promise` resolves when the
* count drains to 0 — i.e. spawning finished and every entry fulfilled.
* Resolved by the scheduler via `resolveNavigationLockPrefetch` when the
* driving prefetch task completes.
*/
export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {
if (lockState !== null) {
......@@ -183,8 +175,6 @@ export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {
const prefetch: NavigationLockPrefetch = {
promise,
resolve: resolve!,
pendingCount: 1,
trackedEntries: new Set(),
}
lockState.activePrefetches.add(prefetch)
return prefetch
......@@ -193,68 +183,28 @@ export function beginNavigationLockPrefetch(): NavigationLockPrefetch | null {
}
/**
* Records a freshly-created segment entry as owned by the current lock scope, so
* navigation reads will match it — and only entries created within the scope
* (see `NavigationLockState.ownedEntries`). Called from
* `createDetachedSegmentCacheEntry`, the single factory every creation path
* funnels through, so re-keyed entries created during response processing (e.g.
* a runtime prefetch resolving a concrete param) are owned too. No-op when no
* lock is held.
* Returns the current lock scope's private segment cache map, or null when no
* lock is held. See `NavigationLockState.segmentCacheMap`.
*/
export function recordNavigationLockOwnedEntry(entry: SegmentCacheEntry): void {
if (lockState !== null) {
lockState.ownedEntries.add(entry)
}
}
/**
* Called by `upgradeToPendingSegment` whenever the locked-navigation prefetch
* spawns a pending segment entry. Adds the entry to the prefetch's ref count and
* decrements when it fulfills (or rejects — `waitForSegmentCacheEntry` resolves
* to null). Deduped so the same entry never double-counts.
*/
export function trackNavigationLockPrefetchEntry(
prefetch: NavigationLockPrefetch,
entry: PendingSegmentCacheEntry
): void {
if (prefetch.trackedEntries.has(entry)) {
return
}
prefetch.trackedEntries.add(entry)
prefetch.pendingCount++
const onSettled = () => {
prefetch.pendingCount--
settleNavigationLockPrefetchIfDrained(prefetch)
}
// Decrement whether the entry fulfills or its request rejects, so a failed
// segment can't leave the navigation waiting forever.
waitForSegmentCacheEntry(entry).then(onSettled, onSettled)
export function getNavigationLockSegmentCacheMap(): CacheMap<SegmentCacheEntry> | null {
return lockState !== null ? lockState.segmentCacheMap : null
}
/**
* Called once the scheduler has finished spawning every request for the
* locked-navigation prefetch, releasing the scheduler's reference from the ref
* count. The prefetch resolves here if every spawned entry already fulfilled.
* Called by the scheduler when the locked-navigation prefetch task completes.
* A task only completes after a full pass observed every segment response it
* cares about, so the data the navigation will read has settled by this
* point. Unregisters from the lock (if still held) and resolves. Resolving is
* idempotent, so it's safe even if the lock already force-resolved this on
* release.
*/
export function finishNavigationLockPrefetchSpawning(
prefetch: NavigationLockPrefetch
): void {
prefetch.pendingCount--
settleNavigationLockPrefetchIfDrained(prefetch)
}
function settleNavigationLockPrefetchIfDrained(
export function resolveNavigationLockPrefetch(
prefetch: NavigationLockPrefetch
): void {
if (prefetch.pendingCount === 0) {
// Unregister from the lock (if still held) and resolve. Resolving is
// idempotent, so it's safe even if the lock already force-resolved this on
// release.
if (lockState !== null) {
lockState.activePrefetches.delete(prefetch)
}
prefetch.resolve()
if (lockState !== null) {
lockState.activePrefetches.delete(prefetch)
}
prefetch.resolve()
}
function acquireLock(): void {
......@@ -274,7 +224,7 @@ function acquireLock(): void {
resolveReleased: resolveReleased!,
fetch: window.fetch,
activePrefetches: new Set(),
ownedEntries: new Set(),
segmentCacheMap: createCacheMap(),
currentNavigation,
resolveCurrentNavigation: resolveCurrentNavigation!,
}
......@@ -563,10 +513,6 @@ export function isNavigationLocked(): boolean {
return false
}
export function getCurrentNavigationLock(): NavigationLockState | null {
return lockState
}
/**
* Returns the current locked navigation's withheld-data gate — the same
* immutable promise `beginLockedNavigation` handed that navigation — or null
......
......@@ -17,6 +17,8 @@ import { createHrefFromUrl } from '../router-reducer/create-href-from-url'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
import {
EntryStatus,
segmentCacheMap,
type SegmentCacheEntry,
readRouteCacheEntry,
deprecated_requestOptimisticRouteCacheEntry,
resolveStaleAt,
......@@ -27,6 +29,7 @@ import {
} from './cache'
import { discoverKnownRoute } from './optimistic-routes'
import { createCacheKey, type NormalizedSearch } from './cache-key'
import type { CacheMap } from './cache-map'
import { schedulePrefetchTask } from './scheduler'
import { PrefetchPriority, FetchStrategy } from './types'
import { getLinkForCurrentNavigation } from '../links'
......@@ -105,7 +108,9 @@ export function navigate(
freshnessPolicy,
scrollBehavior,
navigateType,
navigationLock
navigationLock,
// An unlocked navigation is bound to the shared map.
segmentCacheMap
)
}
......@@ -120,7 +125,10 @@ function navigateImpl(
freshnessPolicy: FreshnessPolicy,
scrollBehavior: ScrollBehavior,
navigateType: 'push' | 'replace',
navigationLock: NavigationLock | null
navigationLock: NavigationLock | null,
// The segment cache map this navigation is bound to: a locked navigation's
// driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.
map: CacheMap<SegmentCacheEntry>
): AppRouterState | Promise<AppRouterState> {
const now = Date.now()
const href = url.href
......@@ -142,7 +150,8 @@ function navigateImpl(
scrollBehavior,
navigateType,
route,
navigationLock
navigationLock,
map
)
}
......@@ -179,7 +188,8 @@ function navigateImpl(
scrollBehavior,
navigateType,
optimisticRoute,
navigationLock
navigationLock,
map
)
}
}
......@@ -202,7 +212,8 @@ function navigateImpl(
freshnessPolicy,
scrollBehavior,
navigateType,
navigationLock
navigationLock,
map
).catch(() => {
// If the navigation fails, return the current state
return state
......@@ -224,6 +235,9 @@ export function navigateToKnownRoute(
scrollBehavior: ScrollBehavior,
navigateType: 'push' | 'replace',
navigationLock: NavigationLock | null,
// The segment cache map this navigation is bound to: a locked navigation's
// driving-task map, or the shared map. See `segmentCacheMap` in cache.ts.
map: CacheMap<SegmentCacheEntry>,
debugInfo: Array<unknown> | null,
// The route cache entry used for this navigation, if it came from route
// prediction. Passed through so it can be marked as having a dynamic rewrite
......@@ -337,6 +351,7 @@ export function navigateToKnownRoute(
navigationSeed.dynamicStaleAt,
isSamePageNavigation,
accumulation,
map,
restrictToShell
)
if (task !== null) {
......@@ -350,6 +365,7 @@ export function navigateToKnownRoute(
routeCacheEntry,
navigateType,
navigationLock,
map,
signal
)
}
......@@ -384,7 +400,8 @@ function navigateUsingPrefetchedRouteTree(
scrollBehavior: ScrollBehavior,
navigateType: 'push' | 'replace',
route: FulfilledRouteCacheEntry,
navigationLock: NavigationLock | null
navigationLock: NavigationLock | null,
map: CacheMap<SegmentCacheEntry>
): AppRouterState {
const routeTree = route.tree
const canonicalUrl = route.canonicalUrl + url.hash
......@@ -413,6 +430,7 @@ function navigateUsingPrefetchedRouteTree(
scrollBehavior,
navigateType,
navigationLock,
map,
null,
route,
// Not an HMR refresh, so there's no request generation to cancel.
......@@ -444,7 +462,8 @@ async function navigateToUnknownRoute(
freshnessPolicy: FreshnessPolicy,
scrollBehavior: ScrollBehavior,
navigateType: 'push' | 'replace',
navigationLock: NavigationLock | null
navigationLock: NavigationLock | null,
map: CacheMap<SegmentCacheEntry>
): Promise<AppRouterState> {
// Runs when a navigation happens but there's no cached prefetch we can use.
// Don't bother to wait for a prefetch response; go straight to a full
......@@ -559,7 +578,8 @@ async function navigateToUnknownRoute(
staleAt,
currentFlightRouterState,
renderedSearch,
isResponsePartial
isResponsePartial,
map
)
})
.catch(() => {
......@@ -586,7 +606,8 @@ async function navigateToUnknownRoute(
processed.rootVaryParamsIterable,
processed.staleAt,
processed.navigationSeed,
null
null,
map
)
}
})
......@@ -627,6 +648,7 @@ async function navigateToUnknownRoute(
scrollBehavior,
navigateType,
navigationLock,
map,
debugInfo,
// Unknown route navigations don't use route prediction - the route tree
// came directly from the server. If a mismatch occurs during dynamic data
......@@ -870,13 +892,13 @@ async function ensurePrefetchThenNavigate(
// 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.
// resolves when the task completes — after every segment response the task
// cares about has settled — 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(
const prefetchTask = schedulePrefetchTask(
cacheKey,
currentFlightRouterState,
fetchStrategy,
......@@ -889,7 +911,10 @@ async function ensurePrefetchThenNavigate(
}
// 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. The navigation inherits the map of
// the prefetch task that drives it: the task was scheduled inside the lock
// scope, so this is the scope's private map, and the navigation reads only
// data fetched under the lock.
const result = await navigateImpl(
state,
url,
......@@ -901,7 +926,8 @@ async function ensurePrefetchThenNavigate(
freshnessPolicy,
scrollBehavior,
navigateType,
navigationLock
navigationLock,
prefetchTask.segmentCacheMap
)
// Only transition to captured-SPA once the navigation is known to be an SPA.
......
......@@ -69,10 +69,11 @@ describe('instant-nav-panel', () => {
})
}
async function clickLink(browser: Playwright, href: string) {
await browser.eval((page) => {
document.querySelector<HTMLAnchorElement>(`[href="${page}"]`)!.click()
}, href)
async function clickLink(browser: Playwright, href: string, id?: string) {
const selector = id ? `#${id}` : `[href="${href}"]`
await browser.eval((selector) => {
document.querySelector<HTMLAnchorElement>(selector)!.click()
}, selector)
}
function getInstantNavPanel(browser: Playwright) {
......@@ -698,18 +699,54 @@ describe('instant-nav-panel', () => {
await openInstantNavPanel(browser)
await clickStartCapturing(browser)
// The prefetch link shares its href with #link-to-target, so select it
// by id rather than by href.
await browser.eval(() => {
document
.querySelector<HTMLAnchorElement>('#link-to-target-prefetch')!
.click()
})
await clickLink(
browser,
'/target-page/my-post?search=foo',
'link-to-target-prefetch'
)
await expectSpaPanel(browser)
await expectTargetPageSpaShellWithRuntimeData(browser)
})
it('works for repeat clicks to links with prefetch={true} (regression)', async () => {
const browser = await openHomeWithTargetPageWarmup()
// 1. Enable the Nav Inspector and click the link
await openInstantNavPanel(browser)
await clickStartCapturing(browser)
await clickLink(
browser,
'/target-page/my-post?search=foo',
'link-to-target-prefetch'
)
await expectSpaPanel(browser)
// 2. Close the Nav Inspector and navigate home
await closePanelViaHeader(browser)
await waitForPanelRouterTransition()
await waitForInstantModeCookieAbsent(browser)
await clickLink(browser, '/')
await browser.waitForElementByCss('[data-testid="home-title"]')
await waitForAppHydration(browser)
// 3. Enable the inspector and click the link again. This used to hang
// in a pending state while firing an infinite loop of prefetch
// requests: the previous capture's runtime-prefetch entries survive in
// the segment cache at concrete vary paths, shadowing the entries the
// new capture's prefetch creates at the more generic shell vary paths,
// so every scheduler pass discarded and refetched forever.
await reopenInstantNavPanelFromMenu(browser)
await expectIdlePanel(browser)
await clickStartCapturing(browser)
await clickLink(
browser,
'/target-page/my-post?search=foo',
'link-to-target-prefetch'
)
await expectSpaPanel(browser)
})
it('should restart capture and return to awaiting navigation after resuming from SPA state', async () => {
const browser = await openHomeWithTargetPageWarmup()
......
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