Skip to content
Projects
Groups
Snippets
Help
Loading...
Sign in
Toggle navigation
N
next.js
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Alex
next.js
Commits
176e9c18
Unverified
Commit
176e9c18
authored
Jun 08, 2026
by
Tim Neutkens
Committed by
GitHub
Jun 08, 2026
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Revert "Remove dead cacheComponents web streams path (#93944)"
This reverts commit
89bd4833
.
parent
c082ffe4
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
1109 additions
and
260 deletions
+1109
-260
app-render.tsx
packages/next/src/server/app-render/app-render.tsx
+1109
-260
No files found.
packages/next/src/server/app-render/app-render.tsx
View file @
176e9c18
...
...
@@ -901,6 +901,178 @@ async function generateDynamicFlightRenderResult(
}
}
/**
* Production-only staged dynamic flight render for cache components. Uses
* staged rendering to separate static (RDC-backed) from runtime/dynamic
* content.
*/
async
function
generateStagedDynamicFlightRenderResultWeb
(
req
:
BaseNextRequest
,
ctx
:
AppRenderContext
,
requestStore
:
RequestStore
):
Promise
<
RenderResult
>
{
const
{
componentMod
,
workStore
,
renderOpts
}
=
ctx
const
{
renderToReadableStream
,
routeModule
}
=
componentMod
const
{
loaderTree
}
=
routeModule
.
userland
const
{
onInstrumentationRequestError
,
experimental
}
=
renderOpts
const
{
appShells
}
=
experimental
function
onFlightDataRenderError
(
err
:
DigestedError
,
silenceLog
:
boolean
)
{
return
onInstrumentationRequestError
?.(
err
,
req
,
createErrorContext
(
ctx
,
'react-server-components-payload'
),
silenceLog
)
}
const
onError
=
createReactServerErrorHandler
(
false
,
false
,
workStore
.
reactServerErrorsByDigest
,
onFlightDataRenderError
)
const
selectStaleTime
=
createSelectStaleTime
(
experimental
)
const
staleTimeIterable
=
new
StaleTimeIterable
()
const
stageController
=
new
StagedRenderingController
({
abortSignal
:
null
,
abandonController
:
null
,
// TODO(cached-navs): this assumes that we checked during build that there's no sync IO.
// but it can happen e.g. after a revalidation or conditionally for a param that wasn't prerendered.
// we should change this to track sync IO, log an error and advance to dynamic.
shouldTrackSyncIO
:
false
,
finalStage
:
null
,
})
// Initialize stale time tracking on the request store.
requestStore
.
stale
=
INFINITE_CACHE
requestStore
.
stagedRendering
=
stageController
requestStore
.
varyParamsAccumulator
=
createResponseVaryParamsAccumulator
()
requestStore
.
asyncApiPromises
=
createAsyncApiPromises
(
stageController
,
requestStore
.
cookies
,
requestStore
.
mutableCookies
,
requestStore
.
headers
)
trackStaleTime
(
requestStore
as
{
stale
:
number
},
staleTimeIterable
,
selectStaleTime
)
// Deferred promise for the static stage byte length. Flight serializes the
// resolved value into the stream so the client knows where the static
// prefix ends.
const
shellByteLengthDeferred
=
appShells
?
createPromiseWithResolvers
<
number
|
null
>
()
:
null
const
staticStageByteLengthDeferred
=
createPromiseWithResolvers
<
number
>
()
// Check if this route has opted into runtime prefetching via
// unstable_instant. If so, we piggyback on the dynamic render to fill caches
// and then spawn a final runtime prerender whose result stream is embedded in
// the RSC payload. This is gated on the explicit opt-in because it adds extra
// server processing, increases the response payload size, and the runtime
// prefetch output should have been validated first.
const
hasRuntimePrefetch
=
await
anySegmentHasRuntimePrefetchEnabled
(
loaderTree
)
let
runtimePrefetchStream
:
ReadableStream
<
Uint8Array
>
|
undefined
if
(
hasRuntimePrefetch
)
{
// Create a mutable cache that gets filled during the dynamic render.
const
prerenderResumeDataCache
=
createPrerenderResumeDataCache
()
requestStore
.
resumeDataCache
=
prerenderResumeDataCache
const
cacheSignal
=
new
CacheSignal
()
trackPendingModules
(
cacheSignal
)
requestStore
.
cacheSignal
=
cacheSignal
// Create a deferred stream for the runtime prefetch result. Its readable
// side goes into the RSC payload (Flight serializes it lazily). The
// writable side receives the runtime prerender result once the dynamic
// render has filled all caches.
const
runtimePrefetchTransform
=
new
TransformStream
<
Uint8Array
>
()
runtimePrefetchStream
=
runtimePrefetchTransform
.
readable
// Wait for the dynamic render to fill caches, then run the final runtime
// prerender (fire-and-forget — does not block the response).
void
cacheSignal
.
cacheReady
()
.
then
(()
=>
spawnRuntimePrefetchWithFilledCaches
(
runtimePrefetchTransform
.
writable
,
ctx
,
prerenderResumeDataCache
,
requestStore
,
onError
)
)
}
const
rscPayload
=
await
workUnitAsyncStorage
.
run
(
requestStore
,
generateDynamicRSCPayload
,
ctx
,
{
staleTimeIterable
,
staticStageByteLengthPromise
:
staticStageByteLengthDeferred
.
promise
,
shellByteLengthPromise
:
shellByteLengthDeferred
?.
promise
,
runtimePrefetchStream
,
}
)
const
{
clientModules
}
=
getClientReferenceManifest
()
const
flightReadableStream
=
await
runInSequentialTasks
(
()
=>
{
// NOTE: no early/late separation in this render
stageController
.
advanceStage
(
RenderStage
.
ShellStatic
)
const
stream
=
workUnitAsyncStorage
.
run
(
requestStore
,
renderToReadableStream
,
rscPayload
,
clientModules
,
{
onError
,
filterStackFrame
}
)
const
[
dynamicStream
,
staticStream
]
=
stream
.
tee
()
void
countShellAndStaticStageBytes
(
staticStream
,
stageController
).
then
(
(
byteLengths
)
=>
{
staticStageByteLengthDeferred
.
resolve
(
byteLengths
[
RenderStage
.
Static
])
shellByteLengthDeferred
?.
resolve
(
byteLengths
[
RenderStage
.
ShellStatic
])
}
)
return
dynamicStream
},
()
=>
{
stageController
.
advanceStage
(
RenderStage
.
Static
)
},
()
=>
{
// This is a separate task that doesn't advance a stage. It forces
// draining the immediate queue so that the stale time iterable and vary
// params accumulators are flushed before we advance to the dynamic stage.
staleTimeIterable
.
close
()
if
(
requestStore
.
varyParamsAccumulator
)
{
finishAccumulatingVaryParams
(
requestStore
.
varyParamsAccumulator
)
}
},
()
=>
{
stageController
.
advanceStage
(
RenderStage
.
Dynamic
)
}
)
return
new
FlightRenderResult
(
flightReadableStream
,
{
fetchMetrics
:
workStore
.
fetchMetrics
,
})
}
/**
* Production-only staged dynamic flight render for cache components (Node.js
* streams). Uses staged rendering to separate static (RDC-backed) from
...
...
@@ -1139,6 +1311,69 @@ type RenderToReadableStreamServerOptions = NonNullable<
>
[
2
]
>
async
function
stagedRenderWithoutCachesInDevWeb
(
ctx
:
AppRenderContext
,
requestStore
:
RequestStore
,
getPayload
:
(
requestStore
:
RequestStore
)
=>
Promise
<
RSCPayload
>
,
options
:
Omit
<
RenderToReadableStreamServerOptions
,
'environmentName'
>
)
{
// We're rendering while bypassing caches,
// so we have no hope of showing a useful runtime stage.
// But we still want things like `params` to show up in devtools correctly,
// which relies on mechanisms we've set up for staged rendering,
// so we do a 2-task version (Static -> Dynamic) instead.
// We aren't filling caches so we don't need to abort this render, it'll
// stream in a single pass
const
stageController
=
new
StagedRenderingController
({
abortSignal
:
null
,
abandonController
:
null
,
shouldTrackSyncIO
:
false
,
// do not track sync IO (we don't have reliable stages)
finalStage
:
null
,
})
const
environmentName
=
()
=>
{
const
currentStage
=
stageController
.
currentStage
return
getEnvironmentNameForStageWithoutCaches
(
currentStage
)
}
requestStore
.
stagedRendering
=
stageController
requestStore
.
asyncApiPromises
=
createAsyncApiPromises
(
stageController
,
requestStore
.
cookies
,
requestStore
.
mutableCookies
,
requestStore
.
headers
)
const
{
clientModules
}
=
getClientReferenceManifest
()
const
rscPayload
=
await
getPayload
(
requestStore
)
return
await
runInSequentialTasks
(
()
=>
{
// NOTE: no early/late separation in this render
stageController
.
advanceStage
(
RenderStage
.
ShellStatic
)
return
workUnitAsyncStorage
.
run
(
requestStore
,
renderToWebFlightStream
,
ctx
.
componentMod
,
rscPayload
,
clientModules
,
{
...
options
,
environmentName
,
}
)
},
()
=>
{
stageController
.
advanceStage
(
RenderStage
.
Static
)
},
()
=>
{
stageController
.
advanceStage
(
RenderStage
.
Dynamic
)
}
)
}
async
function
stagedRenderWithoutCachesInDevNode
(
ctx
:
AppRenderContext
,
requestStore
:
RequestStore
,
...
...
@@ -1333,24 +1568,28 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
runtimeStageEndTime
,
debugChannel
:
returnedDebugChannel
,
requestStore
:
finalRequestStore
,
}
=
await
renderWithRestartOnCacheMissInDevNode
(
}
=
await
(
process
.
env
.
__NEXT_USE_NODE_STREAMS
?
renderWithRestartOnCacheMissInDevNode
(
ctx
,
initialRequestStore
,
createRequestStore
,
getPayload
,
onError
)
:
renderWithRestartOnCacheMissInDevWeb
(
ctx
,
initialRequestStore
,
createRequestStore
,
getPayload
,
onError
))
if
(
shouldValidate
)
{
let
validationDebugChannelClient
:
AnyStream
|
undefined
=
undefined
if
(
returnedDebugChannel
)
{
const
debugChannelClientStream
=
new
ReplayableNodeStream
(
returnedDebugChannel
.
clientSide
.
readable
)
returnedDebugChannel
.
clientSide
.
readable
=
debugChannelClientStream
.
createReplayStream
()
validationDebugChannelClient
=
debugChannelClientStream
.
createReplayStream
()
const
[
t1
,
t2
]
=
teeStream
(
returnedDebugChannel
.
clientSide
.
readable
)
returnedDebugChannel
.
clientSide
.
readable
=
t1
validationDebugChannelClient
=
t2
}
consoleAsyncStorage
.
run
(
{
dim
:
true
},
...
...
@@ -1404,6 +1643,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
setCacheStatus
(
'bypass'
,
htmlRequestId
)
}
if
(
process
.
env
.
__NEXT_USE_NODE_STREAMS
)
{
debugChannel
=
setReactDebugChannel
&&
createNodeDebugChannel
()
stream
=
await
stagedRenderWithoutCachesInDevNode
(
...
...
@@ -1416,6 +1656,20 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
debugChannel
:
debugChannel
?.
serverSide
,
}
)
}
else
{
debugChannel
=
setReactDebugChannel
&&
createWebDebugChannel
()
stream
=
await
stagedRenderWithoutCachesInDevWeb
(
ctx
,
initialRequestStore
,
getPayload
,
{
onError
:
onError
,
filterStackFrame
,
debugChannel
:
debugChannel
?.
serverSide
,
}
)
}
}
if
(
debugChannel
&&
setReactDebugChannel
)
{
...
...
@@ -2852,11 +3106,19 @@ async function renderToHTMLOrFlightImpl(
)
}
else
if
(
cacheComponents
&&
cachedNavigations
)
{
// MARK: RSC cacheComponents
if
(
process
.
env
.
__NEXT_USE_NODE_STREAMS
)
{
return
generateStagedDynamicFlightRenderResultNode
(
req
,
ctx
,
requestStore
)
}
else
{
return
generateStagedDynamicFlightRenderResultWeb
(
req
,
ctx
,
requestStore
)
}
}
else
{
// MARK: RSC dynamic
return
generateDynamicFlightRenderResult
(
req
,
ctx
,
requestStore
)
...
...
@@ -3331,6 +3593,7 @@ async function renderToStream(
// We only have a Prerender environment for projects opted into cacheComponents
cacheComponents
) {
if (process.env.__NEXT_USE_NODE_STREAMS) {
// MARK: nodeStreams dev CacheComponents RSC
let debugChannelClientStream: ReplayableNodeStream | undefined
...
...
@@ -3421,7 +3684,8 @@ async function renderToStream(
// We're either bypassing caches or we can't restart the render.
// Do a dynamic render, but with (basic) environment labels.
const debugChannel = setReactDebugChannel && createNodeDebugChannel()
const debugChannel =
setReactDebugChannel && createNodeDebugChannel()
const serverStream = await stagedRenderWithoutCachesInDevNode(
ctx,
...
...
@@ -3451,7 +3715,129 @@ async function renderToStream(
requestId
)
}
} else {
// MARK: webstreams dev CacheComponents RSC
let debugChannel: DebugChannelPair | undefined
// eslint-disable-next-line @typescript-eslint/no-shadow
const getPayload = async (requestStore: RequestStore) => {
const payload: InitialRSCPayload & RSCPayloadDevProperties =
await workUnitAsyncStorage.run(
requestStore,
getRSCPayload,
tree,
ctx,
{ is404: res.statusCode === 404 }
)
if (isBypassingCachesInDev(requestStore, workStore)) {
// Mark the RSC payload to indicate that caches were bypassed in dev.
// This lets the client know not to cache anything based on this render.
if (renderOpts.setCacheStatus) {
// we know this is available when cacheComponents is enabled, but typeguard to be safe
renderOpts.setCacheStatus('bypass', htmlRequestId)
}
payload._bypassCachesInDev = createElement(
WarnForBypassCachesInDev,
{
route: workStore.route,
}
)
}
return payload
}
if (
// We only do this flow if we can safely recreate the store from scratch
// (which is not the case for renders after an action)
createRequestStore &&
// We only do this flow if we're not bypassing caches in dev using
// "disable cache" in devtools, a hard refresh (cache-control: "no-cache"),
// or draft mode.
!isBypassingCachesInDev(requestStore, workStore)
) {
const {
stream: serverStream,
accumulatedChunksPromise,
syncInterruptReason,
startTime,
staticStageEndTime,
runtimeStageEndTime,
debugChannel: returnedDebugChannel,
requestStore: finalRequestStore,
} = await renderWithRestartOnCacheMissInDevWeb(
ctx,
requestStore,
createRequestStore,
getPayload,
serverComponentsErrorHandler
)
let validationDebugChannelClient: AnyStream | undefined = undefined
if (returnedDebugChannel) {
const [t1, t2] = teeStream(
returnedDebugChannel.clientSide.readable
)
returnedDebugChannel.clientSide.readable = t1
validationDebugChannelClient = t2
}
consoleAsyncStorage.run(
{ dim: true },
spawnStaticShellValidationInDev,
accumulatedChunksPromise,
syncInterruptReason,
startTime,
staticStageEndTime,
runtimeStageEndTime,
ctx,
finalRequestStore,
fallbackParams,
validationDebugChannelClient,
didErrorObservably
)
reactServerResult = new ReactServerResult(serverStream)
requestStore = finalRequestStore
debugChannel = returnedDebugChannel
} else {
logValidationSkipped(ctx)
// We're either bypassing caches or we can't restart the render.
// Do a dynamic render, but with (basic) environment labels.
debugChannel = setReactDebugChannel && createWebDebugChannel()
const serverStream = await stagedRenderWithoutCachesInDevWeb(
ctx,
requestStore,
getPayload,
{
onError: serverComponentsErrorHandler,
filterStackFrame,
debugChannel: debugChannel?.serverSide,
}
)
reactServerResult = new ReactServerResult(serverStream)
}
if (debugChannel && setReactDebugChannel) {
const [readableSsr, readableBrowser] = teeStream(
debugChannel.clientSide.readable
)
reactDebugStream = readableSsr
setReactDebugChannel(
{ readable: readableBrowser },
htmlRequestId,
requestId
)
}
}
} else if (cacheComponents && cachedNavigations) {
if (process.env.__NEXT_USE_NODE_STREAMS) {
// MARK: nodeStreams cacheComponents RSC
// Production Cache Components + Cached Navigations: use staged
// rendering so the RSC payload includes the static stage byte length
...
...
@@ -3536,7 +3922,8 @@ async function renderToStream(
is404: res.statusCode === 404,
staleTimeIterable,
shellByteLengthPromise: shellByteLengthDeferred?.promise,
staticStageByteLengthPromise: staticStageByteLengthDeferred.promise,
staticStageByteLengthPromise:
staticStageByteLengthDeferred.promise,
runtimePrefetchStream,
}
)
...
...
@@ -3594,6 +3981,149 @@ async function renderToStream(
)
reactServerResult = new ReactServerResult(flightStream)
} else {
// MARK: webstreams cacheComponents RSC
// Production Cache Components + Cached Navigations: use staged
// rendering so the RSC payload includes the static stage byte length
// (`
l
` field), enabling the client to cache the static subset during
// hydration.
const { renderToReadableStream } = ctx.componentMod
const selectStaleTime = createSelectStaleTime(experimental)
const staleTimeIterable = new StaleTimeIterable()
const stageController = new StagedRenderingController({
abortSignal: null,
abandonController: null,
// TODO(cached-navs): this assumes that we checked during build that there's no sync IO.
// but it can happen e.g. after a revalidation or conditionally for a param that wasn't prerendered.
// we should change this to track sync IO, log an error and advance to dynamic.
shouldTrackSyncIO: false,
finalStage: null,
})
requestStore.stale = INFINITE_CACHE
requestStore.stagedRendering = stageController
requestStore.asyncApiPromises = createAsyncApiPromises(
stageController,
requestStore.cookies,
requestStore.mutableCookies,
requestStore.headers
)
requestStore.varyParamsAccumulator =
createResponseVaryParamsAccumulator()
trackStaleTime(
requestStore as { stale: number },
staleTimeIterable,
selectStaleTime
)
const shellByteLengthDeferred = appShells
? createPromiseWithResolvers<number | null>()
: null
const staticStageByteLengthDeferred =
createPromiseWithResolvers<number>()
// If the route has runtime prefetching enabled, spawn a runtime
// prerender after the resume render fills caches. The result is
// embedded in the initial RSC payload so the client can cache
// runtime-prefetchable content during hydration.
const hasRuntimePrefetch =
await anySegmentHasRuntimePrefetchEnabled(tree)
let runtimePrefetchStream: ReadableStream<Uint8Array> | undefined
if (hasRuntimePrefetch) {
const prerenderResumeDataCache = createPrerenderResumeDataCache()
requestStore.resumeDataCache = prerenderResumeDataCache
const cacheSignal = new CacheSignal()
trackPendingModules(cacheSignal)
requestStore.cacheSignal = cacheSignal
const runtimePrefetchTransform = new TransformStream<Uint8Array>()
runtimePrefetchStream = runtimePrefetchTransform.readable
void cacheSignal
.cacheReady()
.then(() =>
spawnRuntimePrefetchWithFilledCaches(
runtimePrefetchTransform.writable,
ctx,
prerenderResumeDataCache,
requestStore,
serverComponentsErrorHandler
)
)
}
const RSCPayload = await workUnitAsyncStorage.run(
requestStore,
getRSCPayload,
tree,
ctx,
{
is404: res.statusCode === 404,
staleTimeIterable,
shellByteLengthPromise: shellByteLengthDeferred?.promise,
staticStageByteLengthPromise:
staticStageByteLengthDeferred.promise,
runtimePrefetchStream,
}
)
const flightStream = await runInSequentialTasks(
() => {
// NOTE: no early/late separation in this render
stageController.advanceStage(RenderStage.ShellStatic)
const stream = workUnitAsyncStorage.run(
requestStore,
renderToReadableStream,
RSCPayload,
clientModules,
{
onError: serverComponentsErrorHandler,
filterStackFrame,
}
)
const [dynamicStream, staticStream] = stream.tee()
void countShellAndStaticStageBytes(
staticStream,
stageController
).then((byteLengths) => {
staticStageByteLengthDeferred.resolve(
byteLengths[RenderStage.Static]
)
shellByteLengthDeferred?.resolve(
byteLengths[RenderStage.ShellStatic]
)
})
return dynamicStream
},
() => {
stageController.advanceStage(RenderStage.Static)
},
() => {
// This is a separate task that doesn't advance a stage. It forces
// draining the immediate queue so that the stale time iterable and vary
// params accumulators are flushed before we advance to the dynamic stage.
staleTimeIterable.close()
if (requestStore.varyParamsAccumulator) {
finishAccumulatingVaryParams(requestStore.varyParamsAccumulator)
}
},
() => {
stageController.advanceStage(RenderStage.Dynamic)
}
)
reactServerResult = new ReactServerResult(flightStream)
}
} else {
// MARK: nodeStreams RSC
if (process.env.__NEXT_USE_NODE_STREAMS) {
...
...
@@ -4239,9 +4769,319 @@ async function renderToStream(
/* eslint-enable @next/internal/no-ambiguous-jsx */
}
function getEnvironmentNameForStage(stage: RenderStage) {
switch (stage) {
case RenderStage.Before:
async function renderWithRestartOnCacheMissInDevWeb(
ctx: AppRenderContext,
initialRequestStore: RequestStore,
createRequestStore: () => RequestStore,
getPayload: (requestStore: RequestStore) => Promise<RSCPayload>,
onError: (error: unknown) => void
) {
const { htmlRequestId, renderOpts } = ctx
const { ComponentMod, setCacheStatus, setReactDebugChannel } = renderOpts
let startTime = -Infinity
// If the render is restarted, we'll recreate a fresh request store
let requestStore: RequestStore = initialRequestStore
const environmentName = () => {
const currentStage = requestStore.stagedRendering!.currentStage
return getEnvironmentNameForStage(currentStage)
}
//===============================================
// Initial render
//===============================================
// Try to render the page and see if there's any cache misses.
// If there are, wait for caches to finish and restart the render.
// This render might end up being used as a prospective render (if there's cache misses),
// so we need to set it up for filling caches.
const cacheSignal = new CacheSignal()
// If we encounter async modules that delay rendering, we'll also need to restart.
// TODO(restart-on-cache-miss): technically, we only need to wait for pending *server* modules here,
// but `
trackPendingModules
` doesn't distinguish between client and server.
trackPendingModules(cacheSignal)
const prerenderResumeDataCache = createPrerenderResumeDataCache()
const initialReactController = new AbortController()
const initialDataController = new AbortController() // Controls hanging promises we create
const initialAbandonController = new AbortController() // Controls whether this render is abandoned
const initialStageController = new StagedRenderingController({
abortSignal: initialDataController.signal,
abandonController: initialAbandonController,
shouldTrackSyncIO: true,
finalStage: null,
})
// Use a mutable resume data cache for the warmup. After the warmup we'll swap
// it out for a read-only resume data cache.
requestStore.resumeDataCache = prerenderResumeDataCache
requestStore.stagedRendering = initialStageController
requestStore.asyncApiPromises = createAsyncApiPromises(
initialStageController,
requestStore.cookies,
requestStore.mutableCookies,
requestStore.headers
)
requestStore.cacheSignal = cacheSignal
let debugChannel = setReactDebugChannel && createWebDebugChannel()
const { clientModules } = getClientReferenceManifest()
// Note: The stage controller starts out in the `
Before
` stage,
// where sync IO does not cause aborts, so it's okay if it happens before render.
const initialRscPayload = await getPayload(requestStore)
const advanceStageIfNoCacheMiss = (
stage: Parameters<StagedRenderingController['advanceStage']>[0]
) => {
if (initialAbandonController.signal.aborted === true) {
return
} else if (cacheSignal.hasPendingReads()) {
initialAbandonController.abort()
} else {
initialStageController.advanceStage(stage)
}
}
const initialStreamResult = await runInSequentialTasks(
() => {
initialStageController.advanceStage(RenderStage.ShellEarlyStatic)
startTime = performance.now() + performance.timeOrigin
const streamPair = teeStream(
workUnitAsyncStorage.run(
requestStore,
renderToWebFlightStream,
ComponentMod,
initialRscPayload,
clientModules,
{
onError,
environmentName,
startTime,
filterStackFrame,
debugChannel: debugChannel?.serverSide,
signal: initialReactController.signal,
}
)
)
// 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
// so that it runs after react is finished running its abort code.
initialReactController.signal.addEventListener(
'abort',
() => {
const { reason } = initialReactController.signal
initialDataController.abort(reason)
},
{ once: true }
)
const stream = streamPair[0]
const accumulatedChunksPromise = accumulateStreamChunks(
streamPair[1],
initialStageController,
initialDataController.signal
)
initialDataController.signal.addEventListener(
'abort',
() => {
accumulatedChunksPromise.catch(() => {})
if (stream instanceof ReadableStream) {
stream.cancel()
} else {
stream.destroy()
}
},
{ once: true }
)
return {
stream,
accumulatedChunksPromise,
}
},
() => {
advanceStageIfNoCacheMiss(RenderStage.ShellStatic)
},
() => {
advanceStageIfNoCacheMiss(RenderStage.EarlyStatic)
},
() => {
advanceStageIfNoCacheMiss(RenderStage.Static)
},
() => {
advanceStageIfNoCacheMiss(RenderStage.ShellEarlyRuntime)
},
() => {
advanceStageIfNoCacheMiss(RenderStage.ShellRuntime)
},
() => {
advanceStageIfNoCacheMiss(RenderStage.EarlyRuntime)
},
() => {
advanceStageIfNoCacheMiss(RenderStage.Runtime)
},
() => {
advanceStageIfNoCacheMiss(RenderStage.Dynamic)
}
)
if (initialStageController.currentStage !== RenderStage.Abandoned) {
// No cache misses. We can use the result as-is.
return {
stream: initialStreamResult.stream,
accumulatedChunksPromise: initialStreamResult.accumulatedChunksPromise,
syncInterruptReason: initialStageController.getSyncInterruptReason(),
startTime,
staticStageEndTime: initialStageController.getStaticStageEndTime(),
runtimeStageEndTime: initialStageController.getRuntimeStageEndTime(),
debugChannel,
requestStore,
}
}
if (process.env.__NEXT_DEV_SERVER && setCacheStatus) {
setCacheStatus('filling', htmlRequestId)
}
// Cache miss. We will use the initial render to fill caches, and discard its result.
// Then, we can render again with warm caches.
// TODO(restart-on-cache-miss):
// This might end up waiting for more caches than strictly necessary,
// because we can't abort the render yet, and we'll let runtime/dynamic APIs resolve.
// Ideally we'd only wait for caches that are needed in the static stage.
// This will be optimized in the future by not allowing runtime/dynamic APIs to resolve.
await cacheSignal.cacheReady()
workUnitAsyncStorage.run(
requestStore,
initialReactController.abort.bind(initialReactController)
)
//===============================================
// Final render (restarted)
//===============================================
// The initial render acted as a prospective render to warm the caches.
requestStore = createRequestStore()
const finalStageController = new StagedRenderingController({
// We are going to render this pass all the way through because we've already
// filled any caches so we won't be aborting this time.
abortSignal: null,
abandonController: null,
shouldTrackSyncIO: true,
finalStage: null,
})
// We've filled the caches, so now we can render as usual,
// without any cache-filling mechanics.
requestStore.resumeDataCache = createRenderResumeDataCache(
prerenderResumeDataCache
)
requestStore.stagedRendering = finalStageController
requestStore.cacheSignal = null
requestStore.asyncApiPromises = createAsyncApiPromises(
finalStageController,
requestStore.cookies,
requestStore.mutableCookies,
requestStore.headers
)
// The initial render already wrote to its debug channel.
// We're not using it, so we need to create a new one.
debugChannel = setReactDebugChannel && createWebDebugChannel()
// Note: The stage controller starts out in the `
Before
` stage,
// where sync IO does not cause aborts, so it's okay if it happens before render.
const finalRscPayload = await getPayload(requestStore)
const finalStreamResult = await runInSequentialTasks(
() => {
finalStageController.advanceStage(RenderStage.ShellEarlyStatic)
startTime = performance.now() + performance.timeOrigin
const streamPair = teeStream(
workUnitAsyncStorage.run(
requestStore,
renderToWebFlightStream,
ComponentMod,
finalRscPayload,
clientModules,
{
onError,
environmentName,
startTime,
filterStackFrame,
debugChannel: debugChannel?.serverSide,
}
)
)
return {
stream: streamPair[0],
accumulatedChunksPromise: accumulateStreamChunks(
streamPair[1],
finalStageController,
null
),
}
},
() => {
finalStageController.advanceStage(RenderStage.ShellStatic)
},
() => {
finalStageController.advanceStage(RenderStage.EarlyStatic)
},
() => {
finalStageController.advanceStage(RenderStage.Static)
},
() => {
finalStageController.advanceStage(RenderStage.ShellEarlyRuntime)
},
() => {
finalStageController.advanceStage(RenderStage.ShellRuntime)
},
() => {
finalStageController.advanceStage(RenderStage.EarlyRuntime)
},
() => {
finalStageController.advanceStage(RenderStage.Runtime)
},
() => {
finalStageController.advanceStage(RenderStage.Dynamic)
}
)
if (process.env.__NEXT_DEV_SERVER && setCacheStatus) {
setCacheStatus('filled', htmlRequestId)
}
return {
stream: finalStreamResult.stream,
accumulatedChunksPromise: finalStreamResult.accumulatedChunksPromise,
syncInterruptReason: finalStageController.getSyncInterruptReason(),
startTime,
staticStageEndTime: finalStageController.getStaticStageEndTime(),
runtimeStageEndTime: finalStageController.getRuntimeStageEndTime(),
debugChannel,
requestStore,
}
}
function getEnvironmentNameForStage(stage: RenderStage) {
switch (stage) {
case RenderStage.Before:
case RenderStage.ShellEarlyStatic:
case RenderStage.ShellStatic:
case RenderStage.EarlyStatic:
...
...
@@ -4695,7 +5535,7 @@ function accumulateChunk(
}
async function countShellAndStaticStageBytes(
stream:
Readable
,
stream:
AnyStream
,
stageController: StagedRenderingController
): Promise<
Pick<StageByteLengths, RenderStage.ShellStatic | RenderStage.Static>
...
...
@@ -4707,12 +5547,21 @@ async function countShellAndStaticStageBytes(
const endStage = getNextStage(RenderStage.Static)
stageController.onStage(endStage, abortController.abort.bind(abortController))
if (stream instanceof ReadableStream) {
await countStageBytesUntilAbortWeb(
byteLengths,
stream,
stageController,
abortController.signal
)
} else {
await countStageBytesUntilAbortNode(
byteLengths,
stream,
stageController,
abortController.signal
)
}
return byteLengths
}
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment