Unverified Commit 8f761662 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

[Cached Navs] Extract the shell from a fully cached response (#99619)

Fixes an oversight in the Cached Navigations implementation where a
fully cached navigation response was written into the cache without also
extracting and writing its shell.
parent 88f07ed3
......@@ -55,6 +55,21 @@ let initialServerDataWriter: ReadableStreamDefaultController | undefined =
let initialServerDataLoaded = false
let initialServerDataFlushed = false
// With Cached Navigations, we keep the initial Flight stream's bytes as we
// hand them to React, so hydration can cut a shell from them. We only do this
// when hydration decodes this stream, not a fetched payload. We record chunks
// until the stream is flushed, and hydration keeps its own reference. Each
// lets go of the chunks when it's done.
let initialServerDataChunks: Array<Uint8Array> | null =
process.env.__NEXT_CACHE_COMPONENTS &&
process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS &&
!instantTestStaticFetch &&
// @ts-expect-error
!window.__NEXT_CLIENT_RESUME
? []
: null
let initialServerDataChunksForHydration = initialServerDataChunks
let initialFormStateData: null | any = null
type FlightSegment =
......@@ -85,10 +100,14 @@ function nextServerDataCallback(seg: FlightSegment): void {
if (!initialServerDataBuffer)
throw new Error('Unexpected server data: missing bootstrap script.')
const chunk = encoder.encode(seg[1])
if (initialServerDataChunks !== null) {
initialServerDataChunks.push(chunk)
}
if (initialServerDataWriter) {
initialServerDataWriter.enqueue(encoder.encode(seg[1]))
initialServerDataWriter.enqueue(chunk)
} else {
initialServerDataBuffer.push(seg[1])
initialServerDataBuffer.push(chunk)
}
} else if (seg[0] === 2) {
initialFormStateData = seg[1]
......@@ -102,6 +121,9 @@ function nextServerDataCallback(seg: FlightSegment): void {
for (var i = 0; i < binaryString.length; i++) {
decodedChunk[i] = binaryString.charCodeAt(i)
}
if (initialServerDataChunks !== null) {
initialServerDataChunks.push(decodedChunk)
}
if (initialServerDataWriter) {
initialServerDataWriter.enqueue(decodedChunk)
......@@ -149,6 +171,7 @@ function nextServerDataRegisterWriter(ctr: ReadableStreamDefaultController) {
}
initialServerDataFlushed = true
initialServerDataBuffer = undefined
initialServerDataChunks = null
}
}
......@@ -161,6 +184,7 @@ const DOMContentLoaded = function () {
initialServerDataWriter.close()
initialServerDataFlushed = true
initialServerDataBuffer = undefined
initialServerDataChunks = null
}
initialServerDataLoaded = true
}
......@@ -361,10 +385,13 @@ export async function hydrate(
initializeRouterTransitionModules(instrumentationModules)
const initialTimestamp = Date.now()
const initialRSCPayloadChunks = initialServerDataChunksForHydration
initialServerDataChunksForHydration = null
const actionQueue: AppRouterActionQueue = createMutableActionQueue(
createInitialRouterState({
navigatedAt: initialTimestamp,
initialRSCPayload,
initialRSCPayloadChunks,
location: window.location,
})
)
......
......@@ -508,6 +508,7 @@ async function navigateToUnknownRoute(
dynamicStaleTime,
isResponsePartial,
flightResponse,
responseChunks,
debugInfo,
} = result
......@@ -557,6 +558,7 @@ async function navigateToUnknownRoute(
now,
flightResponse,
isResponsePartial,
responseChunks,
currentFlightRouterState,
renderedSearch,
map
......
......@@ -1787,6 +1787,7 @@ async function fetchMissingDynamicData(
now,
result.flightResponse,
result.isResponsePartial,
result.responseChunks,
dynamicRequestTree,
result.renderedSearch,
map
......
......@@ -19,12 +19,16 @@ import type { NormalizedSearch } from '../segment-cache/cache-key'
export interface InitialRouterStateParameters {
navigatedAt: number
initialRSCPayload: InitialRSCPayload
// The initial Flight stream's bytes, when they were kept, so a shell can be
// cut from them. Null otherwise.
initialRSCPayloadChunks: Array<Uint8Array> | null
location: Location | null
}
export function createInitialRouterState({
navigatedAt,
initialRSCPayload,
initialRSCPayloadChunks,
location,
}: InitialRouterStateParameters): AppRouterState {
const {
......@@ -36,6 +40,7 @@ export function createInitialRouterState({
s: initialStaleTime,
u: initialRuntimeDataAccessed,
r: initialRootVaryParams,
a: initialShellByteLength,
p: initialRuntimePrefetchStream,
d: initialDynamicStaleTimeSeconds,
} = initialRSCPayload
......@@ -119,10 +124,6 @@ export function createInitialRouterState({
false // hasDynamicRewrite
)
// TODO: Implement Shell extraction as part of Cached Navigations.
// Intentionally holding off on doing this until we decide how the Cached
// Navigations behavior should work in combination with App Shells.
// Write the initial page into the segment cache, so navigating back to it
// later doesn't need a request. We reuse the payload that hydration
// already decoded instead of decoding it again. Every Cache Components
......@@ -140,10 +141,12 @@ export function createInitialRouterState({
t: initialTransportData,
r: initialRootVaryParams,
s: initialStaleTime,
a: initialShellByteLength,
p: initialRuntimePrefetchStream,
},
initialStaleTime === undefined ||
initialRuntimeDataAccessed === undefined,
initialRSCPayloadChunks,
initialTree,
initialRenderedSearch,
segmentCacheMap // hydration writes are bound to the shared map
......
......@@ -76,6 +76,11 @@ type SpaFetchServerResponseResult = {
* segment cache by `bufferAndWriteNavigationResponse`.
*/
flightResponse: NavigationFlightResponse
/**
* The response's bytes, when they were kept, so a shell can be cut from
* them. Null otherwise.
*/
responseChunks: Array<Uint8Array> | null
debugInfo: Array<any> | null
/**
* Dev only: resolves once the server has flushed the shell-stage content to
......@@ -177,6 +182,13 @@ export async function fetchServerResponse(
}
const responsePromise = createFetch(url, headers, 'auto', options.signal)
// With Cached Navigations, the response's bytes are kept as they're
// decoded, so a shell can be cut from them.
const responseChunks: Array<Uint8Array> | null =
process.env.__NEXT_CACHE_COMPONENTS &&
process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS
? []
: null
// Start decoding before the response arrives, so React DevTools can show
// the latency from the client to the server. Navigations only ever receive
// live-render responses (per-segment prefetch responses, which omit some
......@@ -192,7 +204,8 @@ export async function fetchServerResponse(
process.env.__NEXT_DEV_SERVER &&
process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION
? options.signal
: undefined
: undefined,
responseChunks
)
const res = await responsePromise
......@@ -281,6 +294,7 @@ export async function fetchServerResponse(
dynamicStaleTime: flightResponse.d ?? UnknownDynamicStaleTime,
isResponsePartial: res.isPartial,
flightResponse,
responseChunks: res.isPartial ? null : responseChunks,
debugInfo: flightResponsePromise._debugInfo ?? null,
revealAfter: flightResponse._revealAfter ?? null,
}
......@@ -429,10 +443,15 @@ export function decodeBufferedResponse<T>(
function decodeNavigationResponse<T>(
responsePromise: Promise<RSCResponse>,
headers: RequestHeaders,
signal: AbortSignal | undefined
signal: AbortSignal | undefined,
// When not null, we also keep each chunk here as it's decoded, so we can
// cut a shell from them later. We skip this for partial responses, because
// only a complete prerender has a shell we can use.
responseChunks: Array<Uint8Array> | null
): Promise<T> & { _debugInfo?: Array<any> } {
let closed = false
let reader: ReadableStreamDefaultReader<Uint8Array> | null = null
let chunks: Array<Uint8Array> | null = null
const stream = new ReadableStream<Uint8Array>({
start(controller) {
if (signal === undefined) {
......@@ -489,6 +508,7 @@ function decodeNavigationResponse<T>(
return
}
reader = body.getReader()
chunks = response.isPartial ? null : responseChunks
}
try {
const { done, value } = await reader.read()
......@@ -498,6 +518,9 @@ function decodeNavigationResponse<T>(
if (done) {
controller.close()
} else {
if (chunks !== null) {
chunks.push(value)
}
controller.enqueue(value)
}
} catch (err) {
......
......@@ -3924,8 +3924,9 @@ export async function resolveStaleAt(
* cache, so later navigations can be served from the cache. A response
* carries at most one: an embedded runtime prefetch stream (`p`), from a live
* render, or the response itself, when it's a complete prerender. Either way,
* it's written like any other prefetch response. This flow owns no pending
* entries, so every write is a detached upsert.
* the full payload and its shell (when it has one) are written like any other
* prefetch response. This flow owns no pending entries, so every write is a
* detached upsert.
*/
export async function bufferAndWriteNavigationResponse(
now: number,
......@@ -3936,6 +3937,9 @@ export async function bufferAndWriteNavigationResponse(
// and the initial payload infers it from `u`. Once the response says
// directly whether it's a complete prerender, read that here instead.
isResponsePartial: boolean,
// The response's bytes, when they were kept, so a shell can be cut from
// them. Null otherwise.
responseChunks: Array<Uint8Array> | null,
baseTree: FlightRouterState,
renderedSearch: string,
// The map the work that spawned this response's request is bound to. See
......@@ -3983,9 +3987,10 @@ export async function bufferAndWriteNavigationResponse(
prefetchResponse = response
isPartial = false
staleAt = await resolveStaleAt(now, response.s)
// Only the full payload is written. Cutting a complete prerender's shell
// needs the response's bytes.
shellResponse = null
shellResponse =
responseChunks !== null
? await resolveShellStageResponse(responseChunks, response, undefined)
: null
} else {
return
}
......
......@@ -2389,6 +2389,8 @@ function App<T>({
// real timestamp.
navigatedAt: -1,
initialRSCPayload: response,
// The SSR render doesn't write into the segment cache.
initialRSCPayloadChunks: null,
// location is not initialized in the SSR render
// it's set to window.location during hydration
location: null,
......@@ -2450,6 +2452,8 @@ function ErrorApp<T>({
// real timestamp.
navigatedAt: -1,
initialRSCPayload: response,
// The SSR render doesn't write into the segment cache.
initialRSCPayloadChunks: null,
// location is not initialized in the SSR render
// it's set to window.location during hydration
location: null,
......
......@@ -1225,6 +1225,114 @@ describe('cached navigations', () => {
)
})
it('reuses the shell of a complete prerender after navigation', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
async beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
// Navigate to /complete-prerender-shell/foo, which is served as a complete
// prerender. The response is itself a prefetch response, so its shell is
// written into the cache, and the shell doesn't depend on the slug.
await act(
async () => {
await browser
.elementByCss('a[href="/complete-prerender-shell/foo"]')
.click()
},
{ includes: 'Param: foo' }
)
expect(await browser.elementById('params-boundary').text()).toContain(
'Param: foo'
)
// Click the bar link. The page segment's shell should be reused from
// cache, so the Suspense fallback for params should appear instantly.
await act(async () => {
await act(
async () => {
await browser
.elementByCss('a[href="/complete-prerender-shell/bar"]')
.click()
},
{
includes: 'Param: bar',
block: true,
}
)
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
expect(await browser.elementById('params-boundary').text()).toBe(
'Loading params...'
)
})
// After unblocking, the new param should be visible
expect(await browser.elementById('params-boundary').text()).toContain(
'Param: bar'
)
})
it('reuses the shell of a complete prerender after initial HTML load', async () => {
let page: Playwright.Page
// Start directly at /complete-prerender-shell/foo — full HTML load of a
// complete prerender. Its shell is cut from the initial Flight stream and
// written into the cache.
const browser = await next.browser('/complete-prerender-shell/foo', {
async beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
expect(await browser.elementById('params-boundary').text()).toContain(
'Param: foo'
)
// Wait for a real request first, so the hydration-time write has finished.
await act(
async () => {
await browser
.elementByCss('a[href="/complete-prerender-shell"]')
.click()
},
{ includes: 'Complete prerender shell hub' }
)
// Click the bar link. The page segment's shell should be reused from the
// cache seeded by the initial HTML load.
await act(async () => {
await act(
async () => {
await browser
.elementByCss('a[href="/complete-prerender-shell/bar"]')
.click()
},
{
includes: 'Param: bar',
block: true,
}
)
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
expect(await browser.elementById('params-boundary').text()).toBe(
'Loading params...'
)
})
// After unblocking, the new param should be visible
expect(await browser.elementById('params-boundary').text()).toContain(
'Param: bar'
)
})
it('does not reuse anything from a draft mode HTML load', async () => {
let page: Playwright.Page
const browser = await next.browser(
......
import { Suspense } from 'react'
// Both slugs are prerendered, so each is served as a complete prerender. The
// page segment reads the slug, so its full payload can't be reused for
// another slug; only its shell, which ends before the params, can.
export function generateStaticParams() {
return [{ slug: 'foo' }, { slug: 'bar' }]
}
export default function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
return (
<main>
<CachedContent />
<div id="params-boundary">
<Suspense fallback={<p>Loading params...</p>}>
<ParamsContent params={params} />
</Suspense>
</div>
</main>
)
}
async function CachedContent() {
'use cache'
// Default cache life, since shells leave out entries under 5 minutes stale.
return <p id="cached-content">Cached content</p>
}
async function ParamsContent({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
// One string, so the tests can match it in the response.
return <p>{`Param: ${slug}`}</p>
}
import Link from 'next/link'
import { ReactNode } from 'react'
export default function Layout({ children }: { children: ReactNode }) {
return (
<>
<Link href="/complete-prerender-shell" prefetch={false}>
Hub
</Link>
<Link href="/complete-prerender-shell/bar" prefetch={false}>
bar
</Link>
{children}
</>
)
}
export default function Page() {
return (
<main>
<h1>Complete prerender shell hub</h1>
</main>
)
}
......@@ -41,6 +41,11 @@ export default function Home() {
Go to Partial Prefetching page with fallback params
</Link>
</li>
<li>
<Link href="/complete-prerender-shell/foo" prefetch={false}>
Go to complete prerender with a shell
</Link>
</li>
<li>
<Link href="/runtime-prefetchable" prefetch={false}>
Go to runtime-prefetchable page
......
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