Unverified Commit 3d98505a authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

[backport] fix: preserve HTTP access fallbacks during prerender recovery (#93470)

Backports:

- #92231

---------
Co-authored-by: 's avatarZack Tanner <1939140+ztanner@users.noreply.github.com>
Co-authored-by: 's avatarAndrew Clark <git@andrewclark.io>
parent bb5ada6e
...@@ -110,7 +110,11 @@ import { ...@@ -110,7 +110,11 @@ import {
walkTreeWithFlightRouterState, walkTreeWithFlightRouterState,
createFullTreeFlightDataForNavigation, createFullTreeFlightDataForNavigation,
} from './walk-tree-with-flight-router-state' } from './walk-tree-with-flight-router-state'
import { createComponentTree, getRootParams } from './create-component-tree' import {
createComponentTree,
getRootParams,
type PrerenderHTTPErrorState,
} from './create-component-tree'
import { getAssetQueryString } from './get-asset-query-string' import { getAssetQueryString } from './get-asset-query-string'
import { import {
getClientReferenceManifest, getClientReferenceManifest,
...@@ -503,6 +507,54 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree { ...@@ -503,6 +507,54 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree {
] ]
} }
type HTTPAccessErrorStatusCode = 404 | 403 | 401
function hasPrerenderHTTPErrorBoundary(
loaderTree: LoaderTree,
triggeredStatus: HTTPAccessErrorStatusCode,
authInterrupts: boolean
): boolean {
switch (triggeredStatus) {
case 404:
return !!loaderTree[2]['not-found']
case 403:
return authInterrupts && !!loaderTree[2].forbidden
case 401:
return authInterrupts && !!loaderTree[2].unauthorized
default:
return false
}
}
function findPrerenderHTTPErrorBoundaryTree(
loaderTree: LoaderTree,
triggeredStatus: HTTPAccessErrorStatusCode,
authInterrupts: boolean
): LoaderTree | null {
let boundaryTree: LoaderTree | null = hasPrerenderHTTPErrorBoundary(
loaderTree,
triggeredStatus,
authInterrupts
)
? loaderTree
: null
const childrenTree = loaderTree[1].children
if (childrenTree) {
const deeperBoundaryTree = findPrerenderHTTPErrorBoundaryTree(
childrenTree,
triggeredStatus,
authInterrupts
)
if (deeperBoundaryTree) {
boundaryTree = deeperBoundaryTree
}
}
return boundaryTree
}
/** /**
* Returns a function that parses the dynamic segment and return the associated value. * Returns a function that parses the dynamic segment and return the associated value.
*/ */
...@@ -1702,6 +1754,9 @@ async function getRSCPayload( ...@@ -1702,6 +1754,9 @@ async function getRSCPayload(
ctx: AppRenderContext, ctx: AppRenderContext,
options: { options: {
is404: boolean is404: boolean
// When set, rerender a segment-scoped HTTP fallback inside the normal app
// router tree instead of falling back to the generic error shell payload.
prerenderHTTPError?: PrerenderHTTPErrorState
staleTimeIterable?: AsyncIterable<number> staleTimeIterable?: AsyncIterable<number>
staticStageByteLengthPromise?: Promise<number> staticStageByteLengthPromise?: Promise<number>
runtimePrefetchStream?: ReadableStream<Uint8Array> runtimePrefetchStream?: ReadableStream<Uint8Array>
...@@ -1709,6 +1764,7 @@ async function getRSCPayload( ...@@ -1709,6 +1764,7 @@ async function getRSCPayload(
): Promise<InitialRSCPayload & { P: ReactNode }> { ): Promise<InitialRSCPayload & { P: ReactNode }> {
const { const {
is404, is404,
prerenderHTTPError,
staleTimeIterable, staleTimeIterable,
staticStageByteLengthPromise, staticStageByteLengthPromise,
runtimePrefetchStream, runtimePrefetchStream,
...@@ -1776,6 +1832,7 @@ async function getRSCPayload( ...@@ -1776,6 +1832,7 @@ async function getRSCPayload(
preloadCallbacks, preloadCallbacks,
authInterrupts: ctx.renderOpts.experimental.authInterrupts, authInterrupts: ctx.renderOpts.experimental.authInterrupts,
MetadataOutlet, MetadataOutlet,
prerenderHTTPError,
}) })
// When the `vary` response header is present with `Next-URL`, that means there's a chance // When the `vary` response header is present with `Next-URL`, that means there's a chance
...@@ -7018,16 +7075,46 @@ async function prerenderToStream( ...@@ -7018,16 +7075,46 @@ async function prerenderToStream(
: INFINITE_CACHE, : INFINITE_CACHE,
tags: [...(prerenderStore?.tags || implicitTags.tags)], tags: [...(prerenderStore?.tags || implicitTags.tags)],
}) })
const errorRSCPayload = await workUnitAsyncStorage.run( let prerenderHTTPError: PrerenderHTTPErrorState | undefined
prerenderLegacyStore, if (cacheComponents && isHTTPAccessFallbackError(err)) {
getErrorRSCPayload, const triggeredStatus = getAccessFallbackHTTPStatus(
tree, err
ctx, ) as HTTPAccessErrorStatusCode
reactServerErrorsByDigest.has((err as any).digest) ? undefined : err, const boundaryTree = findPrerenderHTTPErrorBoundaryTree(
errorType tree,
) triggeredStatus,
ctx.renderOpts.experimental.authInterrupts
)
const errorServerStream = workUnitAsyncStorage.run( if (boundaryTree) {
prerenderHTTPError = {
boundaryTree,
triggeredStatus,
}
}
}
const errorRSCPayload = prerenderHTTPError
? await workUnitAsyncStorage.run(
prerenderLegacyStore,
getRSCPayload,
tree,
ctx,
{
is404: errorType === 'not-found',
prerenderHTTPError,
}
)
: await workUnitAsyncStorage.run(
prerenderLegacyStore,
getErrorRSCPayload,
tree,
ctx,
reactServerErrorsByDigest.has((err as any).digest) ? undefined : err,
errorType
)
const errorServerStreamRaw = workUnitAsyncStorage.run(
prerenderLegacyStore, prerenderLegacyStore,
renderToFlightStream, renderToFlightStream,
ComponentMod, ComponentMod,
...@@ -7039,6 +7126,19 @@ async function prerenderToStream( ...@@ -7039,6 +7126,19 @@ 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] = errorServerStreamRaw.tee()
errorServerStream = appStream
return createReactServerPrerenderResultFromRender(flightStream)
})()
: null
try { try {
const { stream: errorHtmlStream } = await workUnitAsyncStorage.run( const { stream: errorHtmlStream } = await workUnitAsyncStorage.run(
prerenderLegacyStore, prerenderLegacyStore,
...@@ -7058,10 +7158,15 @@ async function prerenderToStream( ...@@ -7058,10 +7158,15 @@ async function prerenderToStream(
} }
) )
const resolvedFlightResult = errorFlightResultPromise
? await errorFlightResultPromise
: reactServerPrerenderResult
if (errorFlightResultPromise) {
reactServerPrerenderResult.consume()
}
if (shouldGenerateStaticFlightData(workStore)) { if (shouldGenerateStaticFlightData(workStore)) {
const flightData = await streamToBuffer( const flightData = await streamToBuffer(resolvedFlightResult.asStream())
reactServerPrerenderResult.asStream()
)
metadata.flightData = flightData metadata.flightData = flightData
await collectSegmentData( await collectSegmentData(
flightData, flightData,
...@@ -7073,9 +7178,7 @@ async function prerenderToStream( ...@@ -7073,9 +7178,7 @@ async function prerenderToStream(
) )
} }
// This is intentionally using the readable datastream from the main const flightStream = resolvedFlightResult.consumeAsStream()
// render rather than the flight data from the error page render
const flightStream = reactServerPrerenderResult.consumeAsStream()
return { return {
digestErrorsMap: reactServerErrorsByDigest, digestErrorsMap: reactServerErrorsByDigest,
......
...@@ -246,8 +246,28 @@ export async function collectSegmentData( ...@@ -246,8 +246,28 @@ export async function collectSegmentData(
// Now that we've finished rendering the route tree, all the segment tasks // Now that we've finished rendering the route tree, all the segment tasks
// should have been spawned. Await them in parallel and write the segment // should have been spawned. Await them in parallel and write the segment
// prefetches to the result map. // prefetches to the result map.
let hasPageSegment = false
for (const [segmentPath, buffer] of await Promise.all(segmentTasks)) { for (const [segmentPath, buffer] of await Promise.all(segmentTasks)) {
resultMap.set(segmentPath, buffer) resultMap.set(segmentPath, buffer)
if (segmentPath.endsWith('__PAGE__')) {
hasPageSegment = true
}
}
if (!hasPageSegment) {
// The build requires at least one segment path ending with __PAGE__ to
// register the catch-all segment data route. When all page segments are
// disabled (e.g. every leaf has runtime prefetching), no __PAGE__ entry
// is emitted. Write a dummy entry with a path that doesn't match any
// real route segment so the client will never request it.
//
// TODO: Remove the __PAGE__ requirement from the build instead of
// working around it here. The invariant is outdated now that segments
// can be disabled.
resultMap.set(
'/todo-remove-fake-segment/__PAGE__' as SegmentRequestKey,
Buffer.alloc(0)
)
} }
return resultMap return resultMap
......
...@@ -44,6 +44,13 @@ import { ...@@ -44,6 +44,13 @@ import {
import type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config' import type { AppSegmentConfig } from '../../build/segment-config/app/app-segment-config'
import { RenderStage, type StagedRenderingController } from './staged-rendering' import { RenderStage, type StagedRenderingController } from './staged-rendering'
type HTTPAccessErrorStatusCode = 404 | 403 | 401
export type PrerenderHTTPErrorState = {
boundaryTree: LoaderTree
triggeredStatus: HTTPAccessErrorStatusCode
}
/** /**
* Use the provided loader tree to create the React Component tree. * Use the provided loader tree to create the React Component tree.
*/ */
...@@ -62,6 +69,7 @@ export function createComponentTree(props: { ...@@ -62,6 +69,7 @@ export function createComponentTree(props: {
preloadCallbacks: PreloadCallbacks preloadCallbacks: PreloadCallbacks
authInterrupts: boolean authInterrupts: boolean
MetadataOutlet: ComponentType MetadataOutlet: ComponentType
prerenderHTTPError?: PrerenderHTTPErrorState
}): Promise<CacheNodeSeedData> { }): Promise<CacheNodeSeedData> {
return getTracer().trace( return getTracer().trace(
NextNodeServerSpan.createComponentTree, NextNodeServerSpan.createComponentTree,
...@@ -99,6 +107,7 @@ async function createComponentTreeInternal( ...@@ -99,6 +107,7 @@ async function createComponentTreeInternal(
preloadCallbacks, preloadCallbacks,
authInterrupts, authInterrupts,
MetadataOutlet, MetadataOutlet,
prerenderHTTPError,
}: { }: {
loaderTree: LoaderTree loaderTree: LoaderTree
parentParams: Params parentParams: Params
...@@ -113,6 +122,7 @@ async function createComponentTreeInternal( ...@@ -113,6 +122,7 @@ async function createComponentTreeInternal(
preloadCallbacks: PreloadCallbacks preloadCallbacks: PreloadCallbacks
authInterrupts: boolean authInterrupts: boolean
MetadataOutlet: ComponentType | null MetadataOutlet: ComponentType | null
prerenderHTTPError?: PrerenderHTTPErrorState
}, },
isRoot: boolean isRoot: boolean
): Promise<CacheNodeSeedData> { ): Promise<CacheNodeSeedData> {
...@@ -595,28 +605,72 @@ async function createComponentTreeInternal( ...@@ -595,28 +605,72 @@ async function createComponentTreeInternal(
} }
} }
const seedData = await createComponentTreeInternal( // The outer prerender catch already found the deepest segment whose
{ // HTTP fallback should replace the throwing page. When we reach that
loaderTree: parallelRoute, // segment's `children` slot, render the fallback directly instead of
parentParams: currentParams, // descending back into the subtree that threw during deserialization.
parentOptionalCatchAllParamName: optionalCatchAllParamName,
parentRuntimePrefetchable: isRuntimePrefetchable, // Like the other segment-level boundary props below, HTTP access
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove, // fallbacks are attached to the default `children` slot, not to named
injectedCSS: injectedCSSWithCurrentLayout, // parallel routes.
injectedJS: injectedJSWithCurrentLayout, const shouldRenderPrerenderHTTPFallback =
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout, prerenderHTTPError?.boundaryTree === tree && isChildrenRouteKey
ctx,
missingSlots, if (shouldRenderPrerenderHTTPFallback) {
preloadCallbacks, let fallbackElement: React.ReactNode | undefined
authInterrupts, switch (prerenderHTTPError.triggeredStatus) {
// `StreamingMetadataOutlet` is used to conditionally throw. In the case of parallel routes we will have more than one page case 404:
// but we only want to throw on the first one. fallbackElement = notFoundElement
MetadataOutlet: isChildrenRouteKey ? MetadataOutlet : null, break
}, case 403:
false fallbackElement = forbiddenElement
) break
case 401:
fallbackElement = unauthorizedElement
break
default:
break
}
childCacheNodeSeedData = seedData if (fallbackElement) {
childCacheNodeSeedData = createSeedData(
ctx,
fallbackElement,
{},
null,
isPossiblyPartialResponse,
false,
emptyVaryParamsAccumulator
)
}
}
if (childCacheNodeSeedData === null) {
const seedData = await createComponentTreeInternal(
{
loaderTree: parallelRoute,
parentParams: currentParams,
parentOptionalCatchAllParamName: optionalCatchAllParamName,
parentRuntimePrefetchable: isRuntimePrefetchable,
rootLayoutIncluded: rootLayoutIncludedAtThisLevelOrAbove,
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
injectedFontPreloadTags:
injectedFontPreloadTagsWithCurrentLayout,
ctx,
missingSlots,
preloadCallbacks,
authInterrupts,
// `StreamingMetadataOutlet` is used to conditionally throw. In the case of parallel routes we will have more than one page
// but we only want to throw on the first one.
MetadataOutlet: isChildrenRouteKey ? MetadataOutlet : null,
prerenderHTTPError,
},
false
)
childCacheNodeSeedData = seedData
}
} }
const templateNode = createElement( const templateNode = createElement(
......
import { Suspense } from 'react'
async function AsyncComponent() {
await new Promise<void>((resolve) => setTimeout(resolve, 100))
return <div id="async-data">Async Data Loaded</div>
}
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<div>
{children}
<Suspense fallback={<div>Loading async...</div>}>
<AsyncComponent />
</Suspense>
</div>
)
}
export default function NotFound() {
return <div id="not-found-text">Custom 404 - Not Found</div>
}
import { notFound } from 'next/navigation'
export default async function Page() {
notFound()
return <p>This will never render</p>
}
...@@ -68,6 +68,20 @@ describe('cache-components', () => { ...@@ -68,6 +68,20 @@ describe('cache-components', () => {
} }
}) })
it('should render not-found with Suspense in layout without connection errors', async () => {
const browser = await next.browser('/cases/not-found-suspense')
// The custom not-found component should render
expect(await browser.elementById('not-found-text').text()).toBe(
'Custom 404 - Not Found'
)
// The async Suspense content in the layout should also render
expect(await browser.elementById('async-data').text()).toBe(
'Async Data Loaded'
)
})
it('should prerender pages that render in a microtask', async () => { it('should prerender pages that render in a microtask', async () => {
let $ = await next.render$('/cases/microtask', {}) let $ = await next.render$('/cases/microtask', {})
if (isNextDev) { if (isNextDev) {
......
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