Unverified Commit 1d14e93c authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Cached Navigations: Cache visited fully static pages in the segment cache (#90306)

When a fully static page is loaded (via initial HTML or client-side
navigation), the segments are now written into the segment cache so
subsequent navigations can be served entirely from cache without server
requests.

Initial HTML: The RSC payload inlined in the HTML is written during
hydration via `getStaleAt` + `writeStaticStageResponseIntoCache` with
`isResponsePartial: false`, using `FetchStrategy.Full` since all
segments are present. A `StaleTimeIterable` (`s` field) is included in
the `InitialRSCPayload` during the Cache Components prerender path to
provide the stale time.

Navigation: The `isResponsePartial` flag from the prepended byte
(stripped by `processFetch`) is now also used to determine how segments
from `writeStaticStageResponseIntoCache` are cached. For fully static
routes (`isResponsePartial: false`), segments are written as non-partial
so no dynamic follow-up is needed.

The route tree used for cache writes is now always derived from the
Flight data itself (via `convertServerPatchToFullTree`), rather than
from a pre-existing route cache entry. This guarantees the tree stays in
sync with the response and avoids key mismatches between the static
stage tree and the per-segment prefetch tree for parallel route slots.

When writing the head into the cache, `isHeadPartial` from the server is
overridden to `false` for non-partial responses, but only when Cache
Components is enabled. This corrects the server's conservative
`isPossiblyPartialHead` marking during static generation. Without Cache
Components, the server already sends the correct value. Responses
without a recognized marker byte (e.g. regular navigations that don't go
through the prerender path) are conservatively treated as partial.

Partially static pages (where the static stage needs to be extracted via
byte-level truncation of the initial HTML Flight stream) will be handled
in a follow-up.

---------
Co-authored-by: 's avatarAndrew Clark <git@andrewclark.io>
parent e4cae370
...@@ -1085,5 +1085,6 @@ ...@@ -1085,5 +1085,6 @@
"1084": "Route \"%s\": Uncached data or \\`connection()\\` was accessed outside of \\`<Suspense>\\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route", "1084": "Route \"%s\": Uncached data or \\`connection()\\` was accessed outside of \\`<Suspense>\\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route",
"1085": "Route \"%s\": Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateMetadata\\` or you have file-based metadata such as icons that depend on dynamic params segments. Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata", "1085": "Route \"%s\": Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateMetadata\\` or you have file-based metadata such as icons that depend on dynamic params segments. Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata",
"1086": "Route \"%s\": %s This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport", "1086": "Route \"%s\": %s This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport",
"1087": "Failed to parse \"%s\":\\n%s%s" "1087": "Failed to parse \"%s\":\\n%s%s",
"1088": "Expected RSC navigation response to have a body"
} }
...@@ -326,6 +326,8 @@ export async function hydrate( ...@@ -326,6 +326,8 @@ export async function hydrate(
initialRenderedSearch: initialRSCPayload.q, initialRenderedSearch: initialRSCPayload.q,
initialCouldBeIntercepted: initialRSCPayload.i, initialCouldBeIntercepted: initialRSCPayload.i,
initialSupportsPerSegmentPrefetching: initialRSCPayload.S, initialSupportsPerSegmentPrefetching: initialRSCPayload.S,
initialStaleTime: initialRSCPayload.s,
initialHeadVaryParams: initialRSCPayload.h,
location: window.location, location: window.location,
}), }),
instrumentationHooks instrumentationHooks
......
import type { FlightDataPath } from '../../../shared/lib/app-router-types' import type { FlightDataPath } from '../../../shared/lib/app-router-types'
import type { VaryParamsThenable } from '../../../shared/lib/segment-cache/vary-params-decoding'
import { createHrefFromUrl } from './create-href-from-url' import { createHrefFromUrl } from './create-href-from-url'
import { extractPathFromFlightRouterState } from './compute-changed-path' import { extractPathFromFlightRouterState } from './compute-changed-path'
...@@ -6,7 +7,11 @@ import { extractPathFromFlightRouterState } from './compute-changed-path' ...@@ -6,7 +7,11 @@ import { extractPathFromFlightRouterState } from './compute-changed-path'
import type { AppRouterState } from './router-reducer-types' import type { AppRouterState } from './router-reducer-types'
import { getFlightDataPartsFromPath } from '../../flight-data-helpers' import { getFlightDataPartsFromPath } from '../../flight-data-helpers'
import { createInitialCacheNodeForHydration } from './ppr-navigations' import { createInitialCacheNodeForHydration } from './ppr-navigations'
import { convertRootFlightRouterStateToRouteTree } from '../segment-cache/cache' import {
convertRootFlightRouterStateToRouteTree,
getStaleAt,
writeStaticStageResponseIntoCache,
} from '../segment-cache/cache'
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'
...@@ -17,6 +22,8 @@ export interface InitialRouterStateParameters { ...@@ -17,6 +22,8 @@ export interface InitialRouterStateParameters {
initialFlightData: FlightDataPath[] initialFlightData: FlightDataPath[]
initialCouldBeIntercepted: boolean initialCouldBeIntercepted: boolean
initialSupportsPerSegmentPrefetching: boolean initialSupportsPerSegmentPrefetching: boolean
initialStaleTime: AsyncIterable<number> | undefined
initialHeadVaryParams: VaryParamsThenable | null
location: Location | null location: Location | null
} }
...@@ -27,6 +34,8 @@ export function createInitialRouterState({ ...@@ -27,6 +34,8 @@ export function createInitialRouterState({
initialRenderedSearch, initialRenderedSearch,
initialCouldBeIntercepted, initialCouldBeIntercepted,
initialSupportsPerSegmentPrefetching, initialSupportsPerSegmentPrefetching,
initialStaleTime,
initialHeadVaryParams,
location, location,
}: InitialRouterStateParameters): AppRouterState { }: InitialRouterStateParameters): AppRouterState {
// When initialized on the server, the canonical URL is provided as an array of parts. // When initialized on the server, the canonical URL is provided as an array of parts.
...@@ -51,7 +60,7 @@ export function createInitialRouterState({ ...@@ -51,7 +60,7 @@ export function createInitialRouterState({
createHrefFromUrl(location) createHrefFromUrl(location)
: initialCanonicalUrl : initialCanonicalUrl
// Conver the initial FlightRouterState into the RouteTree type. // Convert the initial FlightRouterState into the RouteTree type.
// NOTE: The metadataVaryPath isn't used for anything currently because the // NOTE: The metadataVaryPath isn't used for anything currently because the
// head is embedded into the CacheNode tree, but eventually we'll lift it out // head is embedded into the CacheNode tree, but eventually we'll lift it out
// and store it on the top-level state object. // and store it on the top-level state object.
...@@ -69,10 +78,10 @@ export function createInitialRouterState({ ...@@ -69,10 +78,10 @@ export function createInitialRouterState({
initialHead initialHead
) )
// Learn the route pattern so we can predict it for future navigations. // The following only applies in the browser (location !== null) since neither
// Only do this in the browser (location !== null) since route learning // route learning nor segment cache state persists from SSR to client.
// state doesn't persist from SSR to client.
if (location !== null && metadataVaryPath !== null) { if (location !== null && metadataVaryPath !== null) {
// Learn the route pattern so we can predict it for future navigations.
discoverKnownRoute( discoverKnownRoute(
Date.now(), Date.now(),
location.pathname, location.pathname,
...@@ -85,6 +94,31 @@ export function createInitialRouterState({ ...@@ -85,6 +94,31 @@ export function createInitialRouterState({
initialSupportsPerSegmentPrefetching, initialSupportsPerSegmentPrefetching,
false // hasDynamicRewrite false // hasDynamicRewrite
) )
// Write the initial seed data into the segment cache so subsequent
// navigations to the initial page can serve cached segments instantly.
if (initialSeedData !== null && initialStaleTime !== undefined) {
// Currently only fully static pages include initialStaleTime.
const now = Date.now()
getStaleAt(now, initialStaleTime)
.then((staleAt) => {
writeStaticStageResponseIntoCache(
now,
initialFlightData,
undefined, // buildId — not applicable for initial HTML
initialHeadVaryParams,
staleAt,
initialTree,
initialRenderedSearch,
false // isResponsePartial
)
})
.catch(() => {
// The static stage processing failed. Not fatal — the page
// rendered normally, we just won't write into the cache.
})
}
} }
// 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
......
...@@ -41,6 +41,7 @@ import type { NormalizedSearch } from '../segment-cache/cache-key' ...@@ -41,6 +41,7 @@ import type { NormalizedSearch } from '../segment-cache/cache-key'
import { getDeploymentId } from '../../../shared/lib/deployment-id' import { getDeploymentId } from '../../../shared/lib/deployment-id'
import { getNavigationBuildId } from '../../navigation-build-id' import { getNavigationBuildId } from '../../navigation-build-id'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants' import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
import { stripIsPartialByte } from '../segment-cache/cache'
const createFromReadableStream = const createFromReadableStream =
createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream'] createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream']
...@@ -63,6 +64,11 @@ export interface FetchServerResponseOptions { ...@@ -63,6 +64,11 @@ export interface FetchServerResponseOptions {
readonly isHmrRefresh?: boolean readonly isHmrRefresh?: boolean
} }
export type StaticStageData = {
readonly response: NavigationFlightResponse
readonly isResponsePartial: boolean
}
type SpaFetchServerResponseResult = { type SpaFetchServerResponseResult = {
flightData: NormalizedFlightData[] flightData: NormalizedFlightData[]
canonicalUrl: URL canonicalUrl: URL
...@@ -71,7 +77,7 @@ type SpaFetchServerResponseResult = { ...@@ -71,7 +77,7 @@ type SpaFetchServerResponseResult = {
supportsPerSegmentPrefetching: boolean supportsPerSegmentPrefetching: boolean
postponed: boolean postponed: boolean
staleTime: number staleTime: number
staticStageResponse: Promise<NavigationFlightResponse> | null staticStageData: StaticStageData | null
responseHeaders: Headers responseHeaders: Headers
debugInfo: Array<any> | null debugInfo: Array<any> | null
} }
...@@ -236,7 +242,10 @@ export async function fetchServerResponse( ...@@ -236,7 +242,10 @@ export async function fetchServerResponse(
) )
} }
const flightResponse = await flightResponsePromise const [flightResponse, cacheData] = await Promise.all([
flightResponsePromise,
res.cacheData,
])
if ( if (
(res.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? flightResponse.b) !== (res.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? flightResponse.b) !==
...@@ -251,19 +260,10 @@ export async function fetchServerResponse( ...@@ -251,19 +260,10 @@ export async function fetchServerResponse(
return doMpaNavigation(normalizedFlightData) return doMpaNavigation(normalizedFlightData)
} }
// If the server included a static stage byte count, decode the static const staticStageData =
// stage from the cloned response body to seed the segment cache. cacheData !== null
let staticStageResponse: Promise<NavigationFlightResponse> | null = null ? await resolveStaticStageData(cacheData, flightResponse, headers)
if (flightResponse.l !== undefined && res.staticStageBodyPromise !== null) { : null
staticStageResponse = decodeStaticStageResponse(
flightResponse.l,
res.staticStageBodyPromise,
headers
)
} else if (res.staticStageBodyPromise !== null) {
// No static stage byte count — cancel the unused clone.
res.staticStageBodyPromise.then((body) => body?.cancel())
}
return { return {
flightData: normalizedFlightData, flightData: normalizedFlightData,
...@@ -280,7 +280,7 @@ export async function fetchServerResponse( ...@@ -280,7 +280,7 @@ export async function fetchServerResponse(
supportsPerSegmentPrefetching: flightResponse.S, supportsPerSegmentPrefetching: flightResponse.S,
postponed, postponed,
staleTime, staleTime,
staticStageResponse, staticStageData,
responseHeaders: res.headers, responseHeaders: res.headers,
debugInfo: flightResponsePromise._debugInfo ?? null, debugInfo: flightResponsePromise._debugInfo ?? null,
} }
...@@ -312,7 +312,109 @@ export type RSCResponse<T> = { ...@@ -312,7 +312,109 @@ export type RSCResponse<T> = {
status: number status: number
url: string url: string
flightResponsePromise: (Promise<T> & { _debugInfo?: Array<any> }) | null flightResponsePromise: (Promise<T> & { _debugInfo?: Array<any> }) | null
staticStageBodyPromise: Promise<ReadableStream<Uint8Array> | null> | null cacheData: Promise<FetchResponseCacheData | null>
}
type FetchResponseCacheData = {
isResponsePartial: boolean
responseBodyClone: ReadableStream<Uint8Array>
}
/**
* Strips the leading isPartial byte from an RSC navigation response and
* clones the body for segment cache extraction.
*
* When cache components is enabled, the server prepends a single byte:
* '~' (0x7e) for partial, '#' (0x23) for complete. This must be stripped
* before Flight decoding because it's not valid RSC data. The body is
* cloned before Flight can consume it so the clone is available for later use.
*
* When cache components is disabled, returns the original response with
* cacheData: null.
*/
export async function processFetch(response: Response): Promise<{
response: Response
cacheData: FetchResponseCacheData | null
}> {
if (process.env.__NEXT_CACHE_COMPONENTS) {
if (!response.body) {
throw new InvariantError(
'Expected RSC navigation response to have a body'
)
}
const { stream, isPartial } = await stripIsPartialByte(response.body)
const [stream1, stream2] = stream.tee()
const strippedResponse = new Response(stream1, {
headers: response.headers,
status: response.status,
statusText: response.statusText,
})
// The Response constructor doesn't preserve `url` or `redirected` from
// the original. We need both: `url` for React DevTools and `redirected`
// for the redirect replay logic below.
Object.defineProperty(strippedResponse, 'url', { value: response.url })
Object.defineProperty(strippedResponse, 'redirected', {
value: response.redirected,
})
return {
response: strippedResponse,
cacheData: { isResponsePartial: isPartial, responseBodyClone: stream2 },
}
}
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.
*
* - 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 resolveStaticStageData(
cacheData: FetchResponseCacheData,
flightResponse: NavigationFlightResponse,
headers: RequestHeaders
): Promise<StaticStageData | null> {
const { isResponsePartial, responseBodyClone } = cacheData
if (!isResponsePartial) {
// Fully static — cache the entire decoded response as-is.
responseBodyClone.cancel()
return { response: flightResponse, isResponsePartial: false }
}
if (flightResponse.l !== undefined) {
// Partially static — truncate the body clone at the byte boundary.
const staticStageByteLength = await flightResponse.l
const truncatedStream = truncateStream(
responseBodyClone,
staticStageByteLength
)
const response =
await createFromNextReadableStream<NavigationFlightResponse>(
truncatedStream,
headers,
{ allowPartialStream: true }
)
return { response, isResponsePartial: true }
}
// No caching — cancel the unused clone.
responseBodyClone.cancel()
return null
} }
export async function createFetch<T>( export async function createFetch<T>(
...@@ -360,15 +462,8 @@ export async function createFetch<T>( ...@@ -360,15 +462,8 @@ export async function createFetch<T>(
// track them separately. // track them separately.
let fetchUrl = new URL(url) let fetchUrl = new URL(url)
setCacheBustingSearchParam(fetchUrl, headers) setCacheBustingSearchParam(fetchUrl, headers)
let fetchPromise = fetch(fetchUrl, fetchOptions) let processed = fetch(fetchUrl, fetchOptions).then(processFetch)
let fetchPromise = processed.then(({ response }) => response)
// When cache components is enabled, clone the response before Flight
// consumes the body, so we can later truncate the clone to extract the
// static stage for caching.
let staticStageBodyPromise: Promise<ReadableStream<Uint8Array> | null> | null =
process.env.__NEXT_CACHE_COMPONENTS
? fetchPromise.then((response) => response.clone().body)
: null
// Immediately pass the fetch promise to the Flight client so that the debug // Immediately pass the fetch promise to the Flight client so that the debug
// info includes the latency from the client to the server. The internal timer // info includes the latency from the client to the server. The internal timer
...@@ -437,10 +532,8 @@ export async function createFetch<T>( ...@@ -437,10 +532,8 @@ export async function createFetch<T>(
// TODO: We should abort the previous request. // TODO: We should abort the previous request.
fetchUrl = new URL(responseUrl) fetchUrl = new URL(responseUrl)
setCacheBustingSearchParam(fetchUrl, headers) setCacheBustingSearchParam(fetchUrl, headers)
fetchPromise = fetch(fetchUrl, fetchOptions) processed = fetch(fetchUrl, fetchOptions).then(processFetch)
if (process.env.__NEXT_CACHE_COMPONENTS) { fetchPromise = processed.then(({ response }) => response)
staticStageBodyPromise = fetchPromise.then((r) => r.clone().body)
}
flightResponsePromise = shouldImmediatelyDecode flightResponsePromise = shouldImmediatelyDecode
? createFromNextFetch<T>(fetchPromise, headers) ? createFromNextFetch<T>(fetchPromise, headers)
: null : null
...@@ -477,7 +570,7 @@ export async function createFetch<T>( ...@@ -477,7 +570,7 @@ export async function createFetch<T>(
// are later rendered by React. // are later rendered by React.
flightResponsePromise: flightResponsePromise, flightResponsePromise: flightResponsePromise,
staticStageBodyPromise: staticStageBodyPromise, cacheData: processed.then(({ cacheData }) => cacheData),
} }
return rscResponse return rscResponse
...@@ -507,26 +600,6 @@ function createFromNextFetch<T>( ...@@ -507,26 +600,6 @@ function createFromNextFetch<T>(
}) })
} }
async function decodeStaticStageResponse(
staticStageByteLengthPromise: Promise<number>,
staticStageBodyPromise: Promise<ReadableStream<Uint8Array> | null>,
requestHeaders: RequestHeaders
): Promise<NavigationFlightResponse> {
const [byteLength, staticBody] = await Promise.all([
staticStageByteLengthPromise,
staticStageBodyPromise,
])
if (staticBody === null) {
throw new InvariantError('Expected static stage body to be available')
}
const truncatedStream = truncateStream(staticBody, byteLength)
return createFromNextReadableStream<NavigationFlightResponse>(
truncatedStream,
requestHeaders,
{ allowPartialStream: true }
)
}
function truncateStream( function truncateStream(
stream: ReadableStream<Uint8Array>, stream: ReadableStream<Uint8Array>,
byteLength: number byteLength: number
......
...@@ -35,11 +35,12 @@ import { ...@@ -35,11 +35,12 @@ import {
waitForSegmentCacheEntry, waitForSegmentCacheEntry,
markRouteEntryAsDynamicRewrite, markRouteEntryAsDynamicRewrite,
invalidateRouteCacheEntries, invalidateRouteCacheEntries,
processStaticStageResponse, getStaleAt,
writeStaticStageResponseIntoCache, writeStaticStageResponseIntoCache,
EntryStatus, EntryStatus,
} from '../segment-cache/cache' } from '../segment-cache/cache'
import { discoverKnownRoute } from '../segment-cache/optimistic-routes' import { discoverKnownRoute } from '../segment-cache/optimistic-routes'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
import type { NormalizedSearch } from '../segment-cache/cache-key' import type { NormalizedSearch } from '../segment-cache/cache-key'
import { import {
getRenderedSearchFromVaryPath, getRenderedSearchFromVaryPath,
...@@ -1581,23 +1582,33 @@ async function fetchMissingDynamicData( ...@@ -1581,23 +1582,33 @@ async function fetchMissingDynamicData(
await waitForNavigationLock() await waitForNavigationLock()
} }
if (routeCacheEntry !== null && result.staticStageResponse !== null) { if (routeCacheEntry !== null && result.staticStageData !== null) {
const { response: staticStageResponse, isResponsePartial } =
result.staticStageData
const now = Date.now() const now = Date.now()
processStaticStageResponse(now, result.staticStageResponse).then(
({ serverData, headVaryParams, staleAt }) => getStaleAt(now, staticStageResponse.s)
.then((staleAt) => {
const buildId =
result.responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??
staticStageResponse.b
writeStaticStageResponseIntoCache( writeStaticStageResponseIntoCache(
now, now,
serverData, staticStageResponse.f,
result.responseHeaders, buildId,
headVaryParams, staticStageResponse.h,
staleAt, staleAt,
routeCacheEntry dynamicRequestTree,
), result.renderedSearch,
() => { isResponsePartial
)
})
.catch(() => {
// The static stage processing failed. Not fatal — the navigation // The static stage processing failed. Not fatal — the navigation
// completed normally, we just won't write into the cache. // completed normally, we just won't write into the cache.
} })
)
} }
const didReceiveUnknownParallelRoute = writeDynamicDataIntoNavigationTask( const didReceiveUnknownParallelRoute = writeDynamicDataIntoNavigationTask(
......
...@@ -64,6 +64,7 @@ import { ...@@ -64,6 +64,7 @@ import {
} from '../../../../shared/lib/action-revalidation-kind' } from '../../../../shared/lib/action-revalidation-kind'
import { isExternalURL } from '../../app-router-utils' import { isExternalURL } from '../../app-router-utils'
import { FreshnessPolicy } from '../ppr-navigations' import { FreshnessPolicy } from '../ppr-navigations'
import { processFetch } from '../fetch-server-response'
import { invalidateBfCache } from '../../segment-cache/bfcache' import { invalidateBfCache } from '../../segment-cache/bfcache'
const createFromFetch = const createFromFetch =
...@@ -205,8 +206,15 @@ async function fetchServerAction( ...@@ -205,8 +206,15 @@ async function fetchServerAction(
let couldBeIntercepted: boolean = false let couldBeIntercepted: boolean = false
if (isRscResponse) { if (isRscResponse) {
// Server action redirect responses carry the Flight data of the redirect
// target, which may be prerendered with a completeness marker byte
// prepended. Strip it before passing to Flight.
const responsePromise = redirectLocation
? processFetch(res).then(({ response: r }) => r)
: Promise.resolve(res)
const response: ActionFlightResponse = await createFromFetch( const response: ActionFlightResponse = await createFromFetch(
Promise.resolve(res), responsePromise,
{ {
callServer, callServer,
findSourceMapURL, findSourceMapURL,
......
...@@ -7,11 +7,13 @@ import type { ...@@ -7,11 +7,13 @@ import type {
} from '../../../server/app-render/collect-segment-data' } from '../../../server/app-render/collect-segment-data'
import type { import type {
CacheNodeSeedData, CacheNodeSeedData,
FlightData,
Segment as FlightRouterStateSegment, Segment as FlightRouterStateSegment,
} from '../../../shared/lib/app-router-types' } from '../../../shared/lib/app-router-types'
import { import {
readVaryParams, readVaryParams,
type VaryParams, type VaryParams,
type VaryParamsThenable,
} from '../../../shared/lib/segment-cache/vary-params-decoding' } from '../../../shared/lib/segment-cache/vary-params-decoding'
import { import {
NEXT_DID_POSTPONE_HEADER, NEXT_DID_POSTPONE_HEADER,
...@@ -93,6 +95,7 @@ import type { ...@@ -93,6 +95,7 @@ import type {
NavigationFlightResponse, NavigationFlightResponse,
} from '../../../shared/lib/app-router-types' } from '../../../shared/lib/app-router-types'
import { import {
type NormalizedFlightData,
normalizeFlightData, normalizeFlightData,
prepareFlightRouterStateForRequest, prepareFlightRouterStateForRequest,
} from '../../flight-data-helpers' } from '../../flight-data-helpers'
...@@ -106,6 +109,7 @@ import { FetchStrategy } from './types' ...@@ -106,6 +109,7 @@ import { FetchStrategy } from './types'
import { createPromiseWithResolvers } from '../../../shared/lib/promise-with-resolvers' import { createPromiseWithResolvers } from '../../../shared/lib/promise-with-resolvers'
import { readFromBFCacheDuringRegularNavigation } from './bfcache' import { readFromBFCacheDuringRegularNavigation } from './bfcache'
import { discoverKnownRoute, matchKnownRoute } from './optimistic-routes' import { discoverKnownRoute, matchKnownRoute } from './optimistic-routes'
import { convertServerPatchToFullTree, type NavigationSeed } from './navigation'
import { getNavigationBuildId } from '../../navigation-build-id' import { getNavigationBuildId } from '../../navigation-build-id'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants' import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
...@@ -2232,19 +2236,9 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest( ...@@ -2232,19 +2236,9 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
// Track when the network connection closes. // Track when the network connection closes.
const closed = createPromiseWithResolvers<void>() const closed = createPromiseWithResolvers<void>()
let isResponsePartial = false
let responseBody = response.body
// For runtime prefetches, strip the leading isPartial byte before passing
// the stream to Flight.
if (fetchStrategy === FetchStrategy.PPRRuntime) {
const stripped = await stripIsPartialByte(responseBody)
isResponsePartial = stripped.isPartial
responseBody = stripped.stream
}
let fulfilledEntries: Array<FulfilledSegmentCacheEntry> | null = null let fulfilledEntries: Array<FulfilledSegmentCacheEntry> | null = null
const prefetchStream = createPrefetchResponseStream( const prefetchStream = createPrefetchResponseStream(
responseBody, response.body,
closed.resolve, closed.resolve,
function onResponseSizeUpdate(totalBytesReceivedSoFar) { function onResponseSizeUpdate(totalBytesReceivedSoFar) {
// When processing a dynamic response, we don't know how large each // When processing a dynamic response, we don't know how large each
...@@ -2261,12 +2255,15 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest( ...@@ -2261,12 +2255,15 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
} }
} }
) )
const serverData =
await createFromNextReadableStream<NavigationFlightResponse>( const [serverData, cacheData] = await Promise.all([
createFromNextReadableStream<NavigationFlightResponse>(
prefetchStream, prefetchStream,
headers, headers,
{ allowPartialStream: true } { allowPartialStream: true }
) ),
response.cacheData,
])
// Read head vary params synchronously. Individual segments carry their // Read head vary params synchronously. Individual segments carry their
// own thenables in CacheNodeSeedData. // own thenables in CacheNodeSeedData.
...@@ -2277,20 +2274,37 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest( ...@@ -2277,20 +2274,37 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
: null : null
const now = Date.now() const now = Date.now()
const staleAt = await getStaleAt(now, serverData, response) const staleAt = await getStaleAt(now, serverData.s, response)
// PPRRuntime prefetches are partial when the server marks the response
// as '~' (Partial). Full/LoadingBoundary prefetches are always complete.
const isResponsePartial =
fetchStrategy === FetchStrategy.PPRRuntime &&
(cacheData?.isResponsePartial ?? false)
// Aside from writing the data into the cache, this function also returns // Aside from writing the data into the cache, this function also returns
// the entries that were fulfilled, so we can streamingly update their sizes // the entries that were fulfilled, so we can streamingly update their sizes
// in the LRU as more data comes in. // in the LRU as more data comes in.
const buildId =
response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b
const flightDatas = normalizeFlightData(serverData.f)
if (typeof flightDatas === 'string') {
rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)
return null
}
const navigationSeed = convertServerPatchToFullTree(
dynamicRequestTree,
flightDatas,
renderedSearch
)
fulfilledEntries = writeDynamicRenderResponseIntoCache( fulfilledEntries = writeDynamicRenderResponseIntoCache(
now, now,
fetchStrategy, fetchStrategy,
response.headers, flightDatas,
serverData, buildId,
isResponsePartial, isResponsePartial,
headVaryParams, headVaryParams,
staleAt, staleAt,
route, navigationSeed,
spawnedEntries spawnedEntries
) )
...@@ -2339,10 +2353,9 @@ function writeDynamicTreeResponseIntoCache( ...@@ -2339,10 +2353,9 @@ function writeDynamicTreeResponseIntoCache(
} }
const flightRouterState = flightData.tree const flightRouterState = flightData.tree
// If the response contains dynamic holes, then we must conservatively assume // If the response was postponed, segments may contain dynamic holes.
// that any individual segment might contain dynamic holes, and also the // The head has its own partiality flag (flightDataEntry.isHeadPartial)
// head. If it did not contain dynamic holes, then we can assume every segment // which is handled separately in writeDynamicRenderResponseIntoCache.
// and the head is completely static.
const isResponsePartial = const isResponsePartial =
response.headers.get(NEXT_DID_POSTPONE_HEADER) === '1' response.headers.get(NEXT_DID_POSTPONE_HEADER) === '1'
...@@ -2363,7 +2376,7 @@ function writeDynamicTreeResponseIntoCache( ...@@ -2363,7 +2376,7 @@ function writeDynamicTreeResponseIntoCache(
return return
} }
const fulfilledEntry = discoverKnownRoute( discoverKnownRoute(
now, now,
originalPathname, originalPathname,
nextUrl, nextUrl,
...@@ -2378,22 +2391,25 @@ function writeDynamicTreeResponseIntoCache( ...@@ -2378,22 +2391,25 @@ function writeDynamicTreeResponseIntoCache(
// If the server sent segment data as part of the response, we should write // If the server sent segment data as part of the response, we should write
// it into the cache to prevent a second, redundant prefetch request. // it into the cache to prevent a second, redundant prefetch request.
// // TODO: This is a leftover branch from before Client Segment Cache was
// TODO: When `clientSegmentCache` is enabled, the server does not include // enabled everywhere. Tree prefetches should never include segment data. We
// segment data when responding to a route tree prefetch request. However, // can delete it. Leaving for a subsequent PR.
// when `clientSegmentCache` is set to "client-only", and PPR is enabled (or const navigationSeed = convertServerPatchToFullTree(
// the page is fully static), the normal check is bypassed and the server flightRouterState,
// responds with the full page. This is a temporary situation until we can normalizedFlightDataResult,
// remove the "client-only" option. Then, we can delete this function call. renderedSearch
)
const buildId =
response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b
writeDynamicRenderResponseIntoCache( writeDynamicRenderResponseIntoCache(
now, now,
fetchStrategy, fetchStrategy,
response.headers, normalizedFlightDataResult,
serverData, buildId,
isResponsePartial, isResponsePartial,
headVaryParams, headVaryParams,
getStaleAtFromHeader(now, response), getStaleAtFromHeader(now, response),
fulfilledEntry, navigationSeed,
null null
) )
} }
...@@ -2420,18 +2436,15 @@ export function writeDynamicRenderResponseIntoCache( ...@@ -2420,18 +2436,15 @@ export function writeDynamicRenderResponseIntoCache(
| FetchStrategy.PPR | FetchStrategy.PPR
| FetchStrategy.PPRRuntime | FetchStrategy.PPRRuntime
| FetchStrategy.Full, | FetchStrategy.Full,
responseHeaders: Headers, flightDatas: NormalizedFlightData[],
serverData: NavigationFlightResponse, buildId: string | undefined,
isResponsePartial: boolean, isResponsePartial: boolean,
headVaryParams: VaryParams | null, headVaryParams: VaryParams | null,
staleAt: number, staleAt: number,
route: FulfilledRouteCacheEntry, navigationSeed: NavigationSeed,
spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null
): Array<FulfilledSegmentCacheEntry> | null { ): Array<FulfilledSegmentCacheEntry> | null {
const buildId = if (buildId && buildId !== getNavigationBuildId()) {
responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b
if (buildId !== getNavigationBuildId()) {
// The server build does not match the client. Treat as a 404. During // The server build does not match the client. Treat as a 404. During
// an actual navigation, the router will trigger an MPA navigation. // an actual navigation, the router will trigger an MPA navigation.
if (spawnedEntries !== null) { if (spawnedEntries !== null) {
...@@ -2440,15 +2453,14 @@ export function writeDynamicRenderResponseIntoCache( ...@@ -2440,15 +2453,14 @@ export function writeDynamicRenderResponseIntoCache(
return null return null
} }
const flightDatas = normalizeFlightData(serverData.f) const routeTree = navigationSeed.routeTree
if (typeof flightDatas === 'string') { const metadataTree =
// This means navigating to this route will result in an MPA navigation. navigationSeed.metadataVaryPath !== null
// TODO: We should cache this, too, so that the MPA navigation is immediate. ? createMetadataRouteTree(navigationSeed.metadataVaryPath)
return null : null
}
for (const flightData of flightDatas) { for (const flightDataEntry of flightDatas) {
const seedData = flightData.seedData const seedData = flightDataEntry.seedData
if (seedData !== null) { if (seedData !== null) {
// The data sent by the server represents only a subtree of the app. We // The data sent by the server represents only a subtree of the app. We
// need to find the part of the task tree that matches the response. // need to find the part of the task tree that matches the response.
...@@ -2457,8 +2469,8 @@ export function writeDynamicRenderResponseIntoCache( ...@@ -2457,8 +2469,8 @@ export function writeDynamicRenderResponseIntoCache(
// pattern of parallel route key and segment: // pattern of parallel route key and segment:
// //
// [string, Segment, string, Segment, string, Segment, ...] // [string, Segment, string, Segment, string, Segment, ...]
const segmentPath = flightData.segmentPath const segmentPath = flightDataEntry.segmentPath
let tree = route.tree let tree = routeTree
for (let i = 0; i < segmentPath.length; i += 2) { for (let i = 0; i < segmentPath.length; i += 2) {
const parallelRouteKey: string = segmentPath[i] const parallelRouteKey: string = segmentPath[i]
if (tree?.slots?.[parallelRouteKey] !== undefined) { if (tree?.slots?.[parallelRouteKey] !== undefined) {
...@@ -2482,17 +2494,31 @@ export function writeDynamicRenderResponseIntoCache( ...@@ -2482,17 +2494,31 @@ export function writeDynamicRenderResponseIntoCache(
) )
} }
const head = flightData.head const head = flightDataEntry.head
if (head !== null) { if (head !== null && metadataTree !== null) {
// For head entries, use the head-specific vary params passed as parameter. // When Cache Components is enabled, the server conservatively marks
// the head as partial during static generation (isPossiblyPartialHead
// in app-render.tsx), even for fully static pages where the head is
// actually complete. When the response is non-partial, we override
// this since the server confirmed no dynamic content exists.
//
// Without Cache Components, the server always sends the correct
// isHeadPartial value, so no override is needed.
const isHeadPartial =
!isResponsePartial && process.env.__NEXT_CACHE_COMPONENTS
? false
: flightDataEntry.isHeadPartial
fulfillEntrySpawnedByRuntimePrefetch( fulfillEntrySpawnedByRuntimePrefetch(
now, now,
fetchStrategy, fetchStrategy,
head, head,
flightData.isHeadPartial, isHeadPartial,
staleAt, staleAt,
// For head entries, use the head-specific vary params passed as
// parameter.
headVaryParams, headVaryParams,
route.metadata, metadataTree,
spawnedEntries spawnedEntries
) )
} }
...@@ -2823,24 +2849,28 @@ function getStaleAtFromHeader( ...@@ -2823,24 +2849,28 @@ function getStaleAtFromHeader(
return now + staleTimeMs return now + staleTimeMs
} }
async function getStaleAt( /**
* Reads the stale time from an async iterable or a response header and
* returns a staleAt timestamp.
*
* TODO: Buffer the response and then read the iterable values
* synchronously, similar to readVaryParams. This would avoid the need to
* make this async, and we could also use it in
* writeDynamicTreeResponseIntoCache. This will also be needed when React
* starts leaving async iterables hanging when the outer RSC stream is
* aborted e.g. due to sync I/O (with unstable_allowPartialStream).
*/
export async function getStaleAt(
now: number, now: number,
serverData: NavigationFlightResponse, staleTimeIterable: AsyncIterable<number> | undefined,
response?: RSCResponse<unknown> response?: RSCResponse<unknown>
): Promise<number> { ): Promise<number> {
if (serverData.s !== undefined) { if (staleTimeIterable !== undefined) {
// Iterate the async iterable and take the last yielded value. The server // Iterate the async iterable and take the last yielded value. The server
// yields updated staleTime values during the render; the last one is the // yields updated staleTime values during the render; the last one is the
// final staleTime. // final staleTime.
let staleTimeSeconds: number | undefined let staleTimeSeconds: number | undefined
for await (const value of staleTimeIterable) {
// TODO: Buffer the response and then read the iterable values
// synchronously, similar to readVaryParams. This would avoid the need to
// make getStaleAt async, and we could also use it in
// writeDynamicTreeResponseIntoCache. This will also be needed when React
// starts leaving async iterables hanging when the outer RSC stream is
// aborted e.g. due to sync I/O (with unstable_allowPartialStream).
for await (const value of serverData.s) {
staleTimeSeconds = value staleTimeSeconds = value
} }
...@@ -2860,77 +2890,65 @@ async function getStaleAt( ...@@ -2860,77 +2890,65 @@ async function getStaleAt(
return now + STATIC_STALETIME_MS return now + STATIC_STALETIME_MS
} }
type ProcessedStaticStageResponse = {
readonly serverData: NavigationFlightResponse
readonly headVaryParams: VaryParams | null
readonly staleAt: number
}
/**
* Resolves a static stage response promise and computes derived values
* (stale time, vary params). Callers should `.then()` the result into
* `writeStaticStageResponseIntoCache`.
*/
export async function processStaticStageResponse(
now: number,
staticStageResponse: Promise<NavigationFlightResponse>
): Promise<ProcessedStaticStageResponse> {
const serverData = await staticStageResponse
const staleAt = await getStaleAt(now, serverData)
const headVaryParams =
serverData.h !== null ? readVaryParams(serverData.h) : null
return { serverData, headVaryParams, staleAt }
}
/** /**
* Writes the static stage of a dynamic navigation response into the segment * Writes the static stage of a navigation response into the segment cache.
* cache. * When `isResponsePartial` is false, segments are written as non-partial with
* `FetchStrategy.Full` so no dynamic follow-up is needed. Default segments
* are skipped (by `writeSeedDataIntoCache`) to avoid caching fallback content
* that would block refreshes from overwriting with dynamic data.
*/ */
export function writeStaticStageResponseIntoCache( export function writeStaticStageResponseIntoCache(
now: number, now: number,
serverData: NavigationFlightResponse, flightData: FlightData,
responseHeaders: Headers, buildId: string | undefined,
headVaryParams: VaryParams | null, headVaryParamsThenable: VaryParamsThenable | null,
staleAt: number, staleAt: number,
route: FulfilledRouteCacheEntry baseTree: FlightRouterState,
renderedSearch: string,
isResponsePartial: boolean
): void { ): void {
// All segments are partial — the static stage needs a dynamic fetch to fill const fetchStrategy = isResponsePartial
// in runtime/dynamic content within their subtrees. ? FetchStrategy.PPR
const isResponsePartial = true : FetchStrategy.Full
// The static stage corresponds to the default prefetching strategy for const headVaryParams =
// Cache Components (FetchStrategy.PPR). headVaryParamsThenable !== null
const fetchStrategy = FetchStrategy.PPR ? readVaryParams(headVaryParamsThenable)
: null
const flightDatas = normalizeFlightData(flightData)
if (typeof flightDatas === 'string') {
return
}
const navigationSeed = convertServerPatchToFullTree(
baseTree,
flightDatas,
renderedSearch
)
writeDynamicRenderResponseIntoCache( writeDynamicRenderResponseIntoCache(
now, now,
fetchStrategy, fetchStrategy,
responseHeaders, flightDatas,
serverData, buildId,
isResponsePartial, isResponsePartial,
headVaryParams, headVaryParams,
staleAt, staleAt,
route, navigationSeed,
null // spawnedEntries — no pre-created entries; will create or upsert null // spawnedEntries — no pre-created entries; will create or upsert
) )
} }
/** /**
* Checks for and strips the leading isPartial byte from a runtime prefetch * Strips the leading isPartial byte from an RSC response stream.
* response stream. If the first byte is a recognized marker ('~' for partial, *
* '#' for complete), it is stripped and isPartial is set accordingly. If the * The server prepends a single byte: '~' (0x7e) for partial, '#' (0x23) for
* first byte is not a recognized marker (e.g. for static responses that were * complete. These bytes cannot appear as the first byte of a valid RSC Flight
* not generated by the runtime prefetch codepath), the stream is returned * response (Flight rows start with a hex digit or ':').
* intact with isPartial set to false.
* *
* This is safe because the marker bytes (0x7e '~', 0x23 '#') cannot appear as * If the first byte is not a recognized marker, the stream is returned intact
* the first byte of a valid RSC Flight response. Flight rows start with either * and the response is conservatively treated as partial.
* a row ID (a hex character) or ':' (0x3a) for hint and debug chunks. Neither
* overlaps with the marker bytes.
*/ */
async function stripIsPartialByte( export async function stripIsPartialByte(
stream: ReadableStream<Uint8Array> stream: ReadableStream<Uint8Array>
): Promise<{ stream: ReadableStream<Uint8Array>; isPartial: boolean }> { ): Promise<{ stream: ReadableStream<Uint8Array>; isPartial: boolean }> {
const reader = stream.getReader() const reader = stream.getReader()
...@@ -2938,14 +2956,16 @@ async function stripIsPartialByte( ...@@ -2938,14 +2956,16 @@ async function stripIsPartialByte(
if (done || !value || value.byteLength === 0) { if (done || !value || value.byteLength === 0) {
return { return {
stream: new ReadableStream({ start: (c) => c.close() }), stream: new ReadableStream({ start: (c) => c.close() }),
isPartial: false, isPartial: true,
} }
} }
const firstByte = value[0] const firstByte = value[0]
// '~' (0x7e) = partial, '#' (0x23) = complete // '#' (0x23) = complete, '~' (0x7e) = partial.
const hasMarker = firstByte === 0x7e || firstByte === 0x23 // Only '#' explicitly means non-partial. Everything else (including
const isPartial = firstByte === 0x7e // unrecognized bytes) is conservatively treated as partial.
const hasMarker = firstByte === 0x23 || firstByte === 0x7e
const isPartial = firstByte !== 0x23
const remainder = hasMarker const remainder = hasMarker
? value.byteLength > 1 ? value.byteLength > 1
......
...@@ -14,12 +14,13 @@ import { ...@@ -14,12 +14,13 @@ import {
type NavigationRequestAccumulation, type NavigationRequestAccumulation,
} from '../router-reducer/ppr-navigations' } from '../router-reducer/ppr-navigations'
import { createHrefFromUrl } from '../router-reducer/create-href-from-url' import { createHrefFromUrl } from '../router-reducer/create-href-from-url'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
import { import {
EntryStatus, EntryStatus,
readRouteCacheEntry, readRouteCacheEntry,
deprecated_requestOptimisticRouteCacheEntry, deprecated_requestOptimisticRouteCacheEntry,
convertRootFlightRouterStateToRouteTree, convertRootFlightRouterStateToRouteTree,
processStaticStageResponse, getStaleAt,
writeStaticStageResponseIntoCache, writeStaticStageResponseIntoCache,
type RouteTree, type RouteTree,
type FulfilledRouteCacheEntry, type FulfilledRouteCacheEntry,
...@@ -371,7 +372,7 @@ async function navigateToUnknownRoute( ...@@ -371,7 +372,7 @@ async function navigateToUnknownRoute(
renderedSearch, renderedSearch,
couldBeIntercepted, couldBeIntercepted,
supportsPerSegmentPrefetching, supportsPerSegmentPrefetching,
staticStageResponse, staticStageData,
responseHeaders, responseHeaders,
debugInfo, debugInfo,
} = result } = result
...@@ -392,7 +393,7 @@ async function navigateToUnknownRoute( ...@@ -392,7 +393,7 @@ async function navigateToUnknownRoute(
// retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch). // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).
const metadataVaryPath = navigationSeed.metadataVaryPath const metadataVaryPath = navigationSeed.metadataVaryPath
if (metadataVaryPath !== null) { if (metadataVaryPath !== null) {
const fulfilledRoute = discoverKnownRoute( discoverKnownRoute(
now, now,
url.pathname, url.pathname,
nextUrl, nextUrl,
...@@ -405,24 +406,33 @@ async function navigateToUnknownRoute( ...@@ -405,24 +406,33 @@ async function navigateToUnknownRoute(
false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal
) )
// Write the static stage of the response into the segment cache so if (staticStageData !== null) {
// that subsequent navigations can serve cached static segments instantly. const { response: staticStageResponse, isResponsePartial } =
if (staticStageResponse !== null) { staticStageData
processStaticStageResponse(now, staticStageResponse).then(
({ serverData, headVaryParams, staleAt }) => // Write the static stage of the response into the segment cache so that
// subsequent navigations can serve cached static segments instantly.
getStaleAt(now, staticStageResponse.s)
.then((staleAt) => {
const buildId =
responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??
staticStageResponse.b
writeStaticStageResponseIntoCache( writeStaticStageResponseIntoCache(
now, now,
serverData, staticStageResponse.f,
responseHeaders, buildId,
headVaryParams, staticStageResponse.h,
staleAt, staleAt,
fulfilledRoute currentFlightRouterState,
), renderedSearch,
() => { isResponsePartial
)
})
.catch(() => {
// The static stage processing failed. Not fatal — the navigation // The static stage processing failed. Not fatal — the navigation
// completed normally, we just won't write into the cache. // completed normally, we just won't write into the cache.
} })
)
} }
} }
......
...@@ -1456,7 +1456,6 @@ async function finalRuntimeServerPrerender( ...@@ -1456,7 +1456,6 @@ async function finalRuntimeServerPrerender(
} }
) )
// Prepend a byte indicating whether the response contains dynamic holes.
result.prelude = prependIsPartialByte(result.prelude, serverIsDynamic) result.prelude = prependIsPartialByte(result.prelude, serverIsDynamic)
return { return {
...@@ -1828,6 +1827,8 @@ function App<T>({ ...@@ -1828,6 +1827,8 @@ function App<T>({
initialRenderedSearch: response.q, initialRenderedSearch: response.q,
initialCouldBeIntercepted: response.i, initialCouldBeIntercepted: response.i,
initialSupportsPerSegmentPrefetching: response.S, initialSupportsPerSegmentPrefetching: response.S,
initialStaleTime: undefined,
initialHeadVaryParams: null,
// location is not initialized in the SSR render // location is not initialized in the SSR render
// it's set to window.location during hydration // it's set to window.location during hydration
location: null, location: null,
...@@ -1893,6 +1894,8 @@ function ErrorApp<T>({ ...@@ -1893,6 +1894,8 @@ function ErrorApp<T>({
initialRenderedSearch: response.q, initialRenderedSearch: response.q,
initialCouldBeIntercepted: response.i, initialCouldBeIntercepted: response.i,
initialSupportsPerSegmentPrefetching: response.S, initialSupportsPerSegmentPrefetching: response.S,
initialStaleTime: undefined,
initialHeadVaryParams: null,
// location is not initialized in the SSR render // location is not initialized in the SSR render
// it's set to window.location during hydration // it's set to window.location during hydration
location: null, location: null,
...@@ -5139,6 +5142,9 @@ async function prerenderToStream( ...@@ -5139,6 +5142,9 @@ async function prerenderToStream(
res.statusCode === 404 res.statusCode === 404
) )
const staleTimeIterable = new StaleTimeIterable()
finalAttemptRSCPayload.s = staleTimeIterable
const serverDynamicTracking = createDynamicTrackingState( const serverDynamicTracking = createDynamicTrackingState(
isDebugDynamicAccesses isDebugDynamicAccesses
) )
...@@ -5166,6 +5172,12 @@ async function prerenderToStream( ...@@ -5166,6 +5172,12 @@ async function prerenderToStream(
varyParamsAccumulator, varyParamsAccumulator,
}) })
trackStaleTime(
finalServerPrerenderStore,
staleTimeIterable,
selectStaleTime
)
let prerenderIsPending = true let prerenderIsPending = true
const finalRSCPrerenderOptions = { const finalRSCPrerenderOptions = {
filterStackFrame, filterStackFrame,
...@@ -5175,18 +5187,20 @@ async function prerenderToStream( ...@@ -5175,18 +5187,20 @@ async function prerenderToStream(
signal: finalServerReactController.signal, signal: finalServerReactController.signal,
} }
const finalRSCAbortCallback = async () => { const finalRSCAbortCallback = async () => {
// Now that the prerendering is complete, we know which vary // Now that the prerendering is complete, we know the final stale
// params were used to compute the response. Resolve the vary // time and vary params. Close the stale time iterable and resolve
// params thenable so it can be sent to the client. The timing // the vary params thenable so Flight can serialize their values
// here is important: the thenable was included in the Flight // into the stream. The timing here is important: both were
// payload, but it can only be serialized at the very end, after // included in the Flight payload, but they can only be serialized
// all the components have finished. // at the very end, after all the components have finished.
// //
// We resolve the accumulator directly here instead of reading from // We resolve these directly here instead of reading from the work
// the work unit store because this callback runs in a separate // unit store because this callback runs in a separate task (via
// task (via setTimeout) and may not have access to the async // setTimeout) and may not have access to the async storage context.
// storage context. await Promise.all([
await finishAccumulatingVaryParams(varyParamsAccumulator) finishStaleTimeTracking(staleTimeIterable),
finishAccumulatingVaryParams(varyParamsAccumulator),
])
if (finalServerReactController.signal.aborted) { if (finalServerReactController.signal.aborted) {
// If the server controller is already aborted we must have called something // If the server controller is already aborted we must have called something
...@@ -5356,8 +5370,12 @@ async function prerenderToStream( ...@@ -5356,8 +5370,12 @@ async function prerenderToStream(
tracingMetadata: tracingMetadata, tracingMetadata: tracingMetadata,
}) })
const flightData = await streamToBuffer(reactServerResult.asStream()) metadata.flightData = await streamToBuffer(
metadata.flightData = flightData prependIsPartialByte(reactServerResult.asStream(), serverIsDynamic)
)
// collectSegmentData needs the raw flight data without the marker byte.
const flightData = metadata.flightData.subarray(1)
metadata.segmentData = await collectSegmentData( metadata.segmentData = await collectSegmentData(
flightData, flightData,
finalServerPrerenderStore, finalServerPrerenderStore,
......
...@@ -14,6 +14,7 @@ import { INFINITE_CACHE } from '../../lib/constants' ...@@ -14,6 +14,7 @@ import { INFINITE_CACHE } from '../../lib/constants'
export class StaleTimeIterable { export class StaleTimeIterable {
private _resolve: ((result: IteratorResult<number>) => void) | null = null private _resolve: ((result: IteratorResult<number>) => void) | null = null
private _done = false private _done = false
private _buffer: number[] = []
/** The last value passed to `update()`. */ /** The last value passed to `update()`. */
public currentValue: number = 0 public currentValue: number = 0
...@@ -24,6 +25,8 @@ export class StaleTimeIterable { ...@@ -24,6 +25,8 @@ export class StaleTimeIterable {
if (this._resolve) { if (this._resolve) {
this._resolve({ value, done: false }) this._resolve({ value, done: false })
this._resolve = null this._resolve = null
} else {
this._buffer.push(value)
} }
} }
...@@ -39,6 +42,9 @@ export class StaleTimeIterable { ...@@ -39,6 +42,9 @@ export class StaleTimeIterable {
[Symbol.asyncIterator](): AsyncIterator<number> { [Symbol.asyncIterator](): AsyncIterator<number> {
return { return {
next: () => { next: () => {
if (this._buffer.length > 0) {
return Promise.resolve({ value: this._buffer.shift()!, done: false })
}
if (this._done) { if (this._done) {
return Promise.resolve({ value: undefined, done: true }) return Promise.resolve({ value: undefined, done: true })
} }
......
...@@ -262,6 +262,8 @@ export type InitialRSCPayload = { ...@@ -262,6 +262,8 @@ export type InitialRSCPayload = {
* headVaryParams - vary params for the head (metadata) of the response. * headVaryParams - vary params for the head (metadata) of the response.
*/ */
h: VaryParamsThenable | null h: VaryParamsThenable | null
/** staleTime in seconds - Only present when Cache Components is enabled. */
s?: AsyncIterable<number>
} }
// Response from `createFromFetch` for normal rendering // Response from `createFromFetch` for normal rendering
......
...@@ -6,7 +6,9 @@ export default function RootLayout({ children }: { children: ReactNode }) { ...@@ -6,7 +6,9 @@ export default function RootLayout({ children }: { children: ReactNode }) {
<html> <html>
<body> <body>
<nav> <nav>
<Link href="/">Home</Link> <Link href="/" prefetch={false}>
Home
</Link>
</nav> </nav>
{children} {children}
</body> </body>
......
...@@ -15,12 +15,12 @@ describe('cached navigations', () => { ...@@ -15,12 +15,12 @@ describe('cached navigations', () => {
it('serves cached static segments instantly on the second navigation', async () => { it('serves cached static segments instantly on the second navigation', async () => {
let page: Playwright.Page let page: Playwright.Page
const browser = await next.browser('/', { const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) { async beforePageLoad(p: Playwright.Page) {
page = p page = p
await page.clock.install()
}, },
}) })
const act = createRouterAct(page) const act = createRouterAct(page)
await page.clock.install()
// First navigation — full dynamic request, no prefetch // First navigation — full dynamic request, no prefetch
await act( await act(
...@@ -147,52 +147,48 @@ describe('cached navigations', () => { ...@@ -147,52 +147,48 @@ describe('cached navigations', () => {
) )
}) })
// TODO: To be implemented. it('serves a fully static page without any requests on the second navigation', async () => {
it.failing( let page: Playwright.Page
'serves a fully static page without any requests on the second navigation', const browser = await next.browser('/', {
async () => { beforePageLoad(p: Playwright.Page) {
let page: Playwright.Page page = p
const browser = await next.browser('/', { },
beforePageLoad(p: Playwright.Page) { })
page = p const act = createRouterAct(page)
},
})
const act = createRouterAct(page)
// First navigation — full request, no prefetch // First navigation — full request, no prefetch
await act( await act(
async () => { async () => {
await browser.elementByCss('a[href="/fully-static"]').click() await browser.elementByCss('a[href="/fully-static"]').click()
}, },
{ includes: 'Cached content' } { includes: 'Cached content' }
) )
expect(await browser.elementById('cached-content').text()).toContain( expect(await browser.elementById('cached-content').text()).toContain(
'Cached content' 'Cached content'
) )
// Navigate back to home // Navigate back to home
await browser.back() await browser.back()
expect(await browser.elementByCss('h1').text()).toBe('Home') expect(await browser.elementByCss('h1').text()).toBe('Home')
// Second navigation — fully cached, should not issue any requests // Second navigation — fully cached, should not issue any requests
await act(async () => { await act(async () => {
await browser.elementByCss('a[href="/fully-static"]').click() await browser.elementByCss('a[href="/fully-static"]').click()
}, 'no-requests') }, 'no-requests')
expect(await browser.elementById('cached-content').text()).toContain( expect(await browser.elementById('cached-content').text()).toContain(
'Cached content' 'Cached content'
) )
} })
)
it('caches static segments when navigating to a known route without a prefetch', async () => { it('caches static segments when navigating to a known route without a prefetch', async () => {
let page: Playwright.Page let page: Playwright.Page
const browser = await next.browser('/', { const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) { async beforePageLoad(p: Playwright.Page) {
page = p page = p
await page.clock.install()
}, },
}) })
const act = createRouterAct(page) const act = createRouterAct(page)
await page.clock.install()
// First navigation — seeds the route cache (stale after 5 min) and // First navigation — seeds the route cache (stale after 5 min) and
// segment cache (stale after 120s, from cacheLife({ stale: 120 })). // segment cache (stale after 120s, from cacheLife({ stale: 120 })).
...@@ -280,12 +276,12 @@ describe('cached navigations', () => { ...@@ -280,12 +276,12 @@ describe('cached navigations', () => {
it('includes static params in the cached static stage', async () => { it('includes static params in the cached static stage', async () => {
let page: Playwright.Page let page: Playwright.Page
const browser = await next.browser('/', { const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) { async beforePageLoad(p: Playwright.Page) {
page = p page = p
await page.clock.install()
}, },
}) })
const act = createRouterAct(page) const act = createRouterAct(page)
await page.clock.install()
// First navigation // First navigation
await act( await act(
...@@ -340,12 +336,12 @@ describe('cached navigations', () => { ...@@ -340,12 +336,12 @@ describe('cached navigations', () => {
it('defers fallback params to the runtime stage', async () => { it('defers fallback params to the runtime stage', async () => {
let page: Playwright.Page let page: Playwright.Page
const browser = await next.browser('/', { const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) { async beforePageLoad(p: Playwright.Page) {
page = p page = p
await page.clock.install()
}, },
}) })
const act = createRouterAct(page) const act = createRouterAct(page)
await page.clock.install()
// First navigation — "foo" is not in generateStaticParams, so it's a // First navigation — "foo" is not in generateStaticParams, so it's a
// fallback param // fallback param
...@@ -405,4 +401,65 @@ describe('cached navigations', () => { ...@@ -405,4 +401,65 @@ describe('cached navigations', () => {
'Dynamic content' 'Dynamic content'
) )
}) })
it('caches a fully static page from the initial HTML for subsequent navigations', async () => {
let page: Playwright.Page
// Start directly at /fully-static — full HTML load, not a client-side
// navigation. The RSC payload is inlined in the HTML and contains only
// static (cached) content.
const browser = await next.browser('/fully-static', {
async beforePageLoad(p: Playwright.Page) {
page = p
await page.clock.install()
},
})
const act = createRouterAct(page)
// Verify the page rendered fully via HTML
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
// Navigate to home
await act(
async () => {
await browser.elementByCss('a[href="/"]').click()
},
{ includes: 'Home' }
)
expect(await browser.elementByCss('h1').text()).toBe('Home')
// Navigate back to /fully-static. Since it was fully static and cached
// during the initial HTML load, no server requests should be needed.
await act(async () => {
await browser.elementByCss('a[href="/fully-static"]').click()
}, 'no-requests')
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
// Navigate back to home again
await act(async () => {
await browser.elementByCss('a[href="/"]').click()
}, 'no-requests')
expect(await browser.elementByCss('h1').text()).toBe('Home')
// Fast-forward past the stale time (120s from cacheLife({ stale: 120 })).
// Using 180s to stay well under the 300s default — if we accidentally
// used the default instead of the collected stale time, this would
// not expire and the test would fail.
await page.clock.fastForward(180_000)
// Navigate to /fully-static again — cache is stale, so a server
// request should be required.
await act(
async () => {
await browser.elementByCss('a[href="/fully-static"]').click()
},
{ includes: 'Cached content' }
)
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
})
}) })
...@@ -138,4 +138,54 @@ describe('segment cache (refresh)', () => { ...@@ -138,4 +138,54 @@ describe('segment cache (refresh)', () => {
expect(await docsPage.textContent()).toBe('Static docs page') expect(await docsPage.textContent()).toBe('Static docs page')
}, 'no-requests') }, 'no-requests')
}) })
it('re-navigation to a fully static page does not overwrite dynamic slots with default content', async () => {
// Load the main Dashboard page. The @navbar slot renders dynamic content
// (connection() + randomUUID()), but the @main slot is static.
let page: Playwright.Page
const browser = await next.browser('/dashboard', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
// Navigate to the Analytics page. This is a fully static page (both the
// @main/analytics slot and the @navbar/default slot are static), so the
// server responds with a Static completeness marker. The client writes
// all segments into the segment cache.
await act(async () => {
const toggleAnalyticsLink = await browser.elementByCss(
'input[data-link-accordion="/dashboard/analytics"]'
)
await toggleAnalyticsLink.click()
const link = await browser.elementByCss('a[href="/dashboard/analytics"]')
await link.click()
})
// Navigate back to the Dashboard page.
await act(async () => {
const toggleDashboardLink = await browser.elementByCss(
'input[data-link-accordion="/dashboard"]'
)
await toggleDashboardLink.click()
const link = await browser.elementByCss('a[href="/dashboard"]')
await link.click()
})
// Navigate to the Analytics page again. Since it's fully static and was
// already visited, this should be served entirely from the segment cache
// without any server requests.
await act(async () => {
const link = await browser.elementByCss('a[href="/dashboard/analytics"]')
await link.click()
}, 'no-requests')
// Verify the navbar still shows the dynamic content from the original
// /dashboard render, not the static @navbar/default.tsx content.
const navbarDynamicRenderCounter = await browser.elementById(
'navbar-dynamic-render-counter'
)
expect(await navbarDynamicRenderCounter.textContent()).toBe('0')
})
}) })
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