Unverified Commit 75548c9a authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

[backport] Fix Nav Inspector request loop on repeat captures (#97326)

Backports #97050 ("Fix Nav Inspector request loop on repeat captures")
to `next-16-3`.

With the Nav Inspector enabled, clicking a `<Link prefetch={true}>`,
closing the inspector, navigating home, re-enabling it, and clicking the
same link left the app hung in a pending "Compiling…" state while it
fired 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. Because the segment cache resolves
lookups by most-specific-match, 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 — so every scheduler pass
discarded and refetched forever.

Rather than patch the filter, the fix replaces the `ownedEntries`
mechanism with a per-scope segment `CacheMap`. Each lock scope owns a
private map that starts empty and is discarded at release, so a captured
navigation structurally observes only data fetched under the lock. The
map is bound to a unit of work when it 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, history-traversal restores, 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, so the non-testing paths are unchanged.

### Verification on this branch

Cherry-picked from `5dc3ae1f`. Three files conflicted; each was
resolved by keeping the release branch's existing code shape and
applying only the fix's actual change — threading the segment `CacheMap`
through as an explicit parameter.

- **`refresh-reducer.ts`** and **`restore-reducer.ts`** — the conflicts
were confined to the import block. Canary imports
`convertServerPatchToFullTree` from
`./segment-cache/decode-server-response`, a module that doesn't exist on
this branch; `next-16-3` still imports it from
`./segment-cache/navigation`. I kept the release branch's import source
and added the new `segmentCacheMap` import alongside it. The
function-body changes (passing `segmentCacheMap` as the shared map)
applied cleanly, and the `startPPRNavigation`/`spawnDynamicRequests`
argument order lines up with this branch's signatures.

- **`cache.ts`** — the substantive one. `next-16-3` predates the
post-16.3.0 segment-cache refactors, so three areas differ from canary
and had to be adapted rather than taken verbatim from the patch: (1)
`RouteTree` is still non-generic here (`RouteTree`, not
`RouteTree<RSCSegmentData | null>` — this branch has no `RSCSegmentData`
and the tree doesn't carry render data), so the three signatures the
patch retyped were kept as plain `RouteTree`; (2)
`writeSegmentBundleResponse` still has the older `StaticShell`/`else`
re-key split guarded by `__NEXT_VARY_PARAMS`, versus canary's single
`upsertSegmentEntry` — I kept the release-branch logic and threaded
`map` into both of its `upsertSegmentEntry` calls; (3)
`writeDynamicRenderResponseIntoCache` and `writeSeedDataIntoCache` still
use the `flightDatas` + `CacheNodeSeedData` write model rather than
canary's route-tree-carries-data model — I kept the release-branch
traversal and threaded `map` into each `writeSeedDataIntoCache` /
`fulfillEntrySpawnedByRuntimePrefetch` call. Everything else in
`cache.ts` — the `ownedEntries` removal, the `segmentCacheMap` export,
`insertEmptySegmentCacheEntry`, and the `map` parameter added to every
read/write helper — applied cleanly and is identical to canary. I
confirmed no stale references to the removed `ownedEntries` /
`readSegmentCacheEntry` / `navigationLockPrefetch`-param APIs remain,
and that every call site of the retyped helpers passes a map.

The remaining files applied without conflict. `server-patch-reducer.ts`,
`navigation-testing-lock.ts`, `navigation-testing-lock.disabled.ts`, and
the `instant-navs-devtools` test are byte-identical to canary.
`create-initial-router-state.ts`, `ppr-navigations.ts`,
`server-action-reducer.ts`, `navigation.ts`, and `scheduler.ts` differ
from canary only in pre-existing `next-16-3` divergence (the older
transport-data / route-tree models); the fix's own hunks (the
`segmentCacheMap` threading) applied to them cleanly. No local typecheck
was run — this fresh worktree has no `node_modules` and installing it
carries the known corepack/SWC-binary gotchas — so behavioral and type
verification is left to CI on this branch, which carries the
`instant-navs-devtools` regression test from #96692.

**Reviewer, focus here:** the `writeSegmentBundleResponse` resolution in
`cache.ts` (area 2 above) is the hunk I'd most like a second pair of
eyes on. I preserved this branch's `StaticShell`/`else` re-key branch
structure and only inserted the `map` argument into its two
`upsertSegmentEntry` calls; please confirm that routing both branches'
writes through the task's bound map (rather than the module-level
`segmentCacheMap`) is the correct behavior for the older re-key logic.

<!-- NEXT_JS_LLM -->
Co-authored-by: 's avatarSam Selikoff <sam.selikoff@gmail.com>
parent f6bd714a
......@@ -10,6 +10,7 @@ import {
convertRootFlightRouterStateToRouteTree,
resolveStaleAt,
processRuntimePrefetchStream,
segmentCacheMap,
writeDynamicRenderResponseIntoCache,
writePrerenderResponseIntoCache,
} from '../segment-cache/cache'
......@@ -154,7 +155,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(() => {
......@@ -220,7 +223,8 @@ export function createInitialRouterState({
processed.rootVaryParamsIterable,
processed.staleAt,
processed.navigationSeed,
null
null,
segmentCacheMap // hydration writes are bound to the shared map
)
}
})
......
......@@ -26,6 +26,8 @@ import {
type NavigationSeed,
} from '../segment-cache/navigation'
import {
segmentCacheMap,
type SegmentCacheEntry,
type RouteTree,
type RefreshState,
type FulfilledRouteCacheEntry,
......@@ -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,
......@@ -180,6 +183,8 @@ export function createInitialCacheNodeForHydration(
seedDynamicStaleAt,
false,
accumulation,
// Hydration is bound to the shared map.
segmentCacheMap,
restrictToShell
)
return task
......@@ -228,6 +233,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
......@@ -254,6 +262,7 @@ export function startPPRNavigation(
oldRootRefreshState,
parentRefreshState,
accumulation,
map,
restrictToShell
)
}
......@@ -274,6 +283,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
......@@ -337,6 +347,7 @@ function updateCacheNodeOnNavigation(
seedDynamicStaleAt,
parentNeedsDynamicRequest,
accumulation,
map,
restrictToShell
)
}
......@@ -407,6 +418,7 @@ function updateCacheNodeOnNavigation(
oldCacheNode !== undefined
? oldCacheNode.bfcacheId
: generateBFCacheId(freshness),
map,
restrictToShell
)
newCacheNode = result.cacheNode
......@@ -551,6 +563,7 @@ function updateCacheNodeOnNavigation(
oldRootRefreshState,
refreshState,
accumulation,
map,
restrictToShell
)
......@@ -664,6 +677,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
......@@ -695,6 +709,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
......@@ -733,6 +748,7 @@ function createCacheNodeOnNavigation(
seedDynamicStaleAt,
parentNeedsDynamicRequest || needsDynamicRequest,
accumulation,
map,
restrictToShell
)
......@@ -959,6 +975,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
......@@ -1109,6 +1126,7 @@ function createCacheNodeForSegment(
const segmentEntry = readSegmentCacheEntryForNavigation(
now,
map,
tree.varyPath,
restrictToShell
)
......@@ -1216,6 +1234,7 @@ function createCacheNodeForSegment(
if (metadataVaryPath !== null) {
const metadataEntry = readSegmentCacheEntryForNavigation(
now,
map,
metadataVaryPath,
restrictToShell
)
......@@ -1425,6 +1444,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
......@@ -1451,6 +1473,7 @@ export function spawnDynamicRequests(
freshnessPolicy,
routeCacheEntry,
navigationLock,
map,
signal
)
......@@ -1505,6 +1528,7 @@ export function spawnDynamicRequests(
freshnessPolicy,
routeCacheEntry,
navigationLock,
map,
signal
)
)
......@@ -1783,6 +1807,7 @@ async function fetchMissingDynamicData(
freshnessPolicy: FreshnessPolicy,
routeCacheEntry: FulfilledRouteCacheEntry | null,
navigationLock: NavigationLock | null,
map: CacheMap<SegmentCacheEntry>,
signal: AbortSignal | undefined
): Promise<{
exitStatus: NavigationTaskExitStatus
......@@ -1847,7 +1872,8 @@ async function fetchMissingDynamicData(
staleAt,
dynamicRequestTree,
result.renderedSearch,
isResponsePartial
isResponsePartial,
map
)
})
.catch(() => {
......@@ -1875,7 +1901,8 @@ async function fetchMissingDynamicData(
processed.rootVaryParamsIterable,
processed.staleAt,
processed.navigationSeed,
null
null,
map
)
}
})
......
......@@ -8,7 +8,10 @@ import {
convertServerPatchToFullTree,
navigateToKnownRoute,
} from '../../segment-cache/navigation'
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 {
......@@ -100,6 +103,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,
convertServerPatchToFullTree,
} from '../../segment-cache/navigation'
import { segmentCacheMap } from '../../segment-cache/cache'
import { UnknownDynamicStaleTime } from '../../segment-cache/bfcache'
export function restoreReducer(
......@@ -73,6 +74,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
)
......@@ -97,6 +100,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
)
......
......@@ -47,7 +47,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'
......@@ -513,6 +516,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
......
......@@ -25,6 +25,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,
convertRootFlightRouterStateToRouteTree,
......@@ -37,6 +39,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'
......@@ -112,7 +115,9 @@ export function navigate(
freshnessPolicy,
scrollBehavior,
navigateType,
navigationLock
navigationLock,
// An unlocked navigation is bound to the shared map.
segmentCacheMap
)
}
......@@ -127,7 +132,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
......@@ -149,7 +157,8 @@ function navigateImpl(
scrollBehavior,
navigateType,
route,
navigationLock
navigationLock,
map
)
}
......@@ -186,7 +195,8 @@ function navigateImpl(
scrollBehavior,
navigateType,
optimisticRoute,
navigationLock
navigationLock,
map
)
}
}
......@@ -209,7 +219,8 @@ function navigateImpl(
freshnessPolicy,
scrollBehavior,
navigateType,
navigationLock
navigationLock,
map
).catch(() => {
// If the navigation fails, return the current state
return state
......@@ -231,6 +242,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
......@@ -345,6 +359,7 @@ export function navigateToKnownRoute(
navigationSeed.dynamicStaleAt,
isSamePageNavigation,
accumulation,
map,
restrictToShell
)
if (task !== null) {
......@@ -358,6 +373,7 @@ export function navigateToKnownRoute(
routeCacheEntry,
navigateType,
navigationLock,
map,
signal
)
}
......@@ -392,7 +408,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
......@@ -420,6 +437,7 @@ function navigateUsingPrefetchedRouteTree(
scrollBehavior,
navigateType,
navigationLock,
map,
null,
route,
// Not an HMR refresh, so there's no request generation to cancel.
......@@ -451,7 +469,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
......@@ -567,7 +586,8 @@ async function navigateToUnknownRoute(
staleAt,
currentFlightRouterState,
renderedSearch,
isResponsePartial
isResponsePartial,
map
)
})
.catch(() => {
......@@ -595,7 +615,8 @@ async function navigateToUnknownRoute(
processed.rootVaryParamsIterable,
processed.staleAt,
processed.navigationSeed,
null
null,
map
)
}
})
......@@ -636,6 +657,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
......@@ -1085,13 +1107,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,
......@@ -1104,7 +1126,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,
......@@ -1116,7 +1141,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