Unverified Commit e2ef94e2 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Cached Navigations: Serve cached segments instantly on repeat visits (#90223)

When navigating to a dynamic (or partially static) page with Cache Components, the server now uses staged rendering to separate the static portion (backed by the Resume Data Cache) from the dynamic portion (runtime APIs like `cookies`, `headers`, `connection`, or uncached I/O). The static stage byte length is embedded in the RSC payload so the client can extract it.

On the client, the first navigation clones the response stream, truncates it to the static stage byte length, decodes it as a partial Flight response, and writes the result into the segment cache. Subsequent navigations find these cached segments and display them instantly while fetching only the dynamic data from the server.

Server-side changes:
- Add `generateStagedDynamicFlightRenderResult` with `StaleTimeIterable`, byte counting via tee'd stream, and stage-separated rendering
- Enable `asyncApiPromises` checks in production for `cookies`, `headers`, `connection`, `searchParams`, and `params`
- Propagate stale time to `RequestStore` for Cache Components
- Thread `fallbackParams` from prerender manifest to production renders
- Rename `devFallbackParams` → `fallbackParams` (now used in both dev/prod)

Client-side changes:
- Clone response in `fetchServerResponse`, truncate to static byte length, decode with `allowPartialStream`
- Write static stage into segment cache via `writeStaticStageResponseIntoCache`
- Use `getFulfilledRouteVaryPath` in `writeRouteIntoCache` for `Fallback` keying
- Refactor `writeDynamicRenderResponseIntoCache` (remove dead `task` param, accept `headers` directly)

In follow-ups we'll also handle fully static pages, as well as extracting static segment data from the initial load.
parent 5f6aa1cb
...@@ -1070,5 +1070,6 @@ ...@@ -1070,5 +1070,6 @@
"1069": "Invariant: cache entry \"%s\" not found in dir \"%s\"", "1069": "Invariant: cache entry \"%s\" not found in dir \"%s\"",
"1070": "image of size %s could not be tracked by lru cache", "1070": "image of size %s could not be tracked by lru cache",
"1071": "toNodeDebugChannel cannot be used in edge/web runtime, this is a bug in the Next.js codebase", "1071": "toNodeDebugChannel cannot be used in edge/web runtime, this is a bug in the Next.js codebase",
"1072": "Missing segment data: <head>" "1072": "Missing segment data: <head>",
"1073": "Expected static stage body to be available"
} }
...@@ -1098,6 +1098,26 @@ export async function handler( ...@@ -1098,6 +1098,26 @@ export async function handler(
? getFallbackRouteParams(normalizedSrcPage, routeModule) ? getFallbackRouteParams(normalizedSrcPage, routeModule)
: null : null
// For staged dynamic rendering (cached navigations), pass the fallback
// params via request meta so the RequestStore knows which params to defer
// to the runtime stage. We don't pass them as fallbackRouteParams because
// that would replace actual param values with opaque placeholders during
// segment resolution.
if (
isProduction &&
nextConfig.cacheComponents &&
!isPrerendered &&
prerenderInfo?.fallbackRouteParams
) {
const fallbackParams = createOpaqueFallbackRouteParams(
prerenderInfo.fallbackRouteParams
)
if (fallbackParams) {
addRequestMeta(req, 'fallbackParams', fallbackParams)
}
}
// Perform the render. // Perform the render.
return doRender({ return doRender({
span, span,
......
...@@ -7,6 +7,7 @@ import { ...@@ -7,6 +7,7 @@ import {
createFromFetch as createFromFetchBrowser, createFromFetch as createFromFetchBrowser,
} from 'react-server-dom-webpack/client' } from 'react-server-dom-webpack/client'
import { InvariantError } from '../../../shared/lib/invariant-error'
import type { import type {
FlightRouterState, FlightRouterState,
NavigationFlightResponse, NavigationFlightResponse,
...@@ -70,6 +71,8 @@ type SpaFetchServerResponseResult = { ...@@ -70,6 +71,8 @@ type SpaFetchServerResponseResult = {
prerendered: boolean prerendered: boolean
postponed: boolean postponed: boolean
staleTime: number staleTime: number
staticStageResponse: Promise<NavigationFlightResponse> | null
responseHeaders: Headers
debugInfo: Array<any> | null debugInfo: Array<any> | null
} }
...@@ -222,7 +225,7 @@ export async function fetchServerResponse( ...@@ -222,7 +225,7 @@ export async function fetchServerResponse(
).waitForWebpackRuntimeHotUpdate() ).waitForWebpackRuntimeHotUpdate()
} }
let flightResponsePromise = res.flightResponse let flightResponsePromise = res.flightResponsePromise
if (flightResponsePromise === null) { if (flightResponsePromise === null) {
// Typically, `createFetch` would have already started decoding the // Typically, `createFetch` would have already started decoding the
// Flight response. If it hasn't, though, we need to decode it now. // Flight response. If it hasn't, though, we need to decode it now.
...@@ -252,6 +255,20 @@ export async function fetchServerResponse( ...@@ -252,6 +255,20 @@ export async function fetchServerResponse(
return doMpaNavigation(normalizedFlightData) return doMpaNavigation(normalizedFlightData)
} }
// If the server included a static stage byte count, decode the static
// stage from the cloned response body to seed the segment cache.
let staticStageResponse: Promise<NavigationFlightResponse> | null = null
if (flightResponse.l !== undefined && res.staticStageBodyPromise !== 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,
canonicalUrl: canonicalUrl, canonicalUrl: canonicalUrl,
...@@ -267,6 +284,8 @@ export async function fetchServerResponse( ...@@ -267,6 +284,8 @@ export async function fetchServerResponse(
prerendered: flightResponse.S, prerendered: flightResponse.S,
postponed, postponed,
staleTime, staleTime,
staticStageResponse,
responseHeaders: res.headers,
debugInfo: flightResponsePromise._debugInfo ?? null, debugInfo: flightResponsePromise._debugInfo ?? null,
} }
} catch (err) { } catch (err) {
...@@ -296,7 +315,8 @@ export type RSCResponse<T> = { ...@@ -296,7 +315,8 @@ export type RSCResponse<T> = {
body: ReadableStream<Uint8Array> | null body: ReadableStream<Uint8Array> | null
status: number status: number
url: string url: string
flightResponse: (Promise<T> & { _debugInfo?: Array<any> }) | null flightResponsePromise: (Promise<T> & { _debugInfo?: Array<any> }) | null
staticStageBodyPromise: Promise<ReadableStream<Uint8Array> | null> | null
} }
export async function createFetch<T>( export async function createFetch<T>(
...@@ -345,6 +365,15 @@ export async function createFetch<T>( ...@@ -345,6 +365,15 @@ export async function createFetch<T>(
let fetchUrl = new URL(url) let fetchUrl = new URL(url)
setCacheBustingSearchParam(fetchUrl, headers) setCacheBustingSearchParam(fetchUrl, headers)
let fetchPromise = fetch(fetchUrl, fetchOptions) let fetchPromise = fetch(fetchUrl, fetchOptions)
// 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
// in React starts as soon as `createFromFetch` is called. // in React starts as soon as `createFromFetch` is called.
...@@ -413,6 +442,9 @@ export async function createFetch<T>( ...@@ -413,6 +442,9 @@ export async function createFetch<T>(
fetchUrl = new URL(responseUrl) fetchUrl = new URL(responseUrl)
setCacheBustingSearchParam(fetchUrl, headers) setCacheBustingSearchParam(fetchUrl, headers)
fetchPromise = fetch(fetchUrl, fetchOptions) fetchPromise = fetch(fetchUrl, fetchOptions)
if (process.env.__NEXT_CACHE_COMPONENTS) {
staticStageBodyPromise = fetchPromise.then((r) => r.clone().body)
}
flightResponsePromise = shouldImmediatelyDecode flightResponsePromise = shouldImmediatelyDecode
? createFromNextFetch<T>(fetchPromise, headers) ? createFromNextFetch<T>(fetchPromise, headers)
: null : null
...@@ -447,7 +479,9 @@ export async function createFetch<T>( ...@@ -447,7 +479,9 @@ export async function createFetch<T>(
// This is the exact promise returned by `createFromFetch`. It contains // This is the exact promise returned by `createFromFetch`. It contains
// debug information that we need to transfer to any derived promises that // debug information that we need to transfer to any derived promises that
// are later rendered by React. // are later rendered by React.
flightResponse: flightResponsePromise, flightResponsePromise: flightResponsePromise,
staticStageBodyPromise: staticStageBodyPromise,
} }
return rscResponse return rscResponse
...@@ -476,3 +510,61 @@ function createFromNextFetch<T>( ...@@ -476,3 +510,61 @@ function createFromNextFetch<T>(
debugChannel: createDebugChannel && createDebugChannel(requestHeaders), debugChannel: createDebugChannel && createDebugChannel(requestHeaders),
}) })
} }
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(
stream: ReadableStream<Uint8Array>,
byteLength: number
): ReadableStream<Uint8Array> {
const reader = stream.getReader()
let remaining = byteLength
return new ReadableStream({
async pull(controller) {
if (remaining <= 0) {
reader.cancel()
controller.close()
return
}
const { done, value } = await reader.read()
if (done) {
controller.close()
return
}
if (value.byteLength <= remaining) {
controller.enqueue(value)
remaining -= value.byteLength
} else {
controller.enqueue(value.subarray(0, remaining))
remaining = 0
reader.cancel()
controller.close()
}
},
cancel() {
reader.cancel()
},
})
}
...@@ -35,6 +35,8 @@ import { ...@@ -35,6 +35,8 @@ import {
waitForSegmentCacheEntry, waitForSegmentCacheEntry,
markRouteEntryAsDynamicRewrite, markRouteEntryAsDynamicRewrite,
invalidateRouteCacheEntries, invalidateRouteCacheEntries,
processStaticStageResponse,
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'
...@@ -1253,7 +1255,8 @@ export function spawnDynamicRequests( ...@@ -1253,7 +1255,8 @@ export function spawnDynamicRequests(
dynamicRequestTree, dynamicRequestTree,
primaryUrl, primaryUrl,
nextUrl, nextUrl,
freshnessPolicy freshnessPolicy,
routeCacheEntry
) )
const separateRefreshUrls = accumulation.separateRefreshUrls const separateRefreshUrls = accumulation.separateRefreshUrls
...@@ -1304,7 +1307,8 @@ export function spawnDynamicRequests( ...@@ -1304,7 +1307,8 @@ export function spawnDynamicRequests(
// if a refresh fails due to a mismatch, it will trigger a // if a refresh fails due to a mismatch, it will trigger a
// hard refresh. // hard refresh.
nextUrl, nextUrl,
freshnessPolicy freshnessPolicy,
routeCacheEntry
) )
) )
} }
...@@ -1540,7 +1544,8 @@ async function fetchMissingDynamicData( ...@@ -1540,7 +1544,8 @@ async function fetchMissingDynamicData(
dynamicRequestTree: FlightRouterState, dynamicRequestTree: FlightRouterState,
url: URL, url: URL,
nextUrl: string | null, nextUrl: string | null,
freshnessPolicy: FreshnessPolicy freshnessPolicy: FreshnessPolicy,
routeCacheEntry: FulfilledRouteCacheEntry | null
): Promise<{ ): Promise<{
exitStatus: NavigationTaskExitStatus exitStatus: NavigationTaskExitStatus
url: URL url: URL
...@@ -1576,6 +1581,25 @@ async function fetchMissingDynamicData( ...@@ -1576,6 +1581,25 @@ async function fetchMissingDynamicData(
await waitForNavigationLock() await waitForNavigationLock()
} }
if (routeCacheEntry !== null && result.staticStageResponse !== null) {
const now = Date.now()
processStaticStageResponse(now, result.staticStageResponse).then(
({ serverData, headVaryParams, staleAt }) =>
writeStaticStageResponseIntoCache(
now,
serverData,
result.responseHeaders,
headVaryParams,
staleAt,
routeCacheEntry
),
() => {
// The static stage processing failed. Not fatal — the navigation
// completed normally, we just won't write into the cache.
}
)
}
const didReceiveUnknownParallelRoute = writeDynamicDataIntoNavigationTask( const didReceiveUnknownParallelRoute = writeDynamicDataIntoNavigationTask(
task, task,
seed.routeTree, seed.routeTree,
......
...@@ -974,6 +974,48 @@ export function attemptToFulfillDynamicSegmentFromBFCache( ...@@ -974,6 +974,48 @@ export function attemptToFulfillDynamicSegmentFromBFCache(
return null return null
} }
/**
* Attempts to replace an existing segment cache entry with data from the
* bfcache. Unlike `attemptToFulfillDynamicSegmentFromBFCache` (which fills an
* empty entry), this creates a new entry and upserts it, so it works even when
* the segment is already fulfilled.
*/
export function attemptToUpgradeSegmentFromBFCache(
now: number,
tree: RouteTree
): FulfilledSegmentCacheEntry | null {
const varyPath = tree.varyPath
const adjustedCurrentTime = now - STATIC_STALETIME_MS + DYNAMIC_STALETIME_MS
const bfcacheEntry = readFromBFCacheDuringRegularNavigation(
adjustedCurrentTime,
varyPath
)
if (bfcacheEntry !== null) {
const requestedAt = bfcacheEntry.staleAt - DYNAMIC_STALETIME_MS
const dynamicPrefetchStaleAt = requestedAt + STATIC_STALETIME_MS
const pendingSegment = upgradeToPendingSegment(
createDetachedSegmentCacheEntry(now),
FetchStrategy.Full
)
const isPartial = false
const newEntry = fulfillSegmentCacheEntry(
pendingSegment,
bfcacheEntry.rsc,
dynamicPrefetchStaleAt,
isPartial
)
const segmentVaryPath = getSegmentVaryPathForRequest(
FetchStrategy.Full,
tree
)
const upserted = upsertSegmentEntry(now, segmentVaryPath, newEntry)
if (upserted !== null && upserted.status === EntryStatus.Fulfilled) {
return upserted
}
}
return null
}
function pingBlockedTasks(entry: { function pingBlockedTasks(entry: {
blockedTasks: Set<PrefetchTask> | null blockedTasks: Set<PrefetchTask> | null
}): void { }): void {
...@@ -1511,7 +1553,6 @@ export function convertRouteTreeToFlightRouterState( ...@@ -1511,7 +1553,6 @@ export function convertRouteTreeToFlightRouterState(
export async function fetchRouteOnCacheMiss( export async function fetchRouteOnCacheMiss(
entry: PendingRouteCacheEntry, entry: PendingRouteCacheEntry,
task: PrefetchTask,
key: RouteCacheKey key: RouteCacheKey
): Promise<PrefetchSubtaskResult<null> | null> { ): Promise<PrefetchSubtaskResult<null> | null> {
// This function is allowed to use async/await because it contains the actual // This function is allowed to use async/await because it contains the actual
...@@ -1755,7 +1796,6 @@ export async function fetchRouteOnCacheMiss( ...@@ -1755,7 +1796,6 @@ export async function fetchRouteOnCacheMiss(
: null : null
writeDynamicTreeResponseIntoCache( writeDynamicTreeResponseIntoCache(
Date.now(), Date.now(),
task,
// The non-PPR response format is what we'd get if we prefetched these segments // The non-PPR response format is what we'd get if we prefetched these segments
// using the LoadingBoundary fetch strategy, so mark their cache entries accordingly. // using the LoadingBoundary fetch strategy, so mark their cache entries accordingly.
FetchStrategy.LoadingBoundary, FetchStrategy.LoadingBoundary,
...@@ -2071,9 +2111,8 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest( ...@@ -2071,9 +2111,8 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
// in the LRU as more data comes in. // in the LRU as more data comes in.
fulfilledEntries = writeDynamicRenderResponseIntoCache( fulfilledEntries = writeDynamicRenderResponseIntoCache(
now, now,
task,
fetchStrategy, fetchStrategy,
response as RSCResponse<NavigationFlightResponse>, response.headers,
serverData, serverData,
isResponsePartial, isResponsePartial,
headVaryParams, headVaryParams,
...@@ -2093,7 +2132,6 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest( ...@@ -2093,7 +2132,6 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
function writeDynamicTreeResponseIntoCache( function writeDynamicTreeResponseIntoCache(
now: number, now: number,
task: PrefetchTask,
fetchStrategy: fetchStrategy:
| FetchStrategy.LoadingBoundary | FetchStrategy.LoadingBoundary
| FetchStrategy.PPRRuntime | FetchStrategy.PPRRuntime
...@@ -2176,9 +2214,8 @@ function writeDynamicTreeResponseIntoCache( ...@@ -2176,9 +2214,8 @@ function writeDynamicTreeResponseIntoCache(
// remove the "client-only" option. Then, we can delete this function call. // remove the "client-only" option. Then, we can delete this function call.
writeDynamicRenderResponseIntoCache( writeDynamicRenderResponseIntoCache(
now, now,
task,
fetchStrategy, fetchStrategy,
response, response.headers,
serverData, serverData,
isResponsePartial, isResponsePartial,
headVaryParams, headVaryParams,
...@@ -2203,14 +2240,14 @@ function rejectSegmentEntriesIfStillPending( ...@@ -2203,14 +2240,14 @@ function rejectSegmentEntriesIfStillPending(
return fulfilledEntries return fulfilledEntries
} }
function writeDynamicRenderResponseIntoCache( export function writeDynamicRenderResponseIntoCache(
now: number, now: number,
task: PrefetchTask,
fetchStrategy: fetchStrategy:
| FetchStrategy.LoadingBoundary | FetchStrategy.LoadingBoundary
| FetchStrategy.PPR
| FetchStrategy.PPRRuntime | FetchStrategy.PPRRuntime
| FetchStrategy.Full, | FetchStrategy.Full,
response: RSCResponse<NavigationFlightResponse>, responseHeaders: Headers,
serverData: NavigationFlightResponse, serverData: NavigationFlightResponse,
isResponsePartial: boolean, isResponsePartial: boolean,
headVaryParams: VaryParams | null, headVaryParams: VaryParams | null,
...@@ -2218,10 +2255,10 @@ function writeDynamicRenderResponseIntoCache( ...@@ -2218,10 +2255,10 @@ function writeDynamicRenderResponseIntoCache(
route: FulfilledRouteCacheEntry, route: FulfilledRouteCacheEntry,
spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null
): Array<FulfilledSegmentCacheEntry> | null { ): Array<FulfilledSegmentCacheEntry> | null {
if ( const buildId =
(response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b) !== responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b
getNavigationBuildId()
) { 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) {
...@@ -2263,7 +2300,6 @@ function writeDynamicRenderResponseIntoCache( ...@@ -2263,7 +2300,6 @@ function writeDynamicRenderResponseIntoCache(
writeSeedDataIntoCache( writeSeedDataIntoCache(
now, now,
task,
fetchStrategy, fetchStrategy,
tree, tree,
staleAt, staleAt,
...@@ -2308,9 +2344,9 @@ function writeDynamicRenderResponseIntoCache( ...@@ -2308,9 +2344,9 @@ function writeDynamicRenderResponseIntoCache(
function writeSeedDataIntoCache( function writeSeedDataIntoCache(
now: number, now: number,
task: PrefetchTask,
fetchStrategy: fetchStrategy:
| FetchStrategy.LoadingBoundary | FetchStrategy.LoadingBoundary
| FetchStrategy.PPR
| FetchStrategy.PPRRuntime | FetchStrategy.PPRRuntime
| FetchStrategy.Full, | FetchStrategy.Full,
tree: RouteTree, tree: RouteTree,
...@@ -2354,7 +2390,6 @@ function writeSeedDataIntoCache( ...@@ -2354,7 +2390,6 @@ function writeSeedDataIntoCache(
if (childSeedData !== null && childSeedData !== undefined) { if (childSeedData !== null && childSeedData !== undefined) {
writeSeedDataIntoCache( writeSeedDataIntoCache(
now, now,
task,
fetchStrategy, fetchStrategy,
childTree, childTree,
staleAt, staleAt,
...@@ -2371,6 +2406,7 @@ function fulfillEntrySpawnedByRuntimePrefetch( ...@@ -2371,6 +2406,7 @@ function fulfillEntrySpawnedByRuntimePrefetch(
now: number, now: number,
fetchStrategy: fetchStrategy:
| FetchStrategy.LoadingBoundary | FetchStrategy.LoadingBoundary
| FetchStrategy.PPR
| FetchStrategy.PPRRuntime | FetchStrategy.PPRRuntime
| FetchStrategy.Full, | FetchStrategy.Full,
rsc: React.ReactNode, rsc: React.ReactNode,
...@@ -2617,7 +2653,7 @@ function getStaleAtFromHeader( ...@@ -2617,7 +2653,7 @@ function getStaleAtFromHeader(
async function getStaleAt( async function getStaleAt(
now: number, now: number,
serverData: NavigationFlightResponse, serverData: NavigationFlightResponse,
response: RSCResponse<unknown> response?: RSCResponse<unknown>
): Promise<number> { ): Promise<number> {
if (serverData.s !== undefined) { if (serverData.s !== 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
...@@ -2644,7 +2680,68 @@ async function getStaleAt( ...@@ -2644,7 +2680,68 @@ async function getStaleAt(
} }
} }
return getStaleAtFromHeader(now, response) if (response !== undefined) {
return getStaleAtFromHeader(now, response)
}
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
* cache.
*/
export function writeStaticStageResponseIntoCache(
now: number,
serverData: NavigationFlightResponse,
responseHeaders: Headers,
headVaryParams: VaryParams | null,
staleAt: number,
route: FulfilledRouteCacheEntry
): void {
// All segments are partial — the static stage needs a dynamic fetch to fill
// in runtime/dynamic content within their subtrees.
const isResponsePartial = true
// The static stage corresponds to the default prefetching strategy for
// Cache Components (FetchStrategy.PPR).
const fetchStrategy = FetchStrategy.PPR
writeDynamicRenderResponseIntoCache(
now,
fetchStrategy,
responseHeaders,
serverData,
isResponsePartial,
headVaryParams,
staleAt,
route,
null // spawnedEntries — no pre-created entries; will create or upsert
)
} }
/** /**
......
...@@ -19,6 +19,8 @@ import { ...@@ -19,6 +19,8 @@ import {
readRouteCacheEntry, readRouteCacheEntry,
deprecated_requestOptimisticRouteCacheEntry, deprecated_requestOptimisticRouteCacheEntry,
convertRootFlightRouterStateToRouteTree, convertRootFlightRouterStateToRouteTree,
processStaticStageResponse,
writeStaticStageResponseIntoCache,
type RouteTree, type RouteTree,
type FulfilledRouteCacheEntry, type FulfilledRouteCacheEntry,
} from './cache' } from './cache'
...@@ -369,6 +371,8 @@ async function navigateToUnknownRoute( ...@@ -369,6 +371,8 @@ async function navigateToUnknownRoute(
renderedSearch, renderedSearch,
couldBeIntercepted, couldBeIntercepted,
prerendered, prerendered,
staticStageResponse,
responseHeaders,
debugInfo, debugInfo,
} = result } = result
...@@ -388,7 +392,7 @@ async function navigateToUnknownRoute( ...@@ -388,7 +392,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) {
discoverKnownRoute( const fulfilledRoute = discoverKnownRoute(
now, now,
url.pathname, url.pathname,
nextUrl, nextUrl,
...@@ -400,6 +404,26 @@ async function navigateToUnknownRoute( ...@@ -400,6 +404,26 @@ async function navigateToUnknownRoute(
prerendered, prerendered,
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
// that subsequent navigations can serve cached static segments instantly.
if (staticStageResponse !== null) {
processStaticStageResponse(now, staticStageResponse).then(
({ serverData, headVaryParams, staleAt }) =>
writeStaticStageResponseIntoCache(
now,
serverData,
responseHeaders,
headVaryParams,
staleAt,
fulfilledRoute
),
() => {
// The static stage processing failed. Not fatal — the navigation
// completed normally, we just won't write into the cache.
}
)
}
} }
return navigateToKnownRoute( return navigateToKnownRoute(
......
...@@ -26,6 +26,7 @@ import { ...@@ -26,6 +26,7 @@ import {
overwriteRevalidatingSegmentCacheEntry, overwriteRevalidatingSegmentCacheEntry,
canNewFetchStrategyProvideMoreContent, canNewFetchStrategyProvideMoreContent,
attemptToFulfillDynamicSegmentFromBFCache, attemptToFulfillDynamicSegmentFromBFCache,
attemptToUpgradeSegmentFromBFCache,
} from './cache' } from './cache'
import { getSegmentVaryPathForRequest, type SegmentVaryPath } from './vary-path' import { getSegmentVaryPathForRequest, type SegmentVaryPath } from './vary-path'
import type { RouteCacheKey } from './cache-key' import type { RouteCacheKey } from './cache-key'
...@@ -621,7 +622,7 @@ function pingRoute(now: number, task: PrefetchTask): PrefetchTaskExitStatus { ...@@ -621,7 +622,7 @@ function pingRoute(now: number, task: PrefetchTask): PrefetchTaskExitStatus {
if (background(task)) { if (background(task)) {
routeWithoutSearch.status = EntryStatus.Pending routeWithoutSearch.status = EntryStatus.Pending
spawnPrefetchSubtask( spawnPrefetchSubtask(
fetchRouteOnCacheMiss(routeWithoutSearch, task, keyWithoutSearch) fetchRouteOnCacheMiss(routeWithoutSearch, keyWithoutSearch)
) )
} }
break break
...@@ -663,7 +664,7 @@ function pingRootRouteTree( ...@@ -663,7 +664,7 @@ function pingRootRouteTree(
// behavior if PPR is disabled for a route (via the incremental opt-in). // behavior if PPR is disabled for a route (via the incremental opt-in).
// //
// Those cases will be handled here. // Those cases will be handled here.
spawnPrefetchSubtask(fetchRouteOnCacheMiss(route, task, task.key)) spawnPrefetchSubtask(fetchRouteOnCacheMiss(route, task.key))
// If the request takes longer than a minute, a subsequent request should // If the request takes longer than a minute, a subsequent request should
// retry instead of waiting for this one. When the response is received, // retry instead of waiting for this one. When the response is received,
...@@ -1347,11 +1348,22 @@ function pingRouteTreeAndIncludeDynamicData( ...@@ -1347,11 +1348,22 @@ function pingRouteTreeAndIncludeDynamicData(
fetchStrategy fetchStrategy
) )
) { ) {
// The cached segment contains dynamic holes, and was prefetched using a less specific strategy than the current one. // The cached segment contains dynamic holes, and was prefetched using a
// This means we're in one of these cases: // less specific strategy than the current one. This means we're in one
// of these cases:
// - we have a static prefetch, and we're doing a runtime prefetch // - we have a static prefetch, and we're doing a runtime prefetch
// - we have a static or runtime prefetch, and we're doing a Full prefetch (or a navigation). // - we have a static or runtime prefetch, and we're doing a Full
// In either case, we need to include it in the request to get a more specific (or full) version. // prefetch (or a navigation).
// In either case, we need to include it in the request to get a more
// specific (or full) version. However, if there's a non-stale bfcache
// entry from a previous navigation, prefer that over making a new
// request.
if (fetchStrategy === FetchStrategy.Full) {
const fulfilled = attemptToUpgradeSegmentFromBFCache(now, tree)
if (fulfilled !== null) {
break
}
}
spawnedSegment = pingFullSegmentRevalidation(now, tree, fetchStrategy) spawnedSegment = pingFullSegmentRevalidation(now, tree, fetchStrategy)
} }
break break
......
...@@ -7,6 +7,7 @@ import type { ...@@ -7,6 +7,7 @@ import type {
FlightRouterState, FlightRouterState,
CacheNodeSeedData, CacheNodeSeedData,
RSCPayload, RSCPayload,
NavigationFlightResponse,
FlightData, FlightData,
InitialRSCPayload, InitialRSCPayload,
FlightDataPath, FlightDataPath,
...@@ -304,14 +305,9 @@ function maybeAppendBuildIdToRSCPayload<T extends RSCPayload>( ...@@ -304,14 +305,9 @@ function maybeAppendBuildIdToRSCPayload<T extends RSCPayload>(
if (!ctx.sharedContext.deploymentId) { if (!ctx.sharedContext.deploymentId) {
// When using the build id, we need to initialize the id on initial page load, so a build id // When using the build id, we need to initialize the id on initial page load, so a build id
// header wouldn't be enough. // header wouldn't be enough.
return { payload.b = ctx.sharedContext.buildId
...payload,
b: ctx.sharedContext.buildId,
}
} else {
// We rely on a response header
return payload
} }
return payload
} }
interface ParseRequestHeadersOptions { interface ParseRequestHeadersOptions {
...@@ -510,6 +506,7 @@ async function generateDynamicRSCPayload( ...@@ -510,6 +506,7 @@ async function generateDynamicRSCPayload(
actionResult?: ActionResult actionResult?: ActionResult
skipPageRendering?: boolean skipPageRendering?: boolean
staleTimeIterable?: AsyncIterable<number> staleTimeIterable?: AsyncIterable<number>
staticStageByteLengthPromise?: Promise<number>
} }
): Promise<RSCPayload> { ): Promise<RSCPayload> {
// Flight data that is going to be passed to the browser. // Flight data that is going to be passed to the browser.
...@@ -630,19 +627,23 @@ async function generateDynamicRSCPayload( ...@@ -630,19 +627,23 @@ async function generateDynamicRSCPayload(
} }
// Otherwise, it's a regular RSC response. // Otherwise, it's a regular RSC response.
const baseResponse = maybeAppendBuildIdToRSCPayload(ctx, { const baseResponse: NavigationFlightResponse = maybeAppendBuildIdToRSCPayload(
f: flightData, ctx,
q: getRenderedSearch(query), {
i: !!couldBeIntercepted, f: flightData,
S: workStore.isStaticGeneration, q: getRenderedSearch(query),
h: getMetadataVaryParamsThenable(), i: !!couldBeIntercepted,
}) S: workStore.isStaticGeneration,
h: getMetadataVaryParamsThenable(),
}
)
if (options?.staleTimeIterable !== undefined) { if (options?.staleTimeIterable !== undefined) {
return { baseResponse.s = options.staleTimeIterable
...baseResponse, }
s: options.staleTimeIterable,
} if (options?.staticStageByteLengthPromise !== undefined) {
baseResponse.l = options.staticStageByteLengthPromise
} }
return baseResponse return baseResponse
...@@ -740,6 +741,110 @@ async function generateDynamicFlightRenderResult( ...@@ -740,6 +741,110 @@ async function generateDynamicFlightRenderResult(
) )
} }
/**
* Production-only staged dynamic flight render for cache components. Uses
* staged rendering to separate static (RDC-backed) from runtime/dynamic
* content.
*/
async function generateStagedDynamicFlightRenderResult(
req: BaseNextRequest,
ctx: AppRenderContext,
requestStore: RequestStore
): Promise<RenderResult> {
const { componentMod, workStore, renderOpts } = ctx
const { renderToReadableStream } = componentMod
const { onInstrumentationRequestError, experimental } = renderOpts
function onFlightDataRenderError(err: DigestedError, silenceLog: boolean) {
return onInstrumentationRequestError?.(
err,
req,
createErrorContext(ctx, 'react-server-components-payload'),
silenceLog
)
}
const onError = createReactServerErrorHandler(
false,
false,
workStore.reactServerErrorsByDigest,
onFlightDataRenderError
)
const selectStaleTime = createSelectStaleTime(experimental)
const staleTimeIterable = new StaleTimeIterable()
const stageController = new StagedRenderingController()
// Initialize stale time tracking on the request store.
requestStore.stale = INFINITE_CACHE
requestStore.stagedRendering = stageController
requestStore.asyncApiPromises = createAsyncApiPromisesInDev(
stageController,
requestStore.cookies,
requestStore.mutableCookies,
requestStore.headers
)
trackStaleTime(
requestStore as { stale: number },
staleTimeIterable,
selectStaleTime
)
// Deferred promise for the static stage byte length. Flight serializes the
// resolved value into the stream so the client knows where the static
// prefix ends.
let resolveStaticStageByteLength: (count: number) => void
const staticStageByteLengthPromise = new Promise<number>((resolve) => {
resolveStaticStageByteLength = resolve
})
const rscPayload = await workUnitAsyncStorage.run(
requestStore,
generateDynamicRSCPayload,
ctx,
{ staleTimeIterable, staticStageByteLengthPromise }
)
const { clientModules } = getClientReferenceManifest()
const flightReadableStream = await runInSequentialTasks(
() => {
stageController.advanceStage(RenderStage.Static)
const stream = workUnitAsyncStorage.run(
requestStore,
renderToReadableStream,
rscPayload,
clientModules,
{ onError, filterStackFrame }
)
const [dynamicStream, staticStream] = stream.tee()
countStaticStageBytes(staticStream, stageController).then(
resolveStaticStageByteLength
)
return dynamicStream
},
() => {
// This is a separate task that doesn't advance a stage. It forces
// draining the microtask queue so that the stale time iterable is closed
// before we advance to the dynamic stage.
void finishStaleTimeTracking(staleTimeIterable)
},
() => {
stageController.advanceStage(RenderStage.Dynamic)
}
)
return new FlightRenderResult(flightReadableStream, {
fetchMetrics: workStore.fetchMetrics,
})
}
type RenderToReadableStreamServerOptions = NonNullable< type RenderToReadableStreamServerOptions = NonNullable<
Parameters< Parameters<
(typeof import('react-server-dom-webpack/server.node'))['renderToReadableStream'] (typeof import('react-server-dom-webpack/server.node'))['renderToReadableStream']
...@@ -821,7 +926,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev( ...@@ -821,7 +926,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
ctx: AppRenderContext, ctx: AppRenderContext,
initialRequestStore: RequestStore, initialRequestStore: RequestStore,
createRequestStore: (() => RequestStore) | undefined, createRequestStore: (() => RequestStore) | undefined,
devFallbackParams: OpaqueFallbackRouteParams | null fallbackParams: OpaqueFallbackRouteParams | null
): Promise<RenderResult> { ): Promise<RenderResult> {
const { const {
htmlRequestId, htmlRequestId,
...@@ -944,7 +1049,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev( ...@@ -944,7 +1049,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
runtimeStageEndTime, runtimeStageEndTime,
ctx, ctx,
finalRequestStore, finalRequestStore,
devFallbackParams, fallbackParams,
validationDebugChannelClient validationDebugChannelClient
) )
} else { } else {
...@@ -2150,7 +2255,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -2150,7 +2255,7 @@ async function renderToHTMLOrFlightImpl(
null null
const rootParams = getRootParams(loaderTree, ctx.getDynamicParamFromSegment) const rootParams = getRootParams(loaderTree, ctx.getDynamicParamFromSegment)
const devFallbackParams = getRequestMeta(req, 'devFallbackParams') || null const fallbackParams = getRequestMeta(req, 'fallbackParams') || null
const createRequestStore = createRequestStoreForRender.bind( const createRequestStore = createRequestStoreForRender.bind(
null, null,
...@@ -2164,7 +2269,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -2164,7 +2269,7 @@ async function renderToHTMLOrFlightImpl(
isHmrRefresh, isHmrRefresh,
serverComponentsHmrCache, serverComponentsHmrCache,
renderResumeDataCache, renderResumeDataCache,
devFallbackParams fallbackParams
) )
const requestStore = createRequestStore() const requestStore = createRequestStore()
...@@ -2200,8 +2305,10 @@ async function renderToHTMLOrFlightImpl( ...@@ -2200,8 +2305,10 @@ async function renderToHTMLOrFlightImpl(
ctx, ctx,
requestStore, requestStore,
createRequestStore, createRequestStore,
devFallbackParams fallbackParams
) )
} else if (cacheComponents) {
return generateStagedDynamicFlightRenderResult(req, ctx, requestStore)
} else { } else {
return generateDynamicFlightRenderResult(req, ctx, requestStore) return generateDynamicFlightRenderResult(req, ctx, requestStore)
} }
...@@ -2239,7 +2346,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -2239,7 +2346,7 @@ async function renderToHTMLOrFlightImpl(
postponedState, postponedState,
metadata, metadata,
undefined, // Prevent restartable-render behavior in dev + Cache Components mode undefined, // Prevent restartable-render behavior in dev + Cache Components mode
devFallbackParams fallbackParams
) )
return new RenderResult(stream, { return new RenderResult(stream, {
...@@ -2281,7 +2388,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -2281,7 +2388,7 @@ async function renderToHTMLOrFlightImpl(
// and we currently we don't copy changes over when creating a new store, // and we currently we don't copy changes over when creating a new store,
// so the restarted render wouldn't be correct. // so the restarted render wouldn't be correct.
didExecuteServerAction ? undefined : createRequestStore, didExecuteServerAction ? undefined : createRequestStore,
devFallbackParams fallbackParams
) )
// Invalid dynamic usages should only error the request in development. // Invalid dynamic usages should only error the request in development.
...@@ -2488,7 +2595,7 @@ async function renderToStream( ...@@ -2488,7 +2595,7 @@ async function renderToStream(
postponedState: PostponedState | null, postponedState: PostponedState | null,
metadata: AppPageRenderResultMetadata, metadata: AppPageRenderResultMetadata,
createRequestStore: (() => RequestStore) | undefined, createRequestStore: (() => RequestStore) | undefined,
devFallbackParams: OpaqueFallbackRouteParams | null fallbackParams: OpaqueFallbackRouteParams | null
): Promise<ReadableStream<Uint8Array>> { ): Promise<ReadableStream<Uint8Array>> {
/* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */ /* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */
const { const {
...@@ -2721,7 +2828,7 @@ async function renderToStream( ...@@ -2721,7 +2828,7 @@ async function renderToStream(
runtimeStageEndTime, runtimeStageEndTime,
ctx, ctx,
finalRequestStore, finalRequestStore,
devFallbackParams, fallbackParams,
validationDebugChannelClient validationDebugChannelClient
) )
...@@ -3469,6 +3576,33 @@ async function accumulateStreamChunks( ...@@ -3469,6 +3576,33 @@ async function accumulateStreamChunks(
return { staticChunks, runtimeChunks, dynamicChunks } return { staticChunks, runtimeChunks, dynamicChunks }
} }
async function countStaticStageBytes(
stream: ReadableStream<Uint8Array>,
stageController: StagedRenderingController
): Promise<number> {
let byteLength = 0
const reader = stream.getReader()
stageController.onStage(RenderStage.EarlyRuntime, () => {
reader.cancel()
})
while (true) {
const { done, value } = await reader.read()
if (done) {
break
}
if (stageController.currentStage <= RenderStage.Static) {
byteLength += value.byteLength
} else {
reader.cancel()
break
}
}
return byteLength
}
function createAsyncApiPromisesInDev( function createAsyncApiPromisesInDev(
stagedRendering: StagedRenderingController, stagedRendering: StagedRenderingController,
cookies: RequestStore['cookies'], cookies: RequestStore['cookies'],
......
...@@ -69,16 +69,18 @@ export interface RequestStore extends CommonWorkUnitStore { ...@@ -69,16 +69,18 @@ export interface RequestStore extends CommonWorkUnitStore {
*/ */
renderResumeDataCache: RenderResumeDataCache | null renderResumeDataCache: RenderResumeDataCache | null
// DEV-only stale?: number
usedDynamic?: boolean
devFallbackParams?: OpaqueFallbackRouteParams | null
stagedRendering?: StagedRenderingController | null stagedRendering?: StagedRenderingController | null
asyncApiPromises?: DevAsyncApiPromises asyncApiPromises?: AsyncApiPromises
cacheSignal?: CacheSignal | null cacheSignal?: CacheSignal | null
prerenderResumeDataCache?: PrerenderResumeDataCache | null prerenderResumeDataCache?: PrerenderResumeDataCache | null
fallbackParams?: OpaqueFallbackRouteParams | null
// DEV-only
usedDynamic?: boolean
} }
type DevAsyncApiPromises = { export type AsyncApiPromises = {
cookies: Promise<ReadonlyRequestCookies> cookies: Promise<ReadonlyRequestCookies>
earlyCookies: Promise<ReadonlyRequestCookies> earlyCookies: Promise<ReadonlyRequestCookies>
......
...@@ -116,7 +116,7 @@ export function createRequestStoreForRender( ...@@ -116,7 +116,7 @@ export function createRequestStoreForRender(
isHmrRefresh: RequestContext['isHmrRefresh'], isHmrRefresh: RequestContext['isHmrRefresh'],
serverComponentsHmrCache: RequestContext['serverComponentsHmrCache'], serverComponentsHmrCache: RequestContext['serverComponentsHmrCache'],
renderResumeDataCache: RenderResumeDataCache | null, renderResumeDataCache: RenderResumeDataCache | null,
devFallbackParams: OpaqueFallbackRouteParams | null fallbackParams: OpaqueFallbackRouteParams | null
): RequestStore { ): RequestStore {
return createRequestStoreImpl( return createRequestStoreImpl(
// Pages start in render phase by default // Pages start in render phase by default
...@@ -131,7 +131,7 @@ export function createRequestStoreForRender( ...@@ -131,7 +131,7 @@ export function createRequestStoreForRender(
previewProps, previewProps,
isHmrRefresh, isHmrRefresh,
serverComponentsHmrCache, serverComponentsHmrCache,
devFallbackParams fallbackParams
) )
} }
...@@ -171,7 +171,7 @@ function createRequestStoreImpl( ...@@ -171,7 +171,7 @@ function createRequestStoreImpl(
previewProps: WrapperRenderOpts['previewProps'], previewProps: WrapperRenderOpts['previewProps'],
isHmrRefresh: RequestContext['isHmrRefresh'], isHmrRefresh: RequestContext['isHmrRefresh'],
serverComponentsHmrCache: RequestContext['serverComponentsHmrCache'], serverComponentsHmrCache: RequestContext['serverComponentsHmrCache'],
devFallbackParams: OpaqueFallbackRouteParams | null | undefined fallbackParams: OpaqueFallbackRouteParams | null | undefined
): RequestStore { ): RequestStore {
function defaultOnUpdateCookies(cookies: string[]) { function defaultOnUpdateCookies(cookies: string[]) {
if (res) { if (res) {
...@@ -263,7 +263,7 @@ function createRequestStoreImpl( ...@@ -263,7 +263,7 @@ function createRequestStoreImpl(
serverComponentsHmrCache: serverComponentsHmrCache:
serverComponentsHmrCache || serverComponentsHmrCache ||
(globalThis as any).__serverComponentsHmrCache, (globalThis as any).__serverComponentsHmrCache,
devFallbackParams, fallbackParams,
} }
} }
......
...@@ -2360,7 +2360,7 @@ export default abstract class Server< ...@@ -2360,7 +2360,7 @@ export default abstract class Server<
if (smallestFallbackRouteParams) { if (smallestFallbackRouteParams) {
addRequestMeta( addRequestMeta(
req, req,
'devFallbackParams', 'fallbackParams',
createOpaqueFallbackRouteParams(smallestFallbackRouteParams)! createOpaqueFallbackRouteParams(smallestFallbackRouteParams)!
) )
} }
......
...@@ -852,9 +852,9 @@ export default class DevServer extends Server { ...@@ -852,9 +852,9 @@ export default class DevServer extends Server {
} }
// Since generateStaticParams run on the background, when accessing the // Since generateStaticParams run on the background, when accessing the
// devFallbackParams during the render, it is still set to the previous // fallbackParams during the render, it is still set to the previous
// result from the cache. Therefore when the result has changed, re-render // result from the cache. Therefore when the result has changed, re-render
// the Server Component to sync the devFallbackParams with the new result. // the Server Component to sync the fallbackParams with the new result.
if ( if (
isAppPath && isAppPath &&
this.nextConfig.cacheComponents && this.nextConfig.cacheComponents &&
......
...@@ -277,9 +277,10 @@ export interface RequestMeta { ...@@ -277,9 +277,10 @@ export interface RequestMeta {
minimalMode?: boolean minimalMode?: boolean
/** /**
* DEV only: The fallback params that should be used when validating prerenders during dev * The fallback params for this route. In dev, used for validating prerenders.
* In production, used to defer params resolution during staged rendering.
*/ */
devFallbackParams?: OpaqueFallbackRouteParams fallbackParams?: OpaqueFallbackRouteParams
/** /**
* DEV only: Request timings in process.hrtime.bigint() * DEV only: Request timings in process.hrtime.bigint()
......
...@@ -123,6 +123,8 @@ export function connection(): Promise<void> { ...@@ -123,6 +123,8 @@ export function connection(): Promise<void> {
workUnitStore, workUnitStore,
RenderStage.Dynamic RenderStage.Dynamic
) )
} else if (workUnitStore.asyncApiPromises) {
return workUnitStore.asyncApiPromises.connection
} else { } else {
return Promise.resolve(undefined) return Promise.resolve(undefined)
} }
......
...@@ -130,6 +130,17 @@ export function cookies(): Promise<ReadonlyRequestCookies> { ...@@ -130,6 +130,17 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
underlyingCookies, underlyingCookies,
workStore?.route workStore?.route
) )
} else if (workUnitStore.asyncApiPromises) {
const early = isInEarlyRenderStage(workUnitStore)
if (underlyingCookies === workUnitStore.mutableCookies) {
return early
? workUnitStore.asyncApiPromises.earlyMutableCookies
: workUnitStore.asyncApiPromises.mutableCookies
} else {
return early
? workUnitStore.asyncApiPromises.earlyCookies
: workUnitStore.asyncApiPromises.cookies
}
} else { } else {
return makeUntrackedCookies(underlyingCookies) return makeUntrackedCookies(underlyingCookies)
} }
......
...@@ -146,6 +146,10 @@ export function headers(): Promise<ReadonlyHeaders> { ...@@ -146,6 +146,10 @@ export function headers(): Promise<ReadonlyHeaders> {
workStore?.route, workStore?.route,
workUnitStore workUnitStore
) )
} else if (workUnitStore.asyncApiPromises) {
return isInEarlyRenderStage(workUnitStore)
? workUnitStore.asyncApiPromises.earlyHeaders
: workUnitStore.asyncApiPromises.headers
} else { } else {
return makeUntrackedHeaders(workUnitStore.headers) return makeUntrackedHeaders(workUnitStore.headers)
} }
......
...@@ -84,12 +84,12 @@ export function createParamsFromClient( ...@@ -84,12 +84,12 @@ export function createParamsFromClient(
// Semantically we only need the dev tracking when running in `next dev` // Semantically we only need the dev tracking when running in `next dev`
// but since you would never use next dev with production NODE_ENV we use this // but since you would never use next dev with production NODE_ENV we use this
// as a proxy so we can statically exclude this code from production builds. // as a proxy so we can statically exclude this code from production builds.
const devFallbackParams = workUnitStore.devFallbackParams const fallbackParams = workUnitStore.fallbackParams
// Client params are not runtime prefetchable // Client params are not runtime prefetchable
const isRuntimePrefetchable = false const isRuntimePrefetchable = false
return createRenderParamsInDev( return createRenderParamsInDev(
underlyingParams, underlyingParams,
devFallbackParams, fallbackParams,
workStore, workStore,
workUnitStore, workUnitStore,
isRuntimePrefetchable isRuntimePrefetchable
...@@ -169,12 +169,12 @@ export function createServerParamsForRoute( ...@@ -169,12 +169,12 @@ export function createServerParamsForRoute(
// Semantically we only need the dev tracking when running in `next dev` // Semantically we only need the dev tracking when running in `next dev`
// but since you would never use next dev with production NODE_ENV we use this // but since you would never use next dev with production NODE_ENV we use this
// as a proxy so we can statically exclude this code from production builds. // as a proxy so we can statically exclude this code from production builds.
const devFallbackParams = workUnitStore.devFallbackParams const fallbackParams = workUnitStore.fallbackParams
// Route params are not runtime prefetchable // Route params are not runtime prefetchable
const isRuntimePrefetchable = false const isRuntimePrefetchable = false
return createRenderParamsInDev( return createRenderParamsInDev(
underlyingParams, underlyingParams,
devFallbackParams, fallbackParams,
workStore, workStore,
workUnitStore, workUnitStore,
isRuntimePrefetchable isRuntimePrefetchable
...@@ -235,14 +235,23 @@ export function createServerParamsForServerSegment( ...@@ -235,14 +235,23 @@ export function createServerParamsForServerSegment(
// Semantically we only need the dev tracking when running in `next dev` // Semantically we only need the dev tracking when running in `next dev`
// but since you would never use next dev with production NODE_ENV we use this // but since you would never use next dev with production NODE_ENV we use this
// as a proxy so we can statically exclude this code from production builds. // as a proxy so we can statically exclude this code from production builds.
const devFallbackParams = workUnitStore.devFallbackParams const fallbackParams = workUnitStore.fallbackParams
return createRenderParamsInDev( return createRenderParamsInDev(
underlyingParams, underlyingParams,
devFallbackParams, fallbackParams,
workStore, workStore,
workUnitStore, workUnitStore,
isRuntimePrefetchable isRuntimePrefetchable
) )
} else if (
workUnitStore.asyncApiPromises &&
hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)
) {
return (
isRuntimePrefetchable
? workUnitStore.asyncApiPromises.earlySharedParamsParent
: workUnitStore.asyncApiPromises.sharedParamsParent
).then(() => underlyingParams)
} else { } else {
return createRenderParamsInProd(underlyingParams) return createRenderParamsInProd(underlyingParams)
} }
...@@ -398,30 +407,34 @@ function createRuntimePrerenderParams( ...@@ -398,30 +407,34 @@ function createRuntimePrerenderParams(
return stagedRendering.waitForStage(stage).then(() => result) return stagedRendering.waitForStage(stage).then(() => result)
} }
function hasFallbackRouteParams(
underlyingParams: Params,
fallbackParams: OpaqueFallbackRouteParams | null | undefined
): boolean {
if (fallbackParams) {
for (let key in underlyingParams) {
if (fallbackParams.has(key)) {
return true
}
}
}
return false
}
function createRenderParamsInProd(underlyingParams: Params): Promise<Params> { function createRenderParamsInProd(underlyingParams: Params): Promise<Params> {
return makeUntrackedParams(underlyingParams) return makeUntrackedParams(underlyingParams)
} }
function createRenderParamsInDev( function createRenderParamsInDev(
underlyingParams: Params, underlyingParams: Params,
devFallbackParams: OpaqueFallbackRouteParams | null | undefined, fallbackParams: OpaqueFallbackRouteParams | null | undefined,
workStore: WorkStore, workStore: WorkStore,
requestStore: RequestStore, requestStore: RequestStore,
isRuntimePrefetchable: boolean isRuntimePrefetchable: boolean
): Promise<Params> { ): Promise<Params> {
let hasFallbackParams = false
if (devFallbackParams) {
for (let key in underlyingParams) {
if (devFallbackParams.has(key)) {
hasFallbackParams = true
break
}
}
}
return makeDynamicallyTrackedParamsWithDevWarnings( return makeDynamicallyTrackedParamsWithDevWarnings(
underlyingParams, underlyingParams,
hasFallbackParams, hasFallbackRouteParams(underlyingParams, fallbackParams),
workStore, workStore,
requestStore, requestStore,
isRuntimePrefetchable isRuntimePrefetchable
......
...@@ -265,6 +265,12 @@ function createRenderSearchParams( ...@@ -265,6 +265,12 @@ function createRenderSearchParams(
requestStore, requestStore,
isRuntimePrefetchable isRuntimePrefetchable
) )
} else if (requestStore.asyncApiPromises) {
return (
isRuntimePrefetchable
? requestStore.asyncApiPromises.earlySharedSearchParamsParent
: requestStore.asyncApiPromises.sharedSearchParamsParent
).then(() => underlyingSearchParams)
} else { } else {
return makeUntrackedSearchParams(underlyingSearchParams) return makeUntrackedSearchParams(underlyingSearchParams)
} }
......
...@@ -352,6 +352,15 @@ function propagateCacheLifeAndTagsToRevalidateStore( ...@@ -352,6 +352,15 @@ function propagateCacheLifeAndTagsToRevalidateStore(
} }
} }
function propagateCacheStaleTimeToRequestStore(
requestStore: RequestStore,
entry: CacheEntry
): void {
if (requestStore.stale !== undefined && requestStore.stale > entry.stale) {
requestStore.stale = entry.stale
}
}
function propagateCacheLifeAndTags( function propagateCacheLifeAndTags(
cacheContext: CacheContext, cacheContext: CacheContext,
entry: CacheEntry entry: CacheEntry
...@@ -366,6 +375,11 @@ function propagateCacheLifeAndTags( ...@@ -366,6 +375,11 @@ function propagateCacheLifeAndTags(
) )
break break
case 'request': case 'request':
propagateCacheStaleTimeToRequestStore(
cacheContext.outerWorkUnitStore,
entry
)
break
case undefined: case undefined:
break break
default: default:
...@@ -385,6 +399,11 @@ function propagateCacheLifeAndTags( ...@@ -385,6 +399,11 @@ function propagateCacheLifeAndTags(
) )
break break
case 'request': case 'request':
propagateCacheStaleTimeToRequestStore(
cacheContext.outerWorkUnitStore,
entry
)
break
case 'unstable-cache': case 'unstable-cache':
case undefined: case undefined:
break break
......
...@@ -278,6 +278,8 @@ export type NavigationFlightResponse = { ...@@ -278,6 +278,8 @@ export type NavigationFlightResponse = {
i: boolean i: boolean
/** staleTime - Only present in dynamic runtime prefetch responses. */ /** staleTime - Only present in dynamic runtime prefetch responses. */
s?: AsyncIterable<number> s?: AsyncIterable<number>
/** staticStageByteLength - Resolves when the static stage ends. */
l?: Promise<number>
/** headVaryParams */ /** headVaryParams */
h: VaryParamsThenable | null h: VaryParamsThenable | null
} }
......
import { cacheLife } from 'next/cache'
export default async function Page() {
return (
<main>
<CachedContent />
</main>
)
}
async function CachedContent() {
'use cache'
cacheLife({ stale: 120 })
return <p id="cached-content">Cached content</p>
}
import Link from 'next/link'
import { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html>
<body>
<nav>
<Link href="/">Home</Link>
</nav>
{children}
</body>
</html>
)
}
import Link from 'next/link'
export default function Home() {
return (
<main>
<h1>Home</h1>
<h2>
Links with <code>prefetch=false</code>
</h2>
<ul>
<li>
<Link href="/partially-static" prefetch={false}>
Go to partially static page
</Link>
</li>
<li>
<Link href="/fully-static" prefetch={false}>
Go to fully static page
</Link>
</li>
<li>
<Link href="/with-static-params/foo" prefetch={false}>
Go to page with static params
</Link>
</li>
<li>
<Link href="/with-fallback-params/foo" prefetch={false}>
Go to page with fallback params
</Link>
</li>
</ul>
</main>
)
}
import { cacheLife } from 'next/cache'
import { cookies, headers } from 'next/headers'
import { connection } from 'next/server'
import { Suspense } from 'react'
export default async function Page({
searchParams,
}: {
searchParams: Promise<{ q?: string }>
}) {
return (
<main>
<CachedContent />
<div id="search-params-boundary">
<Suspense fallback={<p>Loading search params...</p>}>
<SearchParamsContent searchParams={searchParams} />
</Suspense>
</div>
<div id="cookies-boundary">
<Suspense fallback={<p>Loading cookies...</p>}>
<CookiesContent />
</Suspense>
</div>
<div id="headers-boundary">
<Suspense fallback={<p>Loading headers...</p>}>
<HeadersContent />
</Suspense>
</div>
<div id="connection-boundary">
<Suspense fallback={<p>Loading connection...</p>}>
<ConnectionContent />
</Suspense>
</div>
</main>
)
}
async function CachedContent() {
'use cache'
cacheLife({ stale: 120 })
return <p id="cached-content">Cached content</p>
}
async function SearchParamsContent({
searchParams,
}: {
searchParams: Promise<{ q?: string }>
}) {
const { q } = await searchParams
return <p>Search params: {q ?? 'none'}</p>
}
async function CookiesContent() {
const cookieStore = await cookies()
const value = cookieStore.get('testCookie')?.value ?? 'none'
const timestamp = await getShortLivedCachedTimestamp()
return (
<p>
Cookie: {value}, Cached at: {timestamp}
</p>
)
}
async function getShortLivedCachedTimestamp() {
'use cache'
cacheLife({ stale: 30 })
return Date.now()
}
async function HeadersContent() {
const headerStore = await headers()
const value = headerStore.get('x-test-header') ?? 'none'
return <p>Header: {value}</p>
}
async function ConnectionContent() {
await connection()
return <p>Dynamic content</p>
}
import { cacheLife } from 'next/cache'
import { connection } from 'next/server'
import { Suspense } from 'react'
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'
cacheLife({ stale: 120 })
return <p id="cached-content">Cached content</p>
}
async function ParamsContent({
params,
}: {
params: Promise<{ slug: string }>
}) {
// When the param is a fallback param (not in generateStaticParams), the
// await is deferred to the runtime stage, so this content won't appear
// in the static stage.
const { slug } = await params
return <p>Param: {slug}</p>
}
async function ConnectionContent() {
await connection()
return <p>Dynamic content</p>
}
import { connection } from 'next/server'
import { Suspense } from 'react'
export async function generateStaticParams() {
return [{ slug: 'foo' }]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return (
<main>
<CachedContent />
<div id="params">
<p>Param: {slug}</p>
</div>
<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</p>
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
productionBrowserSourceMaps: true,
experimental: {
exposeTestingApiInProductionBuild: true,
},
}
export default nextConfig
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