MCPcopy Create free account
hub / github.com/TanStack/router / createMultiplexedStream

Function createMultiplexedStream

packages/start-server-core/src/frame-protocol.ts:107–258  ·  view source on GitHub ↗
(
  jsonStream: ReadableStream<string>,
  rawStreams: Map<number, ReadableStream<Uint8Array>>,
  lateStreamSource?: ReadableStream<LateStreamRegistration>,
)

Source from the content-addressed store, hash-verified

105 * @param lateStreamSource Optional stream of late registrations for streams discovered later
106 */
107export function createMultiplexedStream(
108 jsonStream: ReadableStream<string>,
109 rawStreams: Map<number, ReadableStream<Uint8Array>>,
110 lateStreamSource?: ReadableStream<LateStreamRegistration>,
111): ReadableStream<Uint8Array> {
112 // Shared state for the multiplexed stream
113 let controller: ReadableStreamDefaultController<Uint8Array>
114 let cancelled = false
115 const readers: Array<ReadableStreamDefaultReader<any>> = []
116
117 // Helper to enqueue a frame, ignoring errors if stream is closed/cancelled
118 const enqueue = (frame: Uint8Array): boolean => {
119 if (cancelled) return false
120 try {
121 controller.enqueue(frame)
122 return true
123 } catch {
124 return false
125 }
126 }
127
128 // Helper to error the output stream (for fatal errors like JSON stream failure)
129 const errorOutput = (error: unknown): void => {
130 if (cancelled) return
131 cancelled = true
132 try {
133 controller.error(error)
134 } catch {
135 // Already errored
136 }
137 // Cancel all readers to stop other pumps
138 for (const reader of readers) {
139 reader.cancel().catch(() => {})
140 }
141 }
142
143 // Pumps a raw stream, sending CHUNK frames and END/ERROR on completion
144 async function pumpRawStream(
145 streamId: number,
146 stream: ReadableStream<Uint8Array>,
147 ): Promise<void> {
148 const reader = stream.getReader()
149 readers.push(reader)
150 try {
151 while (!cancelled) {
152 const { done, value } = await reader.read()
153 if (done) {
154 enqueue(encodeEndFrame(streamId))
155 return
156 }
157 if (!enqueue(encodeChunkFrame(streamId, value))) return
158 }
159 } catch (error) {
160 // Raw stream error - send ERROR frame, don't fail entire response
161 enqueue(encodeErrorFrame(streamId, error))
162 } finally {
163 reader.releaseLock()
164 }

Callers 2

serializeResultFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected