Unverified Commit 65db12fe authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

[Segment Cache] Support <Link prefetch={true}> (#74172)

This implements support in the Segment Cache for "full" link prefetches,
typically initiated by passing `prefetch={true}` to a `<Link>`.

The goal of a full prefetch is to request all the data needed for a
navigation, both static and dynamic, so that once the navigation occurs,
the router does not need to fetch any additional data. So, a full
prefetch implicitly instructs the client cache to treat the response as
static, even the dynamic data.

The implementation is largely the same as what we do to support
non-PPR-enabled routes — a request tree is sent to the server describing
which segments are already cached and which ones need to be rendered.
While constructing the request tree, if all the segments are already in
the client cache, the request can be skipped entirely. The main
difference is that a full prefetch will only reuse a cached segment
entry if it does not contain any dynamic holes.
parent 4c09fa53
......@@ -279,11 +279,12 @@ function Router({
? // Unlike the old implementation, the Segment Cache doesn't store its
// data in the router reducer state; it writes into a global mutable
// cache. So we don't need to dispatch an action.
(href) =>
(href, options) =>
prefetchWithSegmentCache(
href,
actionQueue.state.nextUrl,
actionQueue.state.tree
actionQueue.state.tree,
options?.kind === PrefetchKind.FULL
)
: (href, options) => {
// Use the old prefetch implementation.
......
......@@ -147,6 +147,7 @@ export type RouteCacheEntry =
export const enum FetchStrategy {
PPR,
Full,
LoadingBoundary,
}
......@@ -1005,9 +1006,10 @@ export async function fetchSegmentOnCacheMiss(
}
}
export async function fetchSegmentPrefetchesForPPRDisabledRoute(
export async function fetchSegmentPrefetchesUsingDynamicRequest(
task: PrefetchTask,
route: FulfilledRouteCacheEntry,
fetchStrategy: FetchStrategy,
dynamicRequestTree: FlightRouterState,
spawnedEntries: Map<string, PendingSegmentCacheEntry>
): Promise<PrefetchSubtaskResult<null> | null> {
......@@ -1015,7 +1017,6 @@ export async function fetchSegmentPrefetchesForPPRDisabledRoute(
const nextUrl = task.key.nextUrl
const headers: RequestHeaders = {
[RSC_HEADER]: '1',
[NEXT_ROUTER_PREFETCH_HEADER]: '1',
[NEXT_ROUTER_STATE_TREE_HEADER]: encodeURIComponent(
JSON.stringify(dynamicRequestTree)
),
......@@ -1023,6 +1024,13 @@ export async function fetchSegmentPrefetchesForPPRDisabledRoute(
if (nextUrl !== null) {
headers[NEXT_URL] = nextUrl
}
// Only set the prefetch header if we're not doing a "full" prefetch. We
// omit the prefetch header from a full prefetch because it's essentially
// just a navigation request that happens ahead of time — it should include
// all the same data in the response.
if (fetchStrategy !== FetchStrategy.Full) {
headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'
}
try {
const response = await fetchPrefetchResponse(href, headers)
if (!response || !response.ok || !response.body) {
......
......@@ -7,11 +7,18 @@ import { schedulePrefetchTask } from './scheduler'
* Entrypoint for prefetching a URL into the Segment Cache.
* @param href - The URL to prefetch. Typically this will come from a <Link>,
* or router.prefetch. It must be validated before we attempt to prefetch it.
* @param nextUrl - A special header used by the server for interception routes.
* Roughly corresponds to the current URL.
* @param treeAtTimeOfPrefetch - The FlightRouterState at the time the prefetch
* was requested. This is only used when PPR is disabled.
* @param includeDynamicData - Whether to prefetch dynamic data, in addition to
* static data. This is used by <Link prefetch={true}>.
*/
export function prefetch(
href: string,
nextUrl: string | null,
treeAtTimeOfPrefetch: FlightRouterState
treeAtTimeOfPrefetch: FlightRouterState,
includeDynamicData: boolean
) {
const url = createPrefetchURL(href)
if (url === null) {
......@@ -19,5 +26,5 @@ export function prefetch(
return
}
const cacheKey = createCacheKey(url.href, nextUrl)
schedulePrefetchTask(cacheKey, treeAtTimeOfPrefetch)
schedulePrefetchTask(cacheKey, treeAtTimeOfPrefetch, includeDynamicData)
}
......@@ -18,6 +18,17 @@ export default function MixedFetchStrategies() {
>
Link to PPR enabled page
</LinkAccordion>
<ul>
<li>
<LinkAccordion
id="ppr-enabled-prefetch-true"
prefetch={true}
href="/mixed-fetch-strategies/has-loading-boundary/a/b/shared-layout/ppr-enabled"
>
Same link, but with prefetch=true
</LinkAccordion>
</li>
</ul>
</li>
<li>
<LinkAccordion
......
......@@ -131,4 +131,186 @@ describe('segment cache (incremental opt in)', () => {
})
}
)
it(
'when a link is prefetched with <Link prefetch=true>, no dynamic request ' +
'is made on navigation',
async () => {
let act
const browser = await next.browser('/mixed-fetch-strategies', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
await act(
async () => {
const checkbox = await browser.elementById(
'ppr-enabled-prefetch-true'
)
await checkbox.click()
},
{
includes: 'Dynamic page content',
}
)
// Navigate to fully prefetched route
const link = await browser.elementByCss('#ppr-enabled-prefetch-true + a')
await act(
async () => {
await link.click()
// We should be able to fully load the page content, including the
// dynamic data, before the server responds.
await browser.elementById('page-content')
},
// Assert that no network requests are initiated within this block.
'no-requests'
)
}
)
it(
'when prefetching with prefetch=true, refetches cache entries that only ' +
'contain partial data',
async () => {
let act
const browser = await next.browser('/mixed-fetch-strategies', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// Prefetch a link with PPR
await act(
async () => {
const checkbox = await browser.elementById('ppr-enabled')
await checkbox.click()
},
{ includes: 'Loading (PPR shell of shared-layout)...' }
)
// Prefetch the same link again, this time with prefetch=true to include
// the dynamic data
await act(
async () => {
const checkbox = await browser.elementById(
'ppr-enabled-prefetch-true'
)
await checkbox.click()
},
{
includes: 'Dynamic content in shared layout',
}
)
// Navigate to the PPR-enabled route
const link = await browser.elementByCss('#ppr-enabled-prefetch-true + a')
await act(
async () => {
await link.click()
// If we prefetched all the segments correctly, we should be able to
// fully load the page content, including the dynamic data, before the
// server responds.
//
// If this fails, it likely means that the partial cache entry that
// resulted from prefetching the normal link (<Link prefetch={false}>)
// was not properly re-fetched when the full link (<Link
// prefetch={true}>) was prefetched.
await browser.elementById('page-content')
},
// Assert that no network requests are initiated within this block.
'no-requests'
)
}
)
it(
'when prefetching with prefetch=true, refetches partial cache entries ' +
"even if there's already a pending PPR request",
async () => {
// This test is hard to describe succinctly because it involves a fairly
// complex race condition between a non-PPR prefetch, a PPR prefetch, and
// a "full" prefetch. Despite the complexity of the scenario, it's worth
// testing because could easily happen in real world conditions.
let act
const browser = await next.browser('/mixed-fetch-strategies', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// Initiate a prefetch for the PPR-disabled route first. This will not
// include the /shared-layout/ segment, because it's inside the
// loading boundary.
await act(
async () => {
const checkbox = await browser.elementById('ppr-disabled')
await checkbox.click()
},
{ includes: 'Loading (has-loading-boundary/loading.tsx)...' }
)
// Then initiate a prefetch for the PPR-enabled route.
await act(async () => {
// Create an inner act scope so we initate a prefetch but block it
// from responding.
await act(
async () => {
const checkbox = await browser.elementById('ppr-enabled')
await checkbox.click()
},
{
// This prefetch should include the /shared-layout/ segment despite
// the presence of the loading boundary, and despite the earlier
// non-PPR attempt.
includes: 'Loading (PPR shell of shared-layout)...',
// We're going to block it from responding, so we can test what
// happens if another prefetch is initiated in the meantime.
block: true,
}
)
// Before the previous prefetch finishes, prefetch the same link again,
// this time with prefetch=true to include the dynamic data.
await act(
async () => {
const checkbox = await browser.elementById(
'ppr-enabled-prefetch-true'
)
await checkbox.click()
},
// This prefetch should load the dynamic data in the shared layout
{
includes: 'Dynamic content in shared layout',
}
)
})
// Navigate to the PPR-enabled route.
await act(
async () => {
const link = await browser.elementByCss(
'#ppr-enabled-prefetch-true + a'
)
await link.click()
// If we prefetched all the segments correctly, we should be able to
// fully load the page content, including the dynamic data, before the
// server responds.
//
// If this fails, it likely means that the pending cache entry that
// resulted from prefetching the normal link (<Link prefetch={false}>)
// was not properly re-fetched when the full link (<Link
// prefetch={true}>) was prefetched.
await browser.elementById('page-content')
},
// Assert that no network requests are initiated within this block.
'no-requests'
)
}
)
})
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