Unverified Commit 6270c09c authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Refactor: Unify history traversal with other nav types (#87128)

This merges the logic inside updateCacheNodeOnPopstateRestoration into
the function used for all other navigation types.

The main difference between history traversal navigations and other
navigation types is our treatment of dynamic data. History traversal
operations are allowed to reuse dynamic data regardless of its freshness
or staleness. So I've updated the `shouldRefreshDynamicData` argument to
be an enum that accounts for our various freshness policies. As of now,
there are three: Default, HistoryTraversal, and RefreshAll.

This is part of an ongoing series of refactors to unify all navigation
types into a single flow, both to simplify the implementation, and to
ensure the behavior is consistent.
parent c18fb497
...@@ -17,6 +17,7 @@ import { ...@@ -17,6 +17,7 @@ import {
} from '../../segment-cache/navigation' } from '../../segment-cache/navigation'
import { NavigationResultTag } from '../../segment-cache/types' import { NavigationResultTag } from '../../segment-cache/types'
import { getStaleTimeMs } from '../../segment-cache/cache' import { getStaleTimeMs } from '../../segment-cache/cache'
import { FreshnessPolicy } from '../ppr-navigations'
// These values are set by `define-env-plugin` (based on `nextConfig.experimental.staleTimes`) // These values are set by `define-env-plugin` (based on `nextConfig.experimental.staleTimes`)
// and default to 5 minutes (static) / 0 seconds (dynamic) // and default to 5 minutes (static) / 0 seconds (dynamic)
...@@ -161,14 +162,13 @@ export function navigateReducer( ...@@ -161,14 +162,13 @@ export function navigateReducer(
// implementation. Eventually we'll rewrite the router reducer to a // implementation. Eventually we'll rewrite the router reducer to a
// state machine. // state machine.
const currentUrl = new URL(state.canonicalUrl, location.origin) const currentUrl = new URL(state.canonicalUrl, location.origin)
const shouldRefreshDynamicData = false
const result = navigateUsingSegmentCache( const result = navigateUsingSegmentCache(
url, url,
currentUrl, currentUrl,
state.cache, state.cache,
state.tree, state.tree,
state.nextUrl, state.nextUrl,
shouldRefreshDynamicData, FreshnessPolicy.Default,
shouldScroll, shouldScroll,
mutable mutable
) )
......
...@@ -8,6 +8,7 @@ import { handleNavigationResult } from './navigate-reducer' ...@@ -8,6 +8,7 @@ import { handleNavigationResult } from './navigate-reducer'
import { navigateToSeededRoute } from '../../segment-cache/navigation' import { navigateToSeededRoute } from '../../segment-cache/navigation'
import { revalidateEntireCache } from '../../segment-cache/cache' import { revalidateEntireCache } from '../../segment-cache/cache'
import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree' import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'
import { FreshnessPolicy } from '../ppr-navigations'
export function refreshReducer( export function refreshReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
...@@ -33,7 +34,6 @@ export function refreshReducer( ...@@ -33,7 +34,6 @@ export function refreshReducer(
const url = currentUrl const url = currentUrl
const currentFlightRouterState = state.tree const currentFlightRouterState = state.tree
const shouldScroll = true const shouldScroll = true
const shouldRefreshDynamicData = true
const seedFlightRouterState = state.tree const seedFlightRouterState = state.tree
const seedRenderedSearch = state.renderedSearch const seedRenderedSearch = state.renderedSearch
...@@ -49,7 +49,7 @@ export function refreshReducer( ...@@ -49,7 +49,7 @@ export function refreshReducer(
seedRenderedSearch, seedRenderedSearch,
seedData, seedData,
seedHead, seedHead,
shouldRefreshDynamicData, FreshnessPolicy.RefreshAll,
nextUrlForRefresh, nextUrlForRefresh,
shouldScroll shouldScroll
) )
......
...@@ -5,15 +5,20 @@ import type { ...@@ -5,15 +5,20 @@ import type {
RestoreAction, RestoreAction,
} from '../router-reducer-types' } from '../router-reducer-types'
import { extractPathFromFlightRouterState } from '../compute-changed-path' import { extractPathFromFlightRouterState } from '../compute-changed-path'
import { updateCacheNodeOnPopstateRestoration } from '../ppr-navigations' import {
FreshnessPolicy,
listenForDynamicRequest,
startPPRNavigation,
type NavigationRequestAccumulation,
} from '../ppr-navigations'
import type { FlightRouterState } from '../../../../shared/lib/app-router-types' import type { FlightRouterState } from '../../../../shared/lib/app-router-types'
import { handleExternalUrl } from './navigate-reducer'
import type { Mutable } from '../router-reducer-types'
export function restoreReducer( export function restoreReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
action: RestoreAction action: RestoreAction
): ReducerState { ): ReducerState {
const { url, historyState } = action
const href = createHrefFromUrl(url)
// This action is used to restore the router state from the history state. // This action is used to restore the router state from the history state.
// However, it's possible that the history state no longer contains the `FlightRouterState`. // However, it's possible that the history state no longer contains the `FlightRouterState`.
// We will copy over the internal state on pushState/replaceState events, but if a history entry // We will copy over the internal state on pushState/replaceState events, but if a history entry
...@@ -22,6 +27,7 @@ export function restoreReducer( ...@@ -22,6 +27,7 @@ export function restoreReducer(
// In this case, we'll continue to use the existing tree so the router doesn't get into an invalid state. // In this case, we'll continue to use the existing tree so the router doesn't get into an invalid state.
let treeToRestore: FlightRouterState | undefined let treeToRestore: FlightRouterState | undefined
let renderedSearch: string | undefined let renderedSearch: string | undefined
const historyState = action.historyState
if (historyState) { if (historyState) {
treeToRestore = historyState.tree treeToRestore = historyState.tree
renderedSearch = historyState.renderedSearch renderedSearch = historyState.renderedSearch
...@@ -30,18 +36,54 @@ export function restoreReducer( ...@@ -30,18 +36,54 @@ export function restoreReducer(
renderedSearch = state.renderedSearch renderedSearch = state.renderedSearch
} }
const oldCache = state.cache const currentUrl = new URL(state.canonicalUrl, location.origin)
const newCache = process.env.__NEXT_PPR const restoredUrl = action.url
? // When PPR is enabled, we update the cache to drop the prefetch const restoredCanonicalUrl = createHrefFromUrl(restoredUrl)
// data for any segment whose dynamic data was already received. This const restoredNextUrl =
// prevents an unnecessary flash back to PPR state during a extractPathFromFlightRouterState(treeToRestore) ?? restoredUrl.pathname
// back/forward navigation.
updateCacheNodeOnPopstateRestoration(oldCache, treeToRestore) const now = Date.now()
: oldCache const accumulation: NavigationRequestAccumulation = {
scrollableSegments: null,
separateRefreshUrls: null,
}
const task = startPPRNavigation(
now,
currentUrl,
state.cache,
state.tree,
treeToRestore,
FreshnessPolicy.HistoryTraversal,
null,
null,
null,
null,
false,
false,
accumulation
)
if (task === null) {
const mutable: Mutable = {
preserveCustomHistoryState: true,
}
return handleExternalUrl(state, mutable, restoredCanonicalUrl, false)
}
if (task.dynamicRequestTree !== null) {
listenForDynamicRequest(
restoredUrl,
restoredNextUrl,
task,
task.dynamicRequestTree,
null,
accumulation
)
}
return { return {
// Set canonical url // Set canonical url
canonicalUrl: href, canonicalUrl: restoredCanonicalUrl,
renderedSearch, renderedSearch,
pushRef: { pushRef: {
pendingPush: false, pendingPush: false,
...@@ -50,10 +92,14 @@ export function restoreReducer( ...@@ -50,10 +92,14 @@ export function restoreReducer(
preserveCustomHistoryState: true, preserveCustomHistoryState: true,
}, },
focusAndScrollRef: state.focusAndScrollRef, focusAndScrollRef: state.focusAndScrollRef,
cache: newCache, cache: task.node,
// Restore provided tree // Restore provided tree
tree: treeToRestore, tree: treeToRestore,
nextUrl: extractPathFromFlightRouterState(treeToRestore) ?? url.pathname,
nextUrl: restoredNextUrl,
// TODO: We need to restore previousNextUrl, too, which represents the
// Next-Url that was used to fetch the data. Anywhere we fetch using the
// canonical URL, there should be a corresponding Next-Url.
previousNextUrl: null, previousNextUrl: null,
debugInfo: null, debugInfo: null,
} }
......
...@@ -61,6 +61,7 @@ import { ...@@ -61,6 +61,7 @@ import {
type ActionRevalidationKind, type ActionRevalidationKind,
} from '../../../../shared/lib/action-revalidation-kind' } from '../../../../shared/lib/action-revalidation-kind'
import { isExternalURL } from '../../app-router-utils' import { isExternalURL } from '../../app-router-utils'
import { FreshnessPolicy } from '../ppr-navigations'
const createFromFetch = const createFromFetch =
createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch'] createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch']
...@@ -388,8 +389,10 @@ export function serverActionReducer( ...@@ -388,8 +389,10 @@ export function serverActionReducer(
// If the action triggered a revalidation of the cache, we should also // If the action triggered a revalidation of the cache, we should also
// refresh all the dynamic data. // refresh all the dynamic data.
const shouldRefreshDynamicData = const freshnessPolicy =
revalidationKind !== ActionDidNotRevalidate revalidationKind === ActionDidNotRevalidate
? FreshnessPolicy.Default
: FreshnessPolicy.RefreshAll
// The server may have sent back new data. If so, we will perform a // The server may have sent back new data. If so, we will perform a
// "seeded" navigation that uses the data from the response. // "seeded" navigation that uses the data from the response.
...@@ -421,7 +424,7 @@ export function serverActionReducer( ...@@ -421,7 +424,7 @@ export function serverActionReducer(
seedRenderedSearch, seedRenderedSearch,
seedData, seedData,
seedHead, seedHead,
shouldRefreshDynamicData, freshnessPolicy,
nextUrl, nextUrl,
shouldScroll shouldScroll
) )
...@@ -443,7 +446,7 @@ export function serverActionReducer( ...@@ -443,7 +446,7 @@ export function serverActionReducer(
state.cache, state.cache,
currentFlightRouterState, currentFlightRouterState,
nextUrl, nextUrl,
shouldRefreshDynamicData, freshnessPolicy,
shouldScroll, shouldScroll,
mutable mutable
) )
......
...@@ -13,6 +13,7 @@ import { fetchServerResponse } from '../router-reducer/fetch-server-response' ...@@ -13,6 +13,7 @@ import { fetchServerResponse } from '../router-reducer/fetch-server-response'
import { import {
startPPRNavigation, startPPRNavigation,
listenForDynamicRequest, listenForDynamicRequest,
FreshnessPolicy,
type NavigationTask, type NavigationTask,
type NavigationRequestAccumulation, type NavigationRequestAccumulation,
} from '../router-reducer/ppr-navigations' } from '../router-reducer/ppr-navigations'
...@@ -72,7 +73,7 @@ export function navigate( ...@@ -72,7 +73,7 @@ export function navigate(
currentCacheNode: CacheNode | null, currentCacheNode: CacheNode | null,
currentFlightRouterState: FlightRouterState, currentFlightRouterState: FlightRouterState,
nextUrl: string | null, nextUrl: string | null,
shouldRefreshDynamicData: boolean, freshnessPolicy: FreshnessPolicy,
shouldScroll: boolean, shouldScroll: boolean,
accumulation: { collectedDebugInfo?: Array<unknown> } accumulation: { collectedDebugInfo?: Array<unknown> }
): NavigationResult { ): NavigationResult {
...@@ -131,7 +132,7 @@ export function navigate( ...@@ -131,7 +132,7 @@ export function navigate(
isPrefetchHeadPartial, isPrefetchHeadPartial,
newCanonicalUrl, newCanonicalUrl,
renderedSearch, renderedSearch,
shouldRefreshDynamicData, freshnessPolicy,
shouldScroll, shouldScroll,
url.hash url.hash
) )
...@@ -176,7 +177,7 @@ export function navigate( ...@@ -176,7 +177,7 @@ export function navigate(
isPrefetchHeadPartial, isPrefetchHeadPartial,
newCanonicalUrl, newCanonicalUrl,
newRenderedSearch, newRenderedSearch,
shouldRefreshDynamicData, freshnessPolicy,
shouldScroll, shouldScroll,
url.hash url.hash
) )
...@@ -198,7 +199,7 @@ export function navigate( ...@@ -198,7 +199,7 @@ export function navigate(
isSamePageNavigation, isSamePageNavigation,
currentCacheNode, currentCacheNode,
currentFlightRouterState, currentFlightRouterState,
shouldRefreshDynamicData, freshnessPolicy,
shouldScroll, shouldScroll,
url.hash, url.hash,
collectedDebugInfo collectedDebugInfo
...@@ -215,7 +216,7 @@ export function navigateToSeededRoute( ...@@ -215,7 +216,7 @@ export function navigateToSeededRoute(
seedRenderedSearch: string, seedRenderedSearch: string,
seedData: CacheNodeSeedData | null, seedData: CacheNodeSeedData | null,
seedHead: HeadData | null, seedHead: HeadData | null,
shouldRefreshDynamicData: boolean, freshnessPolicy: FreshnessPolicy,
nextUrl: string | null, nextUrl: string | null,
shouldScroll: boolean shouldScroll: boolean
): SuccessfulNavigationResult | MPANavigationResult { ): SuccessfulNavigationResult | MPANavigationResult {
...@@ -234,7 +235,7 @@ export function navigateToSeededRoute( ...@@ -234,7 +235,7 @@ export function navigateToSeededRoute(
currentCacheNode, currentCacheNode,
currentFlightRouterState, currentFlightRouterState,
seedFlightRouterState, seedFlightRouterState,
shouldRefreshDynamicData, freshnessPolicy,
seedData, seedData,
seedHead, seedHead,
null, null,
...@@ -284,7 +285,7 @@ function navigateUsingPrefetchedRouteTree( ...@@ -284,7 +285,7 @@ function navigateUsingPrefetchedRouteTree(
isPrefetchHeadPartial: boolean, isPrefetchHeadPartial: boolean,
canonicalUrl: string, canonicalUrl: string,
renderedSearch: string, renderedSearch: string,
shouldRefreshDynamicData: boolean, freshnessPolicy: FreshnessPolicy,
shouldScroll: boolean, shouldScroll: boolean,
hash: string hash: string
): SuccessfulNavigationResult | MPANavigationResult { ): SuccessfulNavigationResult | MPANavigationResult {
...@@ -306,7 +307,7 @@ function navigateUsingPrefetchedRouteTree( ...@@ -306,7 +307,7 @@ function navigateUsingPrefetchedRouteTree(
currentCacheNode, currentCacheNode,
currentFlightRouterState, currentFlightRouterState,
prefetchFlightRouterState, prefetchFlightRouterState,
shouldRefreshDynamicData, freshnessPolicy,
seedData, seedData,
seedHead, seedHead,
prefetchSeedData, prefetchSeedData,
...@@ -512,7 +513,7 @@ async function navigateDynamicallyWithNoPrefetch( ...@@ -512,7 +513,7 @@ async function navigateDynamicallyWithNoPrefetch(
isSamePageNavigation: boolean, isSamePageNavigation: boolean,
currentCacheNode: CacheNode | null, currentCacheNode: CacheNode | null,
currentFlightRouterState: FlightRouterState, currentFlightRouterState: FlightRouterState,
shouldRefreshDynamicData: boolean, freshnessPolicy: FreshnessPolicy,
shouldScroll: boolean, shouldScroll: boolean,
hash: string, hash: string,
collectedDebugInfo: Array<unknown> collectedDebugInfo: Array<unknown>
...@@ -529,10 +530,23 @@ async function navigateDynamicallyWithNoPrefetch( ...@@ -529,10 +530,23 @@ async function navigateDynamicallyWithNoPrefetch(
// tree. So it's the same flow as the "happy path" (prefetch, then // tree. So it's the same flow as the "happy path" (prefetch, then
// navigation), except we use a single server response for both stages. // navigation), except we use a single server response for both stages.
let dynamicRequestTree: FlightRouterState
switch (freshnessPolicy) {
case FreshnessPolicy.Default:
case FreshnessPolicy.HistoryTraversal:
dynamicRequestTree = currentFlightRouterState
break
case FreshnessPolicy.RefreshAll:
dynamicRequestTree = DynamicRequestTreeForEntireRoute
break
default:
freshnessPolicy satisfies never
dynamicRequestTree = currentFlightRouterState
break
}
const promiseForDynamicServerResponse = fetchServerResponse(url, { const promiseForDynamicServerResponse = fetchServerResponse(url, {
flightRouterState: shouldRefreshDynamicData flightRouterState: dynamicRequestTree,
? DynamicRequestTreeForEntireRoute
: currentFlightRouterState,
nextUrl, nextUrl,
}) })
const result = await promiseForDynamicServerResponse const result = await promiseForDynamicServerResponse
...@@ -582,7 +596,7 @@ async function navigateDynamicallyWithNoPrefetch( ...@@ -582,7 +596,7 @@ async function navigateDynamicallyWithNoPrefetch(
currentCacheNode, currentCacheNode,
currentFlightRouterState, currentFlightRouterState,
prefetchFlightRouterState, prefetchFlightRouterState,
shouldRefreshDynamicData, freshnessPolicy,
seedData, seedData,
seedHead, seedHead,
prefetchData, prefetchData,
......
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