Unverified Commit 89bd4833 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Remove dead cacheComponents web streams path (#93944)

### What?

Remove the cacheComponents + web streams rendering branches from
`app-render`.

### Why?

`cacheComponents` does not support the edge runtime, and Node streams
are now always-on for the Node.js runtime in the parent PR. That makes
the cacheComponents web-stream branches dead code.

### How?

- Collapse cacheComponents staged RSC rendering to the Node-stream
implementation.
- Remove the web-stream cacheComponents helper functions and
static-stage byte counter.
- Keep the ordinary non-cacheComponents web-stream paths for
edge/runtime compatibility.

### Verification

- `pnpm --filter=next types`
- `pnpm --filter=next build`
- `pnpm test-start-webpack test/e2e/app-dir/app/standalone.test.ts`

<!-- NEXT_JS_LLM_PR -->
parent ec28a4fd
......@@ -901,178 +901,6 @@ 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
......@@ -1311,69 +1139,6 @@ 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,
......@@ -1568,28 +1333,24 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
runtimeStageEndTime,
debugChannel: returnedDebugChannel,
requestStore: finalRequestStore,
} = await (process.env.__NEXT_USE_NODE_STREAMS
? renderWithRestartOnCacheMissInDevNode(
ctx,
initialRequestStore,
createRequestStore,
getPayload,
onError
)
: renderWithRestartOnCacheMissInDevWeb(
ctx,
initialRequestStore,
createRequestStore,
getPayload,
onError
))
} = await renderWithRestartOnCacheMissInDevNode(
ctx,
initialRequestStore,
createRequestStore,
getPayload,
onError
)
if (shouldValidate) {
let validationDebugChannelClient: AnyStream | undefined = undefined
if (returnedDebugChannel) {
const [t1, t2] = teeStream(returnedDebugChannel.clientSide.readable)
returnedDebugChannel.clientSide.readable = t1
validationDebugChannelClient = t2
const debugChannelClientStream = new ReplayableNodeStream(
returnedDebugChannel.clientSide.readable
)
returnedDebugChannel.clientSide.readable =
debugChannelClientStream.createReplayStream()
validationDebugChannelClient =
debugChannelClientStream.createReplayStream()
}
consoleAsyncStorage.run(
{ dim: true },
......@@ -1643,33 +1404,18 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
setCacheStatus('bypass', htmlRequestId)
}
if (process.env.__NEXT_USE_NODE_STREAMS) {
debugChannel = setReactDebugChannel && createNodeDebugChannel()
stream = await stagedRenderWithoutCachesInDevNode(
ctx,
initialRequestStore,
getPayload,
{
onError: onError,
filterStackFrame,
debugChannel: debugChannel?.serverSide,
}
)
} else {
debugChannel = setReactDebugChannel && createWebDebugChannel()
debugChannel = setReactDebugChannel && createNodeDebugChannel()
stream = await stagedRenderWithoutCachesInDevWeb(
ctx,
initialRequestStore,
getPayload,
{
onError: onError,
filterStackFrame,
debugChannel: debugChannel?.serverSide,
}
)
}
stream = await stagedRenderWithoutCachesInDevNode(
ctx,
initialRequestStore,
getPayload,
{
onError: onError,
filterStackFrame,
debugChannel: debugChannel?.serverSide,
}
)
}
if (debugChannel && setReactDebugChannel) {
......@@ -3106,19 +2852,11 @@ 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
)
}
return generateStagedDynamicFlightRenderResultNode(
req,
ctx,
requestStore
)
} else {
// MARK: RSC dynamic
return generateDynamicFlightRenderResult(req, ctx, requestStore)
......@@ -3593,537 +3331,269 @@ 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
// 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,
}
)
}
// MARK: nodeStreams dev CacheComponents RSC
let debugChannelClientStream: ReplayableNodeStream | undefined
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 renderWithRestartOnCacheMissInDevNode(
ctx,
// eslint-disable-next-line @typescript-eslint/no-shadow
const getPayload = async (requestStore: RequestStore) => {
const payload: InitialRSCPayload & RSCPayloadDevProperties =
await workUnitAsyncStorage.run(
requestStore,
createRequestStore,
getPayload,
serverComponentsErrorHandler
)
let validationDebugChannelClient: AnyStream | undefined = undefined
if (returnedDebugChannel) {
debugChannelClientStream = new ReplayableNodeStream(
returnedDebugChannel.clientSide.readable
)
validationDebugChannelClient =
debugChannelClientStream.createReplayStream()
}
consoleAsyncStorage.run(
{ dim: true },
spawnStaticShellValidationInDev,
accumulatedChunksPromise,
syncInterruptReason,
startTime,
staticStageEndTime,
runtimeStageEndTime,
getRSCPayload,
tree,
ctx,
finalRequestStore,
fallbackParams,
validationDebugChannelClient,
didErrorObservably
{ is404: res.statusCode === 404 }
)
reactServerResult = new ReactServerResult(serverStream)
requestStore = finalRequestStore
} else {
logValidationSkipped(ctx)
// 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 serverStream = await stagedRenderWithoutCachesInDevNode(
ctx,
requestStore,
getPayload,
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,
{
onError: serverComponentsErrorHandler,
filterStackFrame,
debugChannel: debugChannel?.serverSide,
route: workStore.route,
}
)
reactServerResult = new ReactServerResult(serverStream)
if (debugChannel) {
debugChannelClientStream = new ReplayableNodeStream(
debugChannel.clientSide.readable
)
}
}
if (debugChannelClientStream && setReactDebugChannel) {
reactDebugStream = debugChannelClientStream.createReplayStream()
return payload
}
setReactDebugChannel(
{ readable: debugChannelClientStream.createReplayStream() },
htmlRequestId,
requestId
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 renderWithRestartOnCacheMissInDevNode(
ctx,
requestStore,
createRequestStore,
getPayload,
serverComponentsErrorHandler
)
let validationDebugChannelClient: AnyStream | undefined = undefined
if (returnedDebugChannel) {
debugChannelClientStream = new ReplayableNodeStream(
returnedDebugChannel.clientSide.readable
)
validationDebugChannelClient =
debugChannelClientStream.createReplayStream()
}
} 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 }
)
consoleAsyncStorage.run(
{ dim: true },
spawnStaticShellValidationInDev,
accumulatedChunksPromise,
syncInterruptReason,
startTime,
staticStageEndTime,
runtimeStageEndTime,
ctx,
finalRequestStore,
fallbackParams,
validationDebugChannelClient,
didErrorObservably
)
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,
}
)
}
reactServerResult = new ReactServerResult(serverStream)
requestStore = finalRequestStore
} else {
logValidationSkipped(ctx)
return payload
}
// We're either bypassing caches or we can't restart the render.
// Do a dynamic render, but with (basic) environment labels.
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
)
const debugChannel = setReactDebugChannel && createNodeDebugChannel()
let validationDebugChannelClient: AnyStream | undefined = undefined
if (returnedDebugChannel) {
const [t1, t2] = teeStream(
returnedDebugChannel.clientSide.readable
)
returnedDebugChannel.clientSide.readable = t1
validationDebugChannelClient = t2
const serverStream = await stagedRenderWithoutCachesInDevNode(
ctx,
requestStore,
getPayload,
{
onError: serverComponentsErrorHandler,
filterStackFrame,
debugChannel: debugChannel?.serverSide,
}
)
reactServerResult = new ReactServerResult(serverStream)
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(
if (debugChannel) {
debugChannelClientStream = new ReplayableNodeStream(
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
// (`l` field), enabling the client to cache the static subset during
// hydration.
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()
if (debugChannelClientStream && setReactDebugChannel) {
reactDebugStream = debugChannelClientStream.createReplayStream()
trackStaleTime(
requestStore as { stale: number },
staleTimeIterable,
selectStaleTime
setReactDebugChannel(
{ readable: debugChannelClientStream.createReplayStream() },
htmlRequestId,
requestId
)
}
} else if (cacheComponents && cachedNavigations) {
// MARK: nodeStreams 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 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,
})
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,
}
)
requestStore.stale = INFINITE_CACHE
requestStore.stagedRendering = stageController
requestStore.asyncApiPromises = createAsyncApiPromises(
stageController,
requestStore.cookies,
requestStore.mutableCookies,
requestStore.headers
)
requestStore.varyParamsAccumulator =
createResponseVaryParamsAccumulator()
const flightStream = await runInSequentialTasks(
() => {
// NOTE: no early/late separation in this render
stageController.advanceStage(RenderStage.ShellStatic)
trackStaleTime(
requestStore as { stale: number },
staleTimeIterable,
selectStaleTime
)
const stream = workUnitAsyncStorage.run(
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,
renderToNodeFlightStream,
ctx.componentMod,
RSCPayload,
clientModules,
{
onError: serverComponentsErrorHandler,
filterStackFrame,
}
) as Readable
const replayable = new ReplayableNodeStream(stream)
const dynamicStream = replayable.createReplayStream()
const staticStream = replayable.createReplayStream()
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: 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()
serverComponentsErrorHandler
)
)
}
trackStaleTime(
requestStore as { stale: number },
const RSCPayload = await workUnitAsyncStorage.run(
requestStore,
getRSCPayload,
tree,
ctx,
{
is404: res.statusCode === 404,
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
)
)
shellByteLengthPromise: shellByteLengthDeferred?.promise,
staticStageByteLengthPromise: staticStageByteLengthDeferred.promise,
runtimePrefetchStream,
}
)
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 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 stream = workUnitAsyncStorage.run(
requestStore,
renderToNodeFlightStream,
ctx.componentMod,
RSCPayload,
clientModules,
{
onError: serverComponentsErrorHandler,
filterStackFrame,
}
) as Readable
const replayable = new ReplayableNodeStream(stream)
const dynamicStream = replayable.createReplayStream()
const staticStream = replayable.createReplayStream()
void countShellAndStaticStageBytes(
staticStream,
stageController
).then((byteLengths) => {
staticStageByteLengthDeferred.resolve(
byteLengths[RenderStage.Static]
)
shellByteLengthDeferred?.resolve(
byteLengths[RenderStage.ShellStatic]
)
})
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 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)
}
reactServerResult = new ReactServerResult(flightStream)
} else {
// MARK: nodeStreams RSC
if (process.env.__NEXT_USE_NODE_STREAMS) {
......@@ -4769,316 +4239,6 @@ async function renderToStream(
/* eslint-enable @next/internal/no-ambiguous-jsx */
}
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:
......@@ -5535,7 +4695,7 @@ function accumulateChunk(
}
async function countShellAndStaticStageBytes(
stream: AnyStream,
stream: Readable,
stageController: StagedRenderingController
): Promise<
Pick<StageByteLengths, RenderStage.ShellStatic | RenderStage.Static>
......@@ -5547,21 +4707,12 @@ 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
)
}
await countStageBytesUntilAbortNode(
byteLengths,
stream,
stageController,
abortController.signal
)
return byteLengths
}
......
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