Unverified Commit 2256b6be authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Properly handle hanging promise rejections during prerendering (#81754)

We are using hanging promises for excluding request-specific data from a
prerender. When prerendering is aborted, we reject all hanging promises.
In dev mode, React uses these rejections to construct more detailed
owner stacks. This allows us to provide better errors during the
prerender validation.

For this to work reliably, we need to ensure that all hanging promises
are rejected after React's rendering is aborted. However, some hanging
promises are created before React starts rendering (when creating the
RSC component tree). Furthermore, for memory reasons, the first hanging
promise adds a single abort listener that's shared with all subsequent
hanging promises (see #77480). In this case, the shared abort listener
for rejections is added before React can add its own abort listener.

When using the same abort signal for both the React render and the
hanging promises, the hanging promises would be rejected too early,
preventing React from properly constructing the owner stacks.

To ensure that the order of operations is correct, we now use a separate
abort signal for React's rendering that is aborted before the "render
signal" [^1], which is used by the hanging promises, is aborted. For
parity, we're doing this not only in dev mode but also in production
mode, so that the hanging promise rejection handling is always the same.

Technically, I don't think this change is necessary for the SSR
prerender pass, but it felt cleaner to apply it there as well. However,
we could revisit that when we properly split the two prerender stores.
For example, the `cacheSignal` and `prerenderResumeDataCache` also don't
need to be present on the client prerender store.

Reverts #81501.

[^1]: This is an unfortunate name clash. We could also call this one
"cache signal", which would be in line with `React.cacheSignal()` – its
potential successor. But that clashes with our current `cacheSignal`,
which tracks the cache reads. We might revisit this naming problem in a
future PR.
parent 8abbb3dc
......@@ -92,20 +92,32 @@ interface PrerenderStoreModernServer extends PrerenderStoreModernCommon {
interface PrerenderStoreModernCommon extends CommonWorkUnitStore {
/**
* This signal is aborted when the React render is complete. (i.e. it is the same signal passed to react)
* The render signal is aborted after React's `prerender` function is aborted
* (using a separate signal), which happens in two cases:
*
* 1. When all caches are filled during the prospective prerender.
* 2. When the final prerender is aborted immediately after the prerender was
* started.
*
* It can be used to reject any pending I/O, including hanging promises. This
* allows React to properly track the async I/O in dev mode, which yields
* better owner stacks for dynamic validation errors.
*/
readonly renderSignal: AbortSignal
/**
* This is the AbortController which represents the boundary between Prerender and dynamic. In some renders it is
* the same as the controller for the renderSignal but in others it is a separate controller. It should be aborted
* whenever the we are no longer in the prerender phase of rendering. Typically this is after one task or when you call
* a sync API which requires the prerender to end immediately
* This is the AbortController which represents the boundary between Prerender
* and dynamic. In some renders it is the same as the controller for React,
* but in others it is a separate controller. It should be aborted whenever we
* are no longer in the prerender phase of rendering. Typically this is after
* one task, or when you call a sync API which requires the prerender to end
* immediately.
*/
readonly controller: AbortController
/**
* when not null this signal is used to track cache reads during prerendering and
* to await all cache reads completing before aborting the prerender.
* When not null, this signal is used to track cache reads during prerendering
* and to await all cache reads completing, before aborting the prerender.
*/
readonly cacheSignal: null | CacheSignal
......
......@@ -559,7 +559,7 @@ export function createPatchedFetcher(
cacheSignal = null
}
return await makeHangingPromise<Response>(
return makeHangingPromise<Response>(
workUnitStore.renderSignal,
'fetch()'
)
......@@ -669,7 +669,7 @@ export function createPatchedFetcher(
cacheSignal.endRead()
cacheSignal = null
}
return await makeHangingPromise<Response>(
return makeHangingPromise<Response>(
workUnitStore.renderSignal,
'fetch()'
)
......@@ -1010,7 +1010,7 @@ export function createPatchedFetcher(
cacheSignal.endRead()
cacheSignal = null
}
return await makeHangingPromise<Response>(
return makeHangingPromise<Response>(
workUnitStore.renderSignal,
'fetch()'
)
......@@ -1044,7 +1044,7 @@ export function createPatchedFetcher(
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
return await makeHangingPromise<Response>(
return makeHangingPromise<Response>(
workUnitStore.renderSignal,
'fetch()'
)
......
......@@ -821,7 +821,7 @@ export function cache(
)
if (dynamicAccessAbortController.signal.aborted) {
return await makeHangingPromise(
return makeHangingPromise(
workUnitStore.renderSignal,
dynamicAccessAbortController.signal.reason.message
)
......@@ -886,7 +886,7 @@ export function cache(
if (cacheSignal) {
cacheSignal.endRead()
}
return await makeHangingPromise(
return makeHangingPromise(
workUnitStore.renderSignal,
'dynamic "use cache"'
)
......@@ -935,7 +935,7 @@ export function cache(
// transformed with an async function, before being passed into
// the "use cache" function, which escapes the instrumentation.
if (workUnitStore.allowEmptyStaticShell) {
return await makeHangingPromise(
return makeHangingPromise(
workUnitStore.renderSignal,
'dynamic "use cache"'
)
......@@ -1030,7 +1030,7 @@ export function cache(
if (cacheSignal) {
cacheSignal.endRead()
}
return await makeHangingPromise(
return makeHangingPromise(
workUnitStore.renderSignal,
'dynamic "use cache"'
)
......@@ -1087,7 +1087,7 @@ export function cache(
)
if (result.type === 'prerender-dynamic') {
return await result.hangingPromise
return result.hangingPromise
}
const { stream: newStream, pendingCacheEntry } = result
......
......@@ -1758,20 +1758,20 @@ describe('Cache Components Errors', () => {
`)
} else {
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "Route "/sync-attribution/unguarded-async-guarded-clientsync": A component accessed data, headers, params, searchParams, or a short-lived cache without a Suspense boundary nor a "use cache" above it. See more info: https://nextjs.org/docs/messages/next-prerender-missing-suspense",
"environmentLabel": "Server",
"label": "Console Error",
"source": "app/sync-attribution/unguarded-async-guarded-clientsync/page.tsx (33:16) @ RequestData
> 33 | async function RequestData() {
| ^",
"stack": [
"RequestData app/sync-attribution/unguarded-async-guarded-clientsync/page.tsx (33:16)",
"Page app/sync-attribution/unguarded-async-guarded-clientsync/page.tsx (27:9)",
"LogSafely <anonymous>",
],
}
`)
{
"description": "Route "/sync-attribution/unguarded-async-guarded-clientsync": A component accessed data, headers, params, searchParams, or a short-lived cache without a Suspense boundary nor a "use cache" above it. See more info: https://nextjs.org/docs/messages/next-prerender-missing-suspense",
"environmentLabel": "Server",
"label": "Console Error",
"source": "app/sync-attribution/unguarded-async-guarded-clientsync/page.tsx (34:18) @ RequestData
> 34 | ;(await cookies()).get('foo')
| ^",
"stack": [
"RequestData app/sync-attribution/unguarded-async-guarded-clientsync/page.tsx (34:18)",
"Page app/sync-attribution/unguarded-async-guarded-clientsync/page.tsx (27:9)",
"LogSafely <anonymous>",
],
}
`)
}
})
} else {
......
#!/usr/bin/env bash
# Run `test/e2e/app-dir/cache-components-errors/update-snapshots.sh` from the root of
# the monorepo to update the snapshots of the cache components errors test suite.
# Run `test/e2e/app-dir/cache-components-errors/update-snapshots.sh` from the
# root of the monorepo to update the snapshots of the cache components errors
# test suite.
set -xeuo pipefail
SCRIPT_DIR=`dirname ${BASH_SOURCE[0]-$0}`
SCRIPT_DIR=$(dirname "${BASH_SOURCE[0]-$0}")
TESTS=("$SCRIPT_DIR/cache-components-errors.test.ts")
DEV=false
START=false
# Parse CLI flags
for arg in "$@"; do
case "$arg" in
--dev) DEV=true ;;
--start) START=true ;;
*) echo "Unknown option: $arg"; exit 1 ;;
esac
done
# If no flags are provided, update all snapshots.
if [ "$DEV" = false ] && [ "$START" = false ]; then
DEV=true
START=true
fi
# Update `next dev` snapshots for both Turbopack and Webpack.
pnpm test-dev "${TESTS[@]}" --projects jest.config.* -u
if [ "$DEV" = true ]; then
pnpm test-dev "${TESTS[@]}" --projects jest.config.* -u
fi
# The `next start` snapshots can't be created for both prerender modes at the
# same time because of an issue in the typescript plugin for prettier.
NEXT_TEST_DEBUG_PRERENDER=false pnpm test-start "${TESTS[@]}" --projects jest.config.* -u
NEXT_TEST_DEBUG_PRERENDER=true pnpm test-start "${TESTS[@]}" --projects jest.config.* -u
if [ "$START" = true ]; then
NEXT_TEST_DEBUG_PRERENDER=false pnpm test-start "${TESTS[@]}" --projects jest.config.* -u
NEXT_TEST_DEBUG_PRERENDER=true pnpm test-start "${TESTS[@]}" --projects jest.config.* -u
fi
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