Unverified Commit 568c7029 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Track vary params during runtime prefetches (#89297)

**Previous:**

1. https://github.com/vercel/next.js/pull/91487
2. https://github.com/vercel/next.js/pull/91488

**Current:**

3. https://github.com/vercel/next.js/pull/89297

---

Most of the vary params infrastructure was already implemented in
previous PRs for static prerenders. This wires up the remaining pieces
for runtime prefetches — creating the accumulator, setting it on the
prerender store, and resolving it before abort — and adds additional
test cases covering empty/full vary sets, searchParams, metadata, and
per-segment layout/page splits with runtime prefetching.
parent e16f6fb2
...@@ -1537,6 +1537,8 @@ async function finalRuntimeServerPrerender( ...@@ -1537,6 +1537,8 @@ async function finalRuntimeServerPrerender(
true // track sync IO true // track sync IO
) )
const varyParamsAccumulator = createResponseVaryParamsAccumulator()
const finalServerPrerenderStore: PrerenderStoreModernRuntime = { const finalServerPrerenderStore: PrerenderStoreModernRuntime = {
type: 'prerender-runtime', type: 'prerender-runtime',
phase: 'render', phase: 'render',
...@@ -1556,8 +1558,7 @@ async function finalRuntimeServerPrerender( ...@@ -1556,8 +1558,7 @@ async function finalRuntimeServerPrerender(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache, renderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
// TODO: Enable vary params tracking for runtime prefetches. varyParamsAccumulator,
varyParamsAccumulator: null,
// Used to separate the stages in the 5-task pipeline. // Used to separate the stages in the 5-task pipeline.
stagedRendering: finalStageController, stagedRendering: finalStageController,
// These are not present in regular prerenders, but allowed in a runtime prerender. // These are not present in regular prerenders, but allowed in a runtime prerender.
...@@ -1612,10 +1613,13 @@ async function finalRuntimeServerPrerender( ...@@ -1612,10 +1613,13 @@ async function finalRuntimeServerPrerender(
finalStageController.advanceStage(RenderStage.Runtime) finalStageController.advanceStage(RenderStage.Runtime)
}, },
() => { () => {
finishStaleTimeTracking(staleTimeIterable).then(() => { Promise.all([
finishStaleTimeTracking(staleTimeIterable),
finishAccumulatingVaryParams(varyParamsAccumulator),
]).then(() => {
// Abort. This runs as a microtask after Flight has flushed the // Abort. This runs as a microtask after Flight has flushed the
// staleTime closing chunk, but before the next macrotask resolves the // staleTime and varyParams closing chunks, but before the next
// overall result. // macrotask resolves the overall result.
if (finalServerController.signal.aborted) { if (finalServerController.signal.aborted) {
// If the server controller is already aborted we must have called // If the server controller is already aborted we must have called
// something that required aborting the prerender synchronously such // something that required aborting the prerender synchronously such
......
import { Suspense } from 'react'
import { connection } from 'next/server'
/**
* Runtime prefetch page where ALL params are accessed in the static portion.
*
* Both category and itemId are accessed before connection(), so they
* are both tracked in varyParams. Every unique combination of (category, itemId)
* requires its own prefetch — no cache sharing.
*/
export const unstable_instant: {
prefetch: 'runtime'
samples: Array<{ params: { category: string; itemId: string } }>
} = {
prefetch: 'runtime',
samples: [
{ params: { category: 'electronics', itemId: 'phone' } },
{ params: { category: 'clothing', itemId: 'shirt' } },
],
}
type Params = { category: string; itemId: string }
export default async function RuntimePrefetchAllVaryPage({
params,
}: {
params: Promise<Params>
}) {
return (
<div id="runtime-prefetch-all-vary-page">
<Suspense fallback={<div>Loading...</div>}>
<StaticContent params={params} />
</Suspense>
</div>
)
}
async function StaticContent({ params }: { params: Promise<Params> }) {
// Access both params in the static portion — both tracked in varyParams
const { category, itemId } = await params
return (
<>
<div data-static-content="true">
{`Static content - ${category}/${itemId}`}
</div>
<Suspense fallback={<div data-loading="true">Loading details...</div>}>
<DynamicContent />
</Suspense>
</>
)
}
async function DynamicContent() {
await connection()
return <div data-dynamic-content="true">Dynamic details loaded</div>
}
import { LinkAccordion } from '../../../components/link-accordion'
export default function RuntimePrefetchAllVaryIndexPage() {
return (
<div id="runtime-prefetch-all-vary-index">
<h1>Runtime Prefetch - All Params in Static Portion</h1>
<ul>
<li>
<LinkAccordion href="/runtime-prefetch-all-vary/electronics/phone">
Electronics: Phone
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/runtime-prefetch-all-vary/electronics/tablet">
Electronics: Tablet
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/runtime-prefetch-all-vary/clothing/shirt">
Clothing: Shirt
</LinkAccordion>
</li>
</ul>
</div>
)
}
import { Suspense } from 'react'
/**
* Layout that accesses both category and itemId params inside Suspense.
*
* Since this layout accesses both params, it varies on both — changing
* either param requires re-fetching this layout segment.
*/
type Params = { category: string; itemId: string }
export default async function RuntimePrefetchLayoutSplitLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<Params>
}) {
return (
<div data-layout-split-layout="true">
<Suspense fallback={<div>Loading layout...</div>}>
<LayoutContent params={params} />
</Suspense>
{children}
</div>
)
}
async function LayoutContent({ params }: { params: Promise<Params> }) {
const { category, itemId } = await params
return <div data-layout-content="true">{`Layout: ${category}/${itemId}`}</div>
}
import { Suspense } from 'react'
import { connection } from 'next/server'
/**
* Page that accesses only category (not itemId) in the static portion.
*
* Combined with the layout (which accesses both params), this tests that
* vary params are tracked per-segment in runtime prefetches:
* - Layout varies on both category AND itemId → re-fetched when either changes
* - Page varies only on category → cached when only itemId changes
*/
export const unstable_instant: {
prefetch: 'runtime'
samples: Array<{ params: { category: string; itemId: string } }>
} = {
prefetch: 'runtime',
samples: [
{ params: { category: 'electronics', itemId: 'phone' } },
{ params: { category: 'clothing', itemId: 'shirt' } },
],
}
type Params = { category: string; itemId: string }
export default async function RuntimePrefetchLayoutSplitPage({
params,
}: {
params: Promise<Params>
}) {
return (
<div id="runtime-prefetch-layout-split-page">
<Suspense fallback={<div>Loading page...</div>}>
<StaticContent params={params} />
</Suspense>
</div>
)
}
async function StaticContent({ params }: { params: Promise<Params> }) {
// Only access category — page varies on category but NOT itemId
const { category } = await params
return (
<>
<div data-page-content="true">{`Page category: ${category}`}</div>
<Suspense fallback={<div data-loading="true">Loading details...</div>}>
<DynamicContent />
</Suspense>
</>
)
}
async function DynamicContent() {
await connection()
return <div data-dynamic-content="true">Dynamic details loaded</div>
}
import { LinkAccordion } from '../../../components/link-accordion'
export default function RuntimePrefetchLayoutSplitIndexPage() {
return (
<div id="runtime-prefetch-layout-split-index">
<h1>Runtime Prefetch - Layout/Page Param Split</h1>
<ul>
<li>
<LinkAccordion href="/runtime-prefetch-layout-split/electronics/phone">
Electronics: Phone
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/runtime-prefetch-layout-split/electronics/tablet">
Electronics: Tablet
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/runtime-prefetch-layout-split/clothing/shirt">
Clothing: Shirt
</LinkAccordion>
</li>
</ul>
</div>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
/**
* Runtime prefetch page where generateMetadata accesses params but the
* page body does NOT.
*
* This tests that head vary params are tracked separately from segment body
* in the runtime prefetch pipeline. When slug changes:
* - Head segment should be re-fetched (metadata accesses slug)
* - Body segment should be cached (body does NOT access slug)
*/
export const unstable_instant: {
prefetch: 'runtime'
samples: Array<{ params: { slug: string } }>
} = {
prefetch: 'runtime',
samples: [{ params: { slug: 'aaa' } }, { params: { slug: 'bbb' } }],
}
type Params = { slug: string }
export async function generateMetadata({
params,
}: {
params: Promise<Params>
}) {
const { slug } = await params
return { title: `Runtime Metadata: ${slug}` }
}
export default async function RuntimePrefetchMetadataPage() {
// Intentionally NOT accessing params in the body
return (
<div id="runtime-prefetch-metadata-page">
<Suspense fallback={<div>Loading...</div>}>
<DynamicContent />
</Suspense>
<div data-content="true">Static page body - no param access</div>
</div>
)
}
async function DynamicContent() {
await connection()
return <div data-dynamic-content="true">Dynamic content loaded</div>
}
import { LinkAccordion } from '../../../components/link-accordion'
export default function RuntimePrefetchMetadataIndexPage() {
return (
<div id="runtime-prefetch-metadata-index">
<h1>Runtime Prefetch - Metadata Param Access</h1>
<ul>
<li>
<LinkAccordion href="/runtime-prefetch-metadata/aaa">
Slug: aaa
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/runtime-prefetch-metadata/bbb">
Slug: bbb
</LinkAccordion>
</li>
</ul>
</div>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
/**
* Runtime prefetch page where NO params are accessed in the static portion.
*
* Both category and itemId are accessed only after connection(), so they
* are NOT tracked in varyParams. This means ALL param combinations should
* share the same cached loading shell (empty vary params set = max sharing).
*/
export const unstable_instant: {
prefetch: 'runtime'
samples: Array<{ params: { category: string; itemId: string } }>
} = {
prefetch: 'runtime',
samples: [
{ params: { category: 'electronics', itemId: 'phone' } },
{ params: { category: 'clothing', itemId: 'shirt' } },
],
}
type Params = { category: string; itemId: string }
export default async function RuntimePrefetchNoVaryPage({
params,
}: {
params: Promise<Params>
}) {
return (
<div id="runtime-prefetch-no-vary-page">
<Suspense
fallback={
<div data-loading="true">Loading all content dynamically...</div>
}
>
<DynamicContent params={params} />
</Suspense>
</div>
)
}
async function DynamicContent({ params }: { params: Promise<Params> }) {
await connection()
const { category, itemId } = await params
return (
<div data-dynamic-content="true">{`Dynamic: ${category}/${itemId}`}</div>
)
}
import { LinkAccordion } from '../../../components/link-accordion'
export default function RuntimePrefetchNoVaryIndexPage() {
return (
<div id="runtime-prefetch-no-vary-index">
<h1>Runtime Prefetch - No Params in Static Portion</h1>
<ul>
<li>
<LinkAccordion href="/runtime-prefetch-no-vary/electronics/phone">
Electronics: Phone
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/runtime-prefetch-no-vary/electronics/tablet">
Electronics: Tablet
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/runtime-prefetch-no-vary/clothing/shirt">
Clothing: Shirt
</LinkAccordion>
</li>
</ul>
</div>
)
}
import { LinkAccordion } from '../../../components/link-accordion'
export default function RuntimePrefetchSearchParamsIndexPage() {
return (
<div id="runtime-prefetch-search-params-index">
<h1>Runtime Prefetch - SearchParams Not Accessed</h1>
<ul>
<li>
<LinkAccordion href="/runtime-prefetch-search-params/target-page?q=1">
Target q=1
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/runtime-prefetch-search-params/target-page?q=2">
Target q=2
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/runtime-prefetch-search-params/target-page?q=3">
Target q=3
</LinkAccordion>
</li>
</ul>
</div>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
/**
* Runtime prefetch page that does NOT access searchParams.
*
* Since searchParams are not accessed, the '?' sentinel is not added to
* varyParams, and different search param values share the cached segment.
*/
export const unstable_instant = {
prefetch: 'runtime',
samples: [{ searchParams: { q: '1' } }],
}
export default async function RuntimePrefetchSearchParamsTargetPage() {
// Intentionally NOT accessing searchParams
return (
<div id="runtime-prefetch-search-params-target">
<div data-content="true">Static content - searchParams not accessed</div>
<Suspense fallback={<div>Loading...</div>}>
<DynamicContent />
</Suspense>
</div>
)
}
async function DynamicContent() {
await connection()
return <div data-dynamic-content="true">Dynamic content loaded</div>
}
...@@ -83,10 +83,7 @@ describe('segment cache - vary params', () => { ...@@ -83,10 +83,7 @@ describe('segment cache - vary params', () => {
expect(await page.text()).toContain('Item: headphones') expect(await page.text()).toContain('Item: headphones')
}) })
// TODO: Re-enable once vary params tracking is implemented for runtime it('renders cached loading state instantly with runtime prefetching', async () => {
// prefetch abort paths. The abort timing needs to resolve vary params before
// the abort signal fires. See static-siblings-infrastructure branch.
it.skip('renders cached loading state instantly with runtime prefetching', async () => {
// Setup: Page accesses `category` in static portion (tracked in varyParams), // Setup: Page accesses `category` in static portion (tracked in varyParams),
// but accesses `itemId` only after connection() (not tracked). // but accesses `itemId` only after connection() (not tracked).
let act: ReturnType<typeof createRouterAct> let act: ReturnType<typeof createRouterAct>
...@@ -463,6 +460,211 @@ describe('segment cache - vary params', () => { ...@@ -463,6 +460,211 @@ describe('segment cache - vary params', () => {
expect(await page.text()).toContain('Slug: aaa') expect(await page.text()).toContain('Slug: aaa')
}) })
it('shares cached segment across all params when none accessed statically (runtime prefetch)', async () => {
// Both params are accessed only after connection(), so varyParams is
// empty. ALL param combinations share the same cached loading shell.
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/runtime-prefetch-no-vary', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// First prefetch fetches the segment
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch-no-vary/electronics/phone"]'
)
await toggle.click()
},
{ includes: 'Loading all content dynamically' }
)
// All other combinations are cache hits — even different categories
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch-no-vary/electronics/tablet"]'
)
await toggle.click()
}, 'no-requests')
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch-no-vary/clothing/shirt"]'
)
await toggle.click()
}, 'no-requests')
})
it('does not share cached segment when all params accessed statically (runtime prefetch)', async () => {
// Both params are accessed before connection(), so every unique
// combination of (category, itemId) requires its own prefetch.
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/runtime-prefetch-all-vary', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// Each prefetch triggers a new request
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch-all-vary/electronics/phone"]'
)
await toggle.click()
},
{ includes: 'Static content - electronics/phone' }
)
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch-all-vary/electronics/tablet"]'
)
await toggle.click()
},
{ includes: 'Static content - electronics/tablet' }
)
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch-all-vary/clothing/shirt"]'
)
await toggle.click()
},
{ includes: 'Static content - clothing/shirt' }
)
})
it('shares cached segment across search params when not accessed (runtime prefetch)', async () => {
// Runtime prefetch page that does NOT access searchParams. Since '?'
// is not in varyParams, different search param values share the cache.
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/runtime-prefetch-search-params', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// First prefetch fetches the segment
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch-search-params/target-page?q=1"]'
)
await toggle.click()
},
{ includes: 'Static content - searchParams not accessed' }
)
// Different search param values are cache hits
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch-search-params/target-page?q=2"]'
)
await toggle.click()
}, 'no-requests')
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch-search-params/target-page?q=3"]'
)
await toggle.click()
}, 'no-requests')
})
it('tracks metadata param access separately from body (runtime prefetch)', async () => {
// generateMetadata accesses slug, but the page body does NOT.
// Each slug triggers a new head prefetch because metadata varies on slug.
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/runtime-prefetch-metadata', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// First prefetch triggers a request including the metadata
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch-metadata/aaa"]'
)
await toggle.click()
},
{ includes: 'Runtime Metadata: aaa' }
)
// Second prefetch with different slug triggers a new request
// (metadata varies on slug, so it can't reuse the cache)
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch-metadata/bbb"]'
)
await toggle.click()
},
{ includes: 'Runtime Metadata: bbb' }
)
})
it('tracks vary params per-segment with layout/page split (runtime prefetch)', async () => {
// Layout accesses both category and itemId; page accesses only category.
// When itemId changes but category stays the same, the page segment
// should be reused from cache (only varies on category).
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/runtime-prefetch-layout-split', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// First prefetch fetches page segment
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch-layout-split/electronics/phone"]'
)
await toggle.click()
},
{ includes: 'Page category:' }
)
// Second prefetch: same category, different itemId.
// The page segment is a cache hit since it only varies on category.
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch-layout-split/electronics/tablet"]'
)
await toggle.click()
}, 'no-requests')
// Different category triggers a new page segment fetch
await act(
async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="/runtime-prefetch-layout-split/clothing/shirt"]'
)
await toggle.click()
},
{ includes: 'Page category:' }
)
// Navigate and verify correct content
const link = await browser.elementByCss(
'a[href="/runtime-prefetch-layout-split/electronics/tablet"]'
)
await link.click()
const layout = await browser.elementByCss('[data-layout-content]')
expect(await layout.text()).toContain('Layout: electronics/tablet')
const page = await browser.elementById('runtime-prefetch-layout-split-page')
expect(await page.text()).toContain('Page category: electronics')
})
it('tracks root param access via rootParams API', async () => { it('tracks root param access via rootParams API', async () => {
// Root params accessed via rootParams() are tracked in varyParams. // Root params accessed via rootParams() are tracked in varyParams.
// Different param values require separate prefetches. // Different param values require separate prefetches.
......
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