Commit 62575295 authored by Jimmy Lai's avatar Jimmy Lai Committed by Tim Neutkens

feat(node-streams): wire node stream primitives into render pipeline

Integrate the node stream building blocks (from prior PR) into the
actual render paths, all gated behind experimental.useNodeStreams:

- app-render.tsx: add useNodeStreams branching throughout render paths,
  teeDebugChannelForSsrAndBrowser and debugChannelClientForBrowser helpers
- app-render-prerender-utils.ts: ReactServerResult accepts NodeReadable,
  createReactServerPrerenderResultFromPrerender dispatcher
- instant-validation.tsx: node stream branches for validation renders
- render-result.ts: accept Node Readable as response body with piping
- flight-render-result.ts: accept Node Readable in constructor
- app-page.ts: PPR resume path for node streams
- stream-ops.ts/debug-channel-server.ts: widen types to include Readable
parent 558f4248
......@@ -71,6 +71,7 @@ import {
getPostponedStateExceededErrorMessage,
readBodyWithSizeLimit,
} from '../../server/lib/postponed-request-body'
import { chainNodeStreams } from '../../server/stream-utils/chain-node-streams'
// These are injected by the loader afterwards.
......@@ -1495,6 +1496,64 @@ export async function handler(
})
}
if (process.env.__NEXT_USE_NODE_STREAMS) {
// Node streams path: construct the response as a single Node Readable
// chain (cached HTML + optional sentinel + resume render) to avoid
// web stream interop issues with Readable.toWeb().
const { PassThrough, Readable: NodeReadable } =
require('node:stream') as typeof import('node:stream')
const streams: import('node:stream').Readable[] = [
NodeReadable.from(body.toUnchunkedString()),
]
if (process.env.__NEXT_TEST_MODE) {
streams.push(NodeReadable.from('<!-- PPR_BOUNDARY_SENTINEL -->'))
}
const bridge = new PassThrough()
streams.push(bridge)
const combined = chainNodeStreams(...streams)
const result = new RenderResult(combined, {
contentType: body.contentType,
metadata: body.metadata as any,
})
doRender({
span,
postponed: cachedData.postponed,
fallbackRouteParams: null,
forceStaticRender: false,
})
.then(async (renderResult) => {
if (!renderResult) {
throw new Error('Invariant: expected a result to be returned')
}
if (renderResult.value?.kind !== CachedRouteKind.APP_PAGE) {
throw new Error(
`Invariant: expected a page response, got ${renderResult.value?.kind}`
)
}
await renderResult.value.html.pipeToNodeWritable(bridge)
})
.catch((err) => {
bridge.destroy(err instanceof Error ? err : new Error(String(err)))
})
return sendRenderResult({
req,
res,
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
result,
cacheControl: { revalidate: 0, expire: undefined },
})
}
// If we're in test mode, we should add a sentinel chunk to the response
// that's between the static and dynamic parts so we can compare the
// chunks and add assertions.
......
import type { Readable as NodeReadable } from 'node:stream'
import { InvariantError } from '../../shared/lib/invariant-error'
import { teeNodeReadable } from './node-stream-tee'
// React's RSC prerender function will emit an incomplete flight stream when using `prerender`. If the connection
// closes then whatever hanging chunks exist will be errored. This is because prerender (an experimental feature)
// has not yet implemented a concept of resume. For now we will simulate a paused connection by wrapping the stream
// in one that doesn't close even when the underlying is complete.
export class ReactServerResult {
private _stream: null | ReadableStream<Uint8Array>
private _stream: null | ReadableStream<Uint8Array> | NodeReadable
private readonly _runInContext: <T>(fn: () => T) => T
constructor(stream: ReadableStream<Uint8Array>) {
constructor(
stream: ReadableStream<Uint8Array> | NodeReadable,
runInContext?: <T>(fn: () => T) => T
) {
this._stream = stream
this._runInContext = runInContext ?? ((fn) => fn())
}
tee() {
tee(): ReadableStream<Uint8Array> | NodeReadable {
if (this._stream === null) {
throw new Error(
'Cannot tee a ReactServerResult that has already been consumed'
)
}
if (this._stream instanceof ReadableStream) {
const tee = this._stream.tee()
this._stream = tee[0]
return tee[1]
} else if (process.env.NEXT_RUNTIME !== 'edge') {
// Node tee callback handlers run on event boundaries, so keep request ALS
// context stable for whichever branch is consumed later.
const [primary, secondary] = teeNodeReadable(
this._stream as NodeReadable,
this._runInContext
)
this._stream = primary
return secondary
} else {
throw new Error('Cannot tee a Node.js stream in the edge runtime')
}
}
consume() {
consume(): ReadableStream<Uint8Array> | NodeReadable {
if (this._stream === null) {
throw new Error(
'Cannot consume a ReactServerResult that has already been consumed'
......@@ -39,6 +58,10 @@ export type ReactServerPrerenderResolveToType = {
prelude: ReadableStream<Uint8Array>
}
export type ReactServerPrerenderNodeResolveToType = {
prelude: NodeReadable
}
export async function createReactServerPrerenderResult(
underlying: Promise<ReactServerPrerenderResolveToType>
): Promise<ReactServerPrerenderResult> {
......@@ -55,10 +78,42 @@ export async function createReactServerPrerenderResult(
}
}
export async function createReactServerPrerenderResultFromNodeStream(
underlying: Promise<ReactServerPrerenderNodeResolveToType>
): Promise<ReactServerPrerenderResult> {
const chunks: Array<Uint8Array> = []
const { prelude } = await underlying
for await (const chunk of prelude) {
chunks.push(
Buffer.isBuffer(chunk) ? new Uint8Array(chunk) : (chunk as Uint8Array)
)
}
return new ReactServerPrerenderResult(chunks)
}
/**
* Compile-time unified factory: creates a ReactServerPrerenderResult from a
* prerender promise that resolves to { prelude }, using either the web or node
* stream consumer based on __NEXT_USE_NODE_STREAMS.
*/
export async function createReactServerPrerenderResultFromPrerender(
underlying: Promise<{ prelude: ReadableStream<Uint8Array> | NodeReadable }>
): Promise<ReactServerPrerenderResult> {
if (process.env.__NEXT_USE_NODE_STREAMS) {
return createReactServerPrerenderResultFromNodeStream(
underlying as Promise<ReactServerPrerenderNodeResolveToType>
)
}
return createReactServerPrerenderResult(
underlying as Promise<ReactServerPrerenderResolveToType>
)
}
export async function createReactServerPrerenderResultFromRender(
underlying: ReadableStream<Uint8Array>
underlying: ReadableStream<Uint8Array> | NodeReadable
): Promise<ReactServerPrerenderResult> {
const chunks: Array<Uint8Array> = []
if (underlying instanceof ReadableStream) {
const reader = underlying.getReader()
while (true) {
const { done, value } = await reader.read()
......@@ -68,6 +123,14 @@ export async function createReactServerPrerenderResultFromRender(
chunks.push(value)
}
}
} else {
// Node.js Readable
for await (const chunk of underlying) {
chunks.push(
Buffer.isBuffer(chunk) ? new Uint8Array(chunk) : (chunk as Uint8Array)
)
}
}
return new ReactServerPrerenderResult(chunks)
}
export class ReactServerPrerenderResult {
......@@ -115,6 +178,53 @@ export class ReactServerPrerenderResult {
const chunks = this.consumeChunks('consumeAsStream()')
return createClosingStream(chunks)
}
asNodeStream(): NodeReadable {
const chunks = this.assertChunks('asNodeStream()')
return createClosingNodeStream(chunks)
}
consumeAsNodeStream(): NodeReadable {
const chunks = this.consumeChunks('consumeAsNodeStream()')
return createClosingNodeStream(chunks)
}
asUnclosingNodeStream(): NodeReadable {
const chunks = this.assertChunks('asUnclosingNodeStream()')
return createUnclosingNodeStream(chunks)
}
consumeAsUnclosingNodeStream(): NodeReadable {
const chunks = this.consumeChunks('consumeAsUnclosingNodeStream()')
return createUnclosingNodeStream(chunks)
}
// Compile-time unified methods: use __NEXT_USE_NODE_STREAMS to pick
// the right stream type without branching at the call site.
asFlightStream(): ReadableStream<Uint8Array> | NodeReadable {
return process.env.__NEXT_USE_NODE_STREAMS
? this.asNodeStream()
: this.asStream()
}
consumeAsFlightStream(): ReadableStream<Uint8Array> | NodeReadable {
return process.env.__NEXT_USE_NODE_STREAMS
? this.consumeAsNodeStream()
: this.consumeAsStream()
}
asUnclosingFlightStream(): ReadableStream<Uint8Array> | NodeReadable {
return process.env.__NEXT_USE_NODE_STREAMS
? this.asUnclosingNodeStream()
: this.asUnclosingStream()
}
consumeAsUnclosingFlightStream(): ReadableStream<Uint8Array> | NodeReadable {
return process.env.__NEXT_USE_NODE_STREAMS
? this.consumeAsUnclosingNodeStream()
: this.consumeAsUnclosingStream()
}
}
function createUnclosingStream(
......@@ -148,6 +258,38 @@ function createClosingStream(
})
}
function createClosingNodeStream(chunks: Array<Uint8Array>): NodeReadable {
if (process.env.NEXT_RUNTIME === 'edge') {
throw new Error('createClosingNodeStream is not supported in edge runtime')
} else {
const { PassThrough } =
require('node:stream') as typeof import('node:stream')
const pt = new PassThrough()
for (const chunk of chunks) {
pt.write(chunk)
}
pt.end()
return pt
}
}
function createUnclosingNodeStream(chunks: Array<Uint8Array>): NodeReadable {
if (process.env.NEXT_RUNTIME === 'edge') {
throw new Error(
'createUnclosingNodeStream is not supported in edge runtime'
)
} else {
const { PassThrough } =
require('node:stream') as typeof import('node:stream')
const pt = new PassThrough()
for (const chunk of chunks) {
pt.write(chunk)
}
// intentionally do not end the stream
return pt
}
}
export async function processPrelude(
unprocessedPrelude: ReadableStream<Uint8Array>
) {
......@@ -166,8 +308,6 @@ export async function processNodePrelude(unprocessedPrelude: NodeReadable) {
if (process.env.NEXT_RUNTIME === 'edge') {
throw new Error('processNodePrelude is not supported in edge runtime')
} else {
const { teeNodeReadable } =
require('./node-stream-tee') as typeof import('./node-stream-tee')
const [prelude, peek] = teeNodeReadable(unprocessedPrelude)
// Read the first chunk from the peek stream to check if it's empty
......
......@@ -53,6 +53,8 @@ import {
getClientPrerender,
processPrelude as processPreludeOp,
createDocumentClosingStream,
nodeReadableToWeb,
pipeRuntimePrefetchTransform,
} from './stream-ops'
import { stripInternalQueries } from '../internal-utils'
import {
......@@ -174,6 +176,7 @@ import {
ReactServerResult,
createReactServerPrerenderResultFromRender,
} from './app-render-prerender-utils'
import { teeNodeReadable } from './node-stream-tee'
import {
Phase,
printDebugThrownValueForProspectiveRender,
......@@ -244,6 +247,53 @@ import {
} from './debug-channel-server'
import { createNodeStreamWithLateRelease } from './instant-validation/stream-utils'
/**
* Tees a debug channel's client-side readable into an SSR branch and a
* browser branch. The browser branch is always a web ReadableStream because
* setReactDebugChannel sends it to the client via HMR.
*/
function teeDebugChannelForSsrAndBrowser(debugChannel: DebugChannelPair): {
ssrStream: ReadableStream<Uint8Array> | import('node:stream').Readable
browserChannel: { readable: ReadableStream<Uint8Array> }
} {
const readable = debugChannel.clientSide.readable
if (readable instanceof ReadableStream) {
const [ssrStream, browserStream] = readable.tee()
return { ssrStream, browserChannel: { readable: browserStream } }
} else if (process.env.__NEXT_USE_NODE_STREAMS && nodeReadableToWeb) {
// Node Readable: tee natively, convert browser branch to web for HMR
const [ssrStream, browserNodeStream] = teeNodeReadable(readable)
const browserStream = nodeReadableToWeb(browserNodeStream)
return { ssrStream, browserChannel: { readable: browserStream } }
} else {
throw new Error(
'Debug channel readable is not a ReadableStream but node streams are not enabled, this is a bug in the Next.js codebase'
)
}
}
/**
* Returns a web-shaped { readable: ReadableStream } for the browser side of a
* debug channel. When the debug channel already uses web streams, this is a
* no-op. When it uses Node streams, we convert to web for HMR delivery.
*/
function debugChannelClientForBrowser(debugChannel: DebugChannelPair): {
readable: ReadableStream<Uint8Array>
} {
const readable = debugChannel.clientSide.readable
if (readable instanceof ReadableStream) {
return { readable }
} else if (process.env.__NEXT_USE_NODE_STREAMS && nodeReadableToWeb) {
return {
readable: nodeReadableToWeb(readable),
}
} else {
throw new Error(
'Debug channel readable is not a ReadableStream but node streams are not enabled, this is a bug in the Next.js codebase'
)
}
}
// NOTE: Only use this for types, access implementations via ComponentMod
import type * as InstantValidation from './instant-validation/instant-validation'
import { createValidationBoundaryTracking } from './instant-validation/boundary-tracking'
......@@ -702,7 +752,11 @@ async function generateDynamicFlightRenderResult(
const debugChannel = setReactDebugChannel && createDebugChannel()
if (debugChannel) {
setReactDebugChannel(debugChannel.clientSide, htmlRequestId, requestId)
setReactDebugChannel(
debugChannelClientForBrowser(debugChannel),
htmlRequestId,
requestId
)
}
const { clientModules } = getClientReferenceManifest()
......@@ -890,7 +944,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
}
let debugChannel: DebugChannelPair | undefined
let stream: ReadableStream<Uint8Array>
let stream: ReadableStream<Uint8Array> | Readable
if (
// We only do this flow if we can safely recreate the store from scratch
......@@ -924,11 +978,22 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
)
if (shouldValidate) {
let validationDebugChannelClient: Readable | undefined = undefined
let validationDebugChannelClient:
| Readable
| ReadableStream<Uint8Array>
| undefined = undefined
if (returnedDebugChannel) {
const [t1, t2] = returnedDebugChannel.clientSide.readable.tee()
const readable = returnedDebugChannel.clientSide.readable
if (readable instanceof ReadableStream) {
const [t1, t2] = readable.tee()
returnedDebugChannel.clientSide.readable = t1
validationDebugChannelClient = t2
} else {
// Node Readable: tee natively, no web→Node conversion needed
const [t1, t2] = teeNodeReadable(readable)
returnedDebugChannel.clientSide.readable = t1
validationDebugChannelClient = nodeStreamFromReadableStream(t2)
validationDebugChannelClient = t2
}
}
consoleAsyncStorage.run(
{ dim: true },
......@@ -973,7 +1038,11 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
}
if (debugChannel && setReactDebugChannel) {
setReactDebugChannel(debugChannel.clientSide, htmlRequestId, requestId)
setReactDebugChannel(
debugChannelClientForBrowser(debugChannel),
htmlRequestId,
requestId
)
}
return new FlightRenderResult(stream, {
......@@ -1177,7 +1246,9 @@ async function prospectiveRuntimeServerPrerender(
}
try {
return await createReactServerPrerenderResult(pendingInitialServerResult)
return await createReactServerPrerenderResultFromPrerender(
pendingInitialServerResult
)
} catch (err) {
if (
initialServerRenderController.signal.aborted ||
......@@ -1739,7 +1810,7 @@ function ErrorApp<T>({
nonce,
images,
}: {
reactServerStream: BinaryStreamOf<T>
reactServerStream: Readable | BinaryStreamOf<T>
preinitScripts: () => void
ServerInsertedHTMLProvider: ComponentType<{
children: JSX.Element
......@@ -2480,7 +2551,7 @@ async function renderToStream(
metadata: AppPageRenderResultMetadata,
createRequestStore: (() => RequestStore) | undefined,
devFallbackParams: OpaqueFallbackRouteParams | null
): Promise<ReadableStream<Uint8Array>> {
): Promise<ReadableStream<Uint8Array> | Readable> {
/* eslint-disable @next/internal/no-ambiguous-jsx -- React Client */
const {
assetPrefix,
......@@ -2625,7 +2696,10 @@ async function renderToStream(
)
let reactServerResult: null | ReactServerResult = null
let reactDebugStream: ReadableStream<Uint8Array> | undefined
let reactDebugStream:
| ReadableStream<Uint8Array>
| import('node:stream').Readable
| undefined
const setHeader = res.setHeader.bind(res)
const appendHeader = res.appendHeader.bind(res)
......@@ -2695,11 +2769,22 @@ async function renderToStream(
serverComponentsErrorHandler
)
let validationDebugChannelClient: Readable | undefined = undefined
let validationDebugChannelClient:
| Readable
| ReadableStream<Uint8Array>
| undefined = undefined
if (returnedDebugChannel) {
const [t1, t2] = returnedDebugChannel.clientSide.readable.tee()
const readable = returnedDebugChannel.clientSide.readable
if (readable instanceof ReadableStream) {
const [t1, t2] = readable.tee()
returnedDebugChannel.clientSide.readable = t1
validationDebugChannelClient = t2
} else {
// Node Readable: tee natively, no web→Node conversion needed
const [t1, t2] = teeNodeReadable(readable)
returnedDebugChannel.clientSide.readable = t1
validationDebugChannelClient = nodeStreamFromReadableStream(t2)
validationDebugChannelClient = t2
}
}
consoleAsyncStorage.run(
......@@ -2716,7 +2801,9 @@ async function renderToStream(
validationDebugChannelClient
)
reactServerResult = new ReactServerResult(serverStream)
reactServerResult = new ReactServerResult(serverStream, (fn) =>
workUnitAsyncStorage.run(finalRequestStore, fn)
)
requestStore = finalRequestStore
debugChannel = returnedDebugChannel
} else {
......@@ -2738,20 +2825,16 @@ async function renderToStream(
debugChannel: debugChannel?.serverSide,
}
)
reactServerResult = new ReactServerResult(serverStream)
reactServerResult = new ReactServerResult(serverStream, (fn) =>
workUnitAsyncStorage.run(requestStore, fn)
)
}
if (debugChannel && setReactDebugChannel) {
const [readableSsr, readableBrowser] =
debugChannel.clientSide.readable.tee()
reactDebugStream = readableSsr
setReactDebugChannel(
{ readable: readableBrowser },
htmlRequestId,
requestId
)
const { ssrStream, browserChannel } =
teeDebugChannelForSsrAndBrowser(debugChannel)
reactDebugStream = ssrStream
setReactDebugChannel(browserChannel, htmlRequestId, requestId)
}
} else {
// This is a dynamic render. We don't do dynamic tracking because we're not prerendering
......@@ -2767,18 +2850,16 @@ async function renderToStream(
const debugChannel = setReactDebugChannel && createDebugChannel()
if (debugChannel) {
const [readableSsr, readableBrowser] =
debugChannel.clientSide.readable.tee()
reactDebugStream = readableSsr
setReactDebugChannel(
{ readable: readableBrowser },
htmlRequestId,
requestId
)
const { ssrStream, browserChannel } =
teeDebugChannelForSsrAndBrowser(debugChannel)
reactDebugStream = ssrStream
setReactDebugChannel(browserChannel, htmlRequestId, requestId)
}
// Node stream callbacks can run outside the originating ALS scope, so
// preserve the request store explicitly for downstream handlers.
const runInContext = <T,>(fn: () => T): T =>
workUnitAsyncStorage.run(requestStore, fn)
reactServerResult = new ReactServerResult(
renderToFlightStream(
ctx.componentMod,
......@@ -2789,8 +2870,9 @@ async function renderToStream(
onError: serverComponentsErrorHandler,
debugChannel: debugChannel?.serverSide,
},
(fn) => workUnitAsyncStorage.run(requestStore, fn)
)
runInContext
),
runInContext
)
}
......@@ -3184,7 +3266,12 @@ async function renderWithRestartOnCacheMissInDev(
initialStageController.advanceStage(RenderStage.EarlyStatic)
startTime = performance.now() + performance.timeOrigin
const streamPair = renderToFlightStream(
// teeNodeReadable installs event handlers (`data`/`drain`/`end`/`close`)
// that may execute outside the current ALS frame.
const runInContext = <T,>(fn: () => T): T =>
workUnitAsyncStorage.run(requestStore, fn)
const stream = renderToFlightStream(
ComponentMod,
initialRscPayload,
clientModules,
......@@ -3196,9 +3283,8 @@ async function renderWithRestartOnCacheMissInDev(
debugChannel: debugChannel?.serverSide,
signal: initialReactController.signal,
},
(fn) => workUnitAsyncStorage.run(requestStore, fn)
).tee()
runInContext
)
// 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.
......@@ -3206,20 +3292,41 @@ async function renderWithRestartOnCacheMissInDev(
initialDataController.abort(initialReactController.signal.reason)
})
const stream = streamPair[0]
if (
process.env.__NEXT_USE_NODE_STREAMS &&
!(stream instanceof ReadableStream)
) {
const [continuationStream, accumulatingStream] = teeNodeReadable(
stream as import('node:stream').Readable,
runInContext
)
const accumulatedChunksPromise = accumulateNodeStreamChunks(
accumulatingStream,
initialStageController,
initialDataController.signal
)
return {
stream: continuationStream,
accumulatedChunksPromise,
}
}
const [continuationStream, accumulatingStream] = (
stream as ReadableStream<Uint8Array>
).tee()
const accumulatedChunksPromise = accumulateStreamChunks(
streamPair[1],
accumulatingStream,
initialStageController,
initialDataController.signal
)
initialDataController.signal.addEventListener('abort', () => {
accumulatedChunksPromise.catch(() => {})
stream.cancel()
continuationStream.cancel()
})
return {
stream,
stream: continuationStream,
accumulatedChunksPromise,
}
},
......@@ -3331,7 +3438,12 @@ async function renderWithRestartOnCacheMissInDev(
finalStageController.advanceStage(RenderStage.EarlyStatic)
startTime = performance.now() + performance.timeOrigin
const streamPair = renderToFlightStream(
// teeNodeReadable installs event handlers (`data`/`drain`/`end`/`close`)
// that may execute outside the current ALS frame.
const runInContext = <T,>(fn: () => T): T =>
workUnitAsyncStorage.run(requestStore, fn)
const stream = renderToFlightStream(
ComponentMod,
finalRscPayload,
clientModules,
......@@ -3342,13 +3454,35 @@ async function renderWithRestartOnCacheMissInDev(
filterStackFrame,
debugChannel: debugChannel?.serverSide,
},
(fn) => workUnitAsyncStorage.run(requestStore, fn)
).tee()
runInContext
)
if (
process.env.__NEXT_USE_NODE_STREAMS &&
!(stream instanceof ReadableStream)
) {
const [continuationStream, accumulatingStream] = teeNodeReadable(
stream as import('node:stream').Readable,
runInContext
)
const accumulatedChunksPromise = accumulateNodeStreamChunks(
accumulatingStream,
finalStageController,
null
)
return {
stream: continuationStream,
accumulatedChunksPromise,
}
}
const [continuationStream, accumulatingStream] = (
stream as ReadableStream<Uint8Array>
).tee()
return {
stream: streamPair[0],
stream: continuationStream,
accumulatedChunksPromise: accumulateStreamChunks(
streamPair[1],
accumulatingStream,
finalStageController,
null
),
......@@ -3460,6 +3594,64 @@ async function accumulateStreamChunks(
return { staticChunks, runtimeChunks, dynamicChunks }
}
async function accumulateNodeStreamChunks(
stream: Readable,
stageController: StagedRenderingController,
signal: AbortSignal | null
): Promise<AccumulatedStreamChunks> {
const staticChunks: Array<Uint8Array> = []
const runtimeChunks: Array<Uint8Array> = []
const dynamicChunks: Array<Uint8Array> = []
let destroyed = false
function destroy() {
if (!destroyed) {
destroyed = true
stream.destroy()
}
}
if (signal) {
signal.addEventListener('abort', destroy, { once: true })
}
try {
for await (const value of stream) {
if (destroyed) break
const chunk = value as Uint8Array
switch (stageController.currentStage) {
case RenderStage.Before:
throw new InvariantError(
'Unexpected stream chunk while in Before stage'
)
case RenderStage.Static:
staticChunks.push(chunk)
// fall through
case RenderStage.Runtime:
runtimeChunks.push(chunk)
// fall through
case RenderStage.Dynamic:
dynamicChunks.push(chunk)
break
case RenderStage.Abandoned:
break
default:
stageController.currentStage satisfies never
break
}
}
} catch (err) {
// When we destroy the stream we may reject the iteration.
// Only swallow errors caused by our intentional destroy();
// re-throw unexpected errors to avoid silently returning partial data.
if (!destroyed) {
throw err
}
}
return { staticChunks, runtimeChunks, dynamicChunks }
}
function createAsyncApiPromisesInDev(
stagedRendering: StagedRenderingController,
cookies: RequestStore['cookies'],
......@@ -3577,7 +3769,14 @@ async function logMessagesAndSendErrorsToBrowser(
{ filterStackFrame }
)
sendErrorsToBrowser(errorsFlightStream, htmlRequestId)
// sendErrorsToBrowser expects a web ReadableStream. In node-streams mode,
// renderToFlightStream returns a Node Readable, so convert it.
const errorsRscStream =
errorsFlightStream instanceof ReadableStream
? errorsFlightStream
: nodeReadableToWeb!(errorsFlightStream as any)
sendErrorsToBrowser(errorsRscStream, htmlRequestId)
}
}
......@@ -3639,7 +3838,7 @@ async function spawnStaticShellValidationInDevImpl(
ctx: AppRenderContext,
requestStore: RequestStore,
fallbackRouteParams: OpaqueFallbackRouteParams | null,
debugChannelClient: Readable | undefined
debugChannelClient: Readable | ReadableStream<Uint8Array> | undefined
): Promise<void> {
const debug =
process.env.NEXT_PRIVATE_DEBUG_VALIDATION === '1' ? console.log : undefined
......@@ -3675,10 +3874,23 @@ async function spawnStaticShellValidationInDevImpl(
let debugChunks: Uint8Array[] | null = null
if (debugChannelClient) {
debugChunks = []
if (debugChannelClient instanceof ReadableStream) {
// Web ReadableStream: pump via reader (non-nodestreams debug channel)
const reader = debugChannelClient.getReader()
;(async () => {
for (;;) {
const { done, value } = await reader.read()
if (done) break
debugChunks!.push(value)
}
})()
} else {
// Node Readable: use .on('data') event listener
debugChannelClient.on('data', (c) => {
debugChunks!.push(c)
})
}
}
const accumulatedChunks = await accumulatedChunksPromise
const { staticChunks, runtimeChunks, dynamicChunks } = accumulatedChunks
......@@ -4418,7 +4630,7 @@ async function validateInstantConfigNavigation(
}
type PrerenderToStreamResult = {
stream: ReadableStream<Uint8Array>
stream: ReadableStream<Uint8Array> | Readable
digestErrorsMap: Map<string, DigestedError>
ssrErrors: Array<unknown>
dynamicAccess?: null | Array<DynamicAccess>
......@@ -4774,7 +4986,8 @@ async function prerenderToStream(
let initialServerResult
try {
initialServerResult = await createReactServerPrerenderResult(
initialServerResult =
await createReactServerPrerenderResultFromPrerender(
pendingInitialServerResult
)
} catch (err) {
......@@ -4831,7 +5044,7 @@ async function prerenderToStream(
getClientPrerender,
// eslint-disable-next-line @next/internal/no-ambiguous-jsx
<App
reactServerStream={initialServerResult.asUnclosingStream()}
reactServerStream={initialServerResult.asUnclosingFlightStream()}
reactDebugStream={undefined}
debugEndTime={undefined}
preinitScripts={preinitScripts}
......@@ -5097,7 +5310,7 @@ async function prerenderToStream(
getClientPrerender,
// eslint-disable-next-line @next/internal/no-ambiguous-jsx
<App
reactServerStream={reactServerResult.asUnclosingStream()}
reactServerStream={reactServerResult.asUnclosingFlightStream()}
reactDebugStream={undefined}
debugEndTime={undefined}
preinitScripts={preinitScripts}
......@@ -5175,7 +5388,9 @@ async function prerenderToStream(
tracingMetadata: tracingMetadata,
})
const flightData = await streamToBuffer(reactServerResult.asStream())
const flightData = await streamToBuffer(
reactServerResult.asFlightStream()
)
metadata.flightData = flightData
metadata.segmentData = await collectSegmentData(
flightData,
......@@ -5244,7 +5459,9 @@ async function prerenderToStream(
)
}
let htmlStream: ReadableStream<Uint8Array> = prelude
let htmlStream:
| ReadableStream<Uint8Array>
| import('node:stream').Readable = prelude
if (postponed != null) {
// We postponed but nothing dynamic was used. We resume the render now and immediately abort it
// so we can set all the postponed boundaries to client render mode before we store the HTML response
......@@ -5300,7 +5517,7 @@ async function prerenderToStream(
)
finalStream = await continueStaticFallbackPrerender(htmlStream, {
inlinedDataStream: createInlinedDataStream(
emptyReactServerResult.consumeAsStream(),
emptyReactServerResult.consumeAsFlightStream(),
nonce,
formState
),
......@@ -5312,7 +5529,7 @@ async function prerenderToStream(
// Normal static prerender case, no fallback param handling needed
finalStream = await continueStaticPrerender(htmlStream, {
inlinedDataStream: createInlinedDataStream(
reactServerResult.consumeAsStream(),
reactServerResult.consumeAsFlightStream(),
nonce,
formState
),
......@@ -5401,7 +5618,7 @@ async function prerenderToStream(
getClientPrerender,
// eslint-disable-next-line @next/internal/no-ambiguous-jsx
<App
reactServerStream={reactServerResult.asUnclosingStream()}
reactServerStream={reactServerResult.asUnclosingFlightStream()}
reactDebugStream={undefined}
debugEndTime={undefined}
preinitScripts={preinitScripts}
......@@ -5427,7 +5644,9 @@ async function prerenderToStream(
// After awaiting here we've waited for the entire RSC render to complete. Crucially this means
// that when we detect whether we've used dynamic APIs below we know we'll have picked up even
// parts of the React Server render that might not be used in the SSR render.
const flightData = await streamToBuffer(reactServerResult.asStream())
const flightData = await streamToBuffer(
reactServerResult.asFlightStream()
)
if (shouldGenerateStaticFlightData(workStore)) {
metadata.flightData = flightData
......@@ -5532,7 +5751,9 @@ async function prerenderToStream(
)
}
let htmlStream: ReadableStream<Uint8Array> = prelude
let htmlStream:
| ReadableStream<Uint8Array>
| import('node:stream').Readable = prelude
if (postponed != null) {
// We postponed but nothing dynamic was used. We resume the render now and immediately abort it
// so we can set all the postponed boundaries to client render mode before we store the HTML response
......@@ -5564,7 +5785,7 @@ async function prerenderToStream(
ssrErrors: allCapturedErrors,
stream: await continueStaticPrerender(htmlStream, {
inlinedDataStream: createInlinedDataStream(
reactServerResult.consumeAsStream(),
reactServerResult.consumeAsFlightStream(),
nonce,
formState
),
......@@ -5620,7 +5841,7 @@ async function prerenderToStream(
const { stream: htmlStream } = await renderToFizzStream(
// eslint-disable-next-line @next/internal/no-ambiguous-jsx
<App
reactServerStream={reactServerResult.asUnclosingStream()}
reactServerStream={reactServerResult.asUnclosingFlightStream()}
reactDebugStream={undefined}
debugEndTime={undefined}
preinitScripts={preinitScripts}
......@@ -5637,7 +5858,9 @@ async function prerenderToStream(
)
if (shouldGenerateStaticFlightData(workStore)) {
const flightData = await streamToBuffer(reactServerResult.asStream())
const flightData = await streamToBuffer(
reactServerResult.asFlightStream()
)
metadata.flightData = flightData
metadata.segmentData = await collectSegmentData(
flightData,
......@@ -5659,7 +5882,7 @@ async function prerenderToStream(
ssrErrors: allCapturedErrors,
stream: await continueFizzStream(htmlStream, {
inlinedDataStream: createInlinedDataStream(
reactServerResult.consumeAsStream(),
reactServerResult.consumeAsFlightStream(),
nonce,
formState
),
......@@ -5807,7 +6030,7 @@ async function prerenderToStream(
if (shouldGenerateStaticFlightData(workStore)) {
const flightData = await streamToBuffer(
reactServerPrerenderResult.asStream()
reactServerPrerenderResult.asFlightStream()
)
metadata.flightData = flightData
metadata.segmentData = await collectSegmentData(
......@@ -5820,7 +6043,7 @@ async function prerenderToStream(
// This is intentionally using the readable datastream from the main
// render rather than the flight data from the error page render
const flightStream = reactServerPrerenderResult.consumeAsStream()
const flightStream = reactServerPrerenderResult.consumeAsFlightStream()
return {
digestErrorsMap: reactServerErrorsByDigest,
......@@ -5988,30 +6211,3 @@ function WarnForBypassCachesInDev({ route }: { route: string }) {
)
return null
}
function nodeStreamFromReadableStream<T>(stream: ReadableStream<T>) {
if (process.env.NEXT_RUNTIME === 'edge') {
throw new InvariantError(
'nodeStreamFromReadableStream cannot be used in the edge runtime'
)
} else {
const reader = stream.getReader()
const { Readable } = require('node:stream') as typeof import('node:stream')
return new Readable({
read() {
reader
.read()
.then(({ done, value }) => {
if (done) {
this.push(null)
} else {
this.push(value)
}
})
.catch((err) => this.destroy(err))
},
})
}
}
......@@ -2,7 +2,7 @@ import type {
DebugChannelPair,
DebugChannelServer,
DebugChannelClient,
} from './debug-channel-server.web'
} from './debug-channel-server.node'
type DebugChannelRuntimeModule = {
createDebugChannel: () => DebugChannelPair | undefined
......@@ -18,7 +18,7 @@ if (process.env.NEXT_RUNTIME === 'edge') {
require('./debug-channel-server.web') as typeof import('./debug-channel-server.web')
} else if (process.env.__NEXT_USE_NODE_STREAMS) {
debugChannelRuntimeModule =
require('./debug-channel-server.node') as typeof import('./debug-channel-server.node') as unknown as DebugChannelRuntimeModule
require('./debug-channel-server.node') as typeof import('./debug-channel-server.node')
} else {
debugChannelRuntimeModule =
require('./debug-channel-server.web') as typeof import('./debug-channel-server.web')
......
/**
* Web debug channel implementation.
* Loaded by debug-channel-server.ts.
*/
// Types defined inline for now; will move to debug-channel-server.node.ts later.
export type DebugChannelPair = {
serverSide: DebugChannelServer
clientSide: DebugChannelClient
}
import type {
DebugChannelPair,
DebugChannelServer,
} from './debug-channel-server.node'
export type DebugChannelServer = {
readable?: ReadableStream<Uint8Array>
writable: WritableStream<Uint8Array>
}
export type DebugChannelClient = {
readable: ReadableStream<Uint8Array>
writable?: WritableStream<Uint8Array>
}
export type { DebugChannelPair, DebugChannelServer }
export function createDebugChannel(): DebugChannelPair | undefined {
if (process.env.NODE_ENV === 'production') {
......
import type { Readable } from 'node:stream'
import { RSC_CONTENT_TYPE_HEADER } from '../../client/components/app-router-headers'
import RenderResult, { type RenderResultMetadata } from '../render-result'
......@@ -6,7 +7,7 @@ import RenderResult, { type RenderResultMetadata } from '../render-result'
*/
export class FlightRenderResult extends RenderResult {
constructor(
response: string | ReadableStream<Uint8Array>,
response: string | ReadableStream<Uint8Array> | Readable,
metadata: RenderResultMetadata = {},
waitUntil?: Promise<unknown>
) {
......
......@@ -40,8 +40,6 @@ import { createDebugChannel } from '../debug-channel-server'
// eslint-disable-next-line import/no-extraneous-dependencies
import { createFromNodeStream } from 'react-server-dom-webpack/client'
// eslint-disable-next-line import/no-extraneous-dependencies
import { renderToReadableStream } from 'react-server-dom-webpack/server'
import { addSearchParamsIfPageSegment } from '../../../shared/lib/segment'
import type { NextParsedUrlQuery } from '../../request-meta'
......@@ -469,7 +467,55 @@ export async function collectStagedSegmentData(
? createDebugChannel()
: undefined
const segmentStream = renderToReadableStream(
let segmentStream:
| ReadableStream<Uint8Array>
| import('node:stream').Readable
let streamIterator: AsyncIterable<Uint8Array>
if (process.env.__NEXT_USE_NODE_STREAMS) {
const { renderToFlightPipeableStream } =
require('../pipeable-stream-wrappers') as typeof import('../pipeable-stream-wrappers')
const ComponentMod =
// eslint-disable-next-line import/no-extraneous-dependencies
require('react-server-dom-webpack/server.node') as typeof import('react-server-dom-webpack/server.node')
segmentStream = renderToFlightPipeableStream(
ComponentMod.renderToPipeableStream,
segmentData,
clientReferenceManifest.clientModules,
{
filterStackFrame,
debugChannel: segmentDebugChannel?.serverSide,
environmentName,
startTime,
onError(error: unknown) {
const digest = getDigestForWellKnownError(error)
if (digest) {
return digest
}
// We don't need to log the errors because we would have already done that
// when generating the original Flight stream for the whole page.
if (
process.env.NEXT_DEBUG_BUILD ||
process.env.__NEXT_VERBOSE_LOGGING
) {
const workStore = workAsyncStorage.getStore()
printDebugThrownValueForProspectiveRender(
error,
workStore?.route ?? 'unknown route',
Phase.InstantValidation
)
}
},
}
)
streamIterator = segmentStream
} else {
const { renderToReadableStream } =
// eslint-disable-next-line import/no-extraneous-dependencies
require('react-server-dom-webpack/server') as typeof import('react-server-dom-webpack/server')
segmentStream = renderToReadableStream(
segmentData,
clientReferenceManifest.clientModules,
{
......@@ -498,11 +544,15 @@ export async function collectStagedSegmentData(
},
}
)
streamIterator = (
segmentStream as ReadableStream<Uint8Array>
).values()
}
await Promise.all([
// accumulate Flight chunks
(async () => {
for await (const chunk of segmentStream.values()) {
for await (const chunk of streamIterator) {
writeChunk(
segmentCacheItem.chunks,
controller.currentStage,
......@@ -513,7 +563,12 @@ export async function collectStagedSegmentData(
// accumulate Debug chunks
segmentDebugChannel &&
(async () => {
for await (const chunk of segmentDebugChannel.clientSide.readable.values()) {
const readable = segmentDebugChannel.clientSide.readable
const iterable =
readable instanceof ReadableStream
? readable.values()
: (readable as AsyncIterable<Uint8Array>)
for await (const chunk of iterable) {
segmentCacheItem.debugChunks!.push(chunk)
}
})(),
......@@ -694,7 +749,52 @@ export async function createCombinedPayloadStream(
await runInSequentialTasks(
() => {
const stream = renderToReadableStream(
let stream: ReadableStream<Uint8Array> | import('node:stream').Readable
let streamIterator: AsyncIterable<Uint8Array>
if (process.env.__NEXT_USE_NODE_STREAMS) {
const { renderToFlightPipeableStream } =
require('../pipeable-stream-wrappers') as typeof import('../pipeable-stream-wrappers')
const ComponentMod =
// eslint-disable-next-line import/no-extraneous-dependencies
require('react-server-dom-webpack/server.node') as typeof import('react-server-dom-webpack/server.node')
stream = renderToFlightPipeableStream(
ComponentMod.renderToPipeableStream,
payload,
clientReferenceManifest.clientModules,
{
filterStackFrame,
debugChannel: debugChannel?.serverSide,
startTime,
onError(error: unknown) {
const digest = getDigestForWellKnownError(error)
if (digest) {
return digest
}
// We don't need to log the errors because we would have already done that
// when generating the original Flight stream for the whole page.
if (
process.env.NEXT_DEBUG_BUILD ||
process.env.__NEXT_VERBOSE_LOGGING
) {
const workStore = workAsyncStorage.getStore()
printDebugThrownValueForProspectiveRender(
error,
workStore?.route ?? 'unknown route',
Phase.InstantValidation
)
}
},
}
)
streamIterator = stream
} else {
const { renderToReadableStream } =
// eslint-disable-next-line import/no-extraneous-dependencies
require('react-server-dom-webpack/server') as typeof import('react-server-dom-webpack/server')
stream = renderToReadableStream(
payload,
clientReferenceManifest.clientModules,
{
......@@ -722,11 +822,13 @@ export async function createCombinedPayloadStream(
},
}
)
streamIterator = (stream as ReadableStream<Uint8Array>).values()
}
streamFinished = Promise.all([
// Accumulate Flight chunks
(async () => {
for await (const chunk of stream.values()) {
for await (const chunk of streamIterator) {
allChunks.push(chunk)
if (isRenderable) {
renderableChunks.push(chunk)
......@@ -736,7 +838,12 @@ export async function createCombinedPayloadStream(
// Accumulate debug chunks
debugChannel &&
(async () => {
for await (const chunk of debugChannel.clientSide.readable.values()) {
const readable = debugChannel.clientSide.readable
const iterable =
readable instanceof ReadableStream
? readable.values()
: (readable as AsyncIterable<Uint8Array>)
for await (const chunk of iterable) {
debugChunks!.push(chunk)
}
})(),
......
......@@ -10,7 +10,7 @@ import type {
FlightPayload,
FlightClientModules,
FlightRenderOptions,
} from './stream-ops.web'
} from './stream-ops.node'
export type {
AnyStream,
......@@ -23,7 +23,7 @@ export type {
FlightPayload,
FlightClientModules,
FlightRenderOptions,
} from './stream-ops.web'
} from './stream-ops.node'
export type FizzStreamResult = {
stream: AnyStream
......@@ -58,7 +58,9 @@ type StreamOpsRuntimeModule = {
prelude: AnyStream
preludeIsEmpty: boolean
}>
createDocumentClosingStream: () => AnyStream
createDocumentClosingStream: () =>
| ReadableStream<Uint8Array>
| import('node:stream').Readable
createInlinedDataStream: (
source: AnyStream,
nonce: string | undefined,
......@@ -109,7 +111,10 @@ type StreamOpsRuntimeModule = {
let streamOpsRuntimeModule: StreamOpsRuntimeModule
if (process.env.__NEXT_USE_NODE_STREAMS) {
if (process.env.NEXT_RUNTIME === 'edge') {
streamOpsRuntimeModule =
require('./stream-ops.web') as typeof import('./stream-ops.web') as unknown as StreamOpsRuntimeModule
} else if (process.env.__NEXT_USE_NODE_STREAMS) {
streamOpsRuntimeModule =
require('./stream-ops.node') as typeof import('./stream-ops.node') as unknown as StreamOpsRuntimeModule
} else {
......
/**
* Web stream operations for the rendering pipeline.
* Loaded by stream-ops.ts (re-export in this PR, conditional switcher later).
* Loaded by stream-ops.js when __NEXT_USE_NODE_STREAMS is false/undefined.
*/
import type {
AnyStream,
ContinueFizzStreamOptions,
ContinueStaticPrerenderOptions,
ContinueStreamSharedOptions,
ContinueDynamicHTMLResumeOptions,
FlightComponentMod,
ServerPrerenderComponentMod,
FlightPayload,
FlightClientModules,
FlightRenderOptions,
} from './stream-ops.node'
// Re-export shared types so they're available to consumers
export type {
AnyStream,
ContinueFizzStreamOptions,
ContinueStaticPrerenderOptions,
ContinueStreamSharedOptions,
ContinueDynamicHTMLResumeOptions,
FlightComponentMod,
ServerPrerenderComponentMod,
FlightPayload,
FlightClientModules,
FlightRenderOptions,
}
import type { PostponedState, PrerenderOptions } from 'react-dom/static'
import { resume, renderToReadableStream } from 'react-dom/server'
import { prerender } from 'react-dom/static'
......@@ -11,68 +38,15 @@ import {
renderToInitialFizzStream,
streamToString as webStreamToString,
createRuntimePrefetchTransformStream,
continueFizzStream as webContinueFizzStream,
} from '../stream-utils/node-web-streams-helper'
import { createInlinedDataReadableStream } from './use-flight-response'
// ---------------------------------------------------------------------------
// Shared types (web-only for now; will move to stream-ops.node.ts later)
// ---------------------------------------------------------------------------
type FlightRenderToReadableStream = (
model: any,
webpackMap: any,
options?: any
) => ReadableStream<Uint8Array>
export type AnyStream = ReadableStream<Uint8Array>
export type ContinueStreamSharedOptions = {
deploymentId: string | undefined
getServerInsertedHTML: () => Promise<string>
getServerInsertedMetadata: () => Promise<string>
}
export type ContinueFizzStreamOptions = ContinueStreamSharedOptions & {
inlinedDataStream: AnyStream | undefined
isStaticGeneration: boolean
allReady?: Promise<void>
validateRootLayout?: boolean
suffix?: string
}
export type ContinueStaticPrerenderOptions = ContinueStreamSharedOptions & {
inlinedDataStream: AnyStream
}
export type ContinueDynamicHTMLResumeOptions = ContinueStreamSharedOptions & {
inlinedDataStream: AnyStream
delayDataUntilFirstHtmlChunk: boolean
}
export type FlightComponentMod = {
renderToReadableStream: FlightRenderToReadableStream
}
export type ServerPrerenderComponentMod = {
prerender: (...args: any[]) => Promise<any>
}
export type FlightPayload = Parameters<FlightRenderToReadableStream>[0]
export type FlightClientModules = Parameters<FlightRenderToReadableStream>[1]
export type FlightRenderOptions = Parameters<FlightRenderToReadableStream>[2]
export type FizzStreamResult = {
stream: AnyStream
allReady: Promise<void>
abort?: (reason?: unknown) => void
}
// ---------------------------------------------------------------------------
// Continue functions
// ---------------------------------------------------------------------------
export {
continueFizzStream,
continueStaticPrerender,
continueDynamicPrerender,
continueStaticFallbackPrerender,
......@@ -84,18 +58,6 @@ export {
export { processPrelude } from './app-render-prerender-utils'
/**
* Wrapper for continueFizzStream that accepts AnyStream.
* The underlying implementation expects ReactDOMServerReadableStream but at
* the stream-ops boundary we only expose AnyStream.
*/
export function continueFizzStream(
renderStream: AnyStream,
opts: ContinueFizzStreamOptions
): Promise<ReadableStream<Uint8Array>> {
return webContinueFizzStream(renderStream as any, opts)
}
// Not available in web bundles
export const nodeReadableToWeb:
| ((readable: import('node:stream').Readable) => ReadableStream<Uint8Array>)
......@@ -160,6 +122,12 @@ export async function streamToString(stream: AnyStream): Promise<string> {
return webStreamToString(stream as ReadableStream<Uint8Array>)
}
export type FizzStreamResult = {
stream: AnyStream
allReady: Promise<void>
abort?: (reason?: unknown) => void
}
export async function renderToFizzStream(
element: React.ReactElement,
streamOptions: any,
......
import type { OutgoingHttpHeaders, ServerResponse } from 'http'
import type { Readable as NodeReadable } from 'node:stream'
import type { CacheControl } from './lib/cache-control'
import type { FetchMetrics } from './base-http'
......@@ -73,6 +74,7 @@ export type RenderResultMetadata = AppPageRenderResultMetadata &
export type RenderResultResponse =
| ReadableStream<Uint8Array>[]
| ReadableStream<Uint8Array>
| NodeReadable
| string
| Buffer
| null
......@@ -173,6 +175,19 @@ export default class RenderResult<
* @param stream Whether or not to return a promise if the response is dynamic
* @returns The response as a string
*/
private isNodeReadable(
response: RenderResultResponse
): response is NodeReadable {
return (
response !== null &&
typeof response === 'object' &&
!Array.isArray(response) &&
!Buffer.isBuffer(response) &&
!(response instanceof ReadableStream) &&
typeof (response as any).pipe === 'function'
)
}
public toUnchunkedString(stream?: false): string
public toUnchunkedString(stream: true): Promise<string>
public toUnchunkedString(stream = false): Promise<string> | string {
......@@ -189,14 +204,24 @@ export default class RenderResult<
)
}
if (process.env.__NEXT_USE_NODE_STREAMS) {
if (this.isNodeReadable(this.response)) {
const { nodeStreamToString } =
require('./stream-utils/node-stream-helpers') as typeof import('./stream-utils/node-stream-helpers')
return nodeStreamToString(this.response)
}
return streamToString(this.readable)
} else {
return streamToString(this.readable)
}
}
return this.response
}
/**
* Returns a readable stream of the response.
* Returns a web readable stream of the response.
* For Node.js Readable responses, use pipeToNodeResponse directly.
*/
private get readable(): ReadableStream<Uint8Array> {
if (this.response === null) {
......@@ -217,9 +242,16 @@ export default class RenderResult<
return streamFromBuffer(this.response)
}
// If the response is an array of streams, then chain them together.
// If the response is an array of web streams, then chain them together.
if (Array.isArray(this.response)) {
return chainStreams(...this.response)
return chainStreams(...(this.response as ReadableStream<Uint8Array>[]))
}
// Node.js Readable: should not reach here, use pipeToNodeResponse path
if (this.isNodeReadable(this.response)) {
throw new InvariantError(
'Node.js Readable responses should use the pipeToNodeResponse path directly'
)
}
return this.response
......@@ -241,11 +273,15 @@ export default class RenderResult<
if (typeof this.response === 'string') {
return [streamFromString(this.response)]
} else if (Array.isArray(this.response)) {
return this.response
return this.response as ReadableStream<Uint8Array>[]
} else if (Buffer.isBuffer(this.response)) {
return [streamFromBuffer(this.response)]
} else if (this.isNodeReadable(this.response)) {
throw new InvariantError(
'Node.js Readable responses cannot be coerced to web ReadableStream arrays'
)
} else {
return [this.response]
return [this.response as ReadableStream<Uint8Array>]
}
}
......@@ -329,6 +365,44 @@ export default class RenderResult<
* @param res
*/
public async pipeToNodeResponse(res: ServerResponse) {
// If the response is a Node.js Readable, pipe directly without
// going through web stream conversion.
if (
process.env.__NEXT_USE_NODE_STREAMS &&
this.isNodeReadable(this.response)
) {
const { pipeNodeReadableToResponse } =
require('./pipe-readable') as typeof import('./pipe-readable')
await pipeNodeReadableToResponse(this.response, res, this.waitUntil)
return
}
await pipeToNodeResponse(this.readable, res, this.waitUntil)
}
/**
* Pipes a Node.js Readable response to a Node.js Writable stream
* (e.g. a PassThrough used as a bridge). Unlike pipeToNodeResponse,
* this does not assume ServerResponse-specific APIs like flushHeaders().
*/
public async pipeToNodeWritable(
writable: import('node:stream').Writable
): Promise<void> {
if (process.env.__NEXT_USE_NODE_STREAMS) {
const { pipeline } =
require('node:stream/promises') as typeof import('node:stream/promises')
if (this.isNodeReadable(this.response)) {
await pipeline(this.response, writable)
return
}
const { Readable } =
require('node:stream') as typeof import('node:stream')
await pipeline(
Readable.fromWeb(this.readable as import('stream/web').ReadableStream),
writable
)
}
}
}
......@@ -133,18 +133,22 @@ describe('react-dom/server in React Server environment', () => {
expect(await browser.elementByCss('main').text()).toMatchInlineSnapshot(`
"{
"default": [
"renderToPipeableStream",
"renderToReadableStream",
"renderToStaticMarkup",
"renderToString",
"resume",
"resumeToPipeableStream",
"version"
],
"named": [
"default",
"renderToPipeableStream",
"renderToReadableStream",
"renderToStaticMarkup",
"renderToString",
"resume",
"resumeToPipeableStream",
"version"
]
}"
......@@ -481,18 +485,22 @@ describe('react-dom/server in React Server environment', () => {
"{
"default": {
"default": [
"renderToPipeableStream",
"renderToReadableStream",
"renderToStaticMarkup",
"renderToString",
"resume",
"resumeToPipeableStream",
"version"
],
"named": [
"default",
"renderToPipeableStream",
"renderToReadableStream",
"renderToStaticMarkup",
"renderToString",
"resume",
"resumeToPipeableStream",
"version"
]
}
......
import path from 'path'
import { nextTestSetup } from 'e2e-utils'
describe('user bundle - node stream guard', () => {
const { next, isNextDev, isTurbopack, skipped } = nextTestSetup({
// Reuse this fixture because it exercises app-page resume/render bundling.
files: path.join(__dirname, '../ppr-partial-hydration'),
skipDeployment: true,
skipStart: true,
})
if (isNextDev || skipped || isTurbopack) {
it.skip('only testable in webpack production (non-deployment)', () => {})
return
}
it('should keep node-stream-only helpers out of default server chunks', async () => {
const { exitCode } = await next.build()
expect(exitCode).toBe(0)
const pageTrace = JSON.parse(
await next.readFile(
'.next/server/app/with-shell/without-metadata/page.js.nft.json'
)
) as { files: string[] }
const tracedFiles = pageTrace.files.join('\n')
expect(tracedFiles).not.toContain(
'next/dist/server/stream-utils/node-stream-helpers.js'
)
const tracedChunkFiles = pageTrace.files.filter(
(file) => file.startsWith('../../../chunks/') && file.endsWith('.js')
)
const chunkSources = (
await Promise.all(
tracedChunkFiles.map((file) =>
next.readFile(
path.join('.next/server/app/with-shell/without-metadata', file)
)
)
)
).join('\n')
expect(chunkSources).not.toContain('stream-utils/node-stream-helpers')
expect(chunkSources).not.toContain('node:stream/promises')
})
})
......@@ -194,7 +194,9 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/compiled/is-wsl/index.js",
"/node_modules/next/dist/compiled/jsonwebtoken/index.js",
"/node_modules/next/dist/compiled/nanoid/index.cjs",
"/node_modules/next/dist/compiled/next-server/app-page-turbo-experimental-nodestreams.runtime.prod.js",
"/node_modules/next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js",
"/node_modules/next/dist/compiled/next-server/app-page-turbo-nodestreams.runtime.prod.js",
"/node_modules/next/dist/compiled/next-server/app-page-turbo.runtime.prod.js",
"/node_modules/next/dist/compiled/next-server/pages-turbo.runtime.prod.js",
"/node_modules/next/dist/compiled/p-limit/index.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