Unverified Commit 4b85c280 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

[Cached Navs] Don't extract static stage (#99617)

The original `cachedNavigations` experiment had a behavior where if the
feature was not enabled for a particular route, the client would cache
just the static part of the response, since it could be expressed as a
single byte offset without any additional overhead.

We've since decided Cached Navigations is too important of a feature to
be opt-in per route. So now it's always enabled (whenever Partial
Prefetching is enabled).

Therefore it no longer makes sense to extract the static part of the
response. Instead, we'll do the same thing prefetch responses do, and
extract out the shell, since the shell can be reused across different
params values for the same route.

This commit starts by removing the static stage extraction from the
client. Subsequent steps will unify Cache Navigations extraction with
the corresponding part of the prefetching implementation.

When Partial Prefetching is enabled, every navigation response can be
written into the cache: either the entire response is cachable, or it
contains an embedded inner response that is cacheable. Conceptually it's
as if each navigation is accompanied by a corresponding prefetch, and
both requests are returned in the same response.

This unifies the implementation used to write the response (whether it
comes from a navigation or a prefetch) into the client cache.
parent 27accf62
...@@ -183,7 +183,7 @@ nextServerDataLoadingGlobal.length = 0 ...@@ -183,7 +183,7 @@ nextServerDataLoadingGlobal.length = 0
// Patch its push method so subsequent chunks are handled (but not actually pushed to the array). // Patch its push method so subsequent chunks are handled (but not actually pushed to the array).
nextServerDataLoadingGlobal.push = nextServerDataCallback nextServerDataLoadingGlobal.push = nextServerDataCallback
let readable: ReadableStream<Uint8Array> = new ReadableStream({ const readable: ReadableStream<Uint8Array> = new ReadableStream({
start(controller) { start(controller) {
nextServerDataRegisterWriter(controller) nextServerDataRegisterWriter(controller)
}, },
...@@ -193,20 +193,6 @@ if (process.env.NODE_ENV !== 'production') { ...@@ -193,20 +193,6 @@ if (process.env.NODE_ENV !== 'production') {
readable.name = 'hydration' readable.name = 'hydration'
} }
// When Cache Components is enabled, tee the inlined Flight stream so we can
// truncate a clone at the static stage byte boundary and cache it. We don't
// know if `l` is present until React decodes the payload, so always tee and
// cancel the clone if not needed.
let initialFlightStreamForCache: ReadableStream<Uint8Array> | null = null
if (
process.env.__NEXT_CACHE_COMPONENTS &&
process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS
) {
const [forReact, forCache] = readable.tee()
readable = forReact
initialFlightStreamForCache = forCache
}
let debugChannel: let debugChannel:
| { readable?: ReadableStream; writable?: WritableStream } | { readable?: ReadableStream; writable?: WritableStream }
| undefined | undefined
...@@ -379,7 +365,6 @@ export async function hydrate( ...@@ -379,7 +365,6 @@ export async function hydrate(
createInitialRouterState({ createInitialRouterState({
navigatedAt: initialTimestamp, navigatedAt: initialTimestamp,
initialRSCPayload, initialRSCPayload,
initialFlightStreamForCache,
location: window.location, location: window.location,
}) })
) )
......
...@@ -22,8 +22,7 @@ import { ...@@ -22,8 +22,7 @@ import {
type SegmentCacheEntry, type SegmentCacheEntry,
readRouteCacheEntry, readRouteCacheEntry,
deprecated_requestOptimisticRouteCacheEntry, deprecated_requestOptimisticRouteCacheEntry,
spawnStaticStageCacheWrite, bufferAndWriteNavigationResponse,
writeRuntimePrefetchStreamIntoCache,
type FulfilledRouteCacheEntry, type FulfilledRouteCacheEntry,
createRootRouteTree, createRootRouteTree,
} from './segment-cache/cache' } from './segment-cache/cache'
...@@ -508,9 +507,7 @@ async function navigateToUnknownRoute( ...@@ -508,9 +507,7 @@ async function navigateToUnknownRoute(
supportsPerSegmentPrefetching, supportsPerSegmentPrefetching,
dynamicStaleTime, dynamicStaleTime,
isResponsePartial, isResponsePartial,
staticStageResponse, flightResponse,
runtimePrefetchStream,
responseHeaders,
debugInfo, debugInfo,
} = result } = result
...@@ -556,30 +553,17 @@ async function navigateToUnknownRoute( ...@@ -556,30 +553,17 @@ async function navigateToUnknownRoute(
false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal
) )
if (staticStageResponse !== null) { bufferAndWriteNavigationResponse(
spawnStaticStageCacheWrite( now,
now, flightResponse,
staticStageResponse, isResponsePartial,
isResponsePartial, currentFlightRouterState,
responseHeaders, renderedSearch,
currentFlightRouterState, map
renderedSearch, ).catch(() => {
map // The cache write failed. Not fatal — the navigation completed normally,
) // we just won't write into the cache.
} })
if (runtimePrefetchStream !== null) {
writeRuntimePrefetchStreamIntoCache(
now,
runtimePrefetchStream,
currentFlightRouterState,
renderedSearch,
map
).catch(() => {
// The runtime prefetch cache write failed. Not fatal — the
// navigation completed normally, we just won't cache runtime data.
})
}
// In the streaming dev render, this single response's seed content may still // In the streaming dev render, this single response's seed content may still
// be streaming when we build the tree below. An unknown-route navigation // be streaming when we build the tree below. An unknown-route navigation
......
...@@ -34,8 +34,7 @@ import { ...@@ -34,8 +34,7 @@ import {
readSegmentCacheEntryForNavigation, readSegmentCacheEntryForNavigation,
waitForSegmentCacheEntry, waitForSegmentCacheEntry,
invalidateRouteCacheEntries, invalidateRouteCacheEntries,
spawnStaticStageCacheWrite, bufferAndWriteNavigationResponse,
writeRuntimePrefetchStreamIntoCache,
EntryStatus, EntryStatus,
MetadataOnlyRequestTree, MetadataOnlyRequestTree,
} from './segment-cache/cache' } from './segment-cache/cache'
...@@ -1783,28 +1782,17 @@ async function fetchMissingDynamicData( ...@@ -1783,28 +1782,17 @@ async function fetchMissingDynamicData(
await navigationLock await navigationLock
} }
if (routeCacheEntry !== null && result.staticStageResponse !== null) { if (routeCacheEntry !== null) {
spawnStaticStageCacheWrite( bufferAndWriteNavigationResponse(
now, now,
result.staticStageResponse, result.flightResponse,
result.isResponsePartial, result.isResponsePartial,
result.responseHeaders,
dynamicRequestTree,
result.renderedSearch,
map
)
}
if (routeCacheEntry !== null && result.runtimePrefetchStream !== null) {
writeRuntimePrefetchStreamIntoCache(
now,
result.runtimePrefetchStream,
dynamicRequestTree, dynamicRequestTree,
result.renderedSearch, result.renderedSearch,
map map
).catch(() => { ).catch(() => {
// The runtime prefetch cache write failed. Not fatal — the // The cache write failed. Not fatal — the navigation completed
// navigation completed normally, we just won't cache runtime data. // normally, we just won't write into the cache.
}) })
} }
......
...@@ -7,28 +7,24 @@ import type { AppRouterState } from './router-reducer-types' ...@@ -7,28 +7,24 @@ import type { AppRouterState } from './router-reducer-types'
import { transportNodeToFlightRouterState } from '../../../shared/lib/rsc-transport' import { transportNodeToFlightRouterState } from '../../../shared/lib/rsc-transport'
import { createInitialRenderTreeForHydration } from '../render-tree' import { createInitialRenderTreeForHydration } from '../render-tree'
import { import {
writeRuntimePrefetchStreamIntoCache, bufferAndWriteNavigationResponse,
spawnStaticStageCacheWrite,
segmentCacheMap, segmentCacheMap,
createRootRouteTree, createRootRouteTree,
} from '../segment-cache/cache' } from '../segment-cache/cache'
import { createNavigationSeed } from '../segment-cache/decode-server-response' import { createNavigationSeed } from '../segment-cache/decode-server-response'
import { UnknownDynamicStaleTime } from '../segment-cache/bfcache' import { UnknownDynamicStaleTime } from '../segment-cache/bfcache'
import { decodeStageUntilBoundary } from './fetch-server-response'
import { discoverKnownRoute } from '../segment-cache/optimistic-routes' import { discoverKnownRoute } from '../segment-cache/optimistic-routes'
import type { NormalizedSearch } from '../segment-cache/cache-key' import type { NormalizedSearch } from '../segment-cache/cache-key'
export interface InitialRouterStateParameters { export interface InitialRouterStateParameters {
navigatedAt: number navigatedAt: number
initialRSCPayload: InitialRSCPayload initialRSCPayload: InitialRSCPayload
initialFlightStreamForCache?: ReadableStream<Uint8Array> | null
location: Location | null location: Location | null
} }
export function createInitialRouterState({ export function createInitialRouterState({
navigatedAt, navigatedAt,
initialRSCPayload, initialRSCPayload,
initialFlightStreamForCache,
location, location,
}: InitialRouterStateParameters): AppRouterState { }: InitialRouterStateParameters): AppRouterState {
const { const {
...@@ -38,7 +34,7 @@ export function createInitialRouterState({ ...@@ -38,7 +34,7 @@ export function createInitialRouterState({
i: initialCouldBeIntercepted, i: initialCouldBeIntercepted,
S: initialSupportsPerSegmentPrefetching, S: initialSupportsPerSegmentPrefetching,
s: initialStaleTime, s: initialStaleTime,
l: initialStaticStageByteLength, u: initialRuntimeDataAccessed,
r: initialRootVaryParams, r: initialRootVaryParams,
p: initialRuntimePrefetchStream, p: initialRuntimePrefetchStream,
d: initialDynamicStaleTimeSeconds, d: initialDynamicStaleTimeSeconds,
...@@ -127,97 +123,34 @@ export function createInitialRouterState({ ...@@ -127,97 +123,34 @@ export function createInitialRouterState({
// Intentionally holding off on doing this until we decide how the Cached // Intentionally holding off on doing this until we decide how the Cached
// Navigations behavior should work in combination with App Shells. // Navigations behavior should work in combination with App Shells.
// Write the initial payload's segment data into the segment cache so // Write the initial page into the segment cache, so navigating back to it
// subsequent navigations to the initial page can serve cached // later doesn't need a request. We reuse the payload that hydration
// segments instantly. // already decoded instead of decoding it again. Every Cache Components
if (initialStaleTime !== undefined) { // prerender includes `u`, but the initial Flight stream is the
if ( // prerender's own payload only when the prerender is complete. For a
initialStaticStageByteLength !== undefined && // partial prerender, the payload comes from the render that resumes it at
initialFlightStreamForCache != null // request time, and that render doesn't include `u`. So if `u` is
) { // missing, we treat the payload as partial. (See the TODO on
// Partially static page — truncate the cloned Flight stream at the // bufferAndWriteNavigationResponse.)
// static stage byte boundary, decode, and cache the static subset. bufferAndWriteNavigationResponse(
// Promise.resolve wraps the Flight-deserialized thenable into a Date.now(),
// native Promise so we can chain `.then` on it safely. // Only the fields the write reads. `u` is left out on purpose, so the
Promise.resolve(initialStaticStageByteLength) // write treats the payload like a live render's.
.then(async (byteLength) => { {
if (byteLength === 0) { t: initialTransportData,
initialFlightStreamForCache.cancel() r: initialRootVaryParams,
return s: initialStaleTime,
} p: initialRuntimePrefetchStream,
const staticStageResponse = },
await decodeStageUntilBoundary<InitialRSCPayload>( initialStaleTime === undefined ||
initialFlightStreamForCache, initialRuntimeDataAccessed === undefined,
byteLength, initialTree,
undefined initialRenderedSearch,
) segmentCacheMap // hydration writes are bound to the shared map
if (staticStageResponse === null) { ).catch(() => {
return // The cache write failed. Not fatal — the page rendered normally, we
} // just won't write into the cache.
spawnStaticStageCacheWrite( })
Date.now(),
staticStageResponse,
true, // isResponsePartial
null, // responseHeaders — no build-id check for initial HTML
initialTree,
initialRenderedSearch,
segmentCacheMap // hydration writes are bound to the shared map
)
})
.catch(() => {
// The static stage processing failed. Not fatal — the page
// rendered normally, we just won't write into the cache.
})
} else {
// Fully static page — cache the initial payload's segment data as-is.
// We're not using the initial response here (which would allow us to
// combine the two branches) to avoid unnecessary decoding of the
// Flight data, since we can just take the segment data that we
// already decoded during hydration and write it into the
// cache directly.
spawnStaticStageCacheWrite(
Date.now(),
// The transport subset of the initial payload, already decoded
// during hydration. `u` (the runtime-data verdict) is deliberately
// omitted from this synthesized subset — its writes record their
// strategy unrefined — while the truncated branch above forwards
// the decoded payload's own `u`.
{
t: initialTransportData,
r: initialRootVaryParams,
s: initialStaleTime,
},
false, // isResponsePartial
null, // responseHeaders — no build-id check for initial HTML
initialTree,
initialRenderedSearch,
segmentCacheMap // hydration writes are bound to the shared map
)
// Cancel the stream clone — fully static path doesn't need it.
initialFlightStreamForCache?.cancel()
}
} else {
// No caching — cancel the unused stream clone.
initialFlightStreamForCache?.cancel()
}
// If the initial RSC payload includes an embedded runtime prefetch stream,
// decode it and write the runtime data into the segment cache. This allows
// subsequent navigations to serve runtime-prefetchable content from cache
// without a separate prefetch request.
if (initialRuntimePrefetchStream != null) {
writeRuntimePrefetchStreamIntoCache(
Date.now(),
initialRuntimePrefetchStream,
initialTree,
initialRenderedSearch,
segmentCacheMap // hydration writes are bound to the shared map
).catch(() => {
// Runtime prefetch cache write failed. Not fatal — the page rendered
// normally, we just won't cache runtime data.
})
}
} }
// NOTE: We intentionally don't check if any data needs to be fetched from the // NOTE: We intentionally don't check if any data needs to be fetched from the
......
...@@ -78,14 +78,14 @@ type SpaFetchServerResponseResult = { ...@@ -78,14 +78,14 @@ type SpaFetchServerResponseResult = {
/** /**
* Whether the response body was marked partial (contains unresolved * Whether the response body was marked partial (contains unresolved
* dynamic holes), read from the leading isPartial byte. Always false when * dynamic holes), read from the leading isPartial byte. Always false when
* Cache Components is disabled. When `staticStageResponse` is non-null, * Cache Components is disabled.
* this is also its partiality: a complete response is cached whole, a
* partial response is cached as its truncated static-stage prefix.
*/ */
isResponsePartial: boolean isResponsePartial: boolean
staticStageResponse: NavigationFlightResponse | null /**
runtimePrefetchStream: ReadableStream<Uint8Array> | null * The decoded response. It can carry a prefetch response, written into the
responseHeaders: Headers * segment cache by `bufferAndWriteNavigationResponse`.
*/
flightResponse: NavigationFlightResponse
debugInfo: Array<any> | null debugInfo: Array<any> | null
/** /**
* Dev only: resolves once the server has flushed the shell-stage content to * Dev only: resolves once the server has flushed the shell-stage content to
...@@ -270,11 +270,6 @@ export async function fetchServerResponse( ...@@ -270,11 +270,6 @@ export async function fetchServerResponse(
return doMpaNavigation(flightResponse.n) return doMpaNavigation(flightResponse.n)
} }
const staticStageResponse =
cacheData !== null
? await resolveStaticStageResponse(cacheData, flightResponse, headers)
: null
return { return {
transportData: flightResponse.t ?? null, transportData: flightResponse.t ?? null,
canonicalUrl: canonicalUrl, canonicalUrl: canonicalUrl,
...@@ -296,9 +291,7 @@ export async function fetchServerResponse( ...@@ -296,9 +291,7 @@ export async function fetchServerResponse(
dynamicStaleTime: flightResponse.d ?? UnknownDynamicStaleTime, dynamicStaleTime: flightResponse.d ?? UnknownDynamicStaleTime,
isResponsePartial: isResponsePartial:
cacheData !== null ? cacheData.isResponsePartial : false, cacheData !== null ? cacheData.isResponsePartial : false,
staticStageResponse, flightResponse,
runtimePrefetchStream: flightResponse.p ?? null,
responseHeaders: res.headers,
debugInfo: flightResponsePromise._debugInfo ?? null, debugInfo: flightResponsePromise._debugInfo ?? null,
revealAfter: flightResponse._revealAfter ?? null, revealAfter: flightResponse._revealAfter ?? null,
} }
...@@ -364,11 +357,8 @@ export type RSCResponse<T> = { ...@@ -364,11 +357,8 @@ export type RSCResponse<T> = {
type FetchResponseCacheData = { type FetchResponseCacheData = {
isResponsePartial: boolean isResponsePartial: boolean
// Separate clones of the response body for stage extraction. The static // A clone of the response body for shell extraction, derived from a `tee()`
// stage and shell stage are extracted from independent reads, so each // in `processFetch`.
// needs its own ReadableStream. Both are derived from a chain of `tee()`
// calls in `processFetch`.
staticBodyClone?: ReadableStream<Uint8Array>
shellBodyClone?: ReadableStream<Uint8Array> shellBodyClone?: ReadableStream<Uint8Array>
} }
...@@ -401,14 +391,14 @@ export async function processFetch(response: Response): Promise<{ ...@@ -401,14 +391,14 @@ export async function processFetch(response: Response): Promise<{
let cacheData: FetchResponseCacheData let cacheData: FetchResponseCacheData
if (process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS) { if (process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS) {
// Three readers needed: the main Flight decoder, the static-stage // Two readers needed: the main Flight decoder and the shell-stage
// extractor, and the shell-stage extractor. Tee twice. // extractor.
const [stream1, rest] = stream.tee() // TODO: Tee only in the callers that read the clone. Navigations only
const [staticBodyClone, shellBodyClone] = rest.tee() // need it for a complete prerender.
const [stream1, shellBodyClone] = stream.tee()
responseStream = stream1 responseStream = stream1
cacheData = { cacheData = {
isResponsePartial: isPartial, isResponsePartial: isPartial,
staticBodyClone,
shellBodyClone, shellBodyClone,
} }
} else { } else {
...@@ -436,57 +426,6 @@ export async function processFetch(response: Response): Promise<{ ...@@ -436,57 +426,6 @@ export async function processFetch(response: Response): Promise<{
return { response, cacheData: null } return { response, cacheData: null }
} }
/**
* Resolves the static stage response from the raw `processFetch` outputs and
* the decoded flight response, for writing into the segment cache. The
* resolved response's partiality is the whole response's partiality
* (`cacheData.isResponsePartial`): a complete response is resolved whole, a
* partial one as its truncated static-stage prefix.
*
* - Fully static: use the decoded flight response as-is, no truncation needed.
* - Not fully static + `l` field: truncate the body clone at the static stage
* byte boundary and decode.
* - Otherwise: no cache-worthy data.
*/
async function resolveStaticStageResponse<
T extends NavigationFlightResponse | InitialRSCPayload,
>(
cacheData: FetchResponseCacheData,
flightResponse: T,
headers: RequestHeaders | undefined
): Promise<T | null> {
const { isResponsePartial, staticBodyClone } = cacheData
if (staticBodyClone) {
if (!isResponsePartial) {
// Fully static — cache the entire decoded response as-is.
staticBodyClone.cancel()
return flightResponse
}
if (flightResponse.l !== undefined) {
// Partially static — truncate the body clone at the byte boundary and
// decode it.
const staticStageByteLength = await flightResponse.l
if (staticStageByteLength === 0) {
staticBodyClone.cancel()
return null
}
return decodeStageUntilBoundary<T>(
staticBodyClone,
staticStageByteLength,
headers
)
}
// No caching — cancel the unused clone.
staticBodyClone.cancel()
}
return null
}
/** /**
* Resolves the shell stage of a prerender response: * Resolves the shell stage of a prerender response:
* *
...@@ -540,7 +479,7 @@ export async function resolveShellStageResponse< ...@@ -540,7 +479,7 @@ export async function resolveShellStageResponse<
* fails or the root does not resolve before the next task. The caller can still * fails or the root does not resolve before the next task. The caller can still
* use the full response. * use the full response.
*/ */
export async function decodeStageUntilBoundary<T>( async function decodeStageUntilBoundary<T>(
responseBodyClone: ReadableStream<Uint8Array>, responseBodyClone: ReadableStream<Uint8Array>,
byteLength: number, byteLength: number,
headers: RequestHeaders | undefined headers: RequestHeaders | undefined
......
...@@ -591,7 +591,6 @@ async function generateDynamicRSCPayload( ...@@ -591,7 +591,6 @@ async function generateDynamicRSCPayload(
actionResult?: ActionResult actionResult?: ActionResult
skipPageRendering?: boolean skipPageRendering?: boolean
staleTimeIterable?: AsyncIterable<number> staleTimeIterable?: AsyncIterable<number>
staticStageByteLengthPromise?: Promise<number>
shellByteLengthPromise?: Promise<number | null> shellByteLengthPromise?: Promise<number | null>
shellUsedSessionDataPromise?: Promise<boolean> shellUsedSessionDataPromise?: Promise<boolean>
runtimePrefetchStream?: ReadableStream<Uint8Array> runtimePrefetchStream?: ReadableStream<Uint8Array>
...@@ -746,9 +745,6 @@ async function generateDynamicRSCPayload( ...@@ -746,9 +745,6 @@ async function generateDynamicRSCPayload(
baseResponse.s = options.staleTimeIterable baseResponse.s = options.staleTimeIterable
} }
if (options?.staticStageByteLengthPromise !== undefined) {
baseResponse.l = options.staticStageByteLengthPromise
}
if (options?.shellByteLengthPromise !== undefined) { if (options?.shellByteLengthPromise !== undefined) {
baseResponse.a = options.shellByteLengthPromise baseResponse.a = options.shellByteLengthPromise
} }
...@@ -979,8 +975,8 @@ async function generateStagedDynamicFlightRenderResultNode( ...@@ -979,8 +975,8 @@ async function generateStagedDynamicFlightRenderResultNode(
const stageController = new StagedRenderingController({ const stageController = new StagedRenderingController({
abortSignal: null, abortSignal: null,
abandonController: null, abandonController: null,
// Synchronous request-time data ends the static stage before its result can // The prefetch mode controls which stages are allowed to read
// enter the Cached Navigation. // request-time data synchronously.
syncIO: getSyncIOMode(prefetchMode), syncIO: getSyncIOMode(prefetchMode),
finalStage: null, finalStage: null,
}) })
...@@ -1003,7 +999,6 @@ async function generateStagedDynamicFlightRenderResultNode( ...@@ -1003,7 +999,6 @@ async function generateStagedDynamicFlightRenderResultNode(
) )
const shellByteLengthDeferred = createPromiseWithResolvers<number | null>() const shellByteLengthDeferred = createPromiseWithResolvers<number | null>()
const staticStageByteLengthDeferred = createPromiseWithResolvers<number>()
let runtimePrefetchStream: ReadableStream<Uint8Array> | undefined let runtimePrefetchStream: ReadableStream<Uint8Array> | undefined
let startRuntimePrefetchRender: (() => Promise<void>) | undefined let startRuntimePrefetchRender: (() => Promise<void>) | undefined
...@@ -1064,7 +1059,6 @@ async function generateStagedDynamicFlightRenderResultNode( ...@@ -1064,7 +1059,6 @@ async function generateStagedDynamicFlightRenderResultNode(
ctx, ctx,
{ {
staleTimeIterable, staleTimeIterable,
staticStageByteLengthPromise: staticStageByteLengthDeferred.promise,
shellByteLengthPromise: shellByteLengthDeferred.promise, shellByteLengthPromise: shellByteLengthDeferred.promise,
runtimePrefetchStream, runtimePrefetchStream,
} }
...@@ -1095,13 +1089,10 @@ async function generateStagedDynamicFlightRenderResultNode( ...@@ -1095,13 +1089,10 @@ async function generateStagedDynamicFlightRenderResultNode(
const replayable = new ReplayableNodeStream(sourceStream) const replayable = new ReplayableNodeStream(sourceStream)
const dynamicStream = replayable.createReplayStream() const dynamicStream = replayable.createReplayStream()
const staticStream = replayable.createReplayStream() const shellStream = replayable.createReplayStream()
void countShellAndStaticStageBytes(staticStream, stageController).then( void countShellBytes(shellStream, stageController).then(
(byteLengths) => { shellByteLengthDeferred.resolve
staticStageByteLengthDeferred.resolve(byteLengths[RenderStage.Static])
shellByteLengthDeferred.resolve(byteLengths[RenderStage.ShellStatic])
}
) )
return dynamicStream return dynamicStream
...@@ -2071,7 +2062,6 @@ async function getRSCPayload( ...@@ -2071,7 +2062,6 @@ async function getRSCPayload(
is404: boolean is404: boolean
isPrerendering: boolean isPrerendering: boolean
staleTimeIterable?: AsyncIterable<number> staleTimeIterable?: AsyncIterable<number>
staticStageByteLengthPromise?: Promise<number>
shellByteLengthPromise?: Promise<number | null> shellByteLengthPromise?: Promise<number | null>
runtimePrefetchStream?: ReadableStream<Uint8Array> runtimePrefetchStream?: ReadableStream<Uint8Array>
} }
...@@ -2080,7 +2070,6 @@ async function getRSCPayload( ...@@ -2080,7 +2070,6 @@ async function getRSCPayload(
is404, is404,
isPrerendering, isPrerendering,
staleTimeIterable, staleTimeIterable,
staticStageByteLengthPromise,
shellByteLengthPromise, shellByteLengthPromise,
runtimePrefetchStream, runtimePrefetchStream,
} = options } = options
...@@ -2211,7 +2200,6 @@ async function getRSCPayload( ...@@ -2211,7 +2200,6 @@ async function getRSCPayload(
r: getRootParamsVaryParamsAccumulator() ?? undefined, r: getRootParamsVaryParamsAccumulator() ?? undefined,
s: staleTimeIterable, s: staleTimeIterable,
a: shellByteLengthPromise, a: shellByteLengthPromise,
l: staticStageByteLengthPromise,
p: runtimePrefetchStream, p: runtimePrefetchStream,
// Include the per-page dynamic stale time from unstable_dynamicStaleTime, but // Include the per-page dynamic stale time from unstable_dynamicStaleTime, but
// only for dynamic renders. The client treats its presence as // only for dynamic renders. The client treats its presence as
...@@ -3889,9 +3877,9 @@ async function renderToStream( ...@@ -3889,9 +3877,9 @@ async function renderToStream(
} }
} else if (cacheComponents && cachedNavigations) { } else if (cacheComponents && cachedNavigations) {
// Production Cache Components + Cached Navigations: use staged // Production Cache Components + Cached Navigations: use staged
// rendering so the RSC payload includes the static stage byte length // rendering so the RSC payload includes the shell byte length (`a`)
// (`l` field), enabling the client to cache the static subset during // and, with Partial Prefetching, an embedded runtime prefetch that the
// hydration. // client caches during hydration.
const selectStaleTime = createSelectStaleTime(experimental) const selectStaleTime = createSelectStaleTime(experimental)
const staleTimeIterable = new StaleTimeIterable() const staleTimeIterable = new StaleTimeIterable()
...@@ -3900,8 +3888,8 @@ async function renderToStream( ...@@ -3900,8 +3888,8 @@ async function renderToStream(
const stageController = new StagedRenderingController({ const stageController = new StagedRenderingController({
abortSignal: null, abortSignal: null,
abandonController: null, abandonController: null,
// Synchronous request-time data ends the static stage before its // The prefetch mode controls which stages are allowed to read
// result can enter the Cached Navigation. // request-time data synchronously.
syncIO: getSyncIOMode(prefetchMode), syncIO: getSyncIOMode(prefetchMode),
finalStage: null, finalStage: null,
}) })
...@@ -3926,8 +3914,6 @@ async function renderToStream( ...@@ -3926,8 +3914,6 @@ async function renderToStream(
const shellByteLengthDeferred = createPromiseWithResolvers< const shellByteLengthDeferred = createPromiseWithResolvers<
number | null number | null
>() >()
const staticStageByteLengthDeferred =
createPromiseWithResolvers<number>()
let runtimePrefetchStream: ReadableStream<Uint8Array> | undefined let runtimePrefetchStream: ReadableStream<Uint8Array> | undefined
let startRuntimePrefetchRender: (() => Promise<void>) | undefined let startRuntimePrefetchRender: (() => Promise<void>) | undefined
...@@ -3988,7 +3974,6 @@ async function renderToStream( ...@@ -3988,7 +3974,6 @@ async function renderToStream(
isPrerendering: false, isPrerendering: false,
staleTimeIterable, staleTimeIterable,
shellByteLengthPromise: shellByteLengthDeferred.promise, shellByteLengthPromise: shellByteLengthDeferred.promise,
staticStageByteLengthPromise: staticStageByteLengthDeferred.promise,
runtimePrefetchStream, runtimePrefetchStream,
} }
) )
...@@ -4019,19 +4004,11 @@ async function renderToStream( ...@@ -4019,19 +4004,11 @@ async function renderToStream(
const replayable = new ReplayableNodeStream(stream) const replayable = new ReplayableNodeStream(stream)
const dynamicStream = replayable.createReplayStream() const dynamicStream = replayable.createReplayStream()
const staticStream = replayable.createReplayStream() const shellStream = replayable.createReplayStream()
void countShellAndStaticStageBytes( void countShellBytes(shellStream, stageController).then(
staticStream, shellByteLengthDeferred.resolve
stageController )
).then((byteLengths) => {
staticStageByteLengthDeferred.resolve(
byteLengths[RenderStage.Static]
)
shellByteLengthDeferred.resolve(
byteLengths[RenderStage.ShellStatic]
)
})
return dynamicStream return dynamicStream
}, },
...@@ -6404,17 +6381,15 @@ function collectStageChunk( ...@@ -6404,17 +6381,15 @@ function collectStageChunk(
} }
} }
async function countShellAndStaticStageBytes( async function countShellBytes(
stream: Readable, stream: Readable,
stageController: StagedRenderingController stageController: StagedRenderingController
): Promise< ): Promise<number> {
Pick<StageByteLengths, RenderStage.ShellStatic | RenderStage.Static>
> {
const byteLengths = createStageByteLengths() const byteLengths = createStageByteLengths()
// Abort the signal whenever we advance to the stage after static. // Abort the signal whenever we advance to the stage after the shell.
const abortController = new AbortController() const abortController = new AbortController()
const endStage = getNextStage(RenderStage.Static) const endStage = getNextStage(RenderStage.ShellStatic)
stageController.onStage(endStage, abortController.abort.bind(abortController)) stageController.onStage(endStage, abortController.abort.bind(abortController))
await countStageBytesUntilAbortNode( await countStageBytesUntilAbortNode(
...@@ -6423,7 +6398,7 @@ async function countShellAndStaticStageBytes( ...@@ -6423,7 +6398,7 @@ async function countShellAndStaticStageBytes(
stageController, stageController,
abortController.signal abortController.signal
) )
return byteLengths return byteLengths[RenderStage.ShellStatic]
} }
type StageByteLengths = Record<AdvanceableRenderStage, number> type StageByteLengths = Record<AdvanceableRenderStage, number>
......
...@@ -462,8 +462,6 @@ export type InitialRSCPayload = { ...@@ -462,8 +462,6 @@ export type InitialRSCPayload = {
* Only present for static prerenders when Cache Components is enabled. * Only present for static prerenders when Cache Components is enabled.
*/ */
u?: Promise<boolean> u?: Promise<boolean>
/** staticStageByteLength - Resolves when the static stage ends. */
l?: Promise<number>
/** /**
* shellByteLength - Resolves when the shell stage ends. * shellByteLength - Resolves when the shell stage ends.
* If it resolves to null, then the shell is the same as the main response. * If it resolves to null, then the shell is the same as the main response.
...@@ -532,8 +530,6 @@ type NavigationFlightResponseBase = { ...@@ -532,8 +530,6 @@ type NavigationFlightResponseBase = {
* Per-segment prefetch responses carry staleTime per node instead (see * Per-segment prefetch responses carry staleTime per node instead (see
* TransportSegmentData). */ * TransportSegmentData). */
s?: AsyncIterable<number> s?: AsyncIterable<number>
/** staticStageByteLength - Resolves when the static stage ends. */
l?: Promise<number>
/** /**
* shellByteLength - Resolves when the shell stage ends. * shellByteLength - Resolves when the shell stage ends.
* If it resolves to null, then the shell is the same as the main response. * If it resolves to null, then the shell is the same as the main response.
......
...@@ -2,6 +2,9 @@ import { navigation } from 'next/cache' ...@@ -2,6 +2,9 @@ import { navigation } from 'next/cache'
import { Suspense } from 'react' import { Suspense } from 'react'
import UncachedTimePage from '../uncached-time/page' import UncachedTimePage from '../uncached-time/page'
// Partial Prefetching embeds a runtime prefetch in navigations to this route.
export const prefetch = 'partial'
async function Content() { async function Content() {
// The navigation stage defers this subtree past the initial Flight rows. The // The navigation stage defers this subtree past the initial Flight rows. The
// private cache in UncachedTimePage still resolves before the dynamic stage. // private cache in UncachedTimePage still resolves before the dynamic stage.
......
...@@ -19,6 +19,9 @@ export default function Page() { ...@@ -19,6 +19,9 @@ export default function Page() {
<LinkAccordion href="/uncached-time#prefetch-true" prefetch={true}> <LinkAccordion href="/uncached-time#prefetch-true" prefetch={true}>
Full prefetch Full prefetch
</LinkAccordion> </LinkAccordion>
<LinkAccordion href="/partial-uncached-time" prefetch={false}>
Target with Partial Prefetching
</LinkAccordion>
<LinkAccordion href="/delayed-sync-io" prefetch={false}> <LinkAccordion href="/delayed-sync-io" prefetch={false}>
Delayed sync IO Delayed sync IO
</LinkAccordion> </LinkAccordion>
......
...@@ -31,6 +31,9 @@ export default function Page() { ...@@ -31,6 +31,9 @@ export default function Page() {
<LinkAccordion href="/uncached-time" prefetch={false}> <LinkAccordion href="/uncached-time" prefetch={false}>
Target Target
</LinkAccordion> </LinkAccordion>
<LinkAccordion href="/partial-uncached-time" prefetch={false}>
Target with Partial Prefetching
</LinkAccordion>
<LinkAccordion href="/delayed-sync-io" prefetch={false}> <LinkAccordion href="/delayed-sync-io" prefetch={false}>
Delayed sync IO Delayed sync IO
</LinkAccordion> </LinkAccordion>
......
// Partial Prefetching embeds a runtime prefetch in navigations to this route.
export const prefetch = 'partial'
export { default } from '../uncached-time/page'
...@@ -42,8 +42,13 @@ describe('cached-navigations-sync-io', () => { ...@@ -42,8 +42,13 @@ describe('cached-navigations-sync-io', () => {
return { browser, page, act, startDate, navigate } return { browser, page, act, startDate, navigate }
} }
// These routes use Partial Prefetching, so their navigations embed a runtime
// prefetch.
for (const { pathname, description } of [ for (const { pathname, description } of [
{ pathname: '/uncached-time', description: 'does not reuse uncached time' }, {
pathname: '/partial-uncached-time',
description: 'does not reuse uncached time',
},
{ {
pathname: '/delayed-sync-io', pathname: '/delayed-sync-io',
description: 'reuses content before synchronous IO', description: 'reuses content before synchronous IO',
...@@ -64,17 +69,12 @@ describe('cached-navigations-sync-io', () => { ...@@ -64,17 +69,12 @@ describe('cached-navigations-sync-io', () => {
expect(await response?.text()).toContain('Uncached time:') expect(await response?.text()).toContain('Uncached time:')
} }
// - In PPF, we should log a sync IO error. // These routes opt into Partial Prefetching, even without the global
// - Before PPF, we should not log anything, because Cached Navigations // config, so the sync IO in their embedded runtime prefetch is logged.
// are an extra thing that the user did not opt into
const syncIOErrorText = `Route "${pathname}": Next.js encountered the unstable value \`Date.now()\` while prerendering` const syncIOErrorText = `Route "${pathname}": Next.js encountered the unstable value \`Date.now()\` while prerendering`
// No CLI logs in deploy // No CLI logs in deploy
if (!(await gate('deploy'))) { if (!(await gate('deploy'))) {
if (await gate('partialPrefetchingGlobal')) { expect(getCliOutput()).toInclude(syncIOErrorText)
expect(getCliOutput()).toInclude(syncIOErrorText)
} else {
expect(getCliOutput()).not.toInclude(syncIOErrorText)
}
} }
const timestamp = await browser.elementById('timestamp').text() const timestamp = await browser.elementById('timestamp').text()
...@@ -118,8 +118,18 @@ describe('cached-navigations-sync-io', () => { ...@@ -118,8 +118,18 @@ describe('cached-navigations-sync-io', () => {
// In Partial Prefetching, `prefetch={true}` is no longer a full prefetch that includes uncached data. // In Partial Prefetching, `prefetch={true}` is no longer a full prefetch that includes uncached data.
// @gate !partialPrefetchingGlobal // @gate !partialPrefetchingGlobal
it('finishes a full prefetch after synchronous IO interrupts its static stage', async () => { it('finishes a full prefetch after synchronous IO interrupts its static stage', async () => {
const getCliOutput = next.getCliOutputFromHere()
const { browser, act, navigate } = await startBrowser() const { browser, act, navigate } = await startBrowser()
await act(() => navigate('/uncached-time'), { includes: 'Dynamic content' }) await act(() => navigate('/uncached-time'), { includes: 'Dynamic content' })
// This route doesn't opt into Partial Prefetching, so its navigation has no
// embedded runtime prefetch and nothing is logged: Cached Navigations are
// something the user didn't opt into.
// No CLI logs in deploy
if (!(await gate('deploy'))) {
expect(getCliOutput()).not.toInclude(
'Route "/uncached-time": Next.js encountered the unstable value `Date.now()` while prerendering'
)
}
const timestamp = await browser.elementById('timestamp').text() const timestamp = await browser.elementById('timestamp').text()
expect(timestamp).toMatch(/^Uncached time: \d+$/) expect(timestamp).toMatch(/^Uncached time: \d+$/)
await browser.eval('window.navigationMarker = "same document"') await browser.eval('window.navigationMarker = "same document"')
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { getTitle, retry, waitFor } from 'next-test-utils' import { gate, getTitle, retry, waitFor } from 'next-test-utils'
// bump this every time you want to validate flakiness: 1 // bump this every time you want to validate flakiness: 1
...@@ -208,11 +208,17 @@ describe('app dir - navigation', () => { ...@@ -208,11 +208,17 @@ describe('app dir - navigation', () => {
await checkLink('query-param', 2284) await checkLink('query-param', 2284)
await browser.waitForIdleNetwork() await browser.waitForIdleNetwork()
// There should be an RSC request if the query param is changed
const hasQueryParamRscRequest = Array.from(navigationRscRequestUrls).some( const hasQueryParamRscRequest = Array.from(navigationRscRequestUrls).some(
(url) => url.includes('with-query-param') (url) => url.includes('with-query-param')
) )
expect(hasQueryParamRscRequest).toBe(true) if (await gate('cachedNavigations && prefetching')) {
// The page doesn't read search params, and the layout's params didn't
// change, so the navigation is served from the client cache.
expect(hasQueryParamRscRequest).toBe(false)
} else {
// There should be an RSC request if the query param is changed
expect(hasQueryParamRscRequest).toBe(true)
}
}) })
it('should not scroll to hash when scroll={false} is set', async () => { it('should not scroll to hash when scroll={false} is set', async () => {
......
...@@ -26,12 +26,16 @@ describe('segment cache (basic tests)', () => { ...@@ -26,12 +26,16 @@ describe('segment cache (basic tests)', () => {
includes: 'Dynamic page', includes: 'Dynamic page',
}) })
// The target does not read search params, so this should reuse the cached // The route still supports per-segment prefetching after a dynamic
// segments instead of issuing a loading-boundary prefetch. // navigation, so this issues a per-segment prefetch instead of a
// loading-boundary prefetch.
const prefetchButton = await browser.elementByCss( const prefetchButton = await browser.elementByCss(
'button[data-router-prefetch="/partially-static/target-page?query=1"]' 'button[data-router-prefetch="/partially-static/target-page?query=1"]'
) )
await act(async () => prefetchButton.click(), 'no-requests') await act(async () => prefetchButton.click(), {
includes: 'Static layout',
kind: 'static',
})
}) })
it('navigate before any data has loaded into the prefetch cache', async () => { it('navigate before any data has loaded into the prefetch cache', async () => {
......
...@@ -8,7 +8,7 @@ describe('cached navigations - root params', () => { ...@@ -8,7 +8,7 @@ describe('cached navigations - root params', () => {
files: join(__dirname, 'root-params'), files: join(__dirname, 'root-params'),
}) })
it('does not reuse the initial static stage across root param values', async () => { it("does not reuse the initial page's embedded prefetch across root param values", async () => {
let act: ReturnType<typeof createRouterAct> let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/en/foo', { const browser = await next.browser('/en/foo', {
beforePageLoad(page) { beforePageLoad(page) {
...@@ -44,7 +44,7 @@ describe('cached navigations - root params', () => { ...@@ -44,7 +44,7 @@ describe('cached navigations - root params', () => {
) )
}) })
it('reuses the initial static stage when only a fallback param changes', async () => { it("reuses the initial page's embedded prefetch when only a fallback param changes", async () => {
let act: ReturnType<typeof createRouterAct> let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/en/foo', { const browser = await next.browser('/en/foo', {
beforePageLoad(page) { beforePageLoad(page) {
...@@ -59,11 +59,19 @@ describe('cached navigations - root params', () => { ...@@ -59,11 +59,19 @@ describe('cached navigations - root params', () => {
'Cached locale: en' 'Cached locale: en'
) )
// Wait for a real request first, so the hydration-time write has finished.
await act(
async () => {
await browser.elementByCss('a[href="/en/hub"]').click()
},
{ includes: 'Hub page' }
)
await act(async () => { await act(async () => {
await browser.elementByCss('a[href="/en/bar"]').click() await browser.elementByCss('a[href="/en/bar"]').click()
// The router reuses the English static stage and shows a fallback until // The router reuses the English page and shows a fallback until the new
// the new slug's dynamic content arrives. // slug's dynamic content arrives.
expect(await browser.elementById('cached-locale').text()).toBe( expect(await browser.elementById('cached-locale').text()).toBe(
'Cached locale: en' 'Cached locale: en'
) )
......
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()}`
}
...@@ -35,11 +35,27 @@ async function Hub({ ...@@ -35,11 +35,27 @@ async function Hub({
Required fallback shell Required fallback shell
</LinkAccordion> </LinkAccordion>
</div> </div>
<div>
<LinkAccordion
href={`/required-fallback-params/${top}/b2`}
prefetch={false}
>
Required fallback shell, other bottom
</LinkAccordion>
</div>
<div> <div>
<LinkAccordion href={`/fully-static-params/${top}`} prefetch={false}> <LinkAccordion href={`/fully-static-params/${top}`} prefetch={false}>
Fully static page Fully static page
</LinkAccordion> </LinkAccordion>
</div> </div>
<div>
<LinkAccordion
href={`/partial-fully-static-params/${top}`}
prefetch={false}
>
Fully static page with Partial Prefetching
</LinkAccordion>
</div>
{top === 'time' ? ( {top === 'time' ? (
<LinkAccordion <LinkAccordion
href="/fully-static-params/time#full-prefetch" href="/fully-static-params/time#full-prefetch"
......
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 (
...@@ -14,6 +13,14 @@ export default function Home() { ...@@ -14,6 +13,14 @@ export default function Home() {
Go to partially static page Go to partially static page
</Link> </Link>
</li> </li>
<li>
<Link
href="/partially-static-without-runtime-prefetch"
prefetch={false}
>
Go to partially static page without a runtime prefetch
</Link>
</li>
<li> <li>
<Link href="/fully-static" prefetch={false}> <Link href="/fully-static" prefetch={false}>
Go to fully static page Go to fully static page
...@@ -29,6 +36,11 @@ export default function Home() { ...@@ -29,6 +36,11 @@ export default function Home() {
Go to page with fallback params Go to page with fallback params
</Link> </Link>
</li> </li>
<li>
<Link href="/partial-fallback-params/foo" prefetch={false}>
Go to Partial Prefetching page with fallback params
</Link>
</li>
<li> <li>
<Link href="/runtime-prefetchable" prefetch={false}> <Link href="/runtime-prefetchable" prefetch={false}>
Go to runtime-prefetchable page Go to runtime-prefetchable page
...@@ -40,20 +52,6 @@ export default function Home() { ...@@ -40,20 +52,6 @@ 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>
) )
} }
import { connection } from 'next/server'
import { Suspense } from 'react'
// Partial Prefetching embeds a runtime prefetch in navigations to this route.
export const prefetch = 'partial'
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>
<div id="connection-boundary">
<Suspense fallback={<p>Loading connection...</p>}>
<ConnectionContent />
</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
return <p>Param: {slug}</p>
}
async function ConnectionContent() {
await connection()
return <p>Dynamic content</p>
}
import Link from 'next/link'
import { ReactNode } from 'react'
export default function Layout({ children }: { children: ReactNode }) {
return (
<>
<Link href="/partial-fallback-params" prefetch={false}>
Hub
</Link>
<Link href="/partial-fallback-params/bar" prefetch={false}>
bar
</Link>
{children}
</>
)
}
export default function Page() {
return (
<main>
<h1>Partial fallback params hub</h1>
</main>
)
}
// Partial Prefetching embeds a runtime prefetch in navigations to this route.
export const prefetch = 'partial'
export {
default,
generateStaticParams,
} from '../../fully-static-params/[top]/page'
import { connection } from 'next/server'
import { Suspense } from 'react'
// A partial prerender that doesn't opt into Partial Prefetching, so its
// responses don't embed a runtime prefetch.
export default function Page() {
return (
<main>
<CachedContent />
<div id="connection-boundary">
<Suspense fallback={<p>Loading connection...</p>}>
<ConnectionContent />
</Suspense>
</div>
</main>
)
}
async function CachedContent() {
'use cache'
return <p id="cached-content">Cached content</p>
}
async function ConnectionContent() {
await connection()
return <p>Dynamic content ({new Date().toISOString()})</p>
}
...@@ -3,6 +3,9 @@ import { cookies, headers } from 'next/headers' ...@@ -3,6 +3,9 @@ import { cookies, headers } from 'next/headers'
import { connection } from 'next/server' import { connection } from 'next/server'
import { Suspense } from 'react' import { Suspense } from 'react'
// Partial Prefetching embeds a runtime prefetch in navigations to this route.
export const prefetch = 'partial'
export default async function Page({ export default async function Page({
searchParams, searchParams,
}: { }: {
...@@ -47,11 +50,7 @@ async function SearchParamsContent({ ...@@ -47,11 +50,7 @@ async function SearchParamsContent({
searchParams: Promise<{ q?: string }> searchParams: Promise<{ q?: string }>
}) { }) {
const { q } = await searchParams const { q } = await searchParams
return ( return <p>Search params: {q ?? 'none'}</p>
<p>
Search params: {q ?? 'none'} ({new Date().toISOString()})
</p>
)
} }
async function CookiesContent() { async function CookiesContent() {
...@@ -74,11 +73,7 @@ async function getShortLivedCachedDate() { ...@@ -74,11 +73,7 @@ async function getShortLivedCachedDate() {
async function HeadersContent() { async function HeadersContent() {
const headerStore = await headers() const headerStore = await headers()
const value = headerStore.get('x-test-header') ?? 'none' const value = headerStore.get('x-test-header') ?? 'none'
return ( return <p>Header: {value}</p>
<p>
Header: {value} ({new Date().toISOString()})
</p>
)
} }
async function ConnectionContent() { async function ConnectionContent() {
......
import { connection } from 'next/server' import { connection } from 'next/server'
import { Suspense } from 'react' import { Suspense } from 'react'
// Partial Prefetching embeds a runtime prefetch in navigations to this route.
export const prefetch = 'partial'
export default function Page({ export default function Page({
params, params,
}: { }: {
......
...@@ -35,9 +35,6 @@ async function ParamsContent({ ...@@ -35,9 +35,6 @@ async function ParamsContent({
}: { }: {
params: Promise<{ slug: string }> params: Promise<{ slug: string }>
}) { }) {
// When the param is a fallback param (not in generateStaticParams), the
// await is deferred to the PrefetchRuntime stage, so this content won't appear
// in the static stage.
const { slug } = await params const { slug } = await params
return <p>Param: {slug}</p> return <p>Param: {slug}</p>
} }
......
import { connection } from 'next/server' import { connection } from 'next/server'
import { Suspense } from 'react' import { Suspense } from 'react'
// Partial Prefetching embeds a runtime prefetch in navigations to this route.
export const prefetch = 'partial'
export async function generateStaticParams() { export async function generateStaticParams() {
return [{ slug: 'foo' }] return [{ slug: 'foo' }]
} }
......
...@@ -5,8 +5,7 @@ const nextConfig: NextConfig = { ...@@ -5,8 +5,7 @@ const nextConfig: NextConfig = {
productionBrowserSourceMaps: true, productionBrowserSourceMaps: true,
// Enabling Partial Prefetching globally opts every route into runtime Cached // Enabling Partial Prefetching globally opts every route into runtime Cached
// Navigations, even without a per-segment `prefetch` config. // Navigations, even without a per-segment `prefetch` config.
// `cachedNavigations` is left at its default (`true`, the static stage), so // `cachedNavigations` is left at its default (`true`).
// the runtime stage here comes solely from `partialPrefetching`.
partialPrefetching: true, partialPrefetching: true,
experimental: { experimental: {
prefetchInlining: false, prefetchInlining: false,
......
...@@ -2,6 +2,9 @@ import { locale } from 'next/root-params' ...@@ -2,6 +2,9 @@ import { locale } from 'next/root-params'
import { connection } from 'next/server' import { connection } from 'next/server'
import { Suspense } from 'react' import { Suspense } from 'react'
// Partial Prefetching embeds a runtime prefetch in navigations to this route.
export const prefetch = 'partial'
async function getLocale() { async function getLocale() {
'use cache' 'use cache'
return locale() return locale()
......
...@@ -15,6 +15,9 @@ export default function Root({ children }: { children: ReactNode }) { ...@@ -15,6 +15,9 @@ export default function Root({ children }: { children: ReactNode }) {
<Link href="/en/bar" prefetch={false}> <Link href="/en/bar" prefetch={false}>
English bar English bar
</Link> </Link>
<Link href="/en/hub" prefetch={false}>
English hub
</Link>
{children} {children}
</body> </body>
</html> </html>
......
...@@ -2,6 +2,12 @@ ...@@ -2,6 +2,12 @@
* @type {import('next').NextConfig} * @type {import('next').NextConfig}
*/ */
const nextConfig = { const nextConfig = {
// With Cache Components, a navigation writes segment data into the cache
// through its embedded runtime prefetch, which needs Partial Prefetching.
// That's what lets the prefetch in this test find the photo page's
// segments. Partial Prefetching requires Cache Components, so it's only
// enabled in that run.
partialPrefetching: process.env.__NEXT_CACHE_COMPONENTS === 'true',
experimental: { experimental: {
// The client segment cache currently only writes segment data during // The client segment cache currently only writes segment data during
// prefetches, not during navigations. The staleTimes feature is an // prefetches, not during navigations. The staleTimes feature is an
......
...@@ -899,13 +899,19 @@ describe('segment cache - vary params', () => { ...@@ -899,13 +899,19 @@ describe('segment cache - vary params', () => {
expect(await browser.eval('document.title')).toBe('Query title: 1') expect(await browser.eval('document.title')).toBe('Query title: 1')
const initialToken = await browser.elementById('server-token').text() const initialToken = await browser.elementById('server-token').text()
// This page is a live render, so nothing from its initial RSC payload was
// cached, and revealing the link prefetches the route. The prefetch
// doesn't include the head, because the head reads the query.
await act(async () => { await act(async () => {
await browser await browser
.elementByCss( .elementByCss(
'input[data-link-accordion="/navigation-reuse/metadata-query?x=2"]' 'input[data-link-accordion="/navigation-reuse/metadata-query?x=2"]'
) )
.click() .click()
}, 'no-requests') }, [
{ includes: 'Loading metadata-query page...' },
{ includes: 'Query title: 2', block: 'reject' },
])
// The head read the query, so it's fetched again. // The head read the query, so it's fetched again.
await act( await act(
......
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