Unverified Commit 5b6747ad authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Prerender HTTP access fallbacks with Cache Components semantics (#93988)

The body of `if (cacheComponents)` in `prerenderToStream` is extracted
into a local helper, `prerenderWithCacheComponents(getPayload)`. The
catch-block error paths now route through that helper whenever Cache
Components is enabled, which means the legacy `prerender-legacy` store
is no longer reachable from a Cache Components prerender.

As a result, `notFound()`, `forbidden()`, and `unauthorized()` recovery
renders the matching fallback boundary under `prerender` and
`prerender-client` semantics. Dynamic API access in those boundaries —
for example `useSearchParams()` without a surrounding `<Suspense>` — now
surfaces as a blocking-route error instead of the legacy
`BailoutToCSRError`.

The dev side will be handled in a follow-up. The prerender handling
diverged a bit from the dev rendering in #92231, and we'll likely need
to re-align the dev rendering first.

> [!TIP]
> Best reviewed with hidden whitespace changes.
parent fda6986b
...@@ -5603,6 +5603,15 @@ async function spawnStaticShellValidationInDev( ...@@ -5603,6 +5603,15 @@ async function spawnStaticShellValidationInDev(
* While it doesn't return a stream we want it to have identical * While it doesn't return a stream we want it to have identical
* prerender semantics to prerenderToStream and should update it * prerender semantics to prerenderToStream and should update it
* in conjunction with any changes to that function. * in conjunction with any changes to that function.
*
* TODO: HTTP access fallback recovery (`notFound()` / `forbidden()` /
* `unauthorized()`) has been moved to use Cache Components prerender
* semantics in `prerenderToStream` via `prerenderWithCacheComponents`.
* This dev validation path still only validates the page tree, not the
* fallback boundary, so dynamic API access in `not-found.tsx` etc. is
* not yet observed by the dev redbox. Re-validate against the fallback
* boundary tree when an `HTTPAccessFallbackError` surfaces from the
* upstream RSC render to match the build-time behavior.
*/ */
async function spawnStaticShellValidationInDevImpl( async function spawnStaticShellValidationInDevImpl(
accumulatedChunksPromise: Promise<AccumulatedStreamChunks>, accumulatedChunksPromise: Promise<AccumulatedStreamChunks>,
...@@ -7313,8 +7322,9 @@ async function prerenderToStream( ...@@ -7313,8 +7322,9 @@ async function prerenderToStream(
let prerenderStore: PrerenderStore | null = null let prerenderStore: PrerenderStore | null = null
try { const prerenderWithCacheComponents = async (
if (cacheComponents) { getPayload: () => Promise<InitialRSCPayload>
): Promise<PrerenderToStreamResult> => {
/** /**
* cacheComponents with PPR * cacheComponents with PPR
* *
...@@ -7396,10 +7406,7 @@ async function prerenderToStream( ...@@ -7396,10 +7406,7 @@ async function prerenderToStream(
// is if it completes in a microtask and that's likely very rare for any non-trivial app // is if it completes in a microtask and that's likely very rare for any non-trivial app
const initialServerPayload = await workUnitAsyncStorage.run( const initialServerPayload = await workUnitAsyncStorage.run(
initialServerPayloadPrerenderStore, initialServerPayloadPrerenderStore,
getRSCPayload, getPayload
tree,
ctx,
{ is404: res.statusCode === 404 }
) )
const initialServerPrerenderStore: PrerenderStore = (prerenderStore = { const initialServerPrerenderStore: PrerenderStore = (prerenderStore = {
...@@ -7676,10 +7683,7 @@ async function prerenderToStream( ...@@ -7676,10 +7683,7 @@ async function prerenderToStream(
const finalAttemptRSCPayload = await workUnitAsyncStorage.run( const finalAttemptRSCPayload = await workUnitAsyncStorage.run(
finalServerPayloadPrerenderStore, finalServerPayloadPrerenderStore,
getRSCPayload, getPayload
tree,
ctx,
{ is404: res.statusCode === 404 }
) )
let staleTimeIterable: StaleTimeIterable | undefined let staleTimeIterable: StaleTimeIterable | undefined
...@@ -7832,8 +7836,7 @@ async function prerenderToStream( ...@@ -7832,8 +7836,7 @@ async function prerenderToStream(
const finalClientOnHeaders = createOnHeadersCallback(appendHeader) const finalClientOnHeaders = createOnHeadersCallback(appendHeader)
let { prelude: unprocessedPrelude, postponed } = let { prelude: unprocessedPrelude, postponed } = await runInSequentialTasks(
await runInSequentialTasks(
() => { () => {
const pendingFinalClientResult = workUnitAsyncStorage.run( const pendingFinalClientResult = workUnitAsyncStorage.run(
finalClientPrerenderStore, finalClientPrerenderStore,
...@@ -7855,9 +7858,8 @@ async function prerenderToStream( ...@@ -7855,9 +7858,8 @@ async function prerenderToStream(
isPrerenderInterruptedError(err) || isPrerenderInterruptedError(err) ||
finalClientReactController.signal.aborted finalClientReactController.signal.aborted
) { ) {
const componentStack: string | undefined = ( const componentStack: string | undefined = (errorInfo as any)
errorInfo as any .componentStack
).componentStack
if (typeof componentStack === 'string') { if (typeof componentStack === 'string') {
trackAllowedDynamicAccess( trackAllowedDynamicAccess(
workStore, workStore,
...@@ -8092,6 +8094,13 @@ async function prerenderToStream( ...@@ -8092,6 +8094,13 @@ async function prerenderToStream(
), ),
} }
} }
}
try {
if (cacheComponents) {
return await prerenderWithCacheComponents(() =>
getRSCPayload(tree, ctx, { is404: res.statusCode === 404 })
)
} else if (experimental.isRoutePPREnabled) { } else if (experimental.isRoutePPREnabled) {
// We're statically generating with PPR and need to do dynamic tracking // We're statically generating with PPR and need to do dynamic tracking
let dynamicTracking = createDynamicTrackingState(isDebugDynamicAccesses) let dynamicTracking = createDynamicTrackingState(isDebugDynamicAccesses)
...@@ -8491,6 +8500,59 @@ async function prerenderToStream( ...@@ -8491,6 +8500,59 @@ async function prerenderToStream(
metadata.statusCode = res.statusCode metadata.statusCode = res.statusCode
} }
if (cacheComponents) {
// Route the recovery render through the Cache Components prerender helper
// to prerender with CC semantics. This ensures for example that dynamic
// API access in the HTTP fallback boundary (e.g. `useSearchParams()` in
// `not-found.tsx`) is observed by the helper's dynamic validation and
// surfaces as a blocking-route error rather than the legacy
// `BailoutToCSRError`. For recoveries that render the synthetic error
// shell from `getErrorRSCPayload` (generic `Error`, `RedirectError`,
// `HTTPAccessFallbackError` with no matching boundary), the helper still
// runs but no user code participates in the SSR — `global-error.tsx` is
// plumbed into the payload but its `RootErrorBoundary` is never triggered
// because the synthetic shell can't throw. We still route synthetic-shell
// recoveries through the helper for consistency so legacy prerendering is
// never used when Cache Components is on.
let prerenderHTTPError: PrerenderHTTPErrorState | undefined
if (isHTTPAccessFallbackError(err)) {
const triggeredStatus = getAccessFallbackHTTPStatus(
err
) as HTTPAccessErrorStatusCode
const boundaryTree = findPrerenderHTTPErrorBoundaryTree(
tree,
triggeredStatus,
ctx.renderOpts.experimental.authInterrupts
)
if (boundaryTree) {
prerenderHTTPError = {
boundaryTree,
triggeredStatus,
}
}
}
if (prerenderHTTPError) {
return await prerenderWithCacheComponents(() =>
getRSCPayload(tree, ctx, {
is404: errorType === 'not-found',
prerenderHTTPError,
})
)
}
return await prerenderWithCacheComponents(() =>
getErrorRSCPayload(
tree,
ctx,
reactServerErrorsByDigest.has((err as any).digest) ? undefined : err,
errorType
)
)
}
const [errorPreinitScripts, errorBootstrapScript] = getRequiredScripts( const [errorPreinitScripts, errorBootstrapScript] = getRequiredScripts(
buildManifest, buildManifest,
assetPrefix, assetPrefix,
...@@ -8520,37 +8582,8 @@ async function prerenderToStream( ...@@ -8520,37 +8582,8 @@ async function prerenderToStream(
: INFINITE_CACHE, : INFINITE_CACHE,
tags: [...(prerenderStore?.tags || implicitTags.tags)], tags: [...(prerenderStore?.tags || implicitTags.tags)],
}) })
let prerenderHTTPError: PrerenderHTTPErrorState | undefined
if (cacheComponents && isHTTPAccessFallbackError(err)) {
const triggeredStatus = getAccessFallbackHTTPStatus(
err
) as HTTPAccessErrorStatusCode
const boundaryTree = findPrerenderHTTPErrorBoundaryTree(
tree,
triggeredStatus,
ctx.renderOpts.experimental.authInterrupts
)
if (boundaryTree) { const errorRSCPayload = await workUnitAsyncStorage.run(
prerenderHTTPError = {
boundaryTree,
triggeredStatus,
}
}
}
const errorRSCPayload = prerenderHTTPError
? await workUnitAsyncStorage.run(
prerenderLegacyStore,
getRSCPayload,
tree,
ctx,
{
is404: errorType === 'not-found',
prerenderHTTPError,
}
)
: await workUnitAsyncStorage.run(
prerenderLegacyStore, prerenderLegacyStore,
getErrorRSCPayload, getErrorRSCPayload,
tree, tree,
...@@ -8559,7 +8592,7 @@ async function prerenderToStream( ...@@ -8559,7 +8592,7 @@ async function prerenderToStream(
errorType errorType
) )
const errorServerStreamRaw = workUnitAsyncStorage.run( const errorServerStream = workUnitAsyncStorage.run(
prerenderLegacyStore, prerenderLegacyStore,
renderFlightStream, renderFlightStream,
ComponentMod, ComponentMod,
...@@ -8571,19 +8604,6 @@ async function prerenderToStream( ...@@ -8571,19 +8604,6 @@ async function prerenderToStream(
} }
) )
let errorServerStream = errorServerStreamRaw
const errorFlightResultPromise = prerenderHTTPError
? (() => {
// Fizz still needs to read the Flight stream to render ErrorApp, but
// the prerender path also needs a buffered Flight result for the HTML
// prelude and segment data collectors. Tee the stream so each consumer
// gets its own copy.
const [appStream, flightStream] = teeStream(errorServerStreamRaw)
errorServerStream = appStream
return createReactServerPrerenderResultFromRender(flightStream)
})()
: null
try { try {
const { stream: errorHtmlStream } = await workUnitAsyncStorage.run( const { stream: errorHtmlStream } = await workUnitAsyncStorage.run(
prerenderLegacyStore, prerenderLegacyStore,
...@@ -8604,15 +8624,10 @@ async function prerenderToStream( ...@@ -8604,15 +8624,10 @@ async function prerenderToStream(
{ waitForAllReady: true } { waitForAllReady: true }
) )
const resolvedFlightResult = errorFlightResultPromise
? await errorFlightResultPromise
: reactServerPrerenderResult
if (errorFlightResultPromise) {
reactServerPrerenderResult.consume()
}
if (shouldGenerateStaticFlightData(workStore)) { if (shouldGenerateStaticFlightData(workStore)) {
const flightData = await streamToBuffer(resolvedFlightResult.asStream()) const flightData = await streamToBuffer(
reactServerPrerenderResult.asStream()
)
metadata.flightData = flightData metadata.flightData = flightData
await collectSegmentData( await collectSegmentData(
flightData, flightData,
...@@ -8624,14 +8639,12 @@ async function prerenderToStream( ...@@ -8624,14 +8639,12 @@ async function prerenderToStream(
) )
} }
const flightStream = resolvedFlightResult.consumeAsStream()
return { return {
digestErrorsMap: reactServerErrorsByDigest, digestErrorsMap: reactServerErrorsByDigest,
ssrErrors: allCapturedErrors, ssrErrors: allCapturedErrors,
stream: await continueFizzStream(errorHtmlStream, { stream: await continueFizzStream(errorHtmlStream, {
inlinedDataStream: createInlinedDataStream( inlinedDataStream: createInlinedDataStream(
flightStream, reactServerPrerenderResult.consumeAsStream(),
nonce, nonce,
formState formState
), ),
......
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