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

Fix prefetch loop when a predicted route redirects (#98998)

A full or runtime prefetch (e.g. `router.prefetch(url, { kind: 'full'
})` or `<Link prefetch={true}>`) of a URL that matched a learned route
pattern but is redirected by the server (e.g. `/docs/changelog` →
`/changelog` while `/docs/alpha` renders `[collection]/[...slug]`)
caused the client to re-issue the same prefetch indefinitely, at
whatever rate the network allowed, until the tab was closed.

When the server contradicts a route prediction, the client is supposed
to remember that the URL shape can't be predicted and resolve it on the
server from then on. We were storing this information
(`hasDynamicRewrite`) in the wrong place: on the predicted route cache
entry, rather than the optimistic routing table that's used to generate
predictions.

The fix moves the `hasDynamicRewrite` flag to the optimistic routing
table so it applies to all subsequent optimistic routing predictions.

Fixes #98345.

<!-- NEXT_JS_LLM -->
parent a18b9a58
...@@ -34,7 +34,6 @@ import { ...@@ -34,7 +34,6 @@ import {
convertReusedFlightRouterStateToRouteTree, convertReusedFlightRouterStateToRouteTree,
readSegmentCacheEntryForNavigation, readSegmentCacheEntryForNavigation,
waitForSegmentCacheEntry, waitForSegmentCacheEntry,
markRouteEntryAsDynamicRewrite,
invalidateRouteCacheEntries, invalidateRouteCacheEntries,
spawnStaticStageCacheWrite, spawnStaticStageCacheWrite,
writeRuntimePrefetchStreamIntoCache, writeRuntimePrefetchStreamIntoCache,
...@@ -1712,10 +1711,15 @@ function dispatchRetryDueToTreeMismatch( ...@@ -1712,10 +1711,15 @@ function dispatchRetryDueToTreeMismatch(
| FreshnessPolicy.RefreshAll | FreshnessPolicy.RefreshAll
| FreshnessPolicy.HistoryTraversal | FreshnessPolicy.HistoryTraversal
) { ) {
// If the navigation used a route prediction, mark it as having a dynamic // If the navigation used a route prediction, mark the node it was predicted
// rewrite since it resulted in a mismatch. // from as having a dynamic rewrite since it resulted in a mismatch. A route
// entry the server resolved has nothing to mark: nothing was predicted
// from it.
if (routeCacheEntry !== null) { if (routeCacheEntry !== null) {
markRouteEntryAsDynamicRewrite(routeCacheEntry) const predictedFrom = routeCacheEntry.predictedFrom
if (predictedFrom !== null) {
predictedFrom.hasDynamicRewrite = true
}
} else if (seed !== null) { } else if (seed !== null) {
// Even without a direct reference to the route cache entry, we can still // Even without a direct reference to the route cache entry, we can still
// mark the route as having a dynamic rewrite by traversing the known route // mark the route as having a dynamic rewrite by traversing the known route
...@@ -1740,8 +1744,9 @@ function dispatchRetryDueToTreeMismatch( ...@@ -1740,8 +1744,9 @@ function dispatchRetryDueToTreeMismatch(
} }
} }
// Invalidate all route cache entries. Other entries may have been derived // Invalidate all route cache entries. If the navigation used a route entry
// from the template before we knew it had a dynamic rewrite. This also // the server resolved, its tree is what the server just contradicted, so
// the retry must re-fetch it rather than navigate with it again. This also
// triggers re-prefetching of visible links. // triggers re-prefetching of visible links.
invalidateRouteCacheEntries(retryNextUrl, baseTree) invalidateRouteCacheEntries(retryNextUrl, baseTree)
......
...@@ -92,7 +92,11 @@ import { pingVisibleLinks } from '../links' ...@@ -92,7 +92,11 @@ import { pingVisibleLinks } from '../links'
import { FetchStrategy } from './types' import { FetchStrategy } from './types'
import { createPromiseWithResolvers } from '../../../shared/lib/promise-with-resolvers' import { createPromiseWithResolvers } from '../../../shared/lib/promise-with-resolvers'
import { readFromBFCache, UnknownDynamicStaleTime } from './bfcache' import { readFromBFCache, UnknownDynamicStaleTime } from './bfcache'
import { discoverKnownRoute, matchKnownRoute } from './optimistic-routes' import {
discoverKnownRoute,
matchKnownRoute,
type KnownRoutePart,
} from './optimistic-routes'
import { import {
createNavigationSeed, createNavigationSeed,
decodeTransportTreeIntoRouteTree, decodeTransportTreeIntoRouteTree,
...@@ -250,17 +254,17 @@ type RouteCacheEntryShared = { ...@@ -250,17 +254,17 @@ type RouteCacheEntryShared = {
// received a response from the server. // received a response from the server.
couldBeIntercepted: boolean couldBeIntercepted: boolean
// When true, this entry should not be used as a template for route // The node in the known route tree whose pattern this entry was predicted
// prediction. Set when we discover that the URL was rewritten by middleware // from (see matchKnownRoute); the path from the root to that node is the
// to a different route structure (e.g., /foo was rewritten to /bar). Since // URL shape. Null for entries the server resolved. A predicted entry is a
// rewrite behavior can vary by param value, we can't safely predict the // guess that the URL's rewrite (if any) behaves statically; if the server's
// route structure for other URLs matching this pattern. // rendered tree diverges from it, the node is marked so the shape is never
// predicted again (see KnownRoutePart.hasDynamicRewrite).
// //
// This is declared on every entry variant (not just fulfilled entries) so // This is declared on every entry variant (not just fulfilled entries) so
// that all RouteCacheEntry objects share a single hidden class; it is // that all RouteCacheEntry objects share a single hidden class; it is
// pre-initialized to `false` when the entry is created and only meaningful // pre-initialized to `null` when the entry is created.
// once the entry is fulfilled. predictedFrom: KnownRoutePart | null
hasDynamicRewrite: boolean
// Map-related fields. // Map-related fields.
ref: UnknownMapEntry | null ref: UnknownMapEntry | null
...@@ -690,7 +694,7 @@ function createDetachedRouteCacheEntry(): PendingRouteCacheEntry { ...@@ -690,7 +694,7 @@ function createDetachedRouteCacheEntry(): PendingRouteCacheEntry {
couldBeIntercepted: true, couldBeIntercepted: true,
// Similarly, we don't yet know if the route supports PPR. // Similarly, we don't yet know if the route supports PPR.
supportsPerSegmentPrefetching: false, supportsPerSegmentPrefetching: false,
hasDynamicRewrite: false, predictedFrom: null,
renderedSearch: null, renderedSearch: null,
// Map-related fields // Map-related fields
...@@ -842,7 +846,7 @@ export function deprecated_requestOptimisticRouteCacheEntry( ...@@ -842,7 +846,7 @@ export function deprecated_requestOptimisticRouteCacheEntry(
couldBeIntercepted: routeWithNoSearchParams.couldBeIntercepted, couldBeIntercepted: routeWithNoSearchParams.couldBeIntercepted,
supportsPerSegmentPrefetching: supportsPerSegmentPrefetching:
routeWithNoSearchParams.supportsPerSegmentPrefetching, routeWithNoSearchParams.supportsPerSegmentPrefetching,
hasDynamicRewrite: routeWithNoSearchParams.hasDynamicRewrite, predictedFrom: null,
// Override the rendered search with the optimistic value. // Override the rendered search with the optimistic value.
renderedSearch: optimisticRenderedSearch, renderedSearch: optimisticRenderedSearch,
...@@ -1559,7 +1563,6 @@ export function fulfillRouteCacheEntry( ...@@ -1559,7 +1563,6 @@ export function fulfillRouteCacheEntry(
fulfilledEntry.canonicalUrl = canonicalUrl fulfilledEntry.canonicalUrl = canonicalUrl
fulfilledEntry.renderedSearch = renderedSearch fulfilledEntry.renderedSearch = renderedSearch
fulfilledEntry.supportsPerSegmentPrefetching = supportsPerSegmentPrefetching fulfilledEntry.supportsPerSegmentPrefetching = supportsPerSegmentPrefetching
fulfilledEntry.hasDynamicRewrite = false
pingBlockedTasks(entry) pingBlockedTasks(entry)
return fulfilledEntry return fulfilledEntry
} }
...@@ -1596,24 +1599,6 @@ export function writeRouteIntoCache( ...@@ -1596,24 +1599,6 @@ export function writeRouteIntoCache(
return fulfilledEntry return fulfilledEntry
} }
/**
* Marks a route cache entry as having a dynamic rewrite. Called when we
* discover that a route pattern has dynamic rewrite behavior - i.e., we used
* an optimistic route tree for prediction, but the server responded with a
* different rendered pathname.
*
* Once marked, attempts to use this entry as a template for prediction will
* bail out to server resolution.
*/
export function markRouteEntryAsDynamicRewrite(
entry: FulfilledRouteCacheEntry
): void {
entry.hasDynamicRewrite = true
// Note: The caller is responsible for also calling invalidateRouteCacheEntries
// to invalidate other entries that may have been derived from this template
// before we knew it had a dynamic rewrite.
}
function fulfillSegmentCacheEntry( function fulfillSegmentCacheEntry(
segmentCacheEntry: PendingSegmentCacheEntry, segmentCacheEntry: PendingSegmentCacheEntry,
rsc: React.ReactNode, rsc: React.ReactNode,
...@@ -2669,15 +2654,20 @@ export async function fetchSegmentPrefetchesUsingRuntimeRequest( ...@@ -2669,15 +2654,20 @@ export async function fetchSegmentPrefetchesUsingRuntimeRequest(
const buildId = const buildId =
response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b
// When the request tree was derived from the route entry's stored // When the request tree was derived from a predicted route entry, pass the
// prediction, pass the entry to the write path so it can be marked if the // node it was predicted from to the write path so the prediction can be
// server's rendered tree diverges from the prediction. A head-only // disabled if the server's rendered tree diverges from it. For an entry
// request uses the MetadataOnlyRequestTree stub rather than a tree // the server resolved this is null: a divergence from it says nothing
// derived from the route entry, so divergence from it carries no signal. // about route prediction, and its unfulfilled entries take the usual
// backoff. A head-only request uses the MetadataOnlyRequestTree stub
// rather than a tree derived from the route entry, so divergence from it
// carries no signal.
// TODO: This special case goes away once the response is diffed against // TODO: This special case goes away once the response is diffed against
// the base RouteTree (route.tree) instead of the request tree. // the base RouteTree (route.tree) instead of the request tree.
const predictedFromRoute = const predictedFrom =
dynamicRequestTree !== MetadataOnlyRequestTree ? route : null dynamicRequestTree !== MetadataOnlyRequestTree
? route.predictedFrom
: null
// Extract the response's shell-stage payload, when it carries one. No // Extract the response's shell-stage payload, when it carries one. No
// shell can be extracted without cache metadata (only present when // shell can be extracted without cache metadata (only present when
...@@ -2698,12 +2688,6 @@ export async function fetchSegmentPrefetchesUsingRuntimeRequest( ...@@ -2698,12 +2688,6 @@ export async function fetchSegmentPrefetchesUsingRuntimeRequest(
fetchStrategy === FetchStrategy.RuntimeShell) && fetchStrategy === FetchStrategy.RuntimeShell) &&
(cacheData?.isResponsePartial ?? false) (cacheData?.isResponsePartial ?? false)
// Captured immediately before the write — in the same synchronous
// block, so the false→true transition observed below can only have been
// caused by this write, not by a concurrent response for the same route
// marking the entry during one of the awaits above.
const routeHadDynamicRewrite = route.hasDynamicRewrite
// Aside from writing the data into the cache, this also returns the // Aside from writing the data into the cache, this also returns the
// entries that were fulfilled, so we can streamingly update their sizes // entries that were fulfilled, so we can streamingly update their sizes
// in the LRU as more data comes in (Full responses, which stream). // in the LRU as more data comes in (Full responses, which stream).
...@@ -2713,7 +2697,7 @@ export async function fetchSegmentPrefetchesUsingRuntimeRequest( ...@@ -2713,7 +2697,7 @@ export async function fetchSegmentPrefetchesUsingRuntimeRequest(
serverData, serverData,
shellResponse, shellResponse,
dynamicRequestTree, dynamicRequestTree,
predictedFromRoute, predictedFrom,
// Navigation responses always include the param values in the tree, so // Navigation responses always include the param values in the tree, so
// there's no pathname to parse them from (nor a need to). // there's no pathname to parse them from (nor a need to).
null, null,
...@@ -2727,21 +2711,6 @@ export async function fetchSegmentPrefetchesUsingRuntimeRequest( ...@@ -2727,21 +2711,6 @@ export async function fetchSegmentPrefetchesUsingRuntimeRequest(
task.segmentCacheMap task.segmentCacheMap
) )
if (!routeHadDynamicRewrite && route.hasDynamicRewrite) {
// The write path discovered that the server rendered a different route
// tree than the prediction this request was derived from, and marked
// the route entry (see writeServerResponseIntoCache). Invalidate
// entries that were derived from the prediction so they're
// re-prefetched against the server's actual tree. This mirrors
// dispatchRetryDueToTreeMismatch on the navigation path. It can't loop:
// the refetched route entry is built from the server's response, so it
// only mismatches again if the rewrite's behavior changes again.
// TODO: Consider also bounding retries with a counter on the task
// object, so a prefetch that repeatedly fails to settle backs off
// regardless of the reason.
invalidateRouteCacheEntries(key.nextUrl, task.treeAtTimeOfPrefetch)
}
// Return a promise that resolves when the network connection closes, so // Return a promise that resolves when the network connection closes, so
// the scheduler can track the number of concurrent network connections. // the scheduler can track the number of concurrent network connections.
return { value: null, closed: closed.promise } return { value: null, closed: closed.promise }
...@@ -2794,7 +2763,7 @@ function writeResponsePayloadsIntoCache( ...@@ -2794,7 +2763,7 @@ function writeResponsePayloadsIntoCache(
// The next five are threaded through to every write; see // The next five are threaded through to every write; see
// writeServerResponseIntoCache for their meaning. // writeServerResponseIntoCache for their meaning.
baseTree: FlightRouterState | null, baseTree: FlightRouterState | null,
predictedFromRoute: FulfilledRouteCacheEntry | null, predictedFrom: KnownRoutePart | null,
renderedPathname: string | null, renderedPathname: string | null,
renderedSearch: string, renderedSearch: string,
buildId: string | undefined, buildId: string | undefined,
...@@ -2844,7 +2813,7 @@ function writeResponsePayloadsIntoCache( ...@@ -2844,7 +2813,7 @@ function writeResponsePayloadsIntoCache(
FetchStrategy.PPR, FetchStrategy.PPR,
fullPayload, fullPayload,
baseTree, baseTree,
predictedFromRoute, predictedFrom,
renderedPathname, renderedPathname,
renderedSearch, renderedSearch,
buildId, buildId,
...@@ -2874,7 +2843,7 @@ function writeResponsePayloadsIntoCache( ...@@ -2874,7 +2843,7 @@ function writeResponsePayloadsIntoCache(
fetchStrategy, fetchStrategy,
fullPayload, fullPayload,
baseTree, baseTree,
predictedFromRoute, predictedFrom,
renderedPathname, renderedPathname,
renderedSearch, renderedSearch,
buildId, buildId,
...@@ -2926,7 +2895,7 @@ function writeResponsePayloadsIntoCache( ...@@ -2926,7 +2895,7 @@ function writeResponsePayloadsIntoCache(
fetchStrategy, fetchStrategy,
fullPayload, fullPayload,
baseTree, baseTree,
predictedFromRoute, predictedFrom,
renderedPathname, renderedPathname,
renderedSearch, renderedSearch,
buildId, buildId,
...@@ -3016,7 +2985,7 @@ function writeResponsePayloadsIntoCache( ...@@ -3016,7 +2985,7 @@ function writeResponsePayloadsIntoCache(
responseFetchStrategy, responseFetchStrategy,
fullPayload, fullPayload,
baseTree, baseTree,
predictedFromRoute, predictedFrom,
renderedPathname, renderedPathname,
renderedSearch, renderedSearch,
buildId, buildId,
...@@ -3033,7 +3002,7 @@ function writeResponsePayloadsIntoCache( ...@@ -3033,7 +3002,7 @@ function writeResponsePayloadsIntoCache(
shellFetchStrategy, shellFetchStrategy,
shellPayload, shellPayload,
baseTree, baseTree,
predictedFromRoute, predictedFrom,
renderedPathname, renderedPathname,
renderedSearch, renderedSearch,
buildId, buildId,
...@@ -3099,19 +3068,18 @@ function writeServerResponseIntoCache( ...@@ -3099,19 +3068,18 @@ function writeServerResponseIntoCache(
// The base router state the response overlays. Null when the response's // The base router state the response overlays. Null when the response's
// tree is root-anchored (per-segment prefetch payloads). // tree is root-anchored (per-segment prefetch payloads).
baseTree: FlightRouterState | null, baseTree: FlightRouterState | null,
// Non-null when `baseTree` was derived from this route entry. Any // Non-null when `baseTree` was predicted: the node in the known route tree
// route-derived request tree is a prediction that the URL's rewrite (if // whose pattern it was predicted from (see matchKnownRoute). The
// any) behaves statically; if the server's rendered tree diverges from the // prediction assumes the URL's rewrite (if any) behaves statically; if the
// base, that prediction failed — the rewrite behaves dynamically, so the // server's rendered tree diverges from the base, that prediction failed —
// params baked into the request are wrong. The entry is marked as having a // the rewrite behaves dynamically, so the params baked into the request
// dynamic rewrite — the entry doubles as the stored prediction pattern // are wrong. The node is marked so the shape is never predicted again, and
// (see matchKnownRoute), so this also disables a bad prediction that would // the entries that could not be fulfilled are rejected with immediate
// otherwise be re-derived on every retry. The response data is still // expiration so the task retries right away — against the server-resolved
// written into the cache: it's real data keyed by what the server actually // route this time. The response data is still written into the cache: it's
// rendered, useful regardless of whether the prediction matched. The // real data keyed by what the server actually rendered, useful regardless
// caller is responsible for invalidating entries derived from the // of whether the prediction matched.
// prediction (see markRouteEntryAsDynamicRewrite). predictedFrom: KnownRoutePart | null,
predictedFromRoute: FulfilledRouteCacheEntry | null,
// The pathname the response was rendered for, used to resolve dynamic // The pathname the response was rendered for, used to resolve dynamic
// segments the server sent without a param value (`k: null`). Null for // segments the server sent without a param value (`k: null`). Null for
// responses that always carry concrete values (navigation responses). // responses that always carry concrete values (navigation responses).
...@@ -3204,9 +3172,9 @@ function writeServerResponseIntoCache( ...@@ -3204,9 +3172,9 @@ function writeServerResponseIntoCache(
0 0
const treeDivergedFromPrediction = const treeDivergedFromPrediction =
predictedFromRoute !== null && navigationSeed.treeDivergedFromBase predictedFrom !== null && navigationSeed.treeDivergedFromBase
if (treeDivergedFromPrediction) { if (treeDivergedFromPrediction) {
markRouteEntryAsDynamicRewrite(predictedFromRoute) predictedFrom.hasDynamicRewrite = true
} }
// Only static (per-segment) responses can be ISR fallbacks (`f`). A // Only static (per-segment) responses can be ISR fallbacks (`f`). A
...@@ -3314,8 +3282,9 @@ function writeServerResponseIntoCache( ...@@ -3314,8 +3282,9 @@ function writeServerResponseIntoCache(
// When the response diverged from the prediction, the leftover entries // When the response diverged from the prediction, the leftover entries
// can never be fulfilled — their keys were derived from the wrong // can never be fulfilled — their keys were derived from the wrong
// tree. Reject with an immediate expiration instead of the usual // tree. Reject with an immediate expiration instead of the usual
// backoff: the caller invalidates the route, which triggers a // backoff so the task retries right away. The prediction was disabled
// re-prefetch against the server's actual tree. // above, so the retry resolves the route on the server instead of
// predicting it again.
treeDivergedFromPrediction ? -1 : now + REJECTION_BACKOFF_MS treeDivergedFromPrediction ? -1 : now + REJECTION_BACKOFF_MS
) )
} }
......
...@@ -130,6 +130,16 @@ type KnownRoutePartBase = { ...@@ -130,6 +130,16 @@ type KnownRoutePartBase = {
// tree, like we do for static siblings, and attempting to match both. // tree, like we do for static siblings, and attempting to match both.
hasConflictingDynamicChildren: boolean hasConflictingDynamicChildren: boolean
// True once a prediction made from this node's pattern was contradicted by
// the server: the URL has a rewrite or redirect that behaves dynamically
// (e.g. /docs/changelog redirects to /changelog while /docs/alpha renders
// [collection]/[...slug]). Since rewrite behavior can vary by param value,
// no URL terminating at this node can be predicted safely, so matching
// bails out to server resolution. Lives on the node rather than on the
// pattern entry so it survives the pattern being evicted (by staleness or
// cache invalidation) and re-learned from a later response.
hasDynamicRewrite: boolean
// TODO: For prefix rewrite support. When true, this part may not appear in // TODO: For prefix rewrite support. When true, this part may not appear in
// the candidate URL because it was injected by a rewrite. Today, discovery // the candidate URL because it was injected by a rewrite. Today, discovery
// refuses to store a pattern for such routes (see the cache key comparison // refuses to store a pattern for such routes (see the cache key comparison
...@@ -151,7 +161,7 @@ type KnownRoutePartWithDynamicChild = KnownRoutePartBase & { ...@@ -151,7 +161,7 @@ type KnownRoutePartWithDynamicChild = KnownRoutePartBase & {
dynamicChildParamType: DynamicParamTypesShort dynamicChildParamType: DynamicParamTypesShort
} }
type KnownRoutePart = export type KnownRoutePart =
| KnownRoutePartWithoutDynamicChild | KnownRoutePartWithoutDynamicChild
| KnownRoutePartWithDynamicChild | KnownRoutePartWithDynamicChild
...@@ -197,6 +207,7 @@ function createEmptyPart(): KnownRoutePart { ...@@ -197,6 +207,7 @@ function createEmptyPart(): KnownRoutePart {
dynamicChildParamType: null, dynamicChildParamType: null,
pattern: null, pattern: null,
hasConflictingDynamicChildren: false, hasConflictingDynamicChildren: false,
hasDynamicRewrite: false,
} }
} }
...@@ -214,9 +225,9 @@ let knownRouteTreeRoot: KnownRoutePart = createEmptyPart() ...@@ -214,9 +225,9 @@ let knownRouteTreeRoot: KnownRoutePart = createEmptyPart()
* When pendingEntry is provided, it's fulfilled and used. When null, an entry * When pendingEntry is provided, it's fulfilled and used. When null, an entry
* is created and inserted into the route cache map. * is created and inserted into the route cache map.
* *
* When hasDynamicRewrite is true, the route entry is marked as having a * When hasDynamicRewrite is true, the node the route terminates at is marked
* dynamic rewrite, which prevents it from being used as a template for future * as having a dynamic rewrite, which prevents URLs of its shape from being
* predictions. This is set when we detect a mismatch between what we predicted * predicted. This is set when we detect a mismatch between what we predicted
* and what the server returned. * and what the server returned.
* *
* Returns the fulfilled route cache entry. * Returns the fulfilled route cache entry.
...@@ -249,9 +260,6 @@ export function discoverKnownRoute( ...@@ -249,9 +260,6 @@ export function discoverKnownRoute(
canonicalUrl, canonicalUrl,
supportsPerSegmentPrefetching supportsPerSegmentPrefetching
) )
if (hasDynamicRewrite) {
fulfilledEntry.hasDynamicRewrite = true
}
// Populate the known route tree (handles rewrite detection internally). // Populate the known route tree (handles rewrite detection internally).
// The entry is already in the cache; this just stores it as a pattern // The entry is already in the cache; this just stores it as a pattern
// if the URL matches the route structure. // if the URL matches the route structure.
...@@ -680,14 +688,15 @@ function discoverKnownRoutePart( ...@@ -680,14 +688,15 @@ function discoverKnownRoutePart(
) )
} }
// Reached a page node. Create/get the route cache entry and store as a // Reached a page node: the URL terminates here.
// pattern. First, check if there's already a pattern for this route. if (hasDynamicRewrite) {
knownRoutePart.hasDynamicRewrite = true
}
// Create/get the route cache entry and store as a pattern. First, check if
// there's already a pattern for this route.
const existingPattern = readPattern(now, knownRoutePart) const existingPattern = readPattern(now, knownRoutePart)
if (existingPattern !== null) { if (existingPattern !== null) {
// If this route has a dynamic rewrite, mark the existing pattern.
if (hasDynamicRewrite) {
existingPattern.hasDynamicRewrite = true
}
return existingPattern return existingPattern
} }
...@@ -712,10 +721,6 @@ function discoverKnownRoutePart( ...@@ -712,10 +721,6 @@ function discoverKnownRoutePart(
) )
} }
if (hasDynamicRewrite) {
entry.hasDynamicRewrite = true
}
// Store as pattern // Store as pattern
knownRoutePart.pattern = entry knownRoutePart.pattern = entry
return entry return entry
...@@ -800,13 +805,12 @@ export function matchKnownRoute( ...@@ -800,13 +805,12 @@ export function matchKnownRoute(
reifiedTree.prefetchHints reifiedTree.prefetchHints
) )
// Create a synthetic (predicted) entry and store it as the new pattern. // Create a synthetic (predicted) entry. It's not inserted into the route
// // cache; it lives only as long as the task or navigation that read it. It
// Why replace the pattern? We intentionally update the pattern with this // records the node it was predicted from so that if the prediction turns
// synthetic entry so that if our prediction was wrong (server returns a // out to be wrong (the server renders a different tree due to a dynamic
// different pathname due to dynamic rewrite), the entry gets marked with // rewrite), the node can be marked and the shape is never predicted again
// hasDynamicRewrite. Future predictions for this route will see the flag // (see KnownRoutePart.hasDynamicRewrite).
// and bail out to server resolution instead of making the same mistake.
const syntheticEntry: FulfilledRouteCacheEntry = { const syntheticEntry: FulfilledRouteCacheEntry = {
canonicalUrl: pathname + search, canonicalUrl: pathname + search,
status: EntryStatus.Fulfilled, status: EntryStatus.Fulfilled,
...@@ -815,7 +819,7 @@ export function matchKnownRoute( ...@@ -815,7 +819,7 @@ export function matchKnownRoute(
metadata: reifiedMetadata, metadata: reifiedMetadata,
couldBeIntercepted: pattern.couldBeIntercepted, couldBeIntercepted: pattern.couldBeIntercepted,
supportsPerSegmentPrefetching: pattern.supportsPerSegmentPrefetching, supportsPerSegmentPrefetching: pattern.supportsPerSegmentPrefetching,
hasDynamicRewrite: false, predictedFrom: matchedPart,
renderedSearch: search, renderedSearch: search,
ref: null, ref: null,
size: pattern.size, size: pattern.size,
...@@ -823,15 +827,13 @@ export function matchKnownRoute( ...@@ -823,15 +827,13 @@ export function matchKnownRoute(
version: pattern.version, version: pattern.version,
} }
matchedPart.pattern = syntheticEntry
return syntheticEntry return syntheticEntry
} }
/** /**
* Result of a successful match: the matched tree node and its pattern. * Result of a successful match: the matched tree node and its pattern.
* We return both because the caller needs to update the pattern after * We return both because the synthetic entry records the node it was
* creating a synthetic entry (for dynamic rewrite detection). * predicted from (for dynamic rewrite detection).
*/ */
type KnownRouteMatch = { type KnownRouteMatch = {
part: KnownRoutePart part: KnownRoutePart
...@@ -867,9 +869,9 @@ function matchKnownRoutePart( ...@@ -867,9 +869,9 @@ function matchKnownRoutePart(
// /blog/featured would incorrectly match /blog/[slug]. // /blog/featured would incorrectly match /blog/[slug].
if (part.staticChildren === null) { if (part.staticChildren === null) {
// The only safe match is a direct pattern when no URL parts remain. // The only safe match is a direct pattern when no URL parts remain.
if (urlPart === null) { if (urlPart === null && !part.hasDynamicRewrite) {
const pattern = readPattern(now, part) const pattern = readPattern(now, part)
if (pattern !== null && !pattern.hasDynamicRewrite) { if (pattern !== null) {
return { part, pattern } return { part, pattern }
} }
} }
...@@ -919,16 +921,16 @@ function matchKnownRoutePart( ...@@ -919,16 +921,16 @@ function matchKnownRoutePart(
const dynamicPart = part.dynamicChild const dynamicPart = part.dynamicChild
const paramName = part.dynamicChildParamName const paramName = part.dynamicChildParamName
const paramType = part.dynamicChildParamType const paramType = part.dynamicChildParamType
const dynamicPattern = readPattern(now, dynamicPart) // Catch-alls terminate at the dynamic child, so a dynamic rewrite marked
// there rules out predicting any URL that would end in it.
const dynamicPattern = dynamicPart.hasDynamicRewrite
? null
: readPattern(now, dynamicPart)
switch (paramType) { switch (paramType) {
case 'c': case 'c':
// Required catch-all [...param]: consumes 1+ URL parts // Required catch-all [...param]: consumes 1+ URL parts
if ( if (dynamicPattern !== null && urlPart !== null) {
dynamicPattern !== null &&
!dynamicPattern.hasDynamicRewrite &&
urlPart !== null
) {
resolvedParams.set( resolvedParams.set(
paramName, paramName,
pathnameParts.slice(partIndex).map(canonicalizeURLPart).join('/') pathnameParts.slice(partIndex).map(canonicalizeURLPart).join('/')
...@@ -938,7 +940,7 @@ function matchKnownRoutePart( ...@@ -938,7 +940,7 @@ function matchKnownRoutePart(
break break
case 'oc': { case 'oc': {
// Optional catch-all [[...param]]: consumes 0+ URL parts // Optional catch-all [[...param]]: consumes 0+ URL parts
if (dynamicPattern !== null && !dynamicPattern.hasDynamicRewrite) { if (dynamicPattern !== null) {
if (urlPart !== null) { if (urlPart !== null) {
resolvedParams.set( resolvedParams.set(
paramName, paramName,
...@@ -948,8 +950,10 @@ function matchKnownRoutePart( ...@@ -948,8 +950,10 @@ function matchKnownRoutePart(
} }
// urlPart is null - can match with zero parts, but a direct pattern // urlPart is null - can match with zero parts, but a direct pattern
// (e.g., page.tsx alongside [[...param]]) takes precedence. // (e.g., page.tsx alongside [[...param]]) takes precedence.
const directPattern = readPattern(now, part) const directPattern = part.hasDynamicRewrite
if (directPattern === null || directPattern.hasDynamicRewrite) { ? null
: readPattern(now, part)
if (directPattern === null) {
resolvedParams.set(paramName, '') resolvedParams.set(paramName, '')
return { part: dynamicPart, pattern: dynamicPattern } return { part: dynamicPart, pattern: dynamicPattern }
} }
...@@ -990,9 +994,9 @@ function matchKnownRoutePart( ...@@ -990,9 +994,9 @@ function matchKnownRoutePart(
// No children matched. If we've consumed all URL parts, check for a direct // No children matched. If we've consumed all URL parts, check for a direct
// pattern at this node (the route terminates here). // pattern at this node (the route terminates here).
if (urlPart === null) { if (urlPart === null && !part.hasDynamicRewrite) {
const pattern = readPattern(now, part) const pattern = readPattern(now, part)
if (pattern !== null && !pattern.hasDynamicRewrite) { if (pattern !== null) {
return { part, pattern } return { part, pattern }
} }
} }
......
import { connection } from 'next/server'
import { Suspense } from 'react'
import { LinkAccordion } from '../../../components/link-accordion'
import { PrefetchButton } from '../../../components/prefetch-button'
type Params = Promise<{ collection: string; slug: string[] }>
// A sidebar of links under the same route, like the reported site.
const SIDEBAR = ['beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta']
// A static shell with one dynamic hole, so a full prefetch of a page under
// this route needs a runtime request rather than just the static segment data.
export default function DocsPage({ params }: { params: Params }) {
return (
<>
<h1>A page under [collection]/[...slug]</h1>
<Suspense fallback={<p>Loading docs...</p>}>
<Body params={params} />
</Suspense>
<ul>
{SIDEBAR.map((slug) => (
<li key={slug}>
<LinkAccordion href={`/docs/${slug}`}>/docs/{slug}</LinkAccordion>
</li>
))}
</ul>
<PrefetchButton href="/docs/changelog" />
</>
)
}
async function Body({ params }: { params: Params }) {
const { collection, slug } = await params
await connection()
return (
<p id="docs-params">
{collection}/{slug.join('/')}
</p>
)
}
export default function ChangelogPage() {
return (
<>
<h1 id="changelog-page">Changelog</h1>
<p>A static route. /docs/changelog redirects here with a 308.</p>
</>
)
}
import type { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: LinkProps['href']
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
// This component controls when prefetching happens by hiding the Link until
// the checkbox is clicked. Prefetch triggers when the Link enters the viewport.
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
`${children} (link is hidden)`
)}
</>
)
}
'use client'
import { useRouter } from 'next/navigation'
type Router = ReturnType<typeof useRouter>
type PrefetchOptions = Parameters<Router['prefetch']>[1]
export function PrefetchButton({ href }: { href: string }) {
const router = useRouter()
return (
<button
data-prefetch-full={href}
onClick={() =>
router.prefetch(href, {
kind: 'full' as NonNullable<PrefetchOptions>['kind'],
})
}
>
router.prefetch({href}, {'{ kind: "full" }'})
</button>
)
}
/** @type {import('next').NextConfig} */
module.exports = {
cacheComponents: true,
partialPrefetching: true,
async redirects() {
return [
{
// A URL under the dynamic [collection]/[...slug] route permanently
// redirects to a static route whose tree has a different shape.
source: '/docs/changelog',
destination: '/changelog',
permanent: true,
},
]
},
}
import { nextTestSetup } from 'e2e-utils'
import { createRouterAct } from 'router-act'
import type { Page, Request } from 'playwright'
// Prefetching is disabled in dev, and route prediction only happens in a
// production build.
// @force-gate prefetching
describe('optimistic routing - redirect prefetch loop regression', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('does not loop when a full prefetch of a predicted route is redirected', async () => {
let act: ReturnType<typeof createRouterAct>
// Pre-fix, a single router.prefetch of the redirecting URL made the router
// request that URL again and again, indefinitely. Under that loop, `act`'s
// flush keeps observing new requests and never settles — so instead of
// waiting for a jest timeout, each `act` is raced against a promise that
// rejects once the URL has been requested more times than any correct
// sequence needs. This fails fast with a legible error on a buggy build
// and is a no-op on a correct one.
const REDIRECTING_URL = '/docs/changelog'
const MAX_REQUESTS_TO_REDIRECTING_URL = 5
let requestsToRedirectingUrl = 0
let rejectOnLoop!: (error: Error) => void
const loopDetected = new Promise<never>((_, reject) => {
rejectOnLoop = reject
})
// Mark the rejection as handled in case it fires while no race is
// pending; the final assertions still catch it.
loopDetected.catch(() => {})
async function actExpectingNoLoop<T>(
scope: () => Promise<T> | T,
config?: Parameters<typeof act>[1]
): Promise<unknown> {
const actPromise = act(scope, config)
// If the race rejects first, `act` keeps running until the page is torn
// down; swallow its eventual rejection so it doesn't surface as an
// unhandled promise rejection.
actPromise.catch(() => {})
return Promise.race([actPromise, loopDetected])
}
const browser = await next.browser('/docs/alpha', {
beforePageLoad(page: Page) {
act = createRouterAct(page)
page.on('request', (request: Request) => {
if (new URL(request.url()).pathname !== REDIRECTING_URL) {
return
}
requestsToRedirectingUrl++
if (requestsToRedirectingUrl > MAX_REQUESTS_TO_REDIRECTING_URL) {
rejectOnLoop(
new Error(
`${REDIRECTING_URL} was requested more than ` +
`${MAX_REQUESTS_TO_REDIRECTING_URL} times after a single ` +
'prefetch. The URL redirects, so one attempt is enough to ' +
'learn that; a client that keeps asking is looping.'
)
)
}
})
},
})
// The initial page load renders /docs/alpha via [collection]/[...slug],
// which is when the client learns the pattern for that URL shape.
expect(await browser.elementById('docs-params').text()).toBe('docs/alpha')
// Reveal the sidebar links. Their routes are predicted from the pattern
// and their shell is already cached, so revealing them makes no requests —
// which is also what proves the pattern was learned.
//
// They matter for the pre-fix behavior: the redirected response
// invalidated the whole route cache, and the visible links re-fetched
// their route trees ahead of the prefetch task, re-learning the pattern
// the task then predicted the redirecting URL from again.
await actExpectingNoLoop(async () => {
for (const slug of ['beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta']) {
const toggle = await browser.elementByCss(
`input[data-link-accordion="/docs/${slug}"]`
)
await toggle.click()
}
}, 'no-requests')
// Imperatively prefetch the redirecting URL with `kind: 'full'`. The URL
// matches the learned pattern, so the client predicts its route; the
// server redirects to /changelog and renders a different tree. The client
// must take the redirected response, resolve the route for real, and
// settle. `act` returning at all proves the prefetch queue settled
// instead of looping.
await actExpectingNoLoop(async () => {
const button = await browser.elementByCss(
`button[data-prefetch-full="${REDIRECTING_URL}"]`
)
await button.click()
})
// The prefetch completed: navigating to the redirecting URL is served
// entirely from the cache, and lands on the redirect target.
await actExpectingNoLoop(async () => {
await browser.eval(
`window.next.router.push(${JSON.stringify(REDIRECTING_URL)})`
)
}, 'no-requests')
expect(await browser.elementById('changelog-page').text()).toBe('Changelog')
expect(await browser.url()).toBe(`${next.url}/changelog`)
})
})
...@@ -705,6 +705,79 @@ ${fulfilled.body} ...@@ -705,6 +705,79 @@ ${fulfilled.body}
} else { } else {
if (route !== null) { if (route !== null) {
const request = route.request() const request = route.request()
// When fulfilling a redirect, for some reason, the page.route()
// handler installed earlier will not intercept the redirect
// request. Install an event listener to wait for the redirected
// request to finish. This works for this case because we don't
// need to modify or delay the response; we only need to observe
// when it has finished. The listener must be installed before
// fulfilling: the browser can issue the redirected request as
// soon as it receives the redirect, and a listener installed
// afterwards would miss it and latch onto whatever router
// request happens next — a request this act scope is itself
// holding, which would never receive a response.
// TODO: Because this request cannot be intercepted, it's
// incompatible with the "block" option. I haven't yet figured out
// a strategy to make that work. In the meantime, attempting to
// write a test that blocks a redirect will result in an error
// (see error above).
const redirectedRequestFinished =
fulfilled.status === 307 || fulfilled.status === 308
? new Promise<void>((resolve, reject) => {
const handleRequest = (req: Playwright.Request) => {
if (req.redirectedFrom()?.url() !== request.url()) {
return
}
page.off('request', handleRequest)
const handleResponse = (res: Playwright.Response) => {
if (res.url() === req.url()) {
batch.pendingRequests.add({
url: req.url(),
route: null,
result: (async () => {
return {
// For redirects, body may not be available,
// so catch the error and return an empty
// string.
text: await res.text().catch(() => ''),
body: await res
.body()
.catch(() => Buffer.from('')),
headers: res.headers(),
status: res.status(),
}
})(),
didProcess: false,
// The target of a redirect is a navigation, not
// an App Shell prefetch.
isAppShell: false,
// Navigations have no prefetch kind.
kind: undefined,
})
batch.didReceiveRouterRequest = true
page.off('response', handleResponse)
page.off('requestfailed', handleFailure)
resolve()
}
}
const handleFailure = (
failedReq: Playwright.Request
) => {
if (failedReq.url() === req.url()) {
page.off('response', handleResponse)
page.off('requestfailed', handleFailure)
error.message = `Request failed: ${failedReq.failure()?.errorText || 'Unknown error'}\n\nURL: ${req.url()}`
reject(error)
}
}
page.on('response', handleResponse)
page.on('requestfailed', handleFailure)
}
page.on('request', handleRequest)
})
: null
await route.fulfill({ await route.fulfill({
body: fulfilled.body, body: fulfilled.body,
headers: fulfilled.headers, headers: fulfilled.headers,
...@@ -718,63 +791,11 @@ ${fulfilled.body} ...@@ -718,63 +791,11 @@ ${fulfilled.body}
await browserResponse.finished() await browserResponse.finished()
} }
} }
}
}
if (fulfilled.status === 307 || fulfilled.status === 308) { if (redirectedRequestFinished !== null) {
// When fulfilling a redirect, for some reason, the page.route() await redirectedRequestFinished
// handler installed earlier will not intercept the }
// redirect request. Install a one-off event listener to wait for }
// the redirected request to finish. This works for this case
// because we don't need to modify to delay the response; we only
// need to observe when it has finished.
// TODO: Because this request cannot be intercepted, it's
// incompatible with the "block" option. I haven't yet figured out
// a strategy to make that work. In the meantime, attempting to
// write a test that blocks a redirect will result in an error
// (see error above).
await new Promise<void>((resolve, reject) => {
page.once('request', (req) => {
const handleResponse = (res: Playwright.Response) => {
if (res.url() === req.url()) {
batch.pendingRequests.add({
url: req.url(),
route: null,
result: (async () => {
return {
// For redirects, body may not be available, so catch
// the error and return an empty string.
text: await res.text().catch(() => ''),
body: await res.body().catch(() => Buffer.from('')),
headers: res.headers(),
status: res.status(),
}
})(),
didProcess: false,
// The target of a redirect is a navigation, not an App
// Shell prefetch.
isAppShell: false,
// Navigations have no prefetch kind.
kind: undefined,
})
batch.didReceiveRouterRequest = true
page.off('response', handleResponse)
page.off('requestfailed', handleFailure)
resolve()
}
}
const handleFailure = (failedReq: Playwright.Request) => {
if (failedReq.url() === req.url()) {
page.off('response', handleResponse)
page.off('requestfailed', handleFailure)
error.message = `Request failed: ${failedReq.failure()?.errorText || 'Unknown error'}\n\nURL: ${req.url()}`
reject(error)
}
}
page.on('response', handleResponse)
page.on('requestfailed', handleFailure)
})
})
} }
} }
......
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