Unverified Commit d8f95c12 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[PPF] Fix navigation() in prospective runtime prerenders (#98000)

### Long story short

Fixes an analogous bug to #95665, but affecting
`prefetch()/navigation()`. Those two were accidentally always resolving
in the **prospective** runtime prerender, so we were warming content
that isn't needed for the final runtime prerender. We now guard them
properly.

Also, I replaced `PrerenderStoreModernRuntime.isSessionShell` with
`finalStage` (the same stage we're gonna use for the final prerender),
so we can include/exclude `navigation` properly -- the boolean only
distinguished shell/prefetch, not navigation.

### Long story long

We use runtime prerenders for three things: runtime shells, runtime
prefetches, and embedding a prefetch in navigations. These are aborted
after `ShellRuntime`, `Runtime`, and `NavigationRuntime` respectively
(accessible in `stageController.finalStage`). If we're doing the
**final** prerender for a shell, promises that would resolve in e.g.
`NavigationRuntime` would never resolve, because we abort the prerender
before we get there.

However, the **prospective** runtime prerender has no
`StagedRenderingController` and needs to model this separately (so that
the same APIs hang in both). This was [previously done via
`prerenderStore.isSessionShell`](https://github.com/vercel/next.js/pull/95665)
which we checked in URL data apis i.e. `params/searchParams` and the
metadata`pathname` to do this. `isSessionShell: true` meant they should
hang because it's a shell, and `isSessionShell: false` meant they should
resolve.

However, I forgot about this case when implementing
`navigation`/`prefetch`, and made them resolve unconditionally in the
prospective prerender. This means we'd potentially warm content that
would not actually be reached in the final prerender. In other words,
```ts
await navigation()
return <Expensive />
```
would needlessly render `<Expensive />` during the prospective render
but not in the final one. This kinda defeats `navigation`'s main
purpose, i.e. avoiding expensive work.

This PR fixes the bug by replacing `isSessionShell: boolean` with
`finalStage: AdvanceableRenderStage`, which is set to the same value we
put in `stageController.finalStage`. This lets us keep the logic of what
hangs and what resolves relatively close in both prerenders.

---

On a meta level, the fact that the same bug happened twice tells me that
having a `StageRenderingController` that is sometimes `null` is
error-prone, and we should figure out a better solution, but i'm gonna
keep this fix targeted and figure out a more holistic solution in a
follow-up
parent 357e514c
...@@ -1598,17 +1598,6 @@ async function generateRuntimePrefetchResult( ...@@ -1598,17 +1598,6 @@ async function generateRuntimePrefetchResult(
// but we're not going to persist this anywhere. // but we're not going to persist this anywhere.
const prerenderResumeDataCache = createPrerenderResumeDataCache() const prerenderResumeDataCache = createPrerenderResumeDataCache()
await prospectiveRuntimeServerPrerender(
ctx,
isShellPrefetch,
generateDynamicRSCPayload.bind(null, ctx),
prerenderResumeDataCache,
rootParams,
requestStore.headers,
requestStore.cookies,
requestStore.draftMode
)
const mode: RuntimePrerenderMode = isShellPrefetch const mode: RuntimePrerenderMode = isShellPrefetch
? { ? {
type: 'session-shell-only', type: 'session-shell-only',
...@@ -1620,6 +1609,17 @@ async function generateRuntimePrefetchResult( ...@@ -1620,6 +1609,17 @@ async function generateRuntimePrefetchResult(
shellByteLengthDeferred: createPromiseWithResolvers(), shellByteLengthDeferred: createPromiseWithResolvers(),
} }
await prospectiveRuntimeServerPrerender(
ctx,
getFinalStageForRuntimePrerenderMode(mode),
generateDynamicRSCPayload.bind(null, ctx),
prerenderResumeDataCache,
rootParams,
requestStore.headers,
requestStore.cookies,
requestStore.draftMode
)
const debugChannel = setReactDebugChannel const debugChannel = setReactDebugChannel
? createWebDebugChannel() ? createWebDebugChannel()
: undefined : undefined
...@@ -1656,7 +1656,7 @@ async function generateRuntimePrefetchResult( ...@@ -1656,7 +1656,7 @@ async function generateRuntimePrefetchResult(
async function prospectiveRuntimeServerPrerender( async function prospectiveRuntimeServerPrerender(
ctx: AppRenderContext, ctx: AppRenderContext,
isShellPrefetch: boolean, finalStage: AdvanceableRenderStage,
getPayload: () => Promise<RSCPayload>, getPayload: () => Promise<RSCPayload>,
resumeDataCache: PrerenderResumeDataCache | null, resumeDataCache: PrerenderResumeDataCache | null,
rootParams: Params, rootParams: Params,
...@@ -1705,9 +1705,10 @@ async function prospectiveRuntimeServerPrerender( ...@@ -1705,9 +1705,10 @@ async function prospectiveRuntimeServerPrerender(
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
// We don't track vary params during initial prerender, only the final one // We don't track vary params during initial prerender, only the final one
varyParamsAccumulator: null, varyParamsAccumulator: null,
// No stage sequencing needed for prospective renders. // We don't use sequencing needed for prospective renders, but we need to
// track where the final prerender is going to end to avoid warming too much.
stagedRendering: null, stagedRendering: null,
isSessionShell: isShellPrefetch, finalStage,
// These are not present in regular prerenders, but allowed in a runtime // These are not present in regular prerenders, but allowed in a runtime
// prerender. // prerender.
// Any cache keyed on headers() or cookies() needs to be invalidated. // Any cache keyed on headers() or cookies() needs to be invalidated.
...@@ -1854,19 +1855,8 @@ async function finalRuntimeServerPrerender( ...@@ -1854,19 +1855,8 @@ async function finalRuntimeServerPrerender(
isDebugDynamicAccesses isDebugDynamicAccesses
) )
let finalStage: AdvanceableRenderStage const finalStage = getFinalStageForRuntimePrerenderMode(mode)
switch (mode.type) { const stageController = new StagedRenderingController({
case 'session-shell-only':
finalStage = RenderStage.ShellRuntime
break
case 'rewindable-session-shell':
finalStage = RenderStage.Runtime
break
case 'navigation':
finalStage = RenderStage.NavigationRuntime
break
}
const finalStageController = new StagedRenderingController({
abortSignal: finalServerController.signal, abortSignal: finalServerController.signal,
abandonController: null, abandonController: null,
// In dynamic renders, we allow Sync IO in the Runtime stage // In dynamic renders, we allow Sync IO in the Runtime stage
...@@ -1898,8 +1888,8 @@ async function finalRuntimeServerPrerender( ...@@ -1898,8 +1888,8 @@ async function finalRuntimeServerPrerender(
resumeDataCache, resumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
varyParamsAccumulator, varyParamsAccumulator,
stagedRendering: finalStageController, stagedRendering: stageController,
isSessionShell: mode.type === 'session-shell-only', finalStage,
// These are not present in regular prerenders, but allowed in a runtime // These are not present in regular prerenders, but allowed in a runtime
// prerender. // prerender.
headers: HeadersAdapter.fresh(headers), headers: HeadersAdapter.fresh(headers),
...@@ -1923,7 +1913,7 @@ async function finalRuntimeServerPrerender( ...@@ -1923,7 +1913,7 @@ async function finalRuntimeServerPrerender(
collectPrerenderChunk(collectedChunks, finalServerController.signal, chunk) collectPrerenderChunk(collectedChunks, finalServerController.signal, chunk)
increaseChunkByteLengths( increaseChunkByteLengths(
stageByteLengths, stageByteLengths,
finalStageController.currentStage, stageController.currentStage,
chunk.byteLength chunk.byteLength
) )
} }
...@@ -1963,7 +1953,7 @@ async function finalRuntimeServerPrerender( ...@@ -1963,7 +1953,7 @@ async function finalRuntimeServerPrerender(
await runInSequentialTasks( await runInSequentialTasks(
async () => { async () => {
finalStageController.advanceStage(RenderStage.ShellStatic) stageController.advanceStage(RenderStage.ShellStatic)
let stream = workUnitAsyncStorage.run( let stream = workUnitAsyncStorage.run(
finalServerPrerenderStore, finalServerPrerenderStore,
...@@ -1989,19 +1979,19 @@ async function finalRuntimeServerPrerender( ...@@ -1989,19 +1979,19 @@ async function finalRuntimeServerPrerender(
}, },
() => { () => {
if (checkUnexpectedAbort()) return if (checkUnexpectedAbort()) return
finalStageController.advanceStage(RenderStage.PrefetchStatic) stageController.advanceStage(RenderStage.PrefetchStatic)
}, },
() => { () => {
if (checkUnexpectedAbort()) return if (checkUnexpectedAbort()) return
finalStageController.advanceStage(RenderStage.NavigationStatic) stageController.advanceStage(RenderStage.NavigationStatic)
}, },
() => { () => {
if (checkUnexpectedAbort()) return if (checkUnexpectedAbort()) return
finalStageController.advanceStage(RenderStage.Static) stageController.advanceStage(RenderStage.Static)
}, },
() => { () => {
if (checkUnexpectedAbort()) return if (checkUnexpectedAbort()) return
finalStageController.advanceStage(RenderStage.ShellRuntime) stageController.advanceStage(RenderStage.ShellRuntime)
}, },
() => { () => {
if (checkUnexpectedAbort()) return if (checkUnexpectedAbort()) return
...@@ -2009,7 +1999,7 @@ async function finalRuntimeServerPrerender( ...@@ -2009,7 +1999,7 @@ async function finalRuntimeServerPrerender(
// We may not reach this stage depending on the mode. // We may not reach this stage depending on the mode.
if (finalStage < RenderStage.Runtime) return if (finalStage < RenderStage.Runtime) return
finalStageController.advanceStage(RenderStage.Runtime) stageController.advanceStage(RenderStage.Runtime)
}, },
() => { () => {
if (checkUnexpectedAbort()) return if (checkUnexpectedAbort()) return
...@@ -2040,7 +2030,7 @@ async function finalRuntimeServerPrerender( ...@@ -2040,7 +2030,7 @@ async function finalRuntimeServerPrerender(
// We may not reach this stage depending on the mode. // We may not reach this stage depending on the mode.
if (finalStage < RenderStage.NavigationRuntime) return if (finalStage < RenderStage.NavigationRuntime) return
finalStageController.advanceStage(RenderStage.NavigationRuntime) stageController.advanceStage(RenderStage.NavigationRuntime)
}, },
() => { () => {
// Finish the accumulators. We need to wait for Flight to flush the result into the stream, // Finish the accumulators. We need to wait for Flight to flush the result into the stream,
...@@ -2090,6 +2080,19 @@ async function finalRuntimeServerPrerender( ...@@ -2090,6 +2080,19 @@ async function finalRuntimeServerPrerender(
} }
} }
function getFinalStageForRuntimePrerenderMode(
mode: RuntimePrerenderMode
): AdvanceableRenderStage {
switch (mode.type) {
case 'session-shell-only':
return RenderStage.ShellRuntime
case 'rewindable-session-shell':
return RenderStage.Runtime
case 'navigation':
return RenderStage.NavigationRuntime
}
}
/** /**
* Crawlers will inadvertently think the canonicalUrl in the RSC payload should be crawled * Crawlers will inadvertently think the canonicalUrl in the RSC payload should be crawled
* when our intention is to just seed the router state with the current URL. * when our intention is to just seed the router state with the current URL.
......
...@@ -16,7 +16,10 @@ import type { Params } from '../request/params' ...@@ -16,7 +16,10 @@ import type { Params } from '../request/params'
import type { ImplicitTags } from '../lib/implicit-tags' import type { ImplicitTags } from '../lib/implicit-tags'
import type { WorkStore } from './work-async-storage.external' import type { WorkStore } from './work-async-storage.external'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import type { StagedRenderingController } from './staged-rendering' import type {
AdvanceableRenderStage,
StagedRenderingController,
} from './staged-rendering'
import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking' import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'
import type { InstantValidationSampleTracking } from './instant-validation/instant-samples' import type { InstantValidationSampleTracking } from './instant-validation/instant-samples'
...@@ -226,7 +229,7 @@ export interface PrerenderStoreModernRuntime ...@@ -226,7 +229,7 @@ export interface PrerenderStoreModernRuntime
* renders where all stages run without sequencing. * renders where all stages run without sequencing.
*/ */
readonly stagedRendering: StagedRenderingController | null readonly stagedRendering: StagedRenderingController | null
readonly isSessionShell: boolean readonly finalStage: AdvanceableRenderStage
readonly headers: RequestStore['headers'] readonly headers: RequestStore['headers']
readonly cookies: RequestStore['cookies'] readonly cookies: RequestStore['cookies']
......
...@@ -5,6 +5,7 @@ import { ...@@ -5,6 +5,7 @@ import {
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { import {
applyOwnerStack, applyOwnerStack,
makeUntrackedHangingPromise,
RENDER_STAGES_BY_DATA_KIND, RENDER_STAGES_BY_DATA_KIND,
trackIncompatibleShellContent, trackIncompatibleShellContent,
} from '../dynamic-rendering-utils' } from '../dynamic-rendering-utils'
...@@ -52,6 +53,7 @@ export function unstable_prefetch(): Promise<void> { ...@@ -52,6 +53,7 @@ export function unstable_prefetch(): Promise<void> {
const { stagedRendering } = workUnitStore const { stagedRendering } = workUnitStore
if (!stagedRendering) { if (!stagedRendering) {
// Prospective prerender // Prospective prerender
// `unstable_prefetch()` will resolve in the final prerender, so resolve it here as well.
return Promise.resolve(undefined) return Promise.resolve(undefined)
} else { } else {
// Final prerender // Final prerender
...@@ -69,13 +71,23 @@ export function unstable_prefetch(): Promise<void> { ...@@ -69,13 +71,23 @@ export function unstable_prefetch(): Promise<void> {
// Note that this does not mark the subtree as dynamic -- content guarded by // Note that this does not mark the subtree as dynamic -- content guarded by
// prefetch() is still considered cacheable. // prefetch() is still considered cacheable.
const { stagedRendering } = workUnitStore const { stagedRendering } = workUnitStore
const prefetchStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
if (!stagedRendering) { if (!stagedRendering) {
// Prospective prerender // Prospective prerender
return Promise.resolve(undefined) // Make sure we don't unblock content that won't be reached in the final prerender.
if (workUnitStore.finalStage < prefetchStage) {
return makeUntrackedHangingPromise(
workUnitStore.renderSignal,
workStore.route,
'`unstable_prefetch()`'
)
} else {
return Promise.resolve(undefined)
}
} else { } else {
// Final prerender // Final prerender
return stagedRendering.delayUntilStage( return stagedRendering.delayUntilStage(
RENDER_STAGES_BY_DATA_KIND.runtimeLinkData, prefetchStage,
'unstable_prefetch', 'unstable_prefetch',
undefined undefined
) )
...@@ -194,6 +206,7 @@ export function unstable_navigation(): Promise<void> { ...@@ -194,6 +206,7 @@ export function unstable_navigation(): Promise<void> {
const { stagedRendering } = workUnitStore const { stagedRendering } = workUnitStore
if (!stagedRendering) { if (!stagedRendering) {
// Prospective prerender // Prospective prerender
// `unstable_navigation()` will resolve in the final prerender, so resolve it here as well.
return Promise.resolve(undefined) return Promise.resolve(undefined)
} else { } else {
// Final prerender // Final prerender
...@@ -211,13 +224,23 @@ export function unstable_navigation(): Promise<void> { ...@@ -211,13 +224,23 @@ export function unstable_navigation(): Promise<void> {
// Note that this does not mark the subtree as dynamic -- content guarded by // Note that this does not mark the subtree as dynamic -- content guarded by
// navigation() is still considered cacheable. // navigation() is still considered cacheable.
const { stagedRendering } = workUnitStore const { stagedRendering } = workUnitStore
const navigationStage = RenderStage.NavigationRuntime
if (!stagedRendering) { if (!stagedRendering) {
// Prospective prerender // Prospective prerender
return Promise.resolve(undefined) // Make sure we don't unblock content that won't be reached in the final prerender.
if (workUnitStore.finalStage < navigationStage) {
return makeUntrackedHangingPromise(
workUnitStore.renderSignal,
workStore.route,
'`unstable_navigation()`'
)
} else {
return Promise.resolve(undefined)
}
} else { } else {
// Final prerender // Final prerender
return stagedRendering.delayUntilStage( return stagedRendering.delayUntilStage(
RenderStage.NavigationRuntime, navigationStage,
'unstable_navigation', 'unstable_navigation',
undefined undefined
) )
......
...@@ -427,36 +427,27 @@ function createRuntimePrerenderParams( ...@@ -427,36 +427,27 @@ function createRuntimePrerenderParams(
return makeUntrackedParams(userspaceParams) return makeUntrackedParams(userspaceParams)
} }
// Root params are allowed in shells, so we allow them to resolve without a delay.
if (allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {
return makeUntrackedParams(userspaceParams)
}
// Non-root params are URL data, and we need to recover a param-less session shell,
// so we delay all params until the runtime stage (even if they're static)
const paramsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
const { stagedRendering } = workUnitStore const { stagedRendering } = workUnitStore
if (!stagedRendering) { if (!stagedRendering) {
// If there's no staging, we're in a prospective runtime prerender. // If there's no stage controller, we're in a prospective runtime prerender.
if (workUnitStore.isSessionShell) { // Make sure we don't unblock content that won't be reached in the final prerender.
// If we're warming up for a session shell, params should be hanging, if (workUnitStore.finalStage < paramsStage) {
// because they'll be a hanging input in the final prerender.
return makeHangingParams(underlyingParams, workStore, workUnitStore) return makeHangingParams(underlyingParams, workStore, workUnitStore)
} else { } else {
return makeUntrackedParams(userspaceParams) return makeUntrackedParams(userspaceParams)
} }
} }
// We don't have fallbackParams in runtime prerenders, so we don't know return stagedRendering.delayUntilStage(paramsStage, 'params', userspaceParams)
// when params are static. However, root params are static by definition,
// so we can at least check for that.
// Note that resolving them without a delay is valid because root params are
// allowed in shells.
if (allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {
return makeUntrackedParams(userspaceParams)
}
// Semantically, we should resolve static params in the static stage.
// But params are link data, and we need to recover a param-less session shell,
// so we delay all params until the runtime stage instead.
const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
return stagedRendering.delayUntilStage(
staticParamsStage,
'params',
userspaceParams
)
} }
function createRenderParamsForPage( function createRenderParamsForPage(
......
...@@ -57,15 +57,15 @@ export function createServerPathnameForMetadata( ...@@ -57,15 +57,15 @@ export function createServerPathnameForMetadata(
// behavior of always resolving in the runtime stage // behavior of always resolving in the runtime stage
// (i.e. assuming that we have non-static params in the pathname) // (i.e. assuming that we have non-static params in the pathname)
const { stagedRendering } = workUnitStore const { stagedRendering } = workUnitStore
const pathnameStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
if (stagedRendering) { if (stagedRendering) {
const pathnameStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
return stagedRendering.delayUntilStage( return stagedRendering.delayUntilStage(
pathnameStage, pathnameStage,
undefined, undefined,
underlyingPathname underlyingPathname
) )
} else { } else {
if (workUnitStore.isSessionShell) { if (workUnitStore.finalStage < pathnameStage) {
return makeDynamicHangingPromise<string>( return makeDynamicHangingPromise<string>(
workUnitStore.renderSignal, workUnitStore.renderSignal,
workStore.route, workStore.route,
......
...@@ -245,16 +245,20 @@ function createRuntimePrerenderSearchParams( ...@@ -245,16 +245,20 @@ function createRuntimePrerenderSearchParams(
: underlyingSearchParams : underlyingSearchParams
const result = makeUntrackedSearchParams(userspaceSearchParams) const result = makeUntrackedSearchParams(userspaceSearchParams)
const searchParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
const { stagedRendering } = workUnitStore const { stagedRendering } = workUnitStore
if (!stagedRendering) { if (!stagedRendering) {
// If there's no staging, we're in a prospective runtime prerender. // If there's no stage controller, we're in a prospective runtime prerender.
if (workUnitStore.isSessionShell) { // Make sure we don't unblock content that won't be reached in the final prerender.
// If we're warming up for a session shell, search params should hang, if (workUnitStore.finalStage < searchParamsStage) {
// because they'll be a hanging input in the final prerender.
return makeHangingSearchParams(workStore, workUnitStore) return makeHangingSearchParams(workStore, workUnitStore)
} else {
return result
} }
return result
} }
// Unlike `createRuntimePrerenderParams`, which uses `delayUntilStage`, we // Unlike `createRuntimePrerenderParams`, which uses `delayUntilStage`, we
// resolve with `waitForStage(...).then(...)` here. Switching search params to // resolve with `waitForStage(...).then(...)` here. Switching search params to
// `delayUntilStage` drops the source code frame from the instant-validation // `delayUntilStage` drops the source code frame from the instant-validation
...@@ -264,7 +268,6 @@ function createRuntimePrerenderSearchParams( ...@@ -264,7 +268,6 @@ function createRuntimePrerenderSearchParams(
// `suspense-boundaries` tests. The underlying reason in React's async I/O // `suspense-boundaries` tests. The underlying reason in React's async I/O
// await tracking isn't understood yet. TODO: align search params with params // await tracking isn't understood yet. TODO: align search params with params
// on `delayUntilStage` once resolved. // on `delayUntilStage` once resolved.
const searchParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
return stagedRendering.waitForStage(searchParamsStage).then(() => result) return stagedRendering.waitForStage(searchParamsStage).then(() => result)
} }
...@@ -382,9 +385,9 @@ function makeHangingSearchParams( ...@@ -382,9 +385,9 @@ function makeHangingSearchParams(
prerenderStore.renderSignal, prerenderStore.renderSignal,
workStore.route, workStore.route,
'`searchParams`', '`searchParams`',
// This promise is created for every page whether or not it reads search // Passing `null` for the store disables tracking of params usage.
// params, so recording the access at creation would mark every render. // We want accesses of chained promises to be tracked as well.
// The access is tracked in the proxy traps below instead. // TODO: The custom tracking seems unnecessary, we should standardize it
null null
) )
......
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
import { retry } from 'next-test-utils'
const CACHE_MISS_WARNING = 'Unexpected cache miss after cache warming phase'
// The App Shell prefetch (next-router-prefetch: '3') renders the runtime shell
// of the /slug/[slug] route. Because the page is a `'use cache'` page that
// awaits static params, params are a hanging input in the final prerender. If
// the prospective (cache-warming) prerender resolved those params instead of
// leaving them hanging, the cached page's key would differ between the two
// prerenders and the final prerender would log an "Unexpected cache miss"
// warning and degrade the cached segment to a dynamic hole.
describe('App Shell prefetching - cached page with generateStaticParams', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
it('is skipped', () => {})
return
}
it('does not report a cache miss when prefetching the shell of a cached page that reads static params', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Revealing the link prefetches the App Shell for /slug/[slug]. Because the
// shell is param-independent, this single request drives the runtime shell
// prerender of the cached page whose params are a hanging input.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/slug/prerendered"]')
.click()
})
expect(next.cliOutput).not.toContain(CACHE_MISS_WARNING)
})
it('renders the cached page content after navigating to a prefetched shell', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/slug/prerendered"]')
.click()
})
await browser.elementByCss('a[href="/slug/prerendered"]').click()
await retry(async () => {
expect(await browser.elementById('slug').text()).toEqual(
'Slug: prerendered'
)
})
expect(next.cliOutput).not.toContain(CACHE_MISS_WARNING)
})
})
...@@ -2,12 +2,10 @@ import { Suspense } from 'react' ...@@ -2,12 +2,10 @@ import { Suspense } from 'react'
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
// Reading a cookie makes the shell depend on session data, so a prefetch // Reading a cookie makes the shell depend on session data, so a prefetch
// renders a runtime App Shell. This is what exercises the prospective/final // renders a runtime App Shell.
// runtime prerender where params are a hanging input in a cached page.
async function SessionData() { async function SessionData() {
const cookieStore = await cookies() await cookies()
const value = cookieStore.get('testCookie')?.value ?? 'none' return null
return <p id="cookie-value">{`Cookie: ${value}`}</p>
} }
export default async function Layout({ children }: LayoutProps<'/'>) { export default async function Layout({ children }: LayoutProps<'/'>) {
...@@ -17,7 +15,7 @@ export default async function Layout({ children }: LayoutProps<'/'>) { ...@@ -17,7 +15,7 @@ export default async function Layout({ children }: LayoutProps<'/'>) {
<Suspense fallback={<p id="cookie-loading">Loading cookie...</p>}> <Suspense fallback={<p id="cookie-loading">Loading cookie...</p>}>
<SessionData /> <SessionData />
</Suspense> </Suspense>
{children} <Suspense>{children}</Suspense>
</body> </body>
</html> </html>
) )
......
import {
unstable_prefetch as prefetch,
unstable_navigation as navigation,
} from 'next/cache'
import { cookies } from 'next/headers'
import { Suspense } from 'react'
export default async function Page() {
await cookies() // Avoid static prerendering
return (
<main>
<h1>This page gates caches behind prefetch and navigation.</h1>
<Suspense fallback={<p>Loading prefetch data...</p>}>
<PrefetchData />
</Suspense>
<Suspense fallback={<p>Loading navigation data...</p>}>
<NavigationData />
</Suspense>
</main>
)
}
async function PrefetchData() {
await prefetch()
await cachedFn('after prefetch')
return <p>Prefetch data</p>
}
async function NavigationData() {
await navigation()
await cachedFn('after navigation')
return <p>Navigation data</p>
}
async function cachedFn(key: string) {
'use cache'
console.log('cachedFn :: ' + key)
}
import {
unstable_prefetch as prefetch,
unstable_navigation as navigation,
} from 'next/cache'
import { cookies } from 'next/headers'
import { Suspense } from 'react'
export default async function Page() {
await cookies() // Avoid static prerendering
return (
<main>
<h1>This page gates caches behind prefetch and navigation.</h1>
<Suspense fallback={<p>Loading prefetch data...</p>}>
<PrefetchData />
</Suspense>
<Suspense fallback={<p>Loading navigation data...</p>}>
<NavigationData />
</Suspense>
</main>
)
}
async function PrefetchData() {
await prefetch()
await cachedFn('after prefetch')
return <p>Prefetch data</p>
}
async function NavigationData() {
await navigation()
await cachedFn('after navigation')
return <p>Navigation data</p>
}
async function cachedFn(key: string) {
'use cache'
console.log('cachedFn :: ' + key)
}
...@@ -10,8 +10,23 @@ export default function Page() { ...@@ -10,8 +10,23 @@ export default function Page() {
</LinkAccordion> </LinkAccordion>
</li> </li>
<li> <li>
<LinkAccordion href="/slug/not-prerendered"> <LinkAccordion href="/pass-prefetch-to-cache">
not prerendered - /slug/not-prerendered /pass-prefetch-to-cache
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/pass-navigation-to-cache" prefetch={true}>
/pass-navigation-to-cache (prefetch=true)
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/lazy-data-in-shell">
/lazy-data-in-shell
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/lazy-data-in-prefetch" prefetch={true}>
/lazy-data-in-prefetch (prefetch=true)
</LinkAccordion> </LinkAccordion>
</li> </li>
</ul> </ul>
......
import { unstable_navigation as navigation } from 'next/cache'
import { cookies } from 'next/headers'
import { connection } from 'next/server'
import { Suspense } from 'react'
export default async function Page() {
await cookies() // Avoid static prerendering
// `navigation()` should be a hanging input.
const result = await cachedFn(navigation())
return (
<main>
<h1>This page passes a prefetch() promise to a cache</h1>
<p id="cached-data">{result}</p>
<Suspense fallback="Loading dynamic data...">
<DynamicData />
</Suspense>
</main>
)
}
async function DynamicData() {
await connection()
return 'Dynamic data'
}
async function cachedFn(input: any) {
'use cache'
// Make sure the argument is not optimized away as unused
if (Math.random() < 0) {
console.log(input)
}
await new Promise((resolve) => setTimeout(resolve))
return 'Cached data: ' + Date.now()
}
import { unstable_prefetch as prefetch } from 'next/cache'
import { cookies } from 'next/headers'
import { connection } from 'next/server'
import { Suspense } from 'react'
export default async function Page() {
await cookies() // Avoid static prerendering
// `prefetch()` should be a hanging input.
const result = await cachedFn(prefetch())
return (
<main>
<h1>This page passes a prefetch() promise to a cache</h1>
<p id="cached-data">{result}</p>
<Suspense fallback="Loading dynamic data...">
<DynamicData />
</Suspense>
</main>
)
}
async function DynamicData() {
await connection()
return 'Dynamic data'
}
async function cachedFn(input: any) {
'use cache'
// Make sure the argument is not optimized away as unused
if (Math.random() < 0) {
console.log(input)
}
await new Promise((resolve) => setTimeout(resolve))
return 'Cached data: ' + Date.now()
}
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
const CACHE_MISS_WARNING = 'Unexpected cache miss after cache warming phase'
describe('runtime prerender cache warming', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true, // reads CLI output
})
if (skipped) return
if (isNextDev) {
it.skip('no prefetching in dev', () => {})
return
}
it('does not report a cache miss when prefetching the shell of a cached page that reads static params', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Load the App Shell for /slug/[slug].
// Shells cannot access params, so the page gets them as a hanging input.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/slug/prerendered"]')
.click()
}, [
{
includes: 'Slug: prerendered',
block: 'reject',
},
])
// The App Shell request renders the runtime shell of the /slug/[slug] route.
// The page is a `'use cache'` page that awaits static params and params
// should be a hanging input in the final prerender.
// If the prospective (cache-warming) prerender resolved params instead of
// leaving them hanging, the cached page's key would differ between the two
// prerenders and the final prerender would log an "Unexpected cache miss"
// warning and degrade the cached segment to a dynamic hole.
expect(next.cliOutput).not.toContain(CACHE_MISS_WARNING)
// When we navigate, params become available.
await act(() => browser.elementByCss('a[href="/slug/prerendered"]').click())
expect(await browser.elementById('slug').text()).toEqual(
'Slug: prerendered'
)
})
it('prefetch() is a hanging input when passed to a cache in a runtime shell', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Load the App Shell for the page.
// It should include the result of the cache.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/pass-prefetch-to-cache"]')
.click()
}, [
{
includes: 'Cached data',
kind: 'runtime',
},
])
expect(next.cliOutput).not.toContain(CACHE_MISS_WARNING)
// Navigate, but capture the result of the cache as shown in the shell.
const cachedDataInShell = await act(async () => {
await browser.elementByCss('a[href="/pass-prefetch-to-cache"]').click()
return browser.elementByCss('#cached-data').text()
})
// prefetch() was a hanging input in the shell, but resolves in a navigation,
// so the keys don't match and we should get a fresh cache result.
const cachedDataInNavigation = await browser
.elementByCss('#cached-data')
.text()
expect(cachedDataInShell).not.toEqual(cachedDataInNavigation)
})
it('navigation() is a hanging input when passed to a cache in both a runtime shell and prefetch', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Prefetch the page.
// It should include the result of the cache.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/pass-navigation-to-cache"]')
.click()
}, [
// We assert on shells and prefetch behavior in one go,
// because the router fetches both, in two request.
// Shell
{
includes: 'Cached data',
kind: 'runtime',
},
// Prefetch
{
includes: 'Cached data',
kind: 'runtime',
},
])
expect(next.cliOutput).not.toContain(CACHE_MISS_WARNING)
// Navigate, but capture the result of the cache as shown in the shell.
const cachedDataInShell = await act(async () => {
await browser.elementByCss('a[href="/pass-navigation-to-cache"]').click()
return browser.elementByCss('#cached-data').text()
})
// navigation() was a hanging input in the shell, but resolves in a navigation,
// so the keys don't match and we should get a fresh cache result.
const cachedDataInNavigation = await browser
.elementByCss('#cached-data')
.text()
expect(cachedDataInShell).not.toEqual(cachedDataInNavigation)
})
it('caches hidden behind prefetch() are not warmed when rendering a runtime shell', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
const beforeShellIx = next.cliOutput.length
// Load the shell for the page.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/lazy-data-in-shell"]')
.click()
}, [
{
includes: 'This page gates caches behind prefetch and navigation.',
kind: 'runtime',
},
{
includes: 'Prefetch data',
block: 'reject',
},
{
includes: 'Navigation data',
block: 'reject',
},
])
// The caches should not have been warmed, because the prospective prerender
// for a shell shouldn't resolve prefetch() or navigation().
const shellLogs = next.cliOutput.slice(beforeShellIx)
expect(shellLogs).not.toContain('cachedFn :: after prefetch')
expect(shellLogs).not.toContain('cachedFn :: after navigation')
const beforeNavigationIx = next.cliOutput.length
// Navigate, which should run the caches and thus print the logs.
await act(() =>
browser.elementByCss('a[href="/lazy-data-in-shell"]').click()
)
const navigationLogs = next.cliOutput.slice(beforeNavigationIx)
expect(navigationLogs).toContain('cachedFn :: after prefetch')
expect(navigationLogs).toContain('cachedFn :: after navigation')
})
it('caches hidden behind navigation() are not warmed when rendering a runtime shell or prefetch', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
const beforePrefetchIx = next.cliOutput.length
// Load the shell for the page.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/lazy-data-in-prefetch"]')
.click()
}, [
// Shell
{
includes: 'This page gates caches behind prefetch and navigation.',
kind: 'runtime',
},
// Prefetch
{
includes: 'Prefetch data',
kind: 'runtime',
},
{
includes: 'Navigation data',
block: 'reject',
},
])
const shellAndPrefetchLogs = next.cliOutput.slice(beforePrefetchIx)
// The cache behind prefetch() should've been warmed in the prefetch request.
expect(shellAndPrefetchLogs).toContain('cachedFn :: after prefetch')
// The cache behind navigation() should not have been warmed.
expect(shellAndPrefetchLogs).not.toContain('cachedFn :: after navigation')
const beforeNavigationIx = next.cliOutput.length
// Navigate, which should run the caches and thus print the logs.
await act(() =>
browser.elementByCss('a[href="/lazy-data-in-prefetch"]').click()
)
const navigationLogs = next.cliOutput.slice(beforeNavigationIx)
// Already warmed by the prefetch request, and logs are not replayed.
expect(navigationLogs).not.toContain('cachedFn :: after prefetch')
// New in this request.
expect(navigationLogs).toContain('cachedFn :: after navigation')
})
})
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