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

[Segment Cache] Skip dynamic request if possible (#73540)

During a navigation, if all the data has been prefetched, and the target
route does not contain any dynamic data, then we should skip a request
to the server.

This uses the `isPartial` field I added in the previous PRs to track
whether the prefetched data is complete or not.
parent 3970d33e
...@@ -266,6 +266,7 @@ export function navigateReducer( ...@@ -266,6 +266,7 @@ export function navigateReducer(
pathToSegment: flightSegmentPath, pathToSegment: flightSegmentPath,
seedData, seedData,
head, head,
isHeadPartial,
isRootRender, isRootRender,
} = normalizedFlightData } = normalizedFlightData
let treePatch = normalizedFlightData.tree let treePatch = normalizedFlightData.tree
...@@ -316,13 +317,11 @@ export function navigateReducer( ...@@ -316,13 +317,11 @@ export function navigateReducer(
currentTree, currentTree,
treePatch, treePatch,
seedData, seedData,
head head,
isHeadPartial
) )
if (task !== null) { if (task !== null) {
// We've created a new Cache Node tree that contains a prefetched
// version of the next page. This can be rendered instantly.
// Use the tree computed by updateCacheNodeOnNavigation instead // Use the tree computed by updateCacheNodeOnNavigation instead
// of the one computed by applyRouterStatePatchToTree. // of the one computed by applyRouterStatePatchToTree.
// TODO: We should remove applyRouterStatePatchToTree // TODO: We should remove applyRouterStatePatchToTree
...@@ -330,12 +329,13 @@ export function navigateReducer( ...@@ -330,12 +329,13 @@ export function navigateReducer(
const patchedRouterState: FlightRouterState = task.route const patchedRouterState: FlightRouterState = task.route
newTree = patchedRouterState newTree = patchedRouterState
// It's possible that `updateCacheNodeOnNavigation` only spawned tasks to reuse the existing cache, const newCache = task.node
// in which case `task.node` will be null, signaling we don't need to wait for a dynamic request if (newCache !== null) {
// and can simply apply the patched `FlightRouterState`. // We've created a new Cache Node tree that contains a prefetched
if (task.node !== null) { // version of the next page. This can be rendered instantly.
const newCache = task.node mutable.cache = newCache
}
if (task.needsDynamicRequest) {
// The prefetched tree has dynamic holes in it. We initiate a // The prefetched tree has dynamic holes in it. We initiate a
// dynamic request to fill them in. // dynamic request to fill them in.
// //
...@@ -359,8 +359,9 @@ export function navigateReducer( ...@@ -359,8 +359,9 @@ export function navigateReducer(
// because we're not going to await the dynamic request here. Since we're not blocking // because we're not going to await the dynamic request here. Since we're not blocking
// on the dynamic request, `layout-router` will // on the dynamic request, `layout-router` will
// task.node.lazyData = dynamicRequest // task.node.lazyData = dynamicRequest
} else {
mutable.cache = newCache // The prefetched tree does not contain dynamic holes — it's
// fully static. We can skip the dynamic request.
} }
} else { } else {
// Nothing changed, so reuse the old cache. // Nothing changed, so reuse the old cache.
......
...@@ -8,13 +8,11 @@ import type { ...@@ -8,13 +8,11 @@ import type {
LoadingModuleData, LoadingModuleData,
} from '../../../shared/lib/app-router-context.shared-runtime' } from '../../../shared/lib/app-router-context.shared-runtime'
import type { NormalizedFlightData } from '../../flight-data-helpers' import type { NormalizedFlightData } from '../../flight-data-helpers'
import { import { fetchServerResponse } from '../router-reducer/fetch-server-response'
fetchServerResponse,
type FetchServerResponseResult,
} from '../router-reducer/fetch-server-response'
import { import {
updateCacheNodeOnNavigation, updateCacheNodeOnNavigation,
listenForDynamicRequest, listenForDynamicRequest,
type Task as PPRNavigationTask,
} from '../router-reducer/ppr-navigations' } from '../router-reducer/ppr-navigations'
import { createHrefFromUrl as createCanonicalUrl } from '../router-reducer/create-href-from-url' import { createHrefFromUrl as createCanonicalUrl } from '../router-reducer/create-href-from-url'
import { import {
...@@ -94,19 +92,18 @@ export function navigate( ...@@ -94,19 +92,18 @@ export function navigate(
const prefetchFlightRouterState = snapshot.flightRouterState const prefetchFlightRouterState = snapshot.flightRouterState
const prefetchSeedData = snapshot.seedData const prefetchSeedData = snapshot.seedData
const prefetchHead = route.head const prefetchHead = route.head
const isPrefetchHeadPartial = route.isHeadPartial
const canonicalUrl = route.canonicalUrl const canonicalUrl = route.canonicalUrl
const promiseForDynamicServerResponse = fetchServerResponse(url, {
flightRouterState: currentFlightRouterState,
nextUrl,
})
return navigateUsingPrefetchedRouteTree( return navigateUsingPrefetchedRouteTree(
url,
nextUrl,
currentCacheNode, currentCacheNode,
currentFlightRouterState, currentFlightRouterState,
prefetchFlightRouterState, prefetchFlightRouterState,
prefetchSeedData, prefetchSeedData,
prefetchHead, prefetchHead,
canonicalUrl, isPrefetchHeadPartial,
promiseForDynamicServerResponse canonicalUrl
) )
} }
// There's no matching prefetch for this route in the cache. // There's no matching prefetch for this route in the cache.
...@@ -114,21 +111,23 @@ export function navigate( ...@@ -114,21 +111,23 @@ export function navigate(
tag: NavigationResultTag.Async, tag: NavigationResultTag.Async,
data: navigateDynamicallyWithNoPrefetch( data: navigateDynamicallyWithNoPrefetch(
url, url,
nextUrl,
currentCacheNode, currentCacheNode,
currentFlightRouterState, currentFlightRouterState
nextUrl
), ),
} }
} }
function navigateUsingPrefetchedRouteTree( function navigateUsingPrefetchedRouteTree(
url: URL,
nextUrl: string | null,
currentCacheNode: CacheNode, currentCacheNode: CacheNode,
currentFlightRouterState: FlightRouterState, currentFlightRouterState: FlightRouterState,
prefetchFlightRouterState: FlightRouterState, prefetchFlightRouterState: FlightRouterState,
prefetchSeedData: CacheNodeSeedData | null, prefetchSeedData: CacheNodeSeedData | null,
prefetchHead: React.ReactNode | null, prefetchHead: React.ReactNode | null,
canonicalUrl: string, isPrefetchHeadPartial: boolean,
promiseForDynamicServerResponse: Promise<FetchServerResponseResult> canonicalUrl: string
): SuccessfulNavigationResult | NoOpNavigationResult { ): SuccessfulNavigationResult | NoOpNavigationResult {
// Recursively construct a prefetch tree by reading from the Segment Cache. To // Recursively construct a prefetch tree by reading from the Segment Cache. To
// maintain compatibility, we output the same data structures as the old // maintain compatibility, we output the same data structures as the old
...@@ -141,26 +140,42 @@ function navigateUsingPrefetchedRouteTree( ...@@ -141,26 +140,42 @@ function navigateUsingPrefetchedRouteTree(
currentFlightRouterState, currentFlightRouterState,
prefetchFlightRouterState, prefetchFlightRouterState,
prefetchSeedData, prefetchSeedData,
prefetchHead prefetchHead,
isPrefetchHeadPartial
) )
if (task !== null) { if (task !== null) {
const newCacheNode = task.node if (task.needsDynamicRequest) {
if (newCacheNode !== null) { const promiseForDynamicServerResponse = fetchServerResponse(url, {
flightRouterState: currentFlightRouterState,
nextUrl,
})
listenForDynamicRequest(task, promiseForDynamicServerResponse) listenForDynamicRequest(task, promiseForDynamicServerResponse)
} else {
// The prefetched tree does not contain dynamic holes — it's
// fully static. We can skip the dynamic request.
} }
return { return navigationTaskToResult(task, currentCacheNode, canonicalUrl)
tag: NavigationResultTag.Success,
data: {
flightRouterState: task.route,
cacheNode: newCacheNode !== null ? newCacheNode : currentCacheNode,
canonicalUrl,
},
}
} }
// The server sent back an empty tree patch. There's nothing to update. // The server sent back an empty tree patch. There's nothing to update.
return noOpNavigationResult return noOpNavigationResult
} }
function navigationTaskToResult(
task: PPRNavigationTask,
currentCacheNode: CacheNode,
canonicalUrl: string
): SuccessfulNavigationResult {
const newCacheNode = task.node
return {
tag: NavigationResultTag.Success,
data: {
flightRouterState: task.route,
cacheNode: newCacheNode !== null ? newCacheNode : currentCacheNode,
canonicalUrl,
},
}
}
function readRenderSnapshotFromCache( function readRenderSnapshotFromCache(
now: number, now: number,
tree: TreePrefetch tree: TreePrefetch
...@@ -243,9 +258,9 @@ function readRenderSnapshotFromCache( ...@@ -243,9 +258,9 @@ function readRenderSnapshotFromCache(
async function navigateDynamicallyWithNoPrefetch( async function navigateDynamicallyWithNoPrefetch(
url: URL, url: URL,
nextUrl: string | null,
currentCacheNode: CacheNode, currentCacheNode: CacheNode,
currentFlightRouterState: FlightRouterState, currentFlightRouterState: FlightRouterState
nextUrl: string | null
): Promise< ): Promise<
MPANavigationResult | SuccessfulNavigationResult | NoOpNavigationResult MPANavigationResult | SuccessfulNavigationResult | NoOpNavigationResult
> { > {
...@@ -292,17 +307,32 @@ async function navigateDynamicallyWithNoPrefetch( ...@@ -292,17 +307,32 @@ async function navigateDynamicallyWithNoPrefetch(
// nor a prefetch head. // nor a prefetch head.
const prefetchSeedData = null const prefetchSeedData = null
const prefetchHead = null const prefetchHead = null
const isPrefetchHeadPartial = true
const canonicalUrl = createCanonicalUrl(
canonicalUrlOverride ? canonicalUrlOverride : url
)
// Now we proceed exactly as we would for normal navigation. // Now we proceed exactly as we would for normal navigation.
return navigateUsingPrefetchedRouteTree( const task = updateCacheNodeOnNavigation(
currentCacheNode, currentCacheNode,
currentFlightRouterState, currentFlightRouterState,
prefetchFlightRouterState, prefetchFlightRouterState,
prefetchSeedData, prefetchSeedData,
prefetchHead, prefetchHead,
createCanonicalUrl(canonicalUrlOverride ? canonicalUrlOverride : url), isPrefetchHeadPartial
promiseForDynamicServerResponse
) )
if (task !== null) {
if (task.needsDynamicRequest) {
listenForDynamicRequest(task, promiseForDynamicServerResponse)
} else {
// The prefetched tree does not contain dynamic holes — it's
// fully static. We can skip the dynamic request.
}
return navigationTaskToResult(task, currentCacheNode, canonicalUrl)
}
// The server sent back an empty tree patch. There's nothing to update.
return noOpNavigationResult
} }
function simulatePrefetchTreeUsingDynamicTreePatch( function simulatePrefetchTreeUsingDynamicTreePatch(
......
import Link from 'next/link'
export default function FullyStaticStart() {
return (
<>
<p>
Demonstrates that when navigating to a fully prefetched route that does
not contain any dynamic data, we do not need to perform an additional
request on navigation.
</p>
<ul>
<li>
<Link href="/fully-static/target-page">Target</Link>
</li>
</ul>
</>
)
}
export default function Target() {
return <div id="target-page">Target</div>
}
...@@ -140,6 +140,33 @@ describe('segment cache (basic tests)', () => { ...@@ -140,6 +140,33 @@ describe('segment cache (basic tests)', () => {
navigationsLock.release() navigationsLock.release()
}) })
it('skips dynamic request if prefetched data is fully static', async () => {
const interceptor = createRequestInterceptor()
const browser = await next.browser('/fully-static', {
beforePageLoad(page: Page) {
page.route('**/*', async (route: Route) => {
await interceptor.interceptRoute(route)
})
},
})
// Rendering the link triggers a prefetch of the test page.
const link = await browser.elementByCss(
'a[href="/fully-static/target-page"]'
)
const navigationsLock = interceptor.lockNavigations()
await link.click()
// The page should render immediately because it was prefetched.
const div = await browser.elementById('target-page')
expect(await div.innerHTML()).toBe('Target')
// We should have skipped the navigation request because all the data was
// fully static.
const numberOfNavigationRequests = (await navigationsLock.release()).size
expect(numberOfNavigationRequests).toBe(0)
})
}) })
function createRequestInterceptor() { function createRequestInterceptor() {
......
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