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(
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
// 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
......@@ -1354,11 +1360,23 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
// load: plain navigations, and HMR refreshes (a fresh render of the current
// page, with no settled prefetch to draw on). Dynamic content always
// streams in after the shell.
const revealAfterStage =
initialRequestStore.isHmrRefresh !== true &&
(await anySegmentHasRuntimePrefetchEnabled(loaderTree))
? RenderStage.Runtime
: RenderStage.Static
let prefetchStage: StreamRevealStage
if (initialRequestStore.isHmrRefresh === true) {
prefetchStage = 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({
ctx,
......@@ -1369,11 +1387,10 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
shouldValidate,
fallbackRouteParams: fallbackParams,
getDevRenderDidError: () => didErrorObservably,
revealAfterStage,
// 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,
navigationKind: {
type: 'prefetched-client',
prefetchStage,
},
})
stream = result.stream
debugChannel = result.debugChannel
......@@ -3437,12 +3454,9 @@ async function renderToStream(
getDevRenderDidError: () => didErrorObservably,
// An initial HTML load serves the static shell; runtime and
// dynamic content stream in afterward.
revealAfterStage: RenderStage.Static,
// Hold the stream until the shell content has flushed so the
// streamed HTML reflects the prerendered shell rather than a
// premature shell-stage Suspense fallback (see
// `holdStreamUntilRevealed`).
holdStreamUntilRevealed: true,
navigationKind: {
type: 'initial-load',
},
})
reactServerResult = new ReactServerResult(serverStream)
......@@ -4545,6 +4559,11 @@ interface StagedDevRenderSetup {
readonly environmentName: () => string
}
enum PrefetchingMode {
LegacySpeculative = 1,
Partial = 2,
}
/**
* Per-render setup shared by the streaming dev Cache Components renders: a
* cache signal (so caches fill in the background), a prerender resume data
......@@ -4613,10 +4632,18 @@ interface StagedDevRenderOptions {
ctx: AppRenderContext
requestStore: RequestStore
onError: (error: unknown) => void
revealAfterStage: RenderStage.Static | RenderStage.Runtime
holdStreamUntilRevealed: boolean
navigationKind: DevNavigationKind
}
type DevNavigationKind =
| { type: 'initial-load' }
| { type: 'prefetched-client'; prefetchStage: StreamRevealStage }
type StreamRevealStage =
| RenderStage.Static
| RenderStage.ShellRuntime
| RenderStage.Runtime
interface StreamStagedRenderInDevOptions extends StagedDevRenderOptions {
rscPayload: RSCPayload
stageController: StagedRenderingController
......@@ -4647,12 +4674,31 @@ async function streamStagedRenderInDev({
environmentName,
onError,
debugChannel,
revealAfterStage,
holdStreamUntilRevealed,
navigationKind,
}: StreamStagedRenderInDevOptions): Promise<{
stream: Readable
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 { clientModules } = getClientReferenceManifest()
......@@ -4724,6 +4770,19 @@ async function streamStagedRenderInDev({
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
// render in the `ShellEarlyStatic` stage and creates the stream (one replay
// for the response, one to accumulate the chunks). The later tasks advance
......@@ -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()) {
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
// Advance to the dynamic stage even while caches are still filling, so
// dynamic content streams to the browser right away instead of being
// withheld until the slowest cache fill completes. Streaming that content
// promptly is the whole point of the streaming dev render.
......@@ -5003,8 +5016,7 @@ async function stagedRenderWithCachesInDev({
shouldValidate,
fallbackRouteParams,
getDevRenderDidError,
revealAfterStage,
holdStreamUntilRevealed,
navigationKind,
}: StagedRenderWithCachesInDevOptions): Promise<{
stream: Readable
debugChannel: NodeDebugChannelPair | undefined
......@@ -5041,8 +5053,7 @@ async function stagedRenderWithCachesInDev({
environmentName,
onError,
debugChannel,
revealAfterStage,
holdStreamUntilRevealed,
navigationKind,
})
if (shouldValidate) {
......
......@@ -14,6 +14,16 @@ export default function Page() {
/use-cache-private-runtime-prefetch
</Link>
</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>
)
}
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'
const partialPrefetching = !!process.env.__NEXT_PARTIAL_PREFETCHING
describe('cache-components-dev-streaming', () => {
const { next } = nextTestSetup({
files: __dirname,
env: {
__NEXT_PARTIAL_PREFETCHING: partialPrefetching ? 'true' : '',
},
})
it('should stream suspense boundaries while filling caches in the background', async () => {
......@@ -99,30 +104,11 @@ describe('cache-components-dev-streaming', () => {
// 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.
await browser.eval(() => {
const seen = { runtime: false, dynamic: false }
;(window as any).__fallbacksSeen = seen
const check = (node: Node) => {
if (!(node instanceof Element)) {
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 })
})
const fallbackObserver = observeNodeAppearances(browser, [
'runtime-fallback',
'dynamic-fallback',
])
await fallbackObserver.observe()
await browser.elementByCss('a[href="/runtime-prefetch"]').click()
......@@ -136,12 +122,13 @@ describe('cache-components-dev-streaming', () => {
)
})
const appearanceCounts = await fallbackObserver.getResult()
// The runtime-prefetchable content was resolved before the response started
// streaming, so its fallback was never rendered; the dynamic content's
// fallback was.
expect(await browser.eval(() => (window as any).__fallbacksSeen)).toEqual({
runtime: false,
dynamic: true,
expect(appearanceCounts).toEqual({
'runtime-fallback': 0,
'dynamic-fallback': 1,
})
})
......@@ -178,22 +165,11 @@ describe('cache-components-dev-streaming', () => {
// Warm navigation: record whether the fallback ever enters the DOM during
// the navigation, even briefly. It shouldn't, since the warm content is
// delivered with the shell.
await browser.eval(() => {
;(window as any).__privateFallbackSeen = 0
new MutationObserver((records) => {
records.forEach((record) =>
record.addedNodes.forEach((node) => {
if (
node instanceof Element &&
(node.id === 'private-fallback' ||
node.querySelector('#private-fallback'))
) {
;(window as any).__privateFallbackSeen += 1
}
})
)
}).observe(document.body, { childList: true, subtree: true })
})
const fallbackObserver = observeNodeAppearances(browser, [
'private-fallback',
])
await fallbackObserver.observe()
// Regression test for a rare client-side race the `_revealAfter` gate
// fixes. The Flight client decodes the response incrementally, so before
......@@ -212,9 +188,10 @@ describe('cache-components-dev-streaming', () => {
await browser.back()
}
expect(
await browser.eval(() => (window as any).__privateFallbackSeen)
).toBe(0)
const appearanceCounts = await fallbackObserver.getResult()
expect(appearanceCounts).toEqual({
'private-fallback': 0,
})
})
// The following are smoke tests that Cache Components validation still
......@@ -316,4 +293,121 @@ describe('cache-components-dev-streaming', () => {
`)
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 }) {
<body>
<nav>
<Link href="/">/index</Link> |{' '}
<Link href="/params/some-id" prefetch={true}>
/params/some-id
</Link>{' '}
|{' '}
<Link href="/private" prefetch={true}>
/private
</Link>
<ul>
<li>
<ul>
<li>
<Link href="/params/prefetch-auto">
/params/prefetch-auto
</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>
{children}
</body>
......
import { Suspense } from 'react'
import { setTimeout } from 'timers/promises'
// Runtime-prefetchable: a client navigation reveals the runtime shell.
export const prefetch = 'allow-runtime'
async function getCachedValue() {
async function getCachedValue(id: string) {
'use cache'
await setTimeout(1500)
return new Date().toISOString()
return `${id}: new Date().toISOString()`
}
async function ParamsData({ params }: { params: Promise<{ id: string }> }) {
// Awaiting params (without generateStaticParams) is what defers the cache
// read past the static shell.
await params
const value = await getCachedValue()
async function LinkData({ params }: { params: Promise<{ id: string }> }) {
// Awaiting params defers the cache read past the app shell, so it
// should only trigger a cold cache indicator in a speculative prefetch.
const { id } = await params
const value = await getCachedValue(id)
return <p id="params">{value}</p>
}
export default function Page({ params }: { params: Promise<{ id: string }> }) {
return (
<Suspense fallback={<p id="params-fallback">Loading...</p>}>
<ParamsData params={params} />
<LinkData params={params} />
</Suspense>
)
}
import { Suspense } from 'react'
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() {
'use cache: private'
await setTimeout(1500)
......
......@@ -18,14 +18,13 @@ describe('cache-indicator-partial-prefetching', () => {
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('/')
// 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/some-id"]').click()
await browser.elementById('params')
// in the app shell for this navigation, so a cold cache there shows the badge.
await browser.elementByCss('a[href="/cookies"]').click()
await browser.elementById('cookies')
await retry(async () => {
expect(await browser.hasElementByCss('[data-cold-cache-badge]')).toBe(
true
......@@ -45,16 +44,70 @@ describe('cache-indicator-partial-prefetching', () => {
// 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
// appeared.
await browser.elementByCss('a[href="/params/some-id"]').click()
await browser.elementById('params')
await browser.elementByCss('a[href="/cookies"]').click()
await browser.elementById('cookies')
await waitFor(500)
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 () => {
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.
await browser.elementByCss('a[href="/private"]').click()
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