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(
pathToSegment: flightSegmentPath,
seedData,
head,
isHeadPartial,
isRootRender,
} = normalizedFlightData
let treePatch = normalizedFlightData.tree
......@@ -316,13 +317,11 @@ export function navigateReducer(
currentTree,
treePatch,
seedData,
head
head,
isHeadPartial
)
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
// of the one computed by applyRouterStatePatchToTree.
// TODO: We should remove applyRouterStatePatchToTree
......@@ -330,12 +329,13 @@ export function navigateReducer(
const patchedRouterState: FlightRouterState = task.route
newTree = patchedRouterState
// It's possible that `updateCacheNodeOnNavigation` only spawned tasks to reuse the existing cache,
// in which case `task.node` will be null, signaling we don't need to wait for a dynamic request
// and can simply apply the patched `FlightRouterState`.
if (task.node !== null) {
const newCache = task.node
const newCache = task.node
if (newCache !== null) {
// We've created a new Cache Node tree that contains a prefetched
// version of the next page. This can be rendered instantly.
mutable.cache = newCache
}
if (task.needsDynamicRequest) {
// The prefetched tree has dynamic holes in it. We initiate a
// dynamic request to fill them in.
//
......@@ -359,8 +359,9 @@ export function navigateReducer(
// because we're not going to await the dynamic request here. Since we're not blocking
// on the dynamic request, `layout-router` will
// task.node.lazyData = dynamicRequest
mutable.cache = newCache
} else {
// The prefetched tree does not contain dynamic holes — it's
// fully static. We can skip the dynamic request.
}
} else {
// Nothing changed, so reuse the old cache.
......
......@@ -8,13 +8,11 @@ import type {
LoadingModuleData,
} from '../../../shared/lib/app-router-context.shared-runtime'
import type { NormalizedFlightData } from '../../flight-data-helpers'
import {
fetchServerResponse,
type FetchServerResponseResult,
} from '../router-reducer/fetch-server-response'
import { fetchServerResponse } from '../router-reducer/fetch-server-response'
import {
updateCacheNodeOnNavigation,
listenForDynamicRequest,
type Task as PPRNavigationTask,
} from '../router-reducer/ppr-navigations'
import { createHrefFromUrl as createCanonicalUrl } from '../router-reducer/create-href-from-url'
import {
......@@ -94,19 +92,18 @@ export function navigate(
const prefetchFlightRouterState = snapshot.flightRouterState
const prefetchSeedData = snapshot.seedData
const prefetchHead = route.head
const isPrefetchHeadPartial = route.isHeadPartial
const canonicalUrl = route.canonicalUrl
const promiseForDynamicServerResponse = fetchServerResponse(url, {
flightRouterState: currentFlightRouterState,
nextUrl,
})
return navigateUsingPrefetchedRouteTree(
url,
nextUrl,
currentCacheNode,
currentFlightRouterState,
prefetchFlightRouterState,
prefetchSeedData,
prefetchHead,
canonicalUrl,
promiseForDynamicServerResponse
isPrefetchHeadPartial,
canonicalUrl
)
}
// There's no matching prefetch for this route in the cache.
......@@ -114,21 +111,23 @@ export function navigate(
tag: NavigationResultTag.Async,
data: navigateDynamicallyWithNoPrefetch(
url,
nextUrl,
currentCacheNode,
currentFlightRouterState,
nextUrl
currentFlightRouterState
),
}
}
function navigateUsingPrefetchedRouteTree(
url: URL,
nextUrl: string | null,
currentCacheNode: CacheNode,
currentFlightRouterState: FlightRouterState,
prefetchFlightRouterState: FlightRouterState,
prefetchSeedData: CacheNodeSeedData | null,
prefetchHead: React.ReactNode | null,
canonicalUrl: string,
promiseForDynamicServerResponse: Promise<FetchServerResponseResult>
isPrefetchHeadPartial: boolean,
canonicalUrl: string
): SuccessfulNavigationResult | NoOpNavigationResult {
// Recursively construct a prefetch tree by reading from the Segment Cache. To
// maintain compatibility, we output the same data structures as the old
......@@ -141,26 +140,42 @@ function navigateUsingPrefetchedRouteTree(
currentFlightRouterState,
prefetchFlightRouterState,
prefetchSeedData,
prefetchHead
prefetchHead,
isPrefetchHeadPartial
)
if (task !== null) {
const newCacheNode = task.node
if (newCacheNode !== null) {
if (task.needsDynamicRequest) {
const promiseForDynamicServerResponse = fetchServerResponse(url, {
flightRouterState: currentFlightRouterState,
nextUrl,
})
listenForDynamicRequest(task, promiseForDynamicServerResponse)
} else {
// The prefetched tree does not contain dynamic holes — it's
// fully static. We can skip the dynamic request.
}
return {
tag: NavigationResultTag.Success,
data: {
flightRouterState: task.route,
cacheNode: newCacheNode !== null ? newCacheNode : currentCacheNode,
canonicalUrl,
},
}
return navigationTaskToResult(task, currentCacheNode, canonicalUrl)
}
// The server sent back an empty tree patch. There's nothing to update.
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(
now: number,
tree: TreePrefetch
......@@ -243,9 +258,9 @@ function readRenderSnapshotFromCache(
async function navigateDynamicallyWithNoPrefetch(
url: URL,
nextUrl: string | null,
currentCacheNode: CacheNode,
currentFlightRouterState: FlightRouterState,
nextUrl: string | null
currentFlightRouterState: FlightRouterState
): Promise<
MPANavigationResult | SuccessfulNavigationResult | NoOpNavigationResult
> {
......@@ -292,17 +307,32 @@ async function navigateDynamicallyWithNoPrefetch(
// nor a prefetch head.
const prefetchSeedData = null
const prefetchHead = null
const isPrefetchHeadPartial = true
const canonicalUrl = createCanonicalUrl(
canonicalUrlOverride ? canonicalUrlOverride : url
)
// Now we proceed exactly as we would for normal navigation.
return navigateUsingPrefetchedRouteTree(
const task = updateCacheNodeOnNavigation(
currentCacheNode,
currentFlightRouterState,
prefetchFlightRouterState,
prefetchSeedData,
prefetchHead,
createCanonicalUrl(canonicalUrlOverride ? canonicalUrlOverride : url),
promiseForDynamicServerResponse
isPrefetchHeadPartial
)
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(
......
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)', () => {
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() {
......
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