Commit a822c66f authored by Jimmy Lai's avatar Jimmy Lai

feat(node-streams): add conditional Node stream support to instant-validation

Makes instant-validation.tsx conditionally use Node.js native streams
(renderToPipeableStream) instead of web streams (renderToReadableStream)
when __NEXT_USE_NODE_STREAMS is enabled. This prevents hangs that occurred
when instant-validation bypassed the stream API wrappers.

Changes:
- Remove static import of renderToReadableStream
- Add conditional lazy requires for both web and Node Flight APIs
- Use renderToFlightPipeableStream wrapper for Node path (handles debug channel conversion)
- Handle stream iteration differences (Node Readable vs web ReadableStream.values())
- Apply pattern at both rendering call sites: collectStagedSegmentData and createCombinedPayloadStream

Known limitation:
- Debug channel at segment level disabled with Node streams to avoid parallel bridge issues
- Combined payload level debug channel still enabled
- 4/5 instant-validation tests pass; debug channel interaction needs further investigation

Test results with __NEXT_USE_NODE_STREAMS + __NEXT_CACHE_COMPONENTS + __NEXT_EXPERIMENTAL_DEBUG_CHANNEL:
- instant-validation-static-shells: 4 passed, 1 failing (debug channel interaction)
- Without debug channel: all tests pass
Co-Authored-By: 's avatarClaude Sonnet 4.5 <noreply@anthropic.com>
parent 523fce89
export type DebugChannelPair = {
// serverSide is passed opaquely as options.debugChannel to React's
// renderToReadableStream (web) or renderToPipeableStream (Node).
// The two APIs expect different shapes:
// - Web: { readable?, writable: WritableStream }
// - Node: a Writable stream (has .write() directly on the object)
// Consumers should not access properties on serverSide directly.
// serverSide is always in the web shape ({ writable: WritableStream }).
// Consumers that need a Node Writable (for renderToPipeableStream) should
// call toNodeDebugChannel() to convert.
serverSide: DebugChannelServer
clientSide: DebugChannelClient
}
// Passed directly as options.debugChannel to React's render functions.
// React's web API (renderToReadableStream) reads .writable from it.
// React's Node API (renderToPipeableStream) checks .write() on it directly.
export type DebugChannelServer =
| {
readable?: ReadableStream<Uint8Array>
writable: WritableStream<Uint8Array>
}
| import('node:stream').Writable
// Always the web shape: React's renderToReadableStream reads .writable from it.
// For renderToPipeableStream (Node), use toNodeDebugChannel() to convert.
export type DebugChannelServer = {
readable?: ReadableStream<Uint8Array>
writable: WritableStream<Uint8Array>
}
export type DebugChannelClient = {
readable: ReadableStream<Uint8Array>
writable?: WritableStream<Uint8Array>
}
/**
* Converts a web-shaped debug channel to a Node Writable for use with
* React's renderToPipeableStream, which checks typeof debugChannel.write
* to find its debug destination.
*/
export function toNodeDebugChannel(
webDebugChannel: DebugChannelServer
): import('node:stream').Writable {
const { Writable } = require('node:stream') as typeof import('node:stream')
const writer = webDebugChannel.writable.getWriter()
return new Writable({
write(
chunk: Buffer | Uint8Array,
_encoding: string,
callback: (error?: Error | null) => void
) {
writer.write(chunk).then(() => callback(), callback)
},
final(callback: (error?: Error | null) => void) {
writer.close().then(() => callback(), callback)
},
destroy(_err, callback) {
writer.abort(_err).then(
() => callback(_err),
() => callback(_err)
)
},
})
}
export function createDebugChannel(): DebugChannelPair | undefined {
if (process.env.NODE_ENV === 'production') {
return undefined
......@@ -36,33 +60,6 @@ export function createDebugChannel(): DebugChannelPair | undefined {
},
})
// When node streams are enabled, create a Node.js Writable as the server
// side. React's renderToPipeableStream checks typeof debugChannel.write
// to find its debug destination. A web WritableStream doesn't have .write()
// on the object, so it must be a Node Writable.
if (process.env.__NEXT_USE_NODE_STREAMS) {
const { Writable } = require('node:stream') as typeof import('node:stream')
const serverSide = new Writable({
write(
chunk: Buffer | Uint8Array,
_encoding: string,
callback: (error?: Error | null) => void
) {
readableController?.enqueue(chunk)
callback()
},
final(callback: (error?: Error | null) => void) {
readableController?.close()
callback()
},
destroy(_err, callback) {
readableController?.error(_err)
callback(_err)
},
})
return { serverSide, clientSide: { readable: clientSideReadable } }
}
return {
serverSide: {
writable: new WritableStream<Uint8Array>({
......
......@@ -39,8 +39,7 @@ 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'
// renderToReadableStream is now lazy-loaded conditionally below
const filterStackFrame =
process.env.NODE_ENV !== 'production'
......@@ -442,44 +441,98 @@ export async function collectStagedSegmentData(
cache.set(segmentPath, segmentCacheItem)
const segmentTask = async () => {
const segmentDebugChannel = fullPageDebugChunks
? createDebugChannel()
: undefined
const segmentStream = renderToReadableStream(
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
)
}
},
}
)
// When using node streams, skip debug channel at segment level to avoid
// issues with parallel debug channel bridges. Debug info is still captured
// at the combined payload level in createCombinedPayloadStream.
const segmentDebugChannel =
fullPageDebugChunks && !process.env.__NEXT_USE_NODE_STREAMS
? createDebugChannel()
: undefined
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')
// eslint-disable-next-line import/no-extraneous-dependencies
const ComponentMod = 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 {
// eslint-disable-next-line import/no-extraneous-dependencies
const { renderToReadableStream } = require('react-server-dom-webpack/server') as typeof import('react-server-dom-webpack/server')
segmentStream = renderToReadableStream(
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 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,
......@@ -671,39 +724,84 @@ export async function createCombinedPayloadStream(
await scheduleInSequentialTasks(
() => {
const stream = renderToReadableStream(
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
)
}
},
}
)
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')
// eslint-disable-next-line import/no-extraneous-dependencies
const ComponentMod = 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 {
// eslint-disable-next-line import/no-extraneous-dependencies
const { renderToReadableStream } = require('react-server-dom-webpack/server') as typeof import('react-server-dom-webpack/server')
stream = renderToReadableStream(
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 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)
......
......@@ -149,6 +149,16 @@ export function renderToFlightPipeableStream(
): Readable {
const { PassThrough } = getNodeStream()
const passthrough = new PassThrough()
// React's renderToPipeableStream checks typeof debugChannel.write to find
// its debug destination. The web-shaped { writable: WritableStream } doesn't
// have .write() on the object, so convert to a Node Writable.
if (options?.debugChannel) {
const { toNodeDebugChannel } =
require('./debug-channel-server') as typeof import('./debug-channel-server')
options = { ...options, debugChannel: toNodeDebugChannel(options.debugChannel) }
}
const { pipe } = renderToPipeableStreamFn(model, webpackMap, options)
pipe(passthrough as unknown as Writable)
return passthrough
......
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