Unverified Commit 8c6cb0e0 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[PP] Reveal after ShellRuntime when simulating a Shell Prefetch in dev (#95149)

When `partialPrefetching` is on, the shell that we usually care about
displaying is the App Shell, which is represented by the ShellRuntime
stage. We should only show the cold cache indicator for caches that
happen up until then, and release the client-side promise appropriately.
This PR extends the existing `revealAfterStage` mechanics to account for
this.

> Note that this is incomplete: if we're navigating via `<Link
prefetch={true}>` (or have `partialPrefetching: "unstable_eager"), we
might want to use the Runtime stage instead. I'm leaving those for a
follow up -- representing the common case (a shell prefetch) seems like
the most useful thing.

I've re-worked the `revealAfterStage/holdStreamUntilRevealed` setup into
an object (`DevNavigationKind`) that represents the navigation that
we're trying to simulate -- either an initial load or a client nav. This
gets rid of the invalid `holdStreamUntilRevealed = true` +
`revealAfterStage = RenderStage.Runtime/ShellRuntime` combination and
lets us bring the logic closer to where the stream blocking tricks
actually happen.

I've also done some drive-by refactoring of `streamStagedRenderInDev` to
dedupe some repetitive code, because every task was basically doing the
same thing. I've also moved all `revealAfter.resolve()` calls into
separate tasks -- we were inconsistent about this, and the `Static`
`revealAfter.resolve()` was done together with the next stage, but the
`RenderStage.Runtime` was done in a separate task.

---

Strangely, despite the changes working as expected for the Cold Cache
indicator, I can't actually get link data (`await searchParams`) to
trigger a fallback when navigating, so there's a failing test for that
in `cache-components-dev-streaming.test.ts`. I'm not sure why what's
causing this, but I'm leaving that investigation for a follow-up as
well.
parent d4b23403
...@@ -1347,6 +1347,12 @@ async function generateDynamicFlightRenderResultWithStagesInDev( ...@@ -1347,6 +1347,12 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
setCacheStatus('ready', htmlRequestId) setCacheStatus('ready', htmlRequestId)
} }
const prefetchMode =
!!renderOpts.partialPrefetching ||
(await anySegmentHasPartialPrefetchingEnabled(loaderTree))
? PrefetchingMode.Partial
: PrefetchingMode.LegacySpeculative
// A client navigation into a runtime-prefetch route extends the shell // A client navigation into a runtime-prefetch route extends the shell
// through the runtime-prefetchable content: it has already settled on the // through the runtime-prefetchable content: it has already settled on the
// client (via the prefetch) by the time it navigates, so it belongs in this // client (via the prefetch) by the time it navigates, so it belongs in this
...@@ -1354,11 +1360,23 @@ async function generateDynamicFlightRenderResultWithStagesInDev( ...@@ -1354,11 +1360,23 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
// load: plain navigations, and HMR refreshes (a fresh render of the current // load: plain navigations, and HMR refreshes (a fresh render of the current
// page, with no settled prefetch to draw on). Dynamic content always // page, with no settled prefetch to draw on). Dynamic content always
// streams in after the shell. // streams in after the shell.
const revealAfterStage = let prefetchStage: StreamRevealStage
initialRequestStore.isHmrRefresh !== true &&
(await anySegmentHasRuntimePrefetchEnabled(loaderTree)) if (initialRequestStore.isHmrRefresh === true) {
? RenderStage.Runtime prefetchStage = RenderStage.Static
: RenderStage.Static } else {
if (prefetchMode === PrefetchingMode.Partial) {
// TODO(app-shells): model `partialPrefetching: "unstable_eager"`
// TODO(app-shells): if this navigation came from <Link prefetch={true} />,
// we should show the shell for a speculative prefetch
// (which can have more data than the app shell)
prefetchStage = RenderStage.ShellRuntime
} else {
prefetchStage = (await anySegmentHasRuntimePrefetchEnabled(loaderTree))
? RenderStage.Runtime
: RenderStage.Static
}
}
const result = await stagedRenderWithCachesInDev({ const result = await stagedRenderWithCachesInDev({
ctx, ctx,
...@@ -1369,11 +1387,10 @@ async function generateDynamicFlightRenderResultWithStagesInDev( ...@@ -1369,11 +1387,10 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
shouldValidate, shouldValidate,
fallbackRouteParams: fallbackParams, fallbackRouteParams: fallbackParams,
getDevRenderDidError: () => didErrorObservably, getDevRenderDidError: () => didErrorObservably,
revealAfterStage, navigationKind: {
// This stream goes to the browser, which gates revealing the response on type: 'prefetched-client',
// the payload's `_revealAfter`, so release it live and let the browser prefetchStage,
// process chunks as they arrive instead of holding it server-side. },
holdStreamUntilRevealed: false,
}) })
stream = result.stream stream = result.stream
debugChannel = result.debugChannel debugChannel = result.debugChannel
...@@ -3437,12 +3454,9 @@ async function renderToStream( ...@@ -3437,12 +3454,9 @@ async function renderToStream(
getDevRenderDidError: () => didErrorObservably, getDevRenderDidError: () => didErrorObservably,
// An initial HTML load serves the static shell; runtime and // An initial HTML load serves the static shell; runtime and
// dynamic content stream in afterward. // dynamic content stream in afterward.
revealAfterStage: RenderStage.Static, navigationKind: {
// Hold the stream until the shell content has flushed so the type: 'initial-load',
// streamed HTML reflects the prerendered shell rather than a },
// premature shell-stage Suspense fallback (see
// `holdStreamUntilRevealed`).
holdStreamUntilRevealed: true,
}) })
reactServerResult = new ReactServerResult(serverStream) reactServerResult = new ReactServerResult(serverStream)
...@@ -4545,6 +4559,11 @@ interface StagedDevRenderSetup { ...@@ -4545,6 +4559,11 @@ interface StagedDevRenderSetup {
readonly environmentName: () => string readonly environmentName: () => string
} }
enum PrefetchingMode {
LegacySpeculative = 1,
Partial = 2,
}
/** /**
* Per-render setup shared by the streaming dev Cache Components renders: a * Per-render setup shared by the streaming dev Cache Components renders: a
* cache signal (so caches fill in the background), a prerender resume data * cache signal (so caches fill in the background), a prerender resume data
...@@ -4613,10 +4632,18 @@ interface StagedDevRenderOptions { ...@@ -4613,10 +4632,18 @@ interface StagedDevRenderOptions {
ctx: AppRenderContext ctx: AppRenderContext
requestStore: RequestStore requestStore: RequestStore
onError: (error: unknown) => void onError: (error: unknown) => void
revealAfterStage: RenderStage.Static | RenderStage.Runtime navigationKind: DevNavigationKind
holdStreamUntilRevealed: boolean
} }
type DevNavigationKind =
| { type: 'initial-load' }
| { type: 'prefetched-client'; prefetchStage: StreamRevealStage }
type StreamRevealStage =
| RenderStage.Static
| RenderStage.ShellRuntime
| RenderStage.Runtime
interface StreamStagedRenderInDevOptions extends StagedDevRenderOptions { interface StreamStagedRenderInDevOptions extends StagedDevRenderOptions {
rscPayload: RSCPayload rscPayload: RSCPayload
stageController: StagedRenderingController stageController: StagedRenderingController
...@@ -4647,12 +4674,31 @@ async function streamStagedRenderInDev({ ...@@ -4647,12 +4674,31 @@ async function streamStagedRenderInDev({
environmentName, environmentName,
onError, onError,
debugChannel, debugChannel,
revealAfterStage, navigationKind,
holdStreamUntilRevealed,
}: StreamStagedRenderInDevOptions): Promise<{ }: StreamStagedRenderInDevOptions): Promise<{
stream: Readable stream: Readable
resultPromise: Promise<StagedDevRenderResult> resultPromise: Promise<StagedDevRenderResult>
}> { }> {
let holdStreamUntilRevealed: boolean
let revealAfterStage: StreamRevealStage
switch (navigationKind.type) {
case 'initial-load': {
// Hold the stream until the shell content has flushed so the
// streamed HTML reflects the prerendered HTML shell
holdStreamUntilRevealed = true
revealAfterStage = RenderStage.Static
break
}
case 'prefetched-client': {
// This stream goes to the browser, which gates revealing the response on
// the payload's `_revealAfter`, so release it live and let the browser
// process chunks as they arrive instead of holding it server-side.
holdStreamUntilRevealed = false
revealAfterStage = navigationKind.prefetchStage
break
}
}
const { ComponentMod } = ctx.renderOpts const { ComponentMod } = ctx.renderOpts
const { clientModules } = getClientReferenceManifest() const { clientModules } = getClientReferenceManifest()
...@@ -4724,6 +4770,19 @@ async function streamStagedRenderInDev({ ...@@ -4724,6 +4770,19 @@ async function streamStagedRenderInDev({
return hadCacheMiss return hadCacheMiss
} }
const checkCacheMissAndAdvance = (stage: AdvanceableRenderStage) => {
if (checkForCacheMiss()) {
revealAfter.resolve()
}
stageController.advanceStage(stage)
}
const checkReveal = (stage: AdvanceableRenderStage) => {
if (checkForCacheMiss() || revealAfterStage === stage) {
revealAfter.resolve()
}
}
// The render runs to completion; it never aborts. The first task starts the // The render runs to completion; it never aborts. The first task starts the
// render in the `ShellEarlyStatic` stage and creates the stream (one replay // render in the `ShellEarlyStatic` stage and creates the stream (one replay
// for the response, one to accumulate the chunks). The later tasks advance // for the response, one to accumulate the chunks). The later tasks advance
...@@ -4762,68 +4821,22 @@ async function streamStagedRenderInDev({ ...@@ -4762,68 +4821,22 @@ async function streamStagedRenderInDev({
), ),
}) })
}, },
() => checkCacheMissAndAdvance(RenderStage.ShellStatic),
() => checkCacheMissAndAdvance(RenderStage.EarlyStatic),
() => checkCacheMissAndAdvance(RenderStage.Static),
() => checkReveal(RenderStage.Static),
() => checkCacheMissAndAdvance(RenderStage.ShellEarlyRuntime),
() => checkCacheMissAndAdvance(RenderStage.ShellRuntime),
() => checkReveal(RenderStage.ShellRuntime),
() => checkCacheMissAndAdvance(RenderStage.EarlyRuntime),
() => checkCacheMissAndAdvance(RenderStage.Runtime),
() => checkReveal(RenderStage.Runtime),
() => { () => {
if (checkForCacheMiss()) { // Advance to the dynamic stage even while caches are still filling, so
revealAfter.resolve()
}
stageController.advanceStage(RenderStage.ShellStatic)
},
() => {
if (checkForCacheMiss()) {
revealAfter.resolve()
}
stageController.advanceStage(RenderStage.EarlyStatic)
},
() => {
if (checkForCacheMiss()) {
revealAfter.resolve()
}
stageController.advanceStage(RenderStage.Static)
},
() => {
// Reveal on a cache miss, or at the static-shell boundary: the static
// stage's chunks flushed in the previous task, so the static shell is on
// the stream now. `checkForCacheMiss()` is the left operand so its side
// effect (tracking the miss / updating the dev overlay) always runs.
if (checkForCacheMiss() || revealAfterStage === RenderStage.Static) {
revealAfter.resolve()
}
stageController.advanceStage(RenderStage.ShellEarlyRuntime)
},
() => {
if (checkForCacheMiss()) {
revealAfter.resolve()
}
stageController.advanceStage(RenderStage.ShellRuntime)
},
() => {
if (checkForCacheMiss()) {
revealAfter.resolve()
}
stageController.advanceStage(RenderStage.EarlyRuntime)
},
() => {
if (checkForCacheMiss()) {
revealAfter.resolve()
}
stageController.advanceStage(RenderStage.Runtime)
},
() => {
// Reveal on a cache miss, or at the runtime-shell boundary: the runtime
// stage's chunks flushed in the previous task, so the runtime shell is on
// the stream now. `checkForCacheMiss()` is the left operand so its side
// effect (tracking the miss / updating the dev overlay) always runs.
if (checkForCacheMiss() || revealAfterStage === RenderStage.Runtime) {
revealAfter.resolve()
}
},
() => {
// Advance to the dynamic stage in the next task, after the `revealAfter`
// resolution row from the previous task has flushed: that way the row
// precedes any dynamic chunks, so the client unblocks as soon as the
// shell is ready, not only while the dynamic content streams.
//
// Advance as early as possible, even while caches are still filling, so
// dynamic content streams to the browser right away instead of being // dynamic content streams to the browser right away instead of being
// withheld until the slowest cache fill completes. Streaming that content // withheld until the slowest cache fill completes. Streaming that content
// promptly is the whole point of the streaming dev render. // promptly is the whole point of the streaming dev render.
...@@ -5003,8 +5016,7 @@ async function stagedRenderWithCachesInDev({ ...@@ -5003,8 +5016,7 @@ async function stagedRenderWithCachesInDev({
shouldValidate, shouldValidate,
fallbackRouteParams, fallbackRouteParams,
getDevRenderDidError, getDevRenderDidError,
revealAfterStage, navigationKind,
holdStreamUntilRevealed,
}: StagedRenderWithCachesInDevOptions): Promise<{ }: StagedRenderWithCachesInDevOptions): Promise<{
stream: Readable stream: Readable
debugChannel: NodeDebugChannelPair | undefined debugChannel: NodeDebugChannelPair | undefined
...@@ -5041,8 +5053,7 @@ async function stagedRenderWithCachesInDev({ ...@@ -5041,8 +5053,7 @@ async function stagedRenderWithCachesInDev({
environmentName, environmentName,
onError, onError,
debugChannel, debugChannel,
revealAfterStage, navigationKind,
holdStreamUntilRevealed,
}) })
if (shouldValidate) { if (shouldValidate) {
......
...@@ -14,6 +14,16 @@ export default function Page() { ...@@ -14,6 +14,16 @@ export default function Page() {
/use-cache-private-runtime-prefetch /use-cache-private-runtime-prefetch
</Link> </Link>
</li> </li>
<li>
<Link href="/partial-prefetching/session-data">
/partial-prefetching/session-data
</Link>
</li>
<li>
<Link href="/partial-prefetching/link-data?prefetch=auto">
/partial-prefetching/link-data
</Link>
</li>
</ul> </ul>
) )
} }
import { cookies } from 'next/headers'
import { connection } from 'next/server'
import { Suspense } from 'react'
import { setTimeout } from 'timers/promises'
async function SessionData() {
await cookies()
return <p id="session-data">session content</p>
}
async function LinkData({ searchParams }: { searchParams: Promise<any> }) {
await searchParams
return <p id="link-data">link content</p>
}
async function Dynamic() {
await connection()
await setTimeout(1000)
return <p id="dynamic-data">dynamic content</p>
}
export default function Page({ searchParams }: { searchParams: Promise<any> }) {
return (
<main>
<Suspense fallback={<p id="session-fallback">Loading session...</p>}>
<SessionData />
</Suspense>
<Suspense fallback={<p id="link-fallback">Loading link...</p>}>
<LinkData searchParams={searchParams} />
</Suspense>
<Suspense fallback={<p id="dynamic-fallback">Loading dynamic...</p>}>
<Dynamic />
</Suspense>
</main>
)
}
import { connection } from 'next/server'
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { setTimeout } from 'timers/promises'
// Note: this is intended for partialPrefetching where
// shells can access session data, so no `export const prefetch = "allow-runtime"
// is necessary.
// If the flag is not enabled globally, opt the page in manually to excercise both codepaths.
export const prefetch = process.env.__NEXT_PARTIAL_PREFETCHING
? 'auto'
: 'partial'
async function SessionData() {
await cookies()
return <p id="session-data">session content</p>
}
async function Dynamic() {
await connection()
await setTimeout(1000)
return <p id="dynamic-data">dynamic content</p>
}
export default function Page() {
return (
<main>
<Suspense fallback={<p id="session-fallback">Loading session...</p>}>
<SessionData />
</Suspense>
<Suspense fallback={<p id="dynamic-fallback">Loading dynamic...</p>}>
<Dynamic />
</Suspense>
</main>
)
}
process.env.__NEXT_PARTIAL_PREFETCHING = 'true'
require('./cache-components-dev-streaming.test')
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup, Playwright } from 'e2e-utils'
import { retry, waitFor } from 'next-test-utils' import { retry, waitFor } from 'next-test-utils'
const partialPrefetching = !!process.env.__NEXT_PARTIAL_PREFETCHING
describe('cache-components-dev-streaming', () => { describe('cache-components-dev-streaming', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
env: {
__NEXT_PARTIAL_PREFETCHING: partialPrefetching ? 'true' : '',
},
}) })
it('should stream suspense boundaries while filling caches in the background', async () => { it('should stream suspense boundaries while filling caches in the background', async () => {
...@@ -99,30 +104,11 @@ describe('cache-components-dev-streaming', () => { ...@@ -99,30 +104,11 @@ describe('cache-components-dev-streaming', () => {
// Record whether each Suspense fallback ever enters the DOM during the // Record whether each Suspense fallback ever enters the DOM during the
// upcoming navigation. We inspect added nodes rather than the live DOM, so // upcoming navigation. We inspect added nodes rather than the live DOM, so
// a fallback that's added and then quickly replaced is still caught. // a fallback that's added and then quickly replaced is still caught.
await browser.eval(() => { const fallbackObserver = observeNodeAppearances(browser, [
const seen = { runtime: false, dynamic: false } 'runtime-fallback',
;(window as any).__fallbacksSeen = seen 'dynamic-fallback',
const check = (node: Node) => { ])
if (!(node instanceof Element)) { await fallbackObserver.observe()
return
}
if (
node.id === 'runtime-fallback' ||
node.querySelector('#runtime-fallback')
) {
seen.runtime = true
}
if (
node.id === 'dynamic-fallback' ||
node.querySelector('#dynamic-fallback')
) {
seen.dynamic = true
}
}
new MutationObserver((records) => {
records.forEach((record) => record.addedNodes.forEach(check))
}).observe(document.body, { childList: true, subtree: true })
})
await browser.elementByCss('a[href="/runtime-prefetch"]').click() await browser.elementByCss('a[href="/runtime-prefetch"]').click()
...@@ -136,12 +122,13 @@ describe('cache-components-dev-streaming', () => { ...@@ -136,12 +122,13 @@ describe('cache-components-dev-streaming', () => {
) )
}) })
const appearanceCounts = await fallbackObserver.getResult()
// The runtime-prefetchable content was resolved before the response started // The runtime-prefetchable content was resolved before the response started
// streaming, so its fallback was never rendered; the dynamic content's // streaming, so its fallback was never rendered; the dynamic content's
// fallback was. // fallback was.
expect(await browser.eval(() => (window as any).__fallbacksSeen)).toEqual({ expect(appearanceCounts).toEqual({
runtime: false, 'runtime-fallback': 0,
dynamic: true, 'dynamic-fallback': 1,
}) })
}) })
...@@ -178,22 +165,11 @@ describe('cache-components-dev-streaming', () => { ...@@ -178,22 +165,11 @@ describe('cache-components-dev-streaming', () => {
// Warm navigation: record whether the fallback ever enters the DOM during // Warm navigation: record whether the fallback ever enters the DOM during
// the navigation, even briefly. It shouldn't, since the warm content is // the navigation, even briefly. It shouldn't, since the warm content is
// delivered with the shell. // delivered with the shell.
await browser.eval(() => { const fallbackObserver = observeNodeAppearances(browser, [
;(window as any).__privateFallbackSeen = 0 'private-fallback',
new MutationObserver((records) => { ])
records.forEach((record) =>
record.addedNodes.forEach((node) => { await fallbackObserver.observe()
if (
node instanceof Element &&
(node.id === 'private-fallback' ||
node.querySelector('#private-fallback'))
) {
;(window as any).__privateFallbackSeen += 1
}
})
)
}).observe(document.body, { childList: true, subtree: true })
})
// Regression test for a rare client-side race the `_revealAfter` gate // Regression test for a rare client-side race the `_revealAfter` gate
// fixes. The Flight client decodes the response incrementally, so before // fixes. The Flight client decodes the response incrementally, so before
...@@ -212,9 +188,10 @@ describe('cache-components-dev-streaming', () => { ...@@ -212,9 +188,10 @@ describe('cache-components-dev-streaming', () => {
await browser.back() await browser.back()
} }
expect( const appearanceCounts = await fallbackObserver.getResult()
await browser.eval(() => (window as any).__privateFallbackSeen) expect(appearanceCounts).toEqual({
).toBe(0) 'private-fallback': 0,
})
}) })
// The following are smoke tests that Cache Components validation still // The following are smoke tests that Cache Components validation still
...@@ -316,4 +293,121 @@ describe('cache-components-dev-streaming', () => { ...@@ -316,4 +293,121 @@ describe('cache-components-dev-streaming', () => {
`) `)
expect(await browser.elementByCss('#cached').text()).toBe(cachedDate) expect(await browser.elementByCss('#cached').text()).toBe(cachedDate)
}) })
describe('partial prefetching', () => {
it('does not show a Suspense fallback for session data on a client navigation (auto prefetch)', async () => {
const browser = await next.browser('/')
// Record whether each Suspense fallback ever enters the DOM during the
// upcoming navigation.
const fallbackObserver = observeNodeAppearances(browser, [
'session-fallback',
'dynamic-fallback',
])
await fallbackObserver.observe()
await browser
.elementByCss('a[href="/partial-prefetching/session-data"]')
.click()
// Wait for the navigation to fully settle.
await retry(async () => {
expect(await browser.elementByCssInstant('#session-data').text()).toBe(
'session content'
)
expect(await browser.elementByCssInstant('#dynamic-data').text()).toBe(
'dynamic content'
)
})
const appearanceCounts = await fallbackObserver.getResult()
// The runtime shell was resolved before the response started
// streaming, so its fallback was never rendered; the dynamic content's
// fallback was.
expect(appearanceCounts).toEqual({
'session-fallback': 0,
'dynamic-fallback': 1,
})
})
// TODO(app-shells): for some reason we can't observe the fallback here
// even though all the stream unblocking logic seems to work as intended.
it.failing(
'shows a Suspense fallback for link data on a client navigation (auto prefetch)',
async () => {
const browser = await next.browser('/')
// Record whether each Suspense fallback ever enters the DOM during the
// upcoming navigation.
const fallbackObserver = observeNodeAppearances(browser, [
'session-fallback',
'link-fallback',
'dynamic-fallback',
])
await fallbackObserver.observe()
await browser
.elementByCss(
'a[href="/partial-prefetching/link-data?prefetch=auto"]'
)
.click()
// Wait for the navigation to fully settle.
await retry(async () => {
expect(await browser.elementByCssInstant('#link-data').text()).toBe(
'link content'
)
expect(
await browser.elementByCssInstant('#dynamic-data').text()
).toBe('dynamic content')
})
const appearanceCounts = await fallbackObserver.getResult()
expect(appearanceCounts).toEqual({
'session-fallback': 0,
'link-fallback': 1,
'dynamic-fallback': 1,
})
}
)
})
}) })
function observeNodeAppearances(browser: Playwright, ids: string[]) {
// Record whether each Suspense fallback ever enters the DOM during the
// upcoming navigation. We inspect added nodes rather than the live DOM, so
// a fallback that's added and then quickly replaced is still caught.
type SeenCounts = Record<string, number>
const observe = () =>
browser.eval((ids: string[]) => {
const seen: SeenCounts = Object.fromEntries(ids.map((id) => [id, 0]))
;(window as any).__seenNodes = seen
const check = (node: Node) => {
if (!(node instanceof Element)) {
return
}
for (const id of ids) {
if (node.id === id || node.querySelector(`#${id}`)) {
seen[id] += 1
}
}
}
new MutationObserver((records) => {
records.forEach((record) => record.addedNodes.forEach(check))
}).observe(document.body, { childList: true, subtree: true })
}, ids)
const getResult = async (): Promise<SeenCounts> => {
const seen: SeenCounts | undefined = await browser.eval(
() => (window as any).__seenNodes
)
if (!seen) {
throw new Error('Must call observe() before calling getResult()')
}
return seen
}
return { observe, getResult }
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig
import type { NextConfig } from 'next'
const partialPrefetching = !!process.env.__NEXT_PARTIAL_PREFETCHING
const nextConfig: NextConfig = {
cacheComponents: true,
partialPrefetching,
}
export default nextConfig
import { cookies } from 'next/headers'
import { setTimeout } from 'node:timers/promises'
import { Suspense } from 'react'
async function getCachedValue() {
'use cache'
await setTimeout(1500)
return new Date().toISOString()
}
async function SessionData() {
await cookies()
await getCachedValue()
return <p id="cookies">Yum yum, delicious</p>
}
export default function Page() {
return (
<Suspense fallback={<p id="cookies">Loading...</p>}>
<SessionData />
</Suspense>
)
}
...@@ -7,13 +7,28 @@ export default function Root({ children }: { children: ReactNode }) { ...@@ -7,13 +7,28 @@ export default function Root({ children }: { children: ReactNode }) {
<body> <body>
<nav> <nav>
<Link href="/">/index</Link> |{' '} <Link href="/">/index</Link> |{' '}
<Link href="/params/some-id" prefetch={true}> <ul>
/params/some-id <li>
</Link>{' '} <ul>
|{' '} <li>
<Link href="/private" prefetch={true}> <Link href="/params/prefetch-auto">
/private /params/prefetch-auto
</Link> </Link>
</li>
<li>
<Link href="/params/prefetch-true" prefetch={true}>
/params/prefetch-true (prefetch=true)
</Link>
</li>
</ul>
</li>
<li>
<Link href="/cookies">/cookies</Link>
</li>
<li>
<Link href="/private">/private</Link>
</li>
</ul>
</nav> </nav>
{children} {children}
</body> </body>
......
import { Suspense } from 'react' import { Suspense } from 'react'
import { setTimeout } from 'timers/promises' import { setTimeout } from 'timers/promises'
// Runtime-prefetchable: a client navigation reveals the runtime shell.
export const prefetch = 'allow-runtime' export const prefetch = 'allow-runtime'
async function getCachedValue() { async function getCachedValue(id: string) {
'use cache' 'use cache'
await setTimeout(1500) await setTimeout(1500)
return new Date().toISOString() return `${id}: new Date().toISOString()`
} }
async function ParamsData({ params }: { params: Promise<{ id: string }> }) { async function LinkData({ params }: { params: Promise<{ id: string }> }) {
// Awaiting params (without generateStaticParams) is what defers the cache // Awaiting params defers the cache read past the app shell, so it
// read past the static shell. // should only trigger a cold cache indicator in a speculative prefetch.
await params const { id } = await params
const value = await getCachedValue() const value = await getCachedValue(id)
return <p id="params">{value}</p> return <p id="params">{value}</p>
} }
export default function Page({ params }: { params: Promise<{ id: string }> }) { export default function Page({ params }: { params: Promise<{ id: string }> }) {
return ( return (
<Suspense fallback={<p id="params-fallback">Loading...</p>}> <Suspense fallback={<p id="params-fallback">Loading...</p>}>
<ParamsData params={params} /> <LinkData params={params} />
</Suspense> </Suspense>
) )
} }
import { Suspense } from 'react' import { Suspense } from 'react'
import { setTimeout } from 'timers/promises' import { setTimeout } from 'timers/promises'
// Runtime-prefetchable: a client navigation reveals the runtime shell, and a
// private cache resolves in the session-data (runtime) stage, so it's part of
// the runtime shell for a dev client navigation.
export const prefetch = 'allow-runtime'
async function PrivateData() { async function PrivateData() {
'use cache: private' 'use cache: private'
await setTimeout(1500) await setTimeout(1500)
......
...@@ -18,14 +18,13 @@ describe('cache-indicator-partial-prefetching', () => { ...@@ -18,14 +18,13 @@ describe('cache-indicator-partial-prefetching', () => {
return return
} }
it('shows the Cold cache badge on a cold runtime-prefetch navigation to a route whose cache read follows await params, not on a warm one', async () => { it('cache after session data triggers cold cache indicator', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
// Cold navigation: the cache read sits after `await params`, so it resolves // Cold navigation: the cache read sits after `await params`, so it resolves
// in the runtime stage, part of the runtime shell for this navigation, so a // in the app shell for this navigation, so a cold cache there shows the badge.
// cold cache there shows the badge. await browser.elementByCss('a[href="/cookies"]').click()
await browser.elementByCss('a[href="/params/some-id"]').click() await browser.elementById('cookies')
await browser.elementById('params')
await retry(async () => { await retry(async () => {
expect(await browser.hasElementByCss('[data-cold-cache-badge]')).toBe( expect(await browser.hasElementByCss('[data-cold-cache-badge]')).toBe(
true true
...@@ -45,16 +44,70 @@ describe('cache-indicator-partial-prefetching', () => { ...@@ -45,16 +44,70 @@ describe('cache-indicator-partial-prefetching', () => {
// Warm navigation: the runtime shell is a cache hit, so no badge. An absence // Warm navigation: the runtime shell is a cache hit, so no badge. An absence
// can't be retried on, so wait out the replay window, then assert it never // can't be retried on, so wait out the replay window, then assert it never
// appeared. // appeared.
await browser.elementByCss('a[href="/params/some-id"]').click() await browser.elementByCss('a[href="/cookies"]').click()
await browser.elementById('params') await browser.elementById('cookies')
await waitFor(500) await waitFor(500)
expect(await browser.hasElementByCss('[data-cold-cache-badge]')).toBe(false) expect(await browser.hasElementByCss('[data-cold-cache-badge]')).toBe(false)
}) })
describe('cache after link data', () => {
it('does not trigger cold cache indicator without prefetch={true}', async () => {
const browser = await next.browser('/')
// Cold navigation: the cache read sits after `await params`, so it resolves
// in the runtime stage, part of the runtime shell for this navigation, so a
// cold cache there shows the badge.
await browser.elementByCss('a[href="/params/prefetch-auto"]').click()
await browser.elementById('params')
await waitFor(500)
expect(await browser.hasElementByCss('[data-cold-cache-badge]')).toBe(
false
)
})
// TODO(app-shells): simulate `prefetch={true}` behavior
it.failing(
'triggers cold cache indicator with prefetch={true}',
async () => {
const browser = await next.browser('/')
// Cold navigation: the cache read sits after `await params`, so it resolves
// in the runtime stage as part of the speculative prefetch shell for this navigation.
// a cold cache there shows the badge.
await browser.elementByCss('a[href="/params/prefetch-true"]').click()
await browser.elementById('params')
await retry(async () => {
expect(await browser.hasElementByCss('[data-cold-cache-badge]')).toBe(
true
)
})
// Navigate to the static home (a fresh render clears the badge), then wait
// for the background fill to settle so the next navigation is a warm hit.
await browser.elementByCss('a[href="/"]').click()
await retry(async () => {
expect(await browser.hasElementByCss('[data-cold-cache-badge]')).toBe(
false
)
})
await waitFor(2000)
// Warm navigation: the cache is a hit, so no badge.
await browser.elementByCss('a[href="/params/prefetch-true"]').click()
await browser.elementById('params')
await waitFor(500)
expect(await browser.hasElementByCss('[data-cold-cache-badge]')).toBe(
false
)
}
)
})
it('shows the Cold cache badge on a cold runtime-prefetch navigation to a private-cache route, not on a warm one', async () => { it('shows the Cold cache badge on a cold runtime-prefetch navigation to a private-cache route, not on a warm one', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
// Cold navigation: the private cache resolves in the runtime shell, so a // Cold navigation: the private cache resolves in the app shell, so a
// cold cache there shows the badge. // cold cache there shows the badge.
await browser.elementByCss('a[href="/private"]').click() await browser.elementByCss('a[href="/private"]').click()
await browser.elementById('private') await browser.elementById('private')
......
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