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

Avoid proxying React modules through workUnitStore (#85486)

Today the `captureOwnerStack()` function is provided to shared utilities
through an AsyncLocalStorage that scopes the method from the appropriate
React instance. This is so that external code like patches to sync IO
methods can still generate errors with the appropriate React owner
information even when the patched code itself is not bundled and can be
called from etiher SSR or RSC contexts.

This works but it makes plumbing the React instances around tricky.
There is a simpler way. Most of the time you can just try both React's.
If one gives you a non-null/undefined result then you know you are in
that scope. If neither do then you're outside a React scope altogether.

In this change I remove `captureOwnerStack()` from the workUnitStore
types and just call it from the shared server runtime which gives even
external code access to the appropriate React instances for bundled code
parent 1e53071f
...@@ -955,7 +955,6 @@ async function prospectiveRuntimeServerPrerender( ...@@ -955,7 +955,6 @@ async function prospectiveRuntimeServerPrerender(
renderResumeDataCache, renderResumeDataCache,
prerenderResumeDataCache, prerenderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
captureOwnerStack: undefined,
// We only need task sequencing in the final prerender. // We only need task sequencing in the final prerender.
runtimeStagePromise: null, runtimeStagePromise: null,
// These are not present in regular prerenders, but allowed in a runtime prerender. // These are not present in regular prerenders, but allowed in a runtime prerender.
...@@ -1092,7 +1091,6 @@ async function finalRuntimeServerPrerender( ...@@ -1092,7 +1091,6 @@ async function finalRuntimeServerPrerender(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache, renderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
captureOwnerStack: undefined,
// Used to separate the "Static" stage from the "Runtime" stage. // Used to separate the "Static" stage from the "Runtime" stage.
runtimeStagePromise, runtimeStagePromise,
// These are not present in regular prerenders, but allowed in a runtime prerender. // These are not present in regular prerenders, but allowed in a runtime prerender.
...@@ -3315,9 +3313,7 @@ async function spawnDynamicValidationInDev( ...@@ -3315,9 +3313,7 @@ async function spawnDynamicValidationInDev(
// ready to cut the render off. // ready to cut the render off.
const cacheSignal = new CacheSignal() const cacheSignal = new CacheSignal()
const captureOwnerStackClient = ReactClient.captureOwnerStack const { createElement } = ComponentMod
const { captureOwnerStack: captureOwnerStackServer, createElement } =
ComponentMod
// The resume data cache here should use a fresh instance as it's // The resume data cache here should use a fresh instance as it's
// performing a fresh prerender. If we get to implementing the // performing a fresh prerender. If we get to implementing the
...@@ -3350,7 +3346,6 @@ async function spawnDynamicValidationInDev( ...@@ -3350,7 +3346,6 @@ async function spawnDynamicValidationInDev(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null, renderResumeDataCache: null,
hmrRefreshHash, hmrRefreshHash,
captureOwnerStack: captureOwnerStackServer,
} }
// We're not going to use the result of this render because the only time it could be used // We're not going to use the result of this render because the only time it could be used
...@@ -3384,7 +3379,6 @@ async function spawnDynamicValidationInDev( ...@@ -3384,7 +3379,6 @@ async function spawnDynamicValidationInDev(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null, renderResumeDataCache: null,
hmrRefreshHash, hmrRefreshHash,
captureOwnerStack: captureOwnerStackServer,
} }
const pendingInitialServerResult = workUnitAsyncStorage.run( const pendingInitialServerResult = workUnitAsyncStorage.run(
...@@ -3505,7 +3499,6 @@ async function spawnDynamicValidationInDev( ...@@ -3505,7 +3499,6 @@ async function spawnDynamicValidationInDev(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null, renderResumeDataCache: null,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
captureOwnerStack: captureOwnerStackClient,
} }
const prerender = ( const prerender = (
...@@ -3616,7 +3609,6 @@ async function spawnDynamicValidationInDev( ...@@ -3616,7 +3609,6 @@ async function spawnDynamicValidationInDev(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null, renderResumeDataCache: null,
hmrRefreshHash, hmrRefreshHash,
captureOwnerStack: captureOwnerStackServer,
} }
const finalAttemptRSCPayload = await workUnitAsyncStorage.run( const finalAttemptRSCPayload = await workUnitAsyncStorage.run(
...@@ -3650,7 +3642,6 @@ async function spawnDynamicValidationInDev( ...@@ -3650,7 +3642,6 @@ async function spawnDynamicValidationInDev(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null, renderResumeDataCache: null,
hmrRefreshHash, hmrRefreshHash,
captureOwnerStack: captureOwnerStackServer,
} }
const reactServerResult = await createReactServerPrerenderResult( const reactServerResult = await createReactServerPrerenderResult(
...@@ -3730,7 +3721,6 @@ async function spawnDynamicValidationInDev( ...@@ -3730,7 +3721,6 @@ async function spawnDynamicValidationInDev(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null, renderResumeDataCache: null,
hmrRefreshHash, hmrRefreshHash,
captureOwnerStack: captureOwnerStackClient,
} }
let dynamicValidation = createDynamicValidationState() let dynamicValidation = createDynamicValidationState()
...@@ -4108,7 +4098,6 @@ async function prerenderToStream( ...@@ -4108,7 +4098,6 @@ async function prerenderToStream(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache, renderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
captureOwnerStack: undefined, // Not available in production.
} }
// We're not going to use the result of this render because the only time it could be used // We're not going to use the result of this render because the only time it could be used
...@@ -4142,7 +4131,6 @@ async function prerenderToStream( ...@@ -4142,7 +4131,6 @@ async function prerenderToStream(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache, renderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
captureOwnerStack: undefined, // Not available in production.
}) })
const pendingInitialServerResult = workUnitAsyncStorage.run( const pendingInitialServerResult = workUnitAsyncStorage.run(
...@@ -4257,7 +4245,6 @@ async function prerenderToStream( ...@@ -4257,7 +4245,6 @@ async function prerenderToStream(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache, renderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
captureOwnerStack: undefined, // Not available in production.
} }
const prerender = ( const prerender = (
...@@ -4367,7 +4354,6 @@ async function prerenderToStream( ...@@ -4367,7 +4354,6 @@ async function prerenderToStream(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache, renderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
captureOwnerStack: undefined, // Not available in production.
} }
const finalAttemptRSCPayload = await workUnitAsyncStorage.run( const finalAttemptRSCPayload = await workUnitAsyncStorage.run(
...@@ -4402,7 +4388,6 @@ async function prerenderToStream( ...@@ -4402,7 +4388,6 @@ async function prerenderToStream(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache, renderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
captureOwnerStack: undefined, // Not available in production.
}) })
let prerenderIsPending = true let prerenderIsPending = true
...@@ -4488,7 +4473,6 @@ async function prerenderToStream( ...@@ -4488,7 +4473,6 @@ async function prerenderToStream(
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache, renderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
captureOwnerStack: undefined, // Not available in production.
} }
let dynamicValidation = createDynamicValidationState() let dynamicValidation = createDynamicValidationState()
......
...@@ -207,11 +207,6 @@ interface PrerenderStoreModernCommon ...@@ -207,11 +207,6 @@ interface PrerenderStoreModernCommon
* subsequent dynamic render. * subsequent dynamic render.
*/ */
readonly hmrRefreshHash: string | undefined readonly hmrRefreshHash: string | undefined
/**
* Only available in dev mode.
*/
readonly captureOwnerStack: undefined | (() => string | null)
} }
interface StaticPrerenderStoreCommon { interface StaticPrerenderStoreCommon {
......
...@@ -321,13 +321,23 @@ describe('console-exit patches', () => { ...@@ -321,13 +321,23 @@ describe('console-exit patches', () => {
} }
// Install patches - this wraps the current console.log // Install patches - this wraps the current console.log
const { require('next/dist/server/node-environment-extensions/console-dim.external')
registerGetCacheSignal,
} = require('next/dist/server/node-environment-extensions/console-dim.external')
registerGetCacheSignal(() => null) const {
registerGetCacheSignal(() => controller?.signal) registerServerReact,
registerGetCacheSignal(() => null) registerClientReact,
} = require('next/dist/server/runtime-reacts.external')
registerServerReact({
cacheSignal() {
return controller?.signal
},
})
registerClientReact({
cacheSignal() {
return null
},
})
console.log('before abort') console.log('before abort')
controller.abort() controller.abort()
......
...@@ -4,12 +4,7 @@ import { ...@@ -4,12 +4,7 @@ import {
type ConsoleStore, type ConsoleStore,
} from '../app-render/console-async-storage.external' } from '../app-render/console-async-storage.external'
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external' import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
import { getServerReact, getClientReact } from '../runtime-reacts.external'
type GetCacheSignal = () => AbortSignal | null
const cacheSignals: Array<GetCacheSignal> = []
export function registerGetCacheSignal(getSignal: GetCacheSignal): void {
cacheSignals.push(getSignal)
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- we may use later and want parity with the HIDDEN_STYLE value // eslint-disable-next-line @typescript-eslint/no-unused-vars -- we may use later and want parity with the HIDDEN_STYLE value
const DIMMED_STYLE = 'dimmed' const DIMMED_STYLE = 'dimmed'
...@@ -191,33 +186,32 @@ function patchConsoleMethod(methodName: InterceptableConsoleMethod): void { ...@@ -191,33 +186,32 @@ function patchConsoleMethod(methodName: InterceptableConsoleMethod): void {
// the server React cacheSignal implementation. Any particular console call will be in one, the other, or neither // the server React cacheSignal implementation. Any particular console call will be in one, the other, or neither
// scope and these signals return null if you are out of scope so this can be called from a single global patch // scope and these signals return null if you are out of scope so this can be called from a single global patch
// and still work properly. // and still work properly.
for (let i = 0; i < cacheSignals.length; i++) { const signal =
const signal = cacheSignals[i]() // try to get a signal from registered functions getClientReact()?.cacheSignal() ?? getServerReact()?.cacheSignal()
if (signal) { if (signal) {
// We are in a React Server render and can consult the React cache signal to determine if logs // We are in a React Server render and can consult the React cache signal to determine if logs
// are now dimmable. // are now dimmable.
if (signal.aborted) { if (signal.aborted) {
if (currentAbortedLogsStyle === HIDDEN_STYLE) { if (currentAbortedLogsStyle === HIDDEN_STYLE) {
return return
}
return applyWithDimming.call(
this,
consoleStore,
originalMethod,
methodName,
args
)
} else if (consoleStore?.dim === true) {
return applyWithDimming.call(
this,
consoleStore,
originalMethod,
methodName,
args
)
} else {
return originalMethod.apply(this, args)
} }
return applyWithDimming.call(
this,
consoleStore,
originalMethod,
methodName,
args
)
} else if (consoleStore?.dim === true) {
return applyWithDimming.call(
this,
consoleStore,
originalMethod,
methodName,
args
)
} else {
return originalMethod.apply(this, args)
} }
} }
......
import { workAsyncStorage } from '../app-render/work-async-storage.external' import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
workUnitAsyncStorage,
type PrerenderStoreModern,
} from '../app-render/work-unit-async-storage.external'
import { import {
abortOnSynchronousPlatformIOAccess, abortOnSynchronousPlatformIOAccess,
trackSynchronousPlatformIOAccessInDev, trackSynchronousPlatformIOAccessInDev,
} from '../app-render/dynamic-rendering' } from '../app-render/dynamic-rendering'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { getServerReact, getClientReact } from '../runtime-reacts.external'
type ApiType = 'time' | 'random' | 'crypto' type ApiType = 'time' | 'random' | 'crypto'
export function io(expression: string, type: ApiType) { export function io(expression: string, type: ApiType) {
...@@ -47,7 +46,7 @@ export function io(expression: string, type: ApiType) { ...@@ -47,7 +46,7 @@ export function io(expression: string, type: ApiType) {
abortOnSynchronousPlatformIOAccess( abortOnSynchronousPlatformIOAccess(
workStore.route, workStore.route,
expression, expression,
applyOwnerStack(new Error(message), workUnitStore), applyOwnerStack(new Error(message)),
workUnitStore workUnitStore
) )
} }
...@@ -79,7 +78,7 @@ export function io(expression: string, type: ApiType) { ...@@ -79,7 +78,7 @@ export function io(expression: string, type: ApiType) {
abortOnSynchronousPlatformIOAccess( abortOnSynchronousPlatformIOAccess(
workStore.route, workStore.route,
expression, expression,
applyOwnerStack(new Error(message), workUnitStore), applyOwnerStack(new Error(message)),
workUnitStore workUnitStore
) )
} }
...@@ -101,16 +100,15 @@ export function io(expression: string, type: ApiType) { ...@@ -101,16 +100,15 @@ export function io(expression: string, type: ApiType) {
} }
} }
function applyOwnerStack(error: Error, workUnitStore: PrerenderStoreModern) { function applyOwnerStack(error: Error) {
// TODO: Instead of stitching the stacks here, we should log the original // TODO: Instead of stitching the stacks here, we should log the original
// error as-is when it occurs, and let `patchErrorInspect` handle adding the // error as-is when it occurs, and let `patchErrorInspect` handle adding the
// owner stack, instead of logging it deferred in the `LogSafely` component // owner stack, instead of logging it deferred in the `LogSafely` component
// via `throwIfDisallowedDynamic`. // via `throwIfDisallowedDynamic`.
if ( if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' && const ownerStack =
workUnitStore.captureOwnerStack getClientReact()?.captureOwnerStack() ??
) { getServerReact()?.captureOwnerStack()
const ownerStack = workUnitStore.captureOwnerStack()
if (ownerStack) { if (ownerStack) {
let stack = ownerStack let stack = ownerStack
......
...@@ -39,13 +39,12 @@ if (process.env.NEXT_RUNTIME !== 'edge') { ...@@ -39,13 +39,12 @@ if (process.env.NEXT_RUNTIME !== 'edge') {
vendoredReactSSR = vendoredReactSSR =
require('./vendored/ssr/entrypoints') as typeof import('./vendored/ssr/entrypoints') require('./vendored/ssr/entrypoints') as typeof import('./vendored/ssr/entrypoints')
// In Node environments we augment console logging with information contextual to a React render. // In Node environments we need to access the correct React instance from external modules such
// This patching is global so we need to register the cacheSignal getter from our bundled React instances // as global patches. We register the loaded React instances here.
// here when we load them rather than in the external module itself when the patch is applied. const { registerServerReact, registerClientReact } =
const { registerGetCacheSignal } = require('../../runtime-reacts.external') as typeof import('../../runtime-reacts.external')
require('../../node-environment-extensions/console-dim.external') as typeof import('../../node-environment-extensions/console-dim.external') registerServerReact(vendoredReactRSC.React)
registerGetCacheSignal(vendoredReactRSC.React.cacheSignal) registerClientReact(vendoredReactSSR.React)
registerGetCacheSignal(vendoredReactSSR.React.cacheSignal)
} }
/** /**
......
...@@ -413,7 +413,6 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -413,7 +413,6 @@ export class AppRouteRouteModule extends RouteModule<
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null, renderResumeDataCache: null,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
captureOwnerStack: undefined,
}) })
let prospectiveResult let prospectiveResult
...@@ -505,7 +504,6 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -505,7 +504,6 @@ export class AppRouteRouteModule extends RouteModule<
prerenderResumeDataCache, prerenderResumeDataCache,
renderResumeDataCache: null, renderResumeDataCache: null,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
captureOwnerStack: undefined,
}) })
let responseHandled = false let responseHandled = false
......
let ClientReact: typeof import('react') | null = null
export function registerClientReact(react: typeof import('react')) {
ClientReact = react
}
export function getClientReact() {
return ClientReact
}
let ServerReact: typeof import('react') | null = null
export function registerServerReact(react: typeof import('react')) {
ServerReact = react
}
export function getServerReact() {
return ServerReact
}
...@@ -321,6 +321,7 @@ const isReact18 = parseInt(process.env.NEXT_TEST_REACT_VERSION) === 18 ...@@ -321,6 +321,7 @@ const isReact18 = parseInt(process.env.NEXT_TEST_REACT_VERSION) === 18
"/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable.js", "/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable.js",
"/node_modules/next/dist/server/route-modules/pages/vendored/contexts/router-context.js", "/node_modules/next/dist/server/route-modules/pages/vendored/contexts/router-context.js",
"/node_modules/next/dist/server/route-modules/pages/vendored/contexts/server-inserted-html.js", "/node_modules/next/dist/server/route-modules/pages/vendored/contexts/server-inserted-html.js",
"/node_modules/next/dist/server/runtime-reacts.external.js",
"/node_modules/next/dist/shared/lib/deep-freeze.js", "/node_modules/next/dist/shared/lib/deep-freeze.js",
"/node_modules/next/dist/shared/lib/invariant-error.js", "/node_modules/next/dist/shared/lib/invariant-error.js",
"/node_modules/next/dist/shared/lib/is-plain-object.js", "/node_modules/next/dist/shared/lib/is-plain-object.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