Unverified Commit ca0957df authored by Josh Story's avatar Josh Story Committed by GitHub

Prevent unhandled rejection filter from being bundled into the server runtime (#90205)

The unhandled-rejection module was being bundled into
server.runtime.prod.js AND loaded as a standalone file, causing
installUnhandledRejectionFilter() to run twice. Each instance captured
the other's handler as an underlying listener,
creating mutual recursion that overflowed the stack on any unhandled
rejection.

Fix: Rename to .external.tsx so the webpack config externalizes it from
the server runtime bundle. It is now only loaded once from the
standalone file by node-environment.ts.

  Also adds two defensive measures:

- A global symbol guard that noops if a second installation is ever
attempted from a separate module evaluation (e.g. Jest's module system
re-evaluating an already-loaded module in the same process)
- A reentrancy guard on the handler that noops if an underlying listener
synchronously re-emits 'unhandledRejection'
parent 2bf2c9c5
...@@ -1064,5 +1064,6 @@ ...@@ -1064,5 +1064,6 @@
"1063": "`connection` must not be used within a Client Component. Next.js should be preventing `connection` from being included in Client Components statically, but did not in this case.", "1063": "`connection` must not be used within a Client Component. Next.js should be preventing `connection` from being included in Client Components statically, but did not in this case.",
"1064": "createServerParamsForRoute should not be called in client contexts.", "1064": "createServerParamsForRoute should not be called in client contexts.",
"1065": "createServerPathnameForMetadata should not be called in client contexts.", "1065": "createServerPathnameForMetadata should not be called in client contexts.",
"1066": "createServerSearchParamsForServerPage should not be called in a client validation." "1066": "createServerSearchParamsForServerPage should not be called in a client validation.",
"1067": "The Next.js unhandled rejection filter is being installed more than once. This is a bug in Next.js."
} }
...@@ -116,6 +116,11 @@ type ListenerMetadata = { ...@@ -116,6 +116,11 @@ type ListenerMetadata = {
once: boolean once: boolean
} }
// We use a global symbol to detect if the filter has already been installed.
// If two instances of this module are loaded, each captures the other's handler
// as an underlying listener, creating mutual recursion that overflows the stack.
// We error defensively rather than silently degrading.
const FILTER_INSTALLED_KEY = Symbol.for('next.unhandledRejectionFilter')
let filterInstalled = false let filterInstalled = false
// We store the proxied listeners for unhandled rejections here. // We store the proxied listeners for unhandled rejections here.
...@@ -194,10 +199,10 @@ const MACGUFFIN_EVENT = 'Next.UnhandledRejectionFilter.MacguffinEvent' ...@@ -194,10 +199,10 @@ const MACGUFFIN_EVENT = 'Next.UnhandledRejectionFilter.MacguffinEvent'
* This should be called once during server startup to install the global filter. * This should be called once during server startup to install the global filter.
*/ */
function installUnhandledRejectionFilter(): void { function installUnhandledRejectionFilter(): void {
if (filterInstalled) { if ((globalThis as any)[FILTER_INSTALLED_KEY] || filterInstalled) {
warnWithTrace?.( // Already installed by another evaluation of this module in the same
'Unexpected subsequent filter installation. This is a bug in Next.js' // process (e.g., Jest's module system re-evaluating an already-loaded
) // module). Safe to skip since the filter is already active.
return return
} }
...@@ -526,6 +531,7 @@ You can debug event listener operations by running Next.js with \`NEXT_UNHANDLED ...@@ -526,6 +531,7 @@ You can debug event listener operations by running Next.js with \`NEXT_UNHANDLED
) )
filterInstalled = true filterInstalled = true
;(globalThis as any)[FILTER_INSTALLED_KEY] = true
} }
/** /**
...@@ -578,10 +584,18 @@ function uninstallUnhandledRejectionFilter(): void { ...@@ -578,10 +584,18 @@ function uninstallUnhandledRejectionFilter(): void {
/** /**
* The filtering handler that decides whether to suppress or delegate unhandled rejections. * The filtering handler that decides whether to suppress or delegate unhandled rejections.
*/ */
let handlingRejection = false
function filteringUnhandledRejectionHandler( function filteringUnhandledRejectionHandler(
reason: any, reason: any,
promise: Promise<any> promise: Promise<any>
): void { ): void {
if (handlingRejection) {
// An underlying listener synchronously re-emitted 'unhandledRejection'.
// Re-entering the listener loop would overflow the stack.
return
}
const capturedListenerMetadata = Array.from(listenerMetadata) const capturedListenerMetadata = Array.from(listenerMetadata)
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
...@@ -622,6 +636,7 @@ function filteringUnhandledRejectionHandler( ...@@ -622,6 +636,7 @@ function filteringUnhandledRejectionHandler(
// do not automatically terminate the process. // do not automatically terminate the process.
console.error('Unhandled Rejection:', reason) console.error('Unhandled Rejection:', reason)
} else { } else {
handlingRejection = true
try { try {
for (const meta of capturedListenerMetadata) { for (const meta of capturedListenerMetadata) {
if (meta.once) { if (meta.once) {
...@@ -640,6 +655,8 @@ function filteringUnhandledRejectionHandler( ...@@ -640,6 +655,8 @@ function filteringUnhandledRejectionHandler(
setImmediate(() => { setImmediate(() => {
throw error throw error
}) })
} finally {
handlingRejection = false
} }
} }
} }
......
...@@ -12,7 +12,7 @@ import './node-environment-extensions/console-file' ...@@ -12,7 +12,7 @@ import './node-environment-extensions/console-file'
import './node-environment-extensions/console-exit' import './node-environment-extensions/console-exit'
import './node-environment-extensions/console-dim.external' import './node-environment-extensions/console-dim.external'
import './node-environment-extensions/unhandled-rejection' import './node-environment-extensions/unhandled-rejection.external'
import './node-environment-extensions/random' import './node-environment-extensions/random'
import './node-environment-extensions/date' import './node-environment-extensions/date'
import './node-environment-extensions/web-crypto' import './node-environment-extensions/web-crypto'
......
...@@ -479,6 +479,7 @@ async function readNormalizedNFT(next, name) { ...@@ -479,6 +479,7 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/server/load-manifest.external.js", "/node_modules/next/dist/server/load-manifest.external.js",
"/node_modules/next/dist/server/node-environment-extensions/console-dim.external.js", "/node_modules/next/dist/server/node-environment-extensions/console-dim.external.js",
"/node_modules/next/dist/server/node-environment-extensions/fast-set-immediate.external.js", "/node_modules/next/dist/server/node-environment-extensions/fast-set-immediate.external.js",
"/node_modules/next/dist/server/node-environment-extensions/unhandled-rejection.external.js",
"/node_modules/next/dist/server/response-cache/types.js", "/node_modules/next/dist/server/response-cache/types.js",
"/node_modules/next/dist/server/route-modules/app-page/module.compiled.js", "/node_modules/next/dist/server/route-modules/app-page/module.compiled.js",
"/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/app-router-context.js", "/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/app-router-context.js",
......
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