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(
// but we're not going to persist this anywhere.
const prerenderResumeDataCache = createPrerenderResumeDataCache()
await prospectiveRuntimeServerPrerender(
ctx,
isShellPrefetch,
generateDynamicRSCPayload.bind(null, ctx),
prerenderResumeDataCache,
rootParams,
requestStore.headers,
requestStore.cookies,
requestStore.draftMode
)
const mode: RuntimePrerenderMode = isShellPrefetch
? {
type: 'session-shell-only',
......@@ -1620,6 +1609,17 @@ async function generateRuntimePrefetchResult(
shellByteLengthDeferred: createPromiseWithResolvers(),
}
await prospectiveRuntimeServerPrerender(
ctx,
getFinalStageForRuntimePrerenderMode(mode),
generateDynamicRSCPayload.bind(null, ctx),
prerenderResumeDataCache,
rootParams,
requestStore.headers,
requestStore.cookies,
requestStore.draftMode
)
const debugChannel = setReactDebugChannel
? createWebDebugChannel()
: undefined
......@@ -1656,7 +1656,7 @@ async function generateRuntimePrefetchResult(
async function prospectiveRuntimeServerPrerender(
ctx: AppRenderContext,
isShellPrefetch: boolean,
finalStage: AdvanceableRenderStage,
getPayload: () => Promise<RSCPayload>,
resumeDataCache: PrerenderResumeDataCache | null,
rootParams: Params,
......@@ -1705,9 +1705,10 @@ async function prospectiveRuntimeServerPrerender(
hmrRefreshHash: undefined,
// We don't track vary params during initial prerender, only the final one
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,
isSessionShell: isShellPrefetch,
finalStage,
// These are not present in regular prerenders, but allowed in a runtime
// prerender.
// Any cache keyed on headers() or cookies() needs to be invalidated.
......@@ -1854,19 +1855,8 @@ async function finalRuntimeServerPrerender(
isDebugDynamicAccesses
)
let finalStage: AdvanceableRenderStage
switch (mode.type) {
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({
const finalStage = getFinalStageForRuntimePrerenderMode(mode)
const stageController = new StagedRenderingController({
abortSignal: finalServerController.signal,
abandonController: null,
// In dynamic renders, we allow Sync IO in the Runtime stage
......@@ -1898,8 +1888,8 @@ async function finalRuntimeServerPrerender(
resumeDataCache,
hmrRefreshHash: undefined,
varyParamsAccumulator,
stagedRendering: finalStageController,
isSessionShell: mode.type === 'session-shell-only',
stagedRendering: stageController,
finalStage,
// These are not present in regular prerenders, but allowed in a runtime
// prerender.
headers: HeadersAdapter.fresh(headers),
......@@ -1923,7 +1913,7 @@ async function finalRuntimeServerPrerender(
collectPrerenderChunk(collectedChunks, finalServerController.signal, chunk)
increaseChunkByteLengths(
stageByteLengths,
finalStageController.currentStage,
stageController.currentStage,
chunk.byteLength
)
}
......@@ -1963,7 +1953,7 @@ async function finalRuntimeServerPrerender(
await runInSequentialTasks(
async () => {
finalStageController.advanceStage(RenderStage.ShellStatic)
stageController.advanceStage(RenderStage.ShellStatic)
let stream = workUnitAsyncStorage.run(
finalServerPrerenderStore,
......@@ -1989,19 +1979,19 @@ async function finalRuntimeServerPrerender(
},
() => {
if (checkUnexpectedAbort()) return
finalStageController.advanceStage(RenderStage.PrefetchStatic)
stageController.advanceStage(RenderStage.PrefetchStatic)
},
() => {
if (checkUnexpectedAbort()) return
finalStageController.advanceStage(RenderStage.NavigationStatic)
stageController.advanceStage(RenderStage.NavigationStatic)
},
() => {
if (checkUnexpectedAbort()) return
finalStageController.advanceStage(RenderStage.Static)
stageController.advanceStage(RenderStage.Static)
},
() => {
if (checkUnexpectedAbort()) return
finalStageController.advanceStage(RenderStage.ShellRuntime)
stageController.advanceStage(RenderStage.ShellRuntime)
},
() => {
if (checkUnexpectedAbort()) return
......@@ -2009,7 +1999,7 @@ async function finalRuntimeServerPrerender(
// We may not reach this stage depending on the mode.
if (finalStage < RenderStage.Runtime) return
finalStageController.advanceStage(RenderStage.Runtime)
stageController.advanceStage(RenderStage.Runtime)
},
() => {
if (checkUnexpectedAbort()) return
......@@ -2040,7 +2030,7 @@ async function finalRuntimeServerPrerender(
// We may not reach this stage depending on the mode.
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,
......@@ -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
* when our intention is to just seed the router state with the current URL.
......
......@@ -16,7 +16,10 @@ import type { Params } from '../request/params'
import type { ImplicitTags } from '../lib/implicit-tags'
import type { WorkStore } from './work-async-storage.external'
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 { InstantValidationSampleTracking } from './instant-validation/instant-samples'
......@@ -226,7 +229,7 @@ export interface PrerenderStoreModernRuntime
* renders where all stages run without sequencing.
*/
readonly stagedRendering: StagedRenderingController | null
readonly isSessionShell: boolean
readonly finalStage: AdvanceableRenderStage
readonly headers: RequestStore['headers']
readonly cookies: RequestStore['cookies']
......
......@@ -5,6 +5,7 @@ import {
} from '../app-render/work-unit-async-storage.external'
import {
applyOwnerStack,
makeUntrackedHangingPromise,
RENDER_STAGES_BY_DATA_KIND,
trackIncompatibleShellContent,
} from '../dynamic-rendering-utils'
......@@ -52,6 +53,7 @@ export function unstable_prefetch(): Promise<void> {
const { stagedRendering } = workUnitStore
if (!stagedRendering) {
// Prospective prerender
// `unstable_prefetch()` will resolve in the final prerender, so resolve it here as well.
return Promise.resolve(undefined)
} else {
// Final prerender
......@@ -69,13 +71,23 @@ export function unstable_prefetch(): Promise<void> {
// Note that this does not mark the subtree as dynamic -- content guarded by
// prefetch() is still considered cacheable.
const { stagedRendering } = workUnitStore
const prefetchStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
if (!stagedRendering) {
// 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 {
// Final prerender
return stagedRendering.delayUntilStage(
RENDER_STAGES_BY_DATA_KIND.runtimeLinkData,
prefetchStage,
'unstable_prefetch',
undefined
)
......@@ -194,6 +206,7 @@ export function unstable_navigation(): Promise<void> {
const { stagedRendering } = workUnitStore
if (!stagedRendering) {
// Prospective prerender
// `unstable_navigation()` will resolve in the final prerender, so resolve it here as well.
return Promise.resolve(undefined)
} else {
// Final prerender
......@@ -211,13 +224,23 @@ export function unstable_navigation(): Promise<void> {
// Note that this does not mark the subtree as dynamic -- content guarded by
// navigation() is still considered cacheable.
const { stagedRendering } = workUnitStore
const navigationStage = RenderStage.NavigationRuntime
if (!stagedRendering) {
// 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 {
// Final prerender
return stagedRendering.delayUntilStage(
RenderStage.NavigationRuntime,
navigationStage,
'unstable_navigation',
undefined
)
......
......@@ -427,36 +427,27 @@ function createRuntimePrerenderParams(
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
if (!stagedRendering) {
// If there's no staging, we're in a prospective runtime prerender.
if (workUnitStore.isSessionShell) {
// If we're warming up for a session shell, params should be hanging,
// because they'll be a hanging input in the final prerender.
// If there's no stage controller, we're in a prospective runtime prerender.
// Make sure we don't unblock content that won't be reached in the final prerender.
if (workUnitStore.finalStage < paramsStage) {
return makeHangingParams(underlyingParams, workStore, workUnitStore)
} else {
return makeUntrackedParams(userspaceParams)
}
}
// We don't have fallbackParams in runtime prerenders, so we don't know
// 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
)
return stagedRendering.delayUntilStage(paramsStage, 'params', userspaceParams)
}
function createRenderParamsForPage(
......
......@@ -57,15 +57,15 @@ export function createServerPathnameForMetadata(
// behavior of always resolving in the runtime stage
// (i.e. assuming that we have non-static params in the pathname)
const { stagedRendering } = workUnitStore
const pathnameStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
if (stagedRendering) {
const pathnameStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
return stagedRendering.delayUntilStage(
pathnameStage,
undefined,
underlyingPathname
)
} else {
if (workUnitStore.isSessionShell) {
if (workUnitStore.finalStage < pathnameStage) {
return makeDynamicHangingPromise<string>(
workUnitStore.renderSignal,
workStore.route,
......
......@@ -245,16 +245,20 @@ function createRuntimePrerenderSearchParams(
: underlyingSearchParams
const result = makeUntrackedSearchParams(userspaceSearchParams)
const searchParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
const { stagedRendering } = workUnitStore
if (!stagedRendering) {
// If there's no staging, we're in a prospective runtime prerender.
if (workUnitStore.isSessionShell) {
// If we're warming up for a session shell, search params should hang,
// because they'll be a hanging input in the final prerender.
// If there's no stage controller, we're in a prospective runtime prerender.
// Make sure we don't unblock content that won't be reached in the final prerender.
if (workUnitStore.finalStage < searchParamsStage) {
return makeHangingSearchParams(workStore, workUnitStore)
} else {
return result
}
return result
}
// Unlike `createRuntimePrerenderParams`, which uses `delayUntilStage`, we
// resolve with `waitForStage(...).then(...)` here. Switching search params to
// `delayUntilStage` drops the source code frame from the instant-validation
......@@ -264,7 +268,6 @@ function createRuntimePrerenderSearchParams(
// `suspense-boundaries` tests. The underlying reason in React's async I/O
// await tracking isn't understood yet. TODO: align search params with params
// on `delayUntilStage` once resolved.
const searchParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData
return stagedRendering.waitForStage(searchParamsStage).then(() => result)
}
......@@ -382,9 +385,9 @@ function makeHangingSearchParams(
prerenderStore.renderSignal,
workStore.route,
'`searchParams`',
// This promise is created for every page whether or not it reads search
// params, so recording the access at creation would mark every render.
// The access is tracked in the proxy traps below instead.
// Passing `null` for the store disables tracking of params usage.
// We want accesses of chained promises to be tracked as well.
// TODO: The custom tracking seems unnecessary, we should standardize it
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'
import { cookies } from 'next/headers'
// 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
// runtime prerender where params are a hanging input in a cached page.
// renders a runtime App Shell.
async function SessionData() {
const cookieStore = await cookies()
const value = cookieStore.get('testCookie')?.value ?? 'none'
return <p id="cookie-value">{`Cookie: ${value}`}</p>
await cookies()
return null
}
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>}>
<SessionData />
</Suspense>
{children}
<Suspense>{children}</Suspense>
</body>
</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() {
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/slug/not-prerendered">
not prerendered - /slug/not-prerendered
<LinkAccordion href="/pass-prefetch-to-cache">
/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>
</li>
</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