Unverified Commit bb623129 authored by vercel[bot]'s avatar vercel[bot] Committed by GitHub

Fix partial prefetch segment overrides

Co-Authored-By: 's avatarMarcos Hernanz <96699542+marcoshernanz@users.noreply.github.com>
parent d898c8f5
......@@ -305,7 +305,7 @@ import {
type AdvanceableRenderStage,
} from './staged-rendering'
import {
anySegmentHasPartialPrefetchingEnabled,
isPartialPrefetchingEnabledForRoute,
isPageAllowedToBlock,
anySegmentNeedsInstantValidationInDev,
anySegmentNeedsInstantValidationInBuild,
......@@ -1102,14 +1102,17 @@ async function generateStagedDynamicFlightRenderResultNode(
// Check if this route should runtime-cache its navigation. This happens when
// Partial Prefetching is enabled for the route, either per segment (a
// `prefetch` of 'partial') or globally (the
// `partialPrefetching` config). If so, we piggyback on the dynamic render to
// fill caches and then spawn a final runtime prerender whose result stream
// is embedded in the RSC payload. This is gated because it adds extra server
// processing and increases the response payload size.
// `prefetch` of 'partial') or through the `partialPrefetching` app default.
// An explicit segment config overrides the app default. If enabled, we
// piggyback on the dynamic render to fill caches and then spawn a final
// runtime prerender whose result stream is embedded in the RSC payload. This
// is gated because it adds extra server processing and increases the response
// payload size.
if (
Boolean(renderOpts.partialPrefetching) ||
(await anySegmentHasPartialPrefetchingEnabled(loaderTree))
await isPartialPrefetchingEnabledForRoute(
loaderTree,
Boolean(renderOpts.partialPrefetching)
)
) {
// Create a mutable cache that gets filled during the dynamic render.
const prerenderResumeDataCache = createPrerenderResumeDataCache()
......@@ -3877,11 +3880,13 @@ async function renderToStream(
// embedded in the initial RSC payload so the client can cache
// runtime-prefetchable content during hydration. This is enabled when
// Partial Prefetching is on for the route, either per segment (a
// `prefetch` of 'partial') or globally (the
// `partialPrefetching` config).
// `prefetch` of 'partial') or through the `partialPrefetching` app
// default. An explicit segment config overrides the app default.
if (
Boolean(renderOpts.partialPrefetching) ||
(await anySegmentHasPartialPrefetchingEnabled(tree))
await isPartialPrefetchingEnabledForRoute(
tree,
Boolean(renderOpts.partialPrefetching)
)
) {
const prerenderResumeDataCache = createPrerenderResumeDataCache()
requestStore.resumeDataCache = prerenderResumeDataCache
......@@ -5315,12 +5320,13 @@ async function getPrefetchingModeForPage(
const debug =
process.env.NEXT_PRIVATE_DEBUG_VALIDATION === '1' ? console.log : undefined
if (renderOpts.partialPrefetching) {
debug?.('using prefetching mode Partial because of next.config.js')
return PrefetchingMode.Partial
}
if (await anySegmentHasPartialPrefetchingEnabled(loaderTree)) {
debug?.('using prefetching mode Partial because of segment config')
if (
await isPartialPrefetchingEnabledForRoute(
loaderTree,
Boolean(renderOpts.partialPrefetching)
)
) {
debug?.('using prefetching mode Partial')
return PrefetchingMode.Partial
}
......
import type { Prefetch } from '../../../build/segment-config/app/app-segment-config'
import type { LoaderTree } from '../../lib/app-dir-module'
import { isPartialPrefetchingEnabledForRoute } from './instant-config'
function createTree(
prefetch?: Prefetch,
parallelRoutes: LoaderTree[1] = {}
): LoaderTree {
const mod = prefetch === undefined ? {} : { prefetch }
return [
'segment',
parallelRoutes,
{ page: [async () => mod, 'page.tsx'] },
null,
]
}
describe('isPartialPrefetchingEnabledForRoute', () => {
it('uses the app default when no segment has an explicit config', async () => {
const tree = createTree(undefined, {
children: createTree(),
})
await expect(isPartialPrefetchingEnabledForRoute(tree, true)).resolves.toBe(
true
)
await expect(
isPartialPrefetchingEnabledForRoute(tree, false)
).resolves.toBe(false)
})
it('allows a segment to opt in over a disabled app default', async () => {
const tree = createTree(undefined, {
children: createTree('partial'),
})
await expect(
isPartialPrefetchingEnabledForRoute(tree, false)
).resolves.toBe(true)
})
it('allows force-disabled to opt out of an enabled app default', async () => {
const tree = createTree(undefined, {
children: createTree('force-disabled'),
})
await expect(isPartialPrefetchingEnabledForRoute(tree, true)).resolves.toBe(
false
)
})
it('treats an explicit auto config as an override of the app default', async () => {
const tree = createTree(undefined, {
children: createTree('auto'),
})
await expect(isPartialPrefetchingEnabledForRoute(tree, true)).resolves.toBe(
false
)
})
it('preserves a partial opt-in above a force-disabled descendant', async () => {
const tree = createTree('partial', {
children: createTree('force-disabled'),
})
await expect(
isPartialPrefetchingEnabledForRoute(tree, false)
).resolves.toBe(true)
})
it('gives an explicit partial opt-in precedence over other segment overrides', async () => {
const tree = createTree(undefined, {
children: createTree('force-disabled'),
slot: createTree('partial'),
})
await expect(isPartialPrefetchingEnabledForRoute(tree, true)).resolves.toBe(
true
)
})
})
......@@ -51,34 +51,48 @@ export function isFrameworkErrorRoute(route: string | undefined): boolean {
}
/**
* Matches the `prefetch` config that enables Partial Prefetching for the
* segment: 'partial'. A route with Partial Prefetching enabled also
* runtime-caches its navigations, so this gates the runtime prefetch spawn.
* Whether Partial Prefetching is enabled for a route after applying explicit
* segment config over the app-level default. A `prefetch = 'partial'` opt-in
* wins if any segment exports one. Otherwise, any explicit non-partial value
* opts the route out of the app default.
*
* Runtime prefetch responses are generated for the whole route, so this
* decision must be route-wide too.
*/
export async function anySegmentHasPartialPrefetchingEnabled(
tree: LoaderTree
export async function isPartialPrefetchingEnabledForRoute(
tree: LoaderTree,
appDefault: boolean
): Promise<boolean> {
const { mod: layoutOrPageMod } = await getLayoutOrPageModule(tree)
let hasExplicitConfig = false
let hasPartialOptIn = false
// TODO(restart-on-cache-miss): Does this work correctly for client page/layout modules?
const prefetchConfig = layoutOrPageMod
? (layoutOrPageMod as AppSegmentConfig).prefetch
: undefined
if (prefetchConfig === 'partial') {
return true
}
async function visit(segmentTree: LoaderTree): Promise<void> {
const { mod: layoutOrPageMod } = await getLayoutOrPageModule(segmentTree)
const { parallelRoutes } = parseLoaderTree(tree)
for (const parallelRouteKey in parallelRoutes) {
const parallelRoute = parallelRoutes[parallelRouteKey]
const hasChildPartialPrefetching =
await anySegmentHasPartialPrefetchingEnabled(parallelRoute)
if (hasChildPartialPrefetching) {
return true
// TODO(restart-on-cache-miss): Does this work correctly for client page/layout modules?
const prefetchConfig = layoutOrPageMod
? (layoutOrPageMod as AppSegmentConfig).prefetch
: undefined
if (prefetchConfig !== undefined) {
hasExplicitConfig = true
if (prefetchConfig === 'partial') {
hasPartialOptIn = true
return
}
}
const { parallelRoutes } = parseLoaderTree(segmentTree)
for (const parallelRouteKey in parallelRoutes) {
await visit(parallelRoutes[parallelRouteKey])
if (hasPartialOptIn) {
return
}
}
}
return false
await visit(tree)
return hasPartialOptIn || (!hasExplicitConfig && appDefault)
}
export async function isPageAllowedToBlock(tree: LoaderTree): Promise<boolean> {
......
......@@ -4,8 +4,8 @@ import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
// The `partial-prefetching` fixture enables Partial Prefetching globally via
// the next-config `partialPrefetching: true`, which opts every route into
// runtime Cached Navigations even without a per-segment `prefetch` config.
// the next-config `partialPrefetching: true`, which opts routes without an
// explicit segment override into runtime Cached Navigations.
describe('cached navigations - global partialPrefetching', () => {
const { next, isNextDev } = nextTestSetup({
files: path.join(__dirname, 'partial-prefetching'),
......@@ -90,4 +90,60 @@ describe('cached navigations - global partialPrefetching', () => {
'Dynamic content'
)
})
it('does not embed a runtime prefetch in HTML for a force-disabled route', async () => {
const html = await next.render('/runtime-prefetch-disabled')
// One copy renders as HTML and one hydrates it. A third copy would be the
// embedded runtime prefetch used to seed the client cache.
expect((html.match(/Cached content/g) ?? []).length).toBe(2)
})
it('does not runtime-cache a force-disabled route after a dynamic navigation', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
async beforePageLoad(p: Playwright.Page) {
page = p
await page.clock.install()
},
})
const act = createRouterAct(page)
// A plain navigation renders the route, but should not seed the runtime
// segment cache because the destination explicitly opts out.
await act(
async () => {
await browser
.elementByCss('a[href="/runtime-prefetch-disabled"]')
.click()
},
{ includes: 'Dynamic content' }
)
await browser.back()
expect(await browser.elementByCss('h1').text()).toBe('Home')
await act(async () => {
await act(
async () => {
await browser
.elementByCss('a[href="/runtime-prefetch-disabled"]')
.click()
},
{
includes: 'Dynamic content',
block: true,
}
)
const mainText = await (await browser.elementByCss('main')).innerText()
expect(mainText).not.toContain('Search params:')
expect(mainText).not.toContain('Cookie:')
expect(mainText).not.toContain('Header:')
})
expect(await browser.elementById('connection-boundary').text()).toContain(
'Dynamic content'
)
})
})
......@@ -13,6 +13,11 @@ export default function Home() {
Go to runtime-prefetchable page
</Link>
</li>
<li>
<Link href="/runtime-prefetch-disabled" prefetch={false}>
Go to prefetch-disabled page
</Link>
</li>
</ul>
</main>
)
......
import Page from '../runtime-prefetchable/page'
export const prefetch = 'force-disabled'
export default Page
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