Unverified Commit fe2f1e44 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

remove runInContext callbacks from stream-ops (#90609)

The `runInContext` pattern that's used all over `stream-ops` is weird
and feels very unnecessary -- we're passing in callbacks that just get
invoked immediately, and all they do is call `AsyncLocalStorage.run`. We
should just use the standard `AsyncLocalStorage.run` method outside
instead. I commented about getting rid of it somewhere on the original
node streams PR, but that got lost when it was was split up.

I believe the original reasoning for addding it at all was that some of
the node-streams implementations needed to preserve async context for
callbacks -- see eg
[here](https://github.com/vercel/next.js/blob/558f4248e5e5641d78b865a291c099791460d486/packages/next/src/server/app-render/node-stream-tee.ts#L244).
But if that's the motivation, then the current `runInContext` pattern
**is wrong anyway** -- sure, it preserves `workUnitAsyncStorage`, but
doesn't preserve `workAsyncStorage` and whetever other ALSes may be
present, so it's not semantically correct. If this is the goal, then the
relevant callbacks should use `bindSnapshot` (i.e.
`AsyncLocalStorage.bind`) instead, because it preserves the entire
context, not just one ALS.

(Note that technically the `runInContext` pattern is salvageable if we
just always pass `AsyncLocalStorage.snapshot()`, but then i see no
reason why the caller should have to do that. `AsyncLocalStorage.bind`
is cleaner)

Note that this'll require changes in #89859
parent 7643fc94
...@@ -723,7 +723,9 @@ async function generateDynamicFlightRenderResult( ...@@ -723,7 +723,9 @@ async function generateDynamicFlightRenderResult(
options options
) )
const flightStream = renderToFlightStream( const flightStream = workUnitAsyncStorage.run(
requestStore,
renderToFlightStream,
ctx.componentMod, ctx.componentMod,
rscPayload, rscPayload,
clientModules, clientModules,
...@@ -732,8 +734,7 @@ async function generateDynamicFlightRenderResult( ...@@ -732,8 +734,7 @@ async function generateDynamicFlightRenderResult(
temporaryReferences: options?.temporaryReferences, temporaryReferences: options?.temporaryReferences,
filterStackFrame, filterStackFrame,
debugChannel: debugChannel?.serverSide, debugChannel: debugChannel?.serverSide,
}, }
(fn) => workUnitAsyncStorage.run(requestStore, fn)
) )
return new FlightRenderResult( return new FlightRenderResult(
...@@ -902,15 +903,16 @@ async function stagedRenderToReadableStreamWithoutCachesInDev( ...@@ -902,15 +903,16 @@ async function stagedRenderToReadableStreamWithoutCachesInDev(
return await runInSequentialTasks( return await runInSequentialTasks(
() => { () => {
stageController.advanceStage(RenderStage.Static) stageController.advanceStage(RenderStage.Static)
return renderToFlightStream( return workUnitAsyncStorage.run(
requestStore,
renderToFlightStream,
ctx.componentMod, ctx.componentMod,
rscPayload, rscPayload,
clientModules, clientModules,
{ {
...options, ...options,
environmentName, environmentName,
}, }
(fn) => workUnitAsyncStorage.run(requestStore, fn)
) )
}, },
() => { () => {
...@@ -2906,7 +2908,9 @@ async function renderToStream( ...@@ -2906,7 +2908,9 @@ async function renderToStream(
} }
reactServerResult = new ReactServerResult( reactServerResult = new ReactServerResult(
renderToFlightStream( workUnitAsyncStorage.run(
requestStore,
renderToFlightStream,
ctx.componentMod, ctx.componentMod,
RSCPayload, RSCPayload,
clientModules, clientModules,
...@@ -2914,8 +2918,7 @@ async function renderToStream( ...@@ -2914,8 +2918,7 @@ async function renderToStream(
filterStackFrame, filterStackFrame,
onError: serverComponentsErrorHandler, onError: serverComponentsErrorHandler,
debugChannel: debugChannel?.serverSide, debugChannel: debugChannel?.serverSide,
}, }
(fn) => workUnitAsyncStorage.run(requestStore, fn)
) )
) )
} }
...@@ -2966,12 +2969,14 @@ async function renderToStream( ...@@ -2966,12 +2969,14 @@ async function renderToStream(
tracingMetadata: tracingMetadata, tracingMetadata: tracingMetadata,
}) })
const { stream: htmlStream, allReady } = await resumeToFizzStream( const { stream: htmlStream, allReady } =
resumeAppElement, await workUnitAsyncStorage.run(
postponed, requestStore,
{ onError: htmlRendererErrorHandler, nonce }, resumeToFizzStream,
(fn) => workUnitAsyncStorage.run(requestStore, fn) resumeAppElement,
) postponed,
{ onError: htmlRendererErrorHandler, nonce }
)
// End the render span only after React completed rendering (including anything inside Suspense boundaries) // End the render span only after React completed rendering (including anything inside Suspense boundaries)
allReady.finally(() => { allReady.finally(() => {
...@@ -3031,10 +3036,11 @@ async function renderToStream( ...@@ -3031,10 +3036,11 @@ async function renderToStream(
formState, formState,
} }
const { stream: htmlStream, allReady } = await renderToFizzStream( const { stream: htmlStream, allReady } = await workUnitAsyncStorage.run(
requestStore,
renderToFizzStream,
appElement, appElement,
fizzOptions, fizzOptions
(fn) => workUnitAsyncStorage.run(requestStore, fn)
) )
// End the render span only after React completed rendering (including anything inside Suspense boundaries) // End the render span only after React completed rendering (including anything inside Suspense boundaries)
...@@ -3136,15 +3142,16 @@ async function renderToStream( ...@@ -3136,15 +3142,16 @@ async function renderToStream(
errorType errorType
) )
errorServerStream = renderToFlightStream( errorServerStream = workUnitAsyncStorage.run(
requestStore,
renderToFlightStream,
ctx.componentMod, ctx.componentMod,
errorRSCPayload, errorRSCPayload,
clientModules, clientModules,
{ {
filterStackFrame, filterStackFrame,
onError: serverComponentsErrorHandler, onError: serverComponentsErrorHandler,
}, }
(fn) => workUnitAsyncStorage.run(requestStore, fn)
) )
if (reactServerResult === null) { if (reactServerResult === null) {
...@@ -3163,7 +3170,9 @@ async function renderToStream( ...@@ -3163,7 +3170,9 @@ async function renderToStream(
supportsDynamicResponse !== true || !!shouldWaitOnAllReady supportsDynamicResponse !== true || !!shouldWaitOnAllReady
const { stream: errorHtmlStream, allReady: errorAllReady } = const { stream: errorHtmlStream, allReady: errorAllReady } =
await renderToFizzStream( await workUnitAsyncStorage.run(
requestStore,
renderToFizzStream,
<ErrorApp <ErrorApp
reactServerStream={errorServerStream} reactServerStream={errorServerStream}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
...@@ -3176,8 +3185,7 @@ async function renderToStream( ...@@ -3176,8 +3185,7 @@ async function renderToStream(
bootstrapScriptContent, bootstrapScriptContent,
bootstrapScripts: [errorBootstrapScript], bootstrapScripts: [errorBootstrapScript],
formState, formState,
}, }
(fn) => workUnitAsyncStorage.run(requestStore, fn)
) )
// End the render span only after React completed rendering (including anything inside Suspense boundaries) // End the render span only after React completed rendering (including anything inside Suspense boundaries)
...@@ -3310,20 +3318,23 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -3310,20 +3318,23 @@ async function renderWithRestartOnCacheMissInDev(
initialStageController.advanceStage(RenderStage.EarlyStatic) initialStageController.advanceStage(RenderStage.EarlyStatic)
startTime = performance.now() + performance.timeOrigin startTime = performance.now() + performance.timeOrigin
const streamPair = renderToFlightStream( const streamPair = workUnitAsyncStorage
ComponentMod, .run(
initialRscPayload, requestStore,
clientModules, renderToFlightStream,
{ ComponentMod,
onError, initialRscPayload,
environmentName, clientModules,
startTime, {
filterStackFrame, onError,
debugChannel: debugChannel?.serverSide, environmentName,
signal: initialReactController.signal, startTime,
}, filterStackFrame,
(fn) => workUnitAsyncStorage.run(requestStore, fn) debugChannel: debugChannel?.serverSide,
).tee() signal: initialReactController.signal,
}
)
.tee()
// If we abort the render, we want to reject the stage-dependent promises as well. // If we abort the render, we want to reject the stage-dependent promises as well.
// Note that we want to install this listener after the render is started // Note that we want to install this listener after the render is started
...@@ -3457,19 +3468,22 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -3457,19 +3468,22 @@ async function renderWithRestartOnCacheMissInDev(
finalStageController.advanceStage(RenderStage.EarlyStatic) finalStageController.advanceStage(RenderStage.EarlyStatic)
startTime = performance.now() + performance.timeOrigin startTime = performance.now() + performance.timeOrigin
const streamPair = renderToFlightStream( const streamPair = workUnitAsyncStorage
ComponentMod, .run(
finalRscPayload, requestStore,
clientModules, renderToFlightStream,
{ ComponentMod,
onError, finalRscPayload,
environmentName, clientModules,
startTime, {
filterStackFrame, onError,
debugChannel: debugChannel?.serverSide, environmentName,
}, startTime,
(fn) => workUnitAsyncStorage.run(requestStore, fn) filterStackFrame,
).tee() debugChannel: debugChannel?.serverSide,
}
)
.tee()
return { return {
stream: streamPair[0], stream: streamPair[0],
...@@ -5782,7 +5796,9 @@ async function prerenderToStream( ...@@ -5782,7 +5796,9 @@ async function prerenderToStream(
) )
) )
const { stream: htmlStream } = await renderToFizzStream( const { stream: htmlStream } = await workUnitAsyncStorage.run(
prerenderLegacyStore,
renderToFizzStream,
// eslint-disable-next-line @next/internal/no-ambiguous-jsx // eslint-disable-next-line @next/internal/no-ambiguous-jsx
<App <App
reactServerStream={reactServerResult.asUnclosingStream()} reactServerStream={reactServerResult.asUnclosingStream()}
...@@ -5797,8 +5813,7 @@ async function prerenderToStream( ...@@ -5797,8 +5813,7 @@ async function prerenderToStream(
onError: htmlRendererErrorHandler, onError: htmlRendererErrorHandler,
nonce, nonce,
bootstrapScripts: [bootstrapScript], bootstrapScripts: [bootstrapScript],
}, }
(fn) => workUnitAsyncStorage.run(prerenderLegacyStore, fn)
) )
if (shouldGenerateStaticFlightData(workStore)) { if (shouldGenerateStaticFlightData(workStore)) {
...@@ -5936,24 +5951,22 @@ async function prerenderToStream( ...@@ -5936,24 +5951,22 @@ async function prerenderToStream(
errorType errorType
) )
// Keep prerender-legacy async storage stable across node stream event const errorServerStream = workUnitAsyncStorage.run(
// callbacks and pipeable renderer hooks. prerenderLegacyStore,
const runInLegacyContext = <T,>(fn: () => T): T => renderToFlightStream,
workUnitAsyncStorage.run(prerenderLegacyStore, fn)
const errorServerStream = renderToFlightStream(
ComponentMod, ComponentMod,
errorRSCPayload, errorRSCPayload,
clientModules, clientModules,
{ {
filterStackFrame, filterStackFrame,
onError: serverComponentsErrorHandler, onError: serverComponentsErrorHandler,
}, }
runInLegacyContext
) )
try { try {
const { stream: errorHtmlStream } = await renderToFizzStream( const { stream: errorHtmlStream } = await workUnitAsyncStorage.run(
prerenderLegacyStore,
renderToFizzStream,
// eslint-disable-next-line @next/internal/no-ambiguous-jsx // eslint-disable-next-line @next/internal/no-ambiguous-jsx
<ErrorApp <ErrorApp
reactServerStream={errorServerStream} reactServerStream={errorServerStream}
...@@ -5966,8 +5979,7 @@ async function prerenderToStream( ...@@ -5966,8 +5979,7 @@ async function prerenderToStream(
nonce, nonce,
bootstrapScripts: [errorBootstrapScript], bootstrapScripts: [errorBootstrapScript],
formState, formState,
}, }
runInLegacyContext
) )
if (shouldGenerateStaticFlightData(workStore)) { if (shouldGenerateStaticFlightData(workStore)) {
......
...@@ -147,13 +147,9 @@ export function renderToFlightStream( ...@@ -147,13 +147,9 @@ export function renderToFlightStream(
ComponentMod: FlightComponentMod, ComponentMod: FlightComponentMod,
payload: FlightPayload, payload: FlightPayload,
clientModules: FlightClientModules, clientModules: FlightClientModules,
opts: FlightRenderOptions, opts: FlightRenderOptions
runInContext?: <T>(fn: () => T) => T
): AnyStream { ): AnyStream {
const run: <T>(fn: () => T) => T = runInContext ?? ((fn) => fn()) return ComponentMod.renderToReadableStream(payload, clientModules, opts)
return run(() =>
ComponentMod.renderToReadableStream(payload, clientModules, opts)
)
} }
export async function streamToString(stream: AnyStream): Promise<string> { export async function streamToString(stream: AnyStream): Promise<string> {
...@@ -162,28 +158,22 @@ export async function streamToString(stream: AnyStream): Promise<string> { ...@@ -162,28 +158,22 @@ export async function streamToString(stream: AnyStream): Promise<string> {
export async function renderToFizzStream( export async function renderToFizzStream(
element: React.ReactElement, element: React.ReactElement,
streamOptions: any, streamOptions: any
runInContext?: <T>(fn: () => T) => T
): Promise<FizzStreamResult> { ): Promise<FizzStreamResult> {
const run: <T>(fn: () => T) => T = runInContext ?? ((fn) => fn()) const stream = await renderToInitialFizzStream({
const stream = await run(() => ReactDOMServer: { renderToReadableStream },
renderToInitialFizzStream({ element,
ReactDOMServer: { renderToReadableStream }, streamOptions,
element, })
streamOptions,
})
)
return { stream, allReady: stream.allReady, abort: undefined } return { stream, allReady: stream.allReady, abort: undefined }
} }
export async function resumeToFizzStream( export async function resumeToFizzStream(
element: React.ReactElement, element: React.ReactElement,
postponedState: PostponedState, postponedState: PostponedState,
streamOptions: any, streamOptions: any
runInContext?: <T>(fn: () => T) => T
): Promise<FizzStreamResult> { ): Promise<FizzStreamResult> {
const run: <T>(fn: () => T) => T = runInContext ?? ((fn) => fn()) const stream = await resume(element, postponedState, streamOptions)
const stream = await run(() => resume(element, postponedState, streamOptions))
return { stream, allReady: stream.allReady, abort: undefined } return { stream, allReady: stream.allReady, abort: undefined }
} }
......
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