Unverified Commit 69219b49 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[PPF] Use RDC in cachedNavigations codepaths (#98005)

Closes NAR-954

In Partial Prefetching, the embedded runtime stream codepath awas
accidentally dropping the RDC. This PR fixes this by prefilling the
mutable cache from the RDC. we ungate the failing tests introduced in
#99417 and add some more e2e ones.

As a drive-by improvement, i've also moved the `cacheReady()` call to
happen after the main render runs through all the stages. It's pretty
strange to call `cacheReady()` before we've even started the render that
might fill any caches. I'm guessing it works because the code in-between
runs quickly enough, but it's still a potential race and we shouldn't do
it.

### How this bug got introduced

In #94194 we accidentally started clobbering the resume data cache in
the `cachedNavigations` codepath (i.e. when rendering the embedded
runtime prefetch stream).
This assignment used to be non-destructive because
`prerenderResumeDataCache` was separate:

https://github.com/vercel/next.js/blob/b0420899b68a4f7506fdbc93ff5acf6edcfa3d3c/packages/next/src/server/app-render/app-render.tsx#L969-L972
But after unifying `prerenderResumeDataCache` and
`renderResumeDataCache`, we started essentially dropping the RDC and
using an empty one

https://github.com/vercel/next.js/blob/8c661813a1e66cd85b795e3aeae0f04ae3e3201e/packages/next/src/server/app-render/app-render.tsx#L970-L973
This wasn't caught because the tests that checked RDC behavior weren't
exercising this codepath (at the time: no `cachedNavigations` + runtime
prefetch opt in, and later on no `partialPrefetching` opt in)
parent 562d3e7f
...@@ -1128,6 +1128,8 @@ async function generateStagedDynamicFlightRenderResultNode( ...@@ -1128,6 +1128,8 @@ async function generateStagedDynamicFlightRenderResultNode(
const staticStageByteLengthDeferred = createPromiseWithResolvers<number>() const staticStageByteLengthDeferred = createPromiseWithResolvers<number>()
let runtimePrefetchStream: ReadableStream<Uint8Array> | undefined let runtimePrefetchStream: ReadableStream<Uint8Array> | undefined
let startRuntimePrefetchRender: (() => Promise<void>) | undefined
// Partial prefetching waits for cacheReady() before starting an embedded // Partial prefetching waits for cacheReady() before starting an embedded
// runtime prefetch. Track React's native immediates so that this wait // runtime prefetch. Track React's native immediates so that this wait
// includes Flight work that can discover more cache reads. Other prefetch // includes Flight work that can discover more cache reads. Other prefetch
...@@ -1144,7 +1146,10 @@ async function generateStagedDynamicFlightRenderResultNode( ...@@ -1144,7 +1146,10 @@ async function generateStagedDynamicFlightRenderResultNode(
// processing and increases the response payload size. // processing and increases the response payload size.
if (prefetchMode === PrefetchingMode.Partial) { if (prefetchMode === PrefetchingMode.Partial) {
// Create a mutable cache that gets filled during the dynamic render. // Create a mutable cache that gets filled during the dynamic render.
const prerenderResumeDataCache = createPrerenderResumeDataCache() const prerenderResumeDataCache = createPrerenderResumeDataCache(
// Prefill the mutable cache from the RDC if available.
requestStore.resumeDataCache ?? undefined
)
requestStore.resumeDataCache = prerenderResumeDataCache requestStore.resumeDataCache = prerenderResumeDataCache
const cacheSignal = new CacheSignal(immediateTracker) const cacheSignal = new CacheSignal(immediateTracker)
...@@ -1157,20 +1162,16 @@ async function generateStagedDynamicFlightRenderResultNode( ...@@ -1157,20 +1162,16 @@ async function generateStagedDynamicFlightRenderResultNode(
// render has filled all caches. // render has filled all caches.
const runtimePrefetchTransform = new TransformStream<Uint8Array>() const runtimePrefetchTransform = new TransformStream<Uint8Array>()
runtimePrefetchStream = runtimePrefetchTransform.readable runtimePrefetchStream = runtimePrefetchTransform.readable
startRuntimePrefetchRender = async () => {
// Wait for the dynamic render to fill caches, then run the final runtime await cacheSignal.cacheReady()
// prerender (fire-and-forget — does not block the response). return spawnRuntimePrefetchWithFilledCaches(
void cacheSignal runtimePrefetchTransform.writable,
.cacheReady() ctx,
.then(() => prerenderResumeDataCache,
spawnRuntimePrefetchWithFilledCaches( requestStore,
runtimePrefetchTransform.writable, onError
ctx,
prerenderResumeDataCache,
requestStore,
onError
)
) )
}
} }
const rscPayload = await workUnitAsyncStorage.run( const rscPayload = await workUnitAsyncStorage.run(
...@@ -1242,6 +1243,8 @@ async function generateStagedDynamicFlightRenderResultNode( ...@@ -1242,6 +1243,8 @@ async function generateStagedDynamicFlightRenderResultNode(
() => stageController.advanceStage(RenderStage.Dynamic) () => stageController.advanceStage(RenderStage.Dynamic)
) )
void startRuntimePrefetchRender?.()
return new FlightRenderResult(flightStream, { return new FlightRenderResult(flightStream, {
fetchMetrics: workStore.fetchMetrics, fetchMetrics: workStore.fetchMetrics,
}) })
...@@ -4016,6 +4019,8 @@ async function renderToStream( ...@@ -4016,6 +4019,8 @@ async function renderToStream(
createPromiseWithResolvers<number>() createPromiseWithResolvers<number>()
let runtimePrefetchStream: ReadableStream<Uint8Array> | undefined let runtimePrefetchStream: ReadableStream<Uint8Array> | undefined
let startRuntimePrefetchRender: (() => Promise<void>) | undefined
// Partial prefetching waits for cacheReady() before starting an // Partial prefetching waits for cacheReady() before starting an
// embedded runtime prefetch. Track React's native immediates so that // embedded runtime prefetch. Track React's native immediates so that
// this wait includes Flight work that can discover more cache reads. // this wait includes Flight work that can discover more cache reads.
...@@ -4028,12 +4033,13 @@ async function renderToStream( ...@@ -4028,12 +4033,13 @@ async function renderToStream(
// If the route should runtime-cache its navigation, spawn a runtime // If the route should runtime-cache its navigation, spawn a runtime
// prerender after the resume render fills caches. The result is // prerender after the resume render fills caches. The result is
// embedded in the initial RSC payload so the client can cache // embedded in the initial RSC payload so the client can cache
// runtime-prefetchable content during hydration. This is enabled when // runtime-prefetchable content during hydration. This is enabled for
// Partial Prefetching is on for the route, either per segment (a // Partial Prefetching routes.
// `prefetch` of 'partial') or globally (the
// `partialPrefetching` config).
if (prefetchMode === PrefetchingMode.Partial) { if (prefetchMode === PrefetchingMode.Partial) {
const prerenderResumeDataCache = createPrerenderResumeDataCache() const prerenderResumeDataCache = createPrerenderResumeDataCache(
// Prefill the mutable cache from the RDC if available.
requestStore.resumeDataCache ?? undefined
)
requestStore.resumeDataCache = prerenderResumeDataCache requestStore.resumeDataCache = prerenderResumeDataCache
const cacheSignal = new CacheSignal(immediateTracker) const cacheSignal = new CacheSignal(immediateTracker)
...@@ -4043,17 +4049,16 @@ async function renderToStream( ...@@ -4043,17 +4049,16 @@ async function renderToStream(
const runtimePrefetchTransform = new TransformStream<Uint8Array>() const runtimePrefetchTransform = new TransformStream<Uint8Array>()
runtimePrefetchStream = runtimePrefetchTransform.readable runtimePrefetchStream = runtimePrefetchTransform.readable
void cacheSignal startRuntimePrefetchRender = async () => {
.cacheReady() await cacheSignal.cacheReady()
.then(() => return spawnRuntimePrefetchWithFilledCaches(
spawnRuntimePrefetchWithFilledCaches( runtimePrefetchTransform.writable,
runtimePrefetchTransform.writable, ctx,
ctx, prerenderResumeDataCache,
prerenderResumeDataCache, requestStore,
requestStore, serverComponentsErrorHandler
serverComponentsErrorHandler
)
) )
}
} }
const RSCPayload = await workUnitAsyncStorage.run( const RSCPayload = await workUnitAsyncStorage.run(
...@@ -4134,6 +4139,8 @@ async function renderToStream( ...@@ -4134,6 +4139,8 @@ async function renderToStream(
() => stageController.advanceStage(RenderStage.Dynamic) () => stageController.advanceStage(RenderStage.Dynamic)
) )
void startRuntimePrefetchRender?.()
reactServerResult = new ReactServerResult(flightStream) reactServerResult = new ReactServerResult(flightStream)
} else { } else {
// MARK: nodeStreams RSC // MARK: nodeStreams RSC
......
...@@ -2886,7 +2886,8 @@ export async function cache( ...@@ -2886,7 +2886,8 @@ export async function cache(
debug?.( debug?.(
logPrefix, logPrefix,
'Resume Data Cache entry not found', 'Resume Data Cache entry not found',
serializedCacheKey serializedCacheKey,
`(${resumeDataCache.cache.size} entries)`
) )
if (cacheSignal) { if (cacheSignal) {
......
...@@ -120,7 +120,6 @@ describe('resume-data-cache', () => { ...@@ -120,7 +120,6 @@ describe('resume-data-cache', () => {
describe('use cache', () => { describe('use cache', () => {
const valuePattern = /cache-random-.+?-\d+-\d+\.\d+/ const valuePattern = /cache-random-.+?-\d+-\d+\.\d+/
// @gate !partialPrefetchingGlobal
it('initial', async () => { it('initial', async () => {
await testInitial({ await testInitial({
name: 'use cache - initial', name: 'use cache - initial',
...@@ -132,7 +131,6 @@ describe('resume-data-cache', () => { ...@@ -132,7 +131,6 @@ describe('resume-data-cache', () => {
// TODO: propagation of RDC after revalidation seems very flaky in deploy mode, // TODO: propagation of RDC after revalidation seems very flaky in deploy mode,
// so we're skipping this test in deploy until we figure out why // so we're skipping this test in deploy until we figure out why
// @force-gate !deploy // @force-gate !deploy
// @gate !partialPrefetchingGlobal
it('after revalidation', async () => { it('after revalidation', async () => {
await testRevalidation({ await testRevalidation({
name: 'use cache - revalidation', name: 'use cache - revalidation',
...@@ -146,7 +144,6 @@ describe('resume-data-cache', () => { ...@@ -146,7 +144,6 @@ describe('resume-data-cache', () => {
describe('fetch cache', () => { describe('fetch cache', () => {
const valuePattern = /fetch-random-\d+-\d+\.\d+/ const valuePattern = /fetch-random-\d+-\d+\.\d+/
// @gate !(partialPrefetchingGlobal && deploy)
it('initial', async () => { it('initial', async () => {
await testInitial({ await testInitial({
name: 'fetch cache - initial', name: 'fetch cache - initial',
...@@ -158,7 +155,6 @@ describe('resume-data-cache', () => { ...@@ -158,7 +155,6 @@ describe('resume-data-cache', () => {
// TODO: propagation of RDC after revalidation seems very flaky in deploy mode, // TODO: propagation of RDC after revalidation seems very flaky in deploy mode,
// so we're skipping this test in deploy until we figure out why // so we're skipping this test in deploy until we figure out why
// @force-gate !deploy // @force-gate !deploy
// @force-gate !partialPrefetchingGlobal
it('after revalidation', async () => { it('after revalidation', async () => {
await testRevalidation({ await testRevalidation({
name: 'fetch cache - revalidation', name: 'fetch cache - revalidation',
...@@ -170,7 +166,6 @@ describe('resume-data-cache', () => { ...@@ -170,7 +166,6 @@ describe('resume-data-cache', () => {
}) })
}) })
// @gate !partialPrefetchingGlobal
it('should use RDC for server action re-renders', async () => { it('should use RDC for server action re-renders', async () => {
const url = '/server-action' const url = '/server-action'
const valuePattern = /cache-random-\d+\.\d+/ const valuePattern = /cache-random-\d+\.\d+/
...@@ -228,7 +223,6 @@ describe('resume-data-cache', () => { ...@@ -228,7 +223,6 @@ describe('resume-data-cache', () => {
}) })
}) })
// @gate !partialPrefetchingGlobal
it('should see fresh data after updateTag in server action with use cache', async () => { it('should see fresh data after updateTag in server action with use cache', async () => {
// This test verifies that when a server action calls updateTag(), // This test verifies that when a server action calls updateTag(),
// the subsequent re-render sees fresh data instead of stale RDC data. // the subsequent re-render sees fresh data instead of stale RDC data.
...@@ -293,7 +287,6 @@ describe('resume-data-cache', () => { ...@@ -293,7 +287,6 @@ describe('resume-data-cache', () => {
}) })
}) })
// @gate !(partialPrefetchingGlobal && deploy)
it('should see fresh data after updateTag in server action with fetch cache', async () => { it('should see fresh data after updateTag in server action with fetch cache', async () => {
// This test verifies that when a server action calls updateTag(), // This test verifies that when a server action calls updateTag(),
// the subsequent re-render sees fresh data instead of stale RDC data. // the subsequent re-render sees fresh data instead of stale RDC data.
......
...@@ -6,16 +6,12 @@ import { createRouterAct } from 'router-act' ...@@ -6,16 +6,12 @@ import { createRouterAct } from 'router-act'
// The `partial-prefetching` fixture enables Partial Prefetching globally via // The `partial-prefetching` fixture enables Partial Prefetching globally via
// the next-config `partialPrefetching: true`, which opts every route into // the next-config `partialPrefetching: true`, which opts every route into
// runtime Cached Navigations even without a per-segment `prefetch` config. // runtime Cached Navigations even without a per-segment `prefetch` config.
// @force-gate !dev
describe('cached navigations - global partialPrefetching', () => { describe('cached navigations - global partialPrefetching', () => {
const { next, isNextDev } = nextTestSetup({ const { next } = nextTestSetup({
files: path.join(__dirname, 'partial-prefetching'), files: path.join(__dirname, 'partial-prefetching'),
}) })
if (isNextDev) {
it('is skipped', () => {})
return
}
it('runtime-caches a route that has no per-segment prefetch config', async () => { it('runtime-caches a route that has no per-segment prefetch config', async () => {
let page: Playwright.Page let page: Playwright.Page
const browser = await next.browser('/', { const browser = await next.browser('/', {
...@@ -90,4 +86,107 @@ describe('cached navigations - global partialPrefetching', () => { ...@@ -90,4 +86,107 @@ describe('cached navigations - global partialPrefetching', () => {
'Dynamic content' 'Dynamic content'
) )
}) })
it('cache values are consistent across the HTML shell, static prefetches, and cached navigations', async () => {
const href = '/cache-from-rdc'
const htmlId = 'cached-data'
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Reveal a link to the page. This should result in a static prefetch.
await act(async () => {
const linkToggle = await browser.elementByCss(
`[data-prefetch="auto"] input[data-link-accordion="${href}"]`
)
await linkToggle.click()
}, [
{
includes: 'cache-timestamp:',
kind: 'static',
},
])
//===========================
// Test client navigation
//===========================
// Navigate to the page.
const cachedValueFromPrefetch = await act(async () => {
await browser
.elementByCss(`[data-prefetch="auto"] a[href="${href}"]`)
.click()
const cachedValueFromPrefetch = await browser.elementById(htmlId).text()
return cachedValueFromPrefetch
}, [{ includes: 'Navigation-only runtime data' }])
expect(await browser.elementById('runtime-data').text()).toBe(
'Navigation-only runtime data'
)
// The navigation response should also contain the same cache value.
expect(await browser.elementById(htmlId).text()).toBe(
cachedValueFromPrefetch
)
// Navigate back to the index page.
await act(() => browser.elementByCss('a[href="/"]').click(), 'no-requests')
// Then, navigate to the page again (without a prefetch).
// All the UI is cacheable, so it should be re-used from the client
// navigation, and we should navigate without any extra requests.
await act(async () => {
await browser
.elementByCss(`[data-prefetch="false"] a[href="${href}"]`)
.click()
}, 'no-requests')
expect(await browser.elementById('runtime-data').text()).toBe(
'Navigation-only runtime data'
)
// The cached client navigation should have the same cache value.
expect(await browser.elementById(htmlId).text()).toBe(
cachedValueFromPrefetch
)
//===========================
// Test initial load
//===========================
await browser.refresh()
expect(await browser.elementById('runtime-data').text()).toBe(
'Navigation-only runtime data'
)
// The initial load should have the same cache value.
expect(await browser.elementById(htmlId).text()).toBe(
cachedValueFromPrefetch
)
// Navigate to the index page.
await act(() => browser.elementByCss('a[href="/"]').click())
// Then, navigate back to the page without a prefetch.
// All the UI is cacheable, so it should be re-used from the initial
// load, and we should navigate without any extra requests.
await act(async () => {
await browser
.elementByCss(`[data-prefetch="false"] a[href="${href}"]`)
.click()
}, 'no-requests')
expect(await browser.elementById('runtime-data').text()).toBe(
'Navigation-only runtime data'
)
// The cached navigation should have the same cache value.
expect(await browser.elementById(htmlId).text()).toBe(
cachedValueFromPrefetch
)
})
}) })
...@@ -1468,4 +1468,153 @@ describe('cached navigations', () => { ...@@ -1468,4 +1468,153 @@ describe('cached navigations', () => {
it('runtime-caches a route with prefetch = "partial"', async () => { it('runtime-caches a route with prefetch = "partial"', async () => {
await expectRuntimeCachedOnSecondNavigation('/prefetch-partial') await expectRuntimeCachedOnSecondNavigation('/prefetch-partial')
}) })
it('cache values are consistent across the HTML shell, static prefetches, and cached navigations', async () => {
const href = '/cache-from-rdc'
const htmlId = 'cached-data'
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
const getRenderId = async (): Promise<string> => {
return await browser.elementById('render-id').text()
}
// Reveal a link to the page. This should result in a static prefetch.
await act(async () => {
const linkToggle = await browser.elementByCss(
`[data-prefetch="auto"] input[data-link-accordion="${href}"]`
)
await linkToggle.click()
}, [
{
includes: 'cache-timestamp:',
kind: 'static',
},
])
//===========================
// Test client navigation
//===========================
// Navigate to the page.
const { cachedValueFromPrefetch, prefetchRenderId } = await act(
async () => {
await browser
.elementByCss(`[data-prefetch="auto"] a[href="${href}"]`)
.click()
const cachedValueFromPrefetch = await browser.elementById(htmlId).text()
const prefetchRenderId = await getRenderId()
return { cachedValueFromPrefetch, prefetchRenderId }
},
{ includes: 'Dynamic data' }
)
{
expect(await browser.elementById('dynamic-data').text()).toBe(
'Dynamic data'
)
// The navigation response should also contain the same cache value.
expect(await browser.elementById(htmlId).text()).toBe(
cachedValueFromPrefetch
)
const clientNavRenderId = await getRenderId()
// Navigate back to the index page.
await act(
() => browser.elementByCss('a[href="/"]').click(),
'no-requests'
)
// Then, navigate to the page again (without a prefetch).
// We should re-use the cacheable part of the UI from the navigation.
await act(
async () => {
await browser
.elementByCss(`[data-prefetch="false"] a[href="${href}"]`)
.click()
// Make sure we're showing the content from the cached navigation,
// not the static prefetch -- otherwise, the cache consistency check
// would be meaningless.
const visibleRenderId = await getRenderId()
expect(visibleRenderId).not.toBe(prefetchRenderId)
expect(visibleRenderId).toBe(clientNavRenderId)
// The cacheable UI extracted from the navigation (shown while navigating)
// should have the same cache value.
expect(await browser.elementById(htmlId).text()).toBe(
cachedValueFromPrefetch
)
},
{ includes: 'Dynamic data' }
)
expect(await browser.elementById('dynamic-data').text()).toBe(
'Dynamic data'
)
// The second navigation result should have the same cache value.
expect(await browser.elementById(htmlId).text()).toBe(
cachedValueFromPrefetch
)
// We have uncached data, so this was a fresh render.
expect(await getRenderId()).not.toBe(clientNavRenderId)
}
//===========================
// Test initial load
//===========================
{
await browser.refresh()
expect(await browser.elementById('dynamic-data').text()).toBe(
'Dynamic data'
)
// The initial load should have the same cache value.
expect(await browser.elementById(htmlId).text()).toBe(
cachedValueFromPrefetch
)
const initialLoadRenderId = await getRenderId()
// Navigate to the index page.
await act(() => browser.elementByCss('a[href="/"]').click())
// Then, navigate back to the page without a prefetch.
// We should re-use the cacheable part of the UI from the navigation.
await act(
async () => {
await browser
.elementByCss(`[data-prefetch="false"] a[href="${href}"]`)
.click()
// Make sure we're showing the content from the cached navigation.
const visibleRenderId = await getRenderId()
expect(visibleRenderId).toBe(initialLoadRenderId)
// The cacheable UI extracted from the navigation (shown while navigating)
// should have the same cache value.
expect(await browser.elementById(htmlId).text()).toBe(
cachedValueFromPrefetch
)
},
{ includes: 'Dynamic data' }
)
expect(await browser.elementById('dynamic-data').text()).toBe(
'Dynamic data'
)
// The second navigation result should have the same cache value.
expect(await browser.elementById(htmlId).text()).toBe(
cachedValueFromPrefetch
)
// We have uncached data, so this was a fresh render.
expect(await getRenderId()).not.toBe(initialLoadRenderId)
}
})
}) })
import Link from 'next/link'
import { connection } from 'next/server'
import { Suspense } from 'react'
export default async function Page() {
const cachedTimestamp = await getCachedTimestamp()
return (
<main>
<p id="cached-data">{cachedTimestamp}</p>
<p id="render-id" suppressHydrationWarning>
{Math.floor(performance.timeOrigin + performance.now())}
</p>
<Link
href="/"
// Avoid creating requests that interfere with act()
prefetch={false}
>
Go back to index page
</Link>
<Suspense fallback={<div>Loading non-prerenderable data...</div>}>
{(async () => {
// Use cookies() after navigation() so that the page
// doesn't require a runtime shell.
await connection()
return <p id="dynamic-data">Dynamic data</p>
})()}
</Suspense>
</main>
)
}
async function getCachedTimestamp() {
'use cache'
await new Promise((resolve) => setTimeout(resolve))
return `cache-timestamp: ${Date.now()}`
}
import Link from 'next/link' import Link from 'next/link'
import { LinkAccordion } from '../components/link-accordion'
export default function Home() { export default function Home() {
return ( return (
...@@ -39,6 +40,20 @@ export default function Home() { ...@@ -39,6 +40,20 @@ export default function Home() {
</Link> </Link>
</li> </li>
</ul> </ul>
<h2>Cache value consistency</h2>
<ul>
<li data-prefetch="auto">
<LinkAccordion href="/cache-from-rdc">
/cache-from-rdc (prefetch="auto")
</LinkAccordion>
</li>
<li data-prefetch="false">
<Link href="/cache-from-rdc" prefetch={false}>
/cache-from-rdc (prefetch="false")
</Link>
</li>
</ul>
</main> </main>
) )
} }
'use client' 'use client'
import Link, { LinkProps } from 'next/link' import Link, { type LinkProps } from 'next/link'
import { useState } from 'react' import { useState } from 'react'
export function LinkAccordion({ export function LinkAccordion({
href, href,
children, children,
prefetch, prefetch = 'auto',
}: { }: {
href: string href: string
children: React.ReactNode children: React.ReactNode
prefetch?: LinkProps['prefetch'] prefetch?: LinkProps['prefetch']
}) { }) {
const [isVisible, setIsVisible] = useState(false) const [isVisible, setIsVisible] = useState(false)
const prefetchAttr = prefetch === null ? 'auto' : `${prefetch}`
return ( return (
<> <>
<input <input
type="checkbox" type="checkbox"
checked={isVisible} checked={isVisible}
onChange={() => setIsVisible(!isVisible)} onChange={() => setIsVisible(!isVisible)}
data-prefetch={prefetchAttr}
data-link-accordion={href} data-link-accordion={href}
/> />
{isVisible ? ( {isVisible ? (
...@@ -26,7 +28,7 @@ export function LinkAccordion({ ...@@ -26,7 +28,7 @@ export function LinkAccordion({
{children} {children}
</Link> </Link>
) : ( ) : (
`${children} (link is hidden)` <>{children} (link is hidden)</>
)} )}
</> </>
) )
......
import { navigation } from 'next/cache'
import { cookies } from 'next/headers'
import Link from 'next/link'
import { Suspense } from 'react'
export default async function Page() {
const cachedTimestamp = await getCachedTimestamp()
return (
<main>
<p id="cached-data">{cachedTimestamp}</p>
<Link
href="/"
// Avoid creating requests that interfere with act()
prefetch={false}
>
Go back to index page
</Link>
<Suspense fallback={<div>Loading runtime data...</div>}>
{(async () => {
// Use cookies() after navigation() so that the page
// doesn't require a runtime shell.
await navigation()
await cookies()
return <p id="runtime-data">Navigation-only runtime data</p>
})()}
</Suspense>
</main>
)
}
async function getCachedTimestamp() {
'use cache'
await new Promise((resolve) => setTimeout(resolve))
return `cache-timestamp: ${Date.now()}`
}
import Link from 'next/link' import Link from 'next/link'
import { LinkAccordion } from '../components/link-accordion'
export default function Home() { export default function Home() {
return ( return (
<main> <main>
<h1>Home</h1> <h1>Home</h1>
<h2> <h2>Runtime prefetchable</h2>
Links with <code>prefetch=false</code>
</h2>
<ul> <ul>
<li> <li>
<Link href="/runtime-prefetchable" prefetch={false}> <Link href="/runtime-prefetchable" prefetch={false}>
...@@ -14,6 +13,20 @@ export default function Home() { ...@@ -14,6 +13,20 @@ export default function Home() {
</Link> </Link>
</li> </li>
</ul> </ul>
<h2>Cache value consistency</h2>
<ul>
<li data-prefetch="auto">
<LinkAccordion href="/cache-from-rdc">
/cache-from-rdc (prefetch="auto")
</LinkAccordion>
</li>
<li data-prefetch="false">
<Link href="/cache-from-rdc" prefetch={false}>
/cache-from-rdc (prefetch="false")
</Link>
</li>
</ul>
</main> </main>
) )
} }
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch = 'auto',
}: {
href: string
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
const prefetchAttr = prefetch === null ? 'auto' : `${prefetch}`
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-prefetch={prefetchAttr}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
...@@ -661,7 +661,6 @@ describe('use-cache', () => { ...@@ -661,7 +661,6 @@ describe('use-cache', () => {
}) })
if (withCacheComponents) { if (withCacheComponents) {
// @gate !partialPrefetchingGlobal
it('should omit non-prerenderable caches from prerendered shells', async () => { it('should omit non-prerenderable caches from prerendered shells', async () => {
const cacheValues = { const cacheValues = {
prerenderable: /(?<!non-)prerenderable: \d+/, prerenderable: /(?<!non-)prerenderable: \d+/,
...@@ -694,7 +693,6 @@ describe('use-cache', () => { ...@@ -694,7 +693,6 @@ describe('use-cache', () => {
) )
}) })
// @gate !partialPrefetchingGlobal
it('should omit non-prefetchable caches from prerendered shells', async () => { it('should omit non-prefetchable caches from prerendered shells', async () => {
const cacheValues = { const cacheValues = {
prerenderable: /prerenderable: \d+/, prerenderable: /prerenderable: \d+/,
...@@ -752,7 +750,6 @@ describe('use-cache', () => { ...@@ -752,7 +750,6 @@ describe('use-cache', () => {
}) })
} }
// @gate !partialPrefetchingGlobal
it('should not have hydration errors when resuming a partial shell with non-prerenderable caches', async () => { it('should not have hydration errors when resuming a partial shell with non-prerenderable caches', async () => {
const cacheValues = { const cacheValues = {
prerenderable: /(?<!non-)prerenderable: \d+/, prerenderable: /(?<!non-)prerenderable: \d+/,
...@@ -1341,7 +1338,6 @@ describe('use-cache', () => { ...@@ -1341,7 +1338,6 @@ describe('use-cache', () => {
}) })
if (withCacheComponents) { if (withCacheComponents) {
// @gate !partialPrefetchingGlobal || dev
it('can resume a cached generateMetadata function', async () => { it('can resume a cached generateMetadata function', async () => {
// In dev the initial request fills the caches while streaming the // In dev the initial request fills the caches while streaming the
// response. The second request will have filled caches and serves a // response. The second request will have filled caches and serves a
...@@ -1513,7 +1509,6 @@ describe('use-cache', () => { ...@@ -1513,7 +1509,6 @@ describe('use-cache', () => {
).toBe(description) ).toBe(description)
}) })
// @gate !partialPrefetchingGlobal || dev
it('can resume a cached generateViewport function', async () => { it('can resume a cached generateViewport function', async () => {
// First load the page with JavaScript disabled, to ensure that the // First load the page with JavaScript disabled, to ensure that the
// generateViewport result was included in the prerendered shell. // generateViewport result was included in the prerendered shell.
...@@ -1655,7 +1650,6 @@ describe('use-cache', () => { ...@@ -1655,7 +1650,6 @@ describe('use-cache', () => {
}) })
} }
// @gate !partialPrefetchingGlobal || dev
it('should allow nested short-lived caches after connection()', async () => { it('should allow nested short-lived caches after connection()', async () => {
const cacheValues = { const cacheValues = {
'revalidate-zero': /bare-revalidate-zero: \d+/, 'revalidate-zero': /bare-revalidate-zero: \d+/,
......
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