Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

NodeStream.ts

462 lines15.2 KB

1/**
2 * Adapters between Node streams and Effect streams, channels, and readables.
3 *
4 * This module is the stream boundary for Node APIs: wrap `Readable` or
5 * `Duplex` values as Effect `Stream`s and `Channel`s, pipe an Effect stream
6 * through a Node duplex transform, expose an Effect `Stream` back to Node as a
7 * `Readable`, or collect bounded readable payloads into strings, array
8 * buffers, and `Uint8Array`s. Common sources include files, HTTP bodies, child
9 * process stdio, sockets, and compression or crypto transforms.
10 *
11 * **Mental model**
12 *
13 * Read adapters pull from Node's readable side into Effect. Duplex adapters
14 * write upstream Effect chunks to Node while reading transformed chunks back.
15 * `toReadable` runs an Effect stream from the caller's context, while
16 * `toReadableNever` is for streams that need no services.
17 *
18 * **Gotchas**
19 *
20 * Node backpressure is preserved: writes pause until `drain` before more input
21 * is pulled. Readables are destroyed on scope finalization by default, and
22 * duplex writable sides are ended when upstream completes unless configured
23 * otherwise. For externally owned or long-lived streams, choose `closeOnDone`
24 * and `endOnDone` deliberately; for collection helpers, set `maxBytes` when
25 * input size is not already bounded.
26 *
27 * @since 4.0.0
28 */
29import * as Arr from "effect/Array"
30import * as Cause from "effect/Cause"
31import * as Channel from "effect/Channel"
32import * as Context from "effect/Context"
33import * as Effect from "effect/Effect"
34import * as Exit from "effect/Exit"
35import * as Fiber from "effect/Fiber"
36import type { SizeInput } from "effect/FileSystem"
37import { dual, type LazyArg } from "effect/Function"
38import * as Latch from "effect/Latch"
39import * as MutableRef from "effect/MutableRef"
40import * as Pull from "effect/Pull"
41import * as Scope from "effect/Scope"
42import * as Stream from "effect/Stream"
43import type { Duplex } from "node:stream"
44import { Readable } from "node:stream"
45import { pullIntoWritable } from "./NodeSink.ts"
46​
47/**
48 * Converts a Node readable stream into an Effect `Stream`, reading chunks with
49 * an optional chunk size, mapping stream errors with `onError`, and destroying
50 * the readable on completion unless `closeOnDone` is `false`.
51 *
52 * @category constructors
53 * @since 4.0.0
54 */
55export const fromReadable = <A = Uint8Array, E = Cause.UnknownError>(options: {
56 readonly evaluate: LazyArg<Readable | NodeJS.ReadableStream>
57 readonly onError?: (error: unknown) => E
58 readonly chunkSize?: number | undefined
59 readonly bufferSize?: number | undefined
60 readonly closeOnDone?: boolean | undefined
61}): Stream.Stream<A, E> => Stream.fromChannel(fromReadableChannel<A, E>(options))
62​
63/**
64 * Creates a `Channel` that pulls chunks from a Node readable stream, mapping
65 * errors with `onError` and destroying the readable on completion unless
66 * `closeOnDone` is `false`.
67 *
68 * @category constructors
69 * @since 4.0.0
70 */
71export const fromReadableChannel = <A = Uint8Array, E = Cause.UnknownError>(options: {
72 readonly evaluate: LazyArg<Readable | NodeJS.ReadableStream>
73 readonly onError?: (error: unknown) => E
74 readonly chunkSize?: number | undefined
75 readonly closeOnDone?: boolean | undefined
76}): Channel.Channel<Arr.NonEmptyReadonlyArray<A>, E> =>
77 Channel.fromTransform((_, scope) =>
78 readableToPullUnsafe({
79 scope,
80 readable: options.evaluate(),
81 onError: options.onError ?? defaultOnError as any,
82 chunkSize: options.chunkSize,
83 closeOnDone: options.closeOnDone
84 })
85 )
86​
87/**
88 * Creates a `Channel` over a Node `Duplex`, writing upstream chunks with
89 * backpressure while emitting chunks read from the duplex and optionally ending
90 * the writable side when upstream completes.
91 *
92 * @category constructors
93 * @since 4.0.0
94 */
95export const fromDuplex = <IE, I = Uint8Array, O = Uint8Array, E = Cause.UnknownError>(
96 options: {
97 readonly evaluate: LazyArg<Duplex>
98 readonly onError?: (error: unknown) => E
99 readonly chunkSize?: number | undefined
100 readonly bufferSize?: number | undefined
101 readonly endOnDone?: boolean | undefined
102 readonly encoding?: BufferEncoding | undefined
103 }
104): Channel.Channel<Arr.NonEmptyReadonlyArray<O>, IE | E, void, Arr.NonEmptyReadonlyArray<I>, IE> =>
105 Channel.fromTransform((upstream, scope) => {
106 const duplex = options.evaluate()
107 const exit = MutableRef.make<Exit.Exit<never, IE | E | Cause.Done> | undefined>(undefined)
108​
109 return pullIntoWritable({
110 pull: upstream,
111 writable: duplex,
112 onError: options.onError ?? defaultOnError as any,
113 endOnDone: options.endOnDone,
114 encoding: options.encoding
115 }).pipe(
116 Effect.catchCause((cause) => {
117 if (Pull.isDoneCause(cause)) return Effect.void
118 exit.current = Exit.failCause(cause as Cause.Cause<IE | E | Cause.Done>)
119 return Effect.void
120 }),
121 Effect.forkIn(scope),
122 Effect.flatMap(() =>
123 readableToPullUnsafe({
124 scope,
125 exit,
126 readable: duplex,
127 onError: options.onError ?? defaultOnError as any,
128 chunkSize: options.chunkSize
129 })
130 )
131 )
132 })
133​
134/**
135 * Pipes an Effect `Stream` through a Node `Duplex`, writing the stream's
136 * chunks to the duplex and emitting chunks read back from it.
137 *
138 * @category combinators
139 * @since 4.0.0
140 */
141export const pipeThroughDuplex: {
142 <B = Uint8Array, E2 = Cause.UnknownError>(
143 options: {
144 readonly evaluate: LazyArg<Duplex>
145 readonly onError?: (error: unknown) => E2
146 readonly chunkSize?: number | undefined
147 readonly bufferSize?: number | undefined
148 readonly endOnDone?: boolean | undefined
149 readonly encoding?: BufferEncoding | undefined
150 }
151 ): <R, E, A>(self: Stream.Stream<A, E, R>) => Stream.Stream<B, E2 | E, R>
152 <R, E, A, B = Uint8Array, E2 = Cause.UnknownError>(
153 self: Stream.Stream<A, E, R>,
154 options: {
155 readonly evaluate: LazyArg<Duplex>
156 readonly onError?: (error: unknown) => E2
157 readonly chunkSize?: number | undefined
158 readonly bufferSize?: number | undefined
159 readonly endOnDone?: boolean | undefined
160 readonly encoding?: BufferEncoding | undefined
161 }
162 ): Stream.Stream<B, E | E2, R>
163} = dual(2, <R, E, A, B = Uint8Array, E2 = Cause.UnknownError>(
164 self: Stream.Stream<A, E, R>,
165 options: {
166 readonly evaluate: LazyArg<Duplex>
167 readonly onError?: (error: unknown) => E2
168 readonly chunkSize?: number | undefined
169 readonly bufferSize?: number | undefined
170 readonly endOnDone?: boolean | undefined
171 readonly encoding?: BufferEncoding | undefined
172 }
173): Stream.Stream<B, E | E2, R> =>
174 Stream.pipeThroughChannelOrFail(
175 self,
176 fromDuplex(options)
177 ))
178​
179/**
180 * Pipes a stream of strings or bytes through a Node `Duplex` using default
181 * options and `Cause.UnknownError` for stream failures.
182 *
183 * @category combinators
184 * @since 4.0.0
185 */
186export const pipeThroughSimple: {
187 (
188 duplex: LazyArg<Duplex>
189 ): <R, E>(self: Stream.Stream<string | Uint8Array, E, R>) => Stream.Stream<Uint8Array, E | Cause.UnknownError, R>
190 <R, E>(
191 self: Stream.Stream<string | Uint8Array, E, R>,
192 duplex: LazyArg<Duplex>
193 ): Stream.Stream<Uint8Array, Cause.UnknownError | E, R>
194} = dual(2, <R, E>(
195 self: Stream.Stream<string | Uint8Array, E, R>,
196 duplex: LazyArg<Duplex>
197): Stream.Stream<Uint8Array, Cause.UnknownError | E, R> => pipeThroughDuplex(self, { evaluate: duplex }))
198​
199/**
200 * Converts an Effect `Stream` into a Node `Readable`, using the caller's
201 * Effect context to run the stream and destroying the readable if the stream
202 * fails.
203 *
204 * @category converting
205 * @since 4.0.0
206 */
207export const toReadable = <E, R>(stream: Stream.Stream<string | Uint8Array, E, R>): Effect.Effect<Readable, never, R> =>
208 Effect.map(
209 Effect.context<R>(),
210 (context) => new StreamAdapter(context, stream)
211 )
212​
213/**
214 * Converts a service-free Effect `Stream` into a Node `Readable` using an
215 * empty Effect context.
216 *
217 * @category converting
218 * @since 4.0.0
219 */
220export const toReadableNever = <E>(stream: Stream.Stream<string | Uint8Array, E, never>): Readable =>
221 new StreamAdapter(
222 Context.empty(),
223 stream
224 )
225​
226/**
227 * Consumes a Node readable stream into a string using the selected encoding,
228 * failing through `onError` on stream errors or when `maxBytes` is exceeded
229 * and destroying the stream on interruption or failure.
230 *
231 * @category converting
232 * @since 4.0.0
233 */
234export const toString = <E = Cause.UnknownError>(
235 readable: LazyArg<Readable | NodeJS.ReadableStream>,
236 options?: {
237 readonly onError?: (error: unknown) => E
238 readonly encoding?: BufferEncoding | undefined
239 readonly maxBytes?: SizeInput | undefined
240 }
241): Effect.Effect<string, E> => {
242 const maxBytesNumber = options?.maxBytes ? Number(options.maxBytes) : undefined
243 const onError = options?.onError ?? defaultOnError
244 const encoding = options?.encoding ?? "utf8"
245 return Effect.callback((resume) => {
246 const stream = readable() as Readable
247 stream.setEncoding(encoding)
248​
249 stream.once("error", (err) => {
250 if ("closed" in stream && !stream.closed) {
251 stream.destroy()
252 }
253 resume(Effect.fail(onError(err) as E))
254 })
255 stream.once("error", (err) => {
256 resume(Effect.fail(onError(err) as E))
257 })
258​
259 let string = ""
260 let bytes = 0
261 stream.once("end", () => {
262 resume(Effect.succeed(string))
263 })
264 stream.on("data", (chunk) => {
265 string += chunk
266 bytes += Buffer.byteLength(chunk)
267 if (maxBytesNumber && bytes > maxBytesNumber) {
268 resume(Effect.fail(onError(new Error("maxBytes exceeded")) as E))
269 }
270 })
271 return Effect.sync(() => {
272 if ("closed" in stream && !stream.closed) {
273 stream.destroy()
274 }
275 })
276 })
278​
279/**
280 * Consumes a Node readable stream into an `ArrayBuffer`, failing through
281 * `onError` on stream errors or when `maxBytes` is exceeded and destroying the
282 * stream on interruption or failure.
283 *
284 * @category converting
285 * @since 4.0.0
286 */
287export const toArrayBuffer = <E = Cause.UnknownError>(
288 readable: LazyArg<Readable | NodeJS.ReadableStream>,
289 options?: {
290 readonly onError?: (error: unknown) => E
291 readonly maxBytes?: SizeInput | undefined
292 }
293): Effect.Effect<ArrayBuffer, E> => {
294 const maxBytesNumber = options?.maxBytes ? Number(options.maxBytes) : undefined
295 const onError = options?.onError ?? defaultOnError
296 return Effect.callback((resume) => {
297 const stream = readable() as Readable
298 const buffers: Array<Uint8Array> = []
299 let bytes = 0
300 stream.once("error", (err) => {
301 if ("closed" in stream && !stream.closed) {
302 stream.destroy()
303 }
304 resume(Effect.fail(onError(err) as E))
305 })
306 stream.once("end", () => {
307 const buffer = buffers.length === 1 ? buffers[0] : Buffer.concat(buffers)
308 if (buffer.byteOffset === 0 && buffer.buffer.byteLength === buffer.byteLength) {
309 return resume(Effect.succeed(buffer.buffer as ArrayBuffer))
310 }
311 resume(
312 Effect.succeed(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength) as ArrayBuffer)
313 )
314 })
315 stream.on("data", (chunk) => {
316 buffers.push(chunk)
317 bytes += chunk.length
318 if (maxBytesNumber && bytes > maxBytesNumber) {
319 resume(Effect.fail(onError(new Error("maxBytes exceeded")) as E))
320 }
321 })
322 return Effect.sync(() => {
323 if ("closed" in stream && !stream.closed) {
324 stream.destroy()
325 }
326 })
327 })
329​
330/**
331 * Consumes a Node readable stream into a `Uint8Array`, using the same error
332 * mapping and `maxBytes` handling as `toArrayBuffer`.
333 *
334 * @category converting
335 * @since 4.0.0
336 */
337export const toUint8Array = <E = Cause.UnknownError>(
338 readable: LazyArg<Readable | NodeJS.ReadableStream>,
339 options?: {
340 readonly onError?: (error: unknown) => E
341 readonly maxBytes?: SizeInput | undefined
342 }
343): Effect.Effect<Uint8Array, E> => Effect.map(toArrayBuffer(readable, options), (buffer) => new Uint8Array(buffer))
344​
345// ----------------------------------------------------------------------------
346// internal
347// ----------------------------------------------------------------------------
348​
349const readableToPullUnsafe = <A, E>(options: {
350 readonly scope: Scope.Scope
351 readonly exit?: MutableRef.MutableRef<Exit.Exit<never, E | Cause.Done> | undefined> | undefined
352 readonly readable: Readable | NodeJS.ReadableStream
353 readonly onError: (error: unknown) => E
354 readonly chunkSize: number | undefined
355 readonly closeOnDone?: boolean | undefined
356}) => {
357 const readable = options.readable as Readable
358 if (readable.readableEnded) return Effect.succeed(Cause.done())
359​
360 const closeOnDone = options.closeOnDone ?? true
361 const exit = options.exit ?? MutableRef.make(undefined)
362 const latch = Latch.makeUnsafe(false)
363 function onReadable() {
364 latch.openUnsafe()
365 }
366 function onError(error: unknown) {
367 exit.current = Exit.fail(options.onError(error))
368 latch.openUnsafe()
369 }
370 function onEnd() {
371 exit.current = Exit.fail(Cause.Done())
372 latch.openUnsafe()
373 }
374 readable.on("readable", onReadable)
375 readable.once("error", onError)
376 readable.once("end", onEnd)
377​
378 const pull = Effect.suspend(function loop(): Pull.Pull<Arr.NonEmptyReadonlyArray<A>, E> {
379 let item = options.readable.read(options.chunkSize) as A | null
380 if (item === null) {
381 if (exit.current) {
382 return exit.current
383 }
384 latch.closeUnsafe()
385 return Effect.flatMap(latch.await, loop)
386 }
387 const chunk = Arr.of(item as A)
388 while (true) {
389 item = options.readable.read(options.chunkSize)
390 if (item === null) break
391 chunk.push(item)
392 }
393 return Effect.succeed(chunk)
394 })
395​
396 return Effect.as(
397 Scope.addFinalizer(
398 options.scope,
399 Effect.sync(() => {
400 readable.off("readable", onReadable)
401 readable.off("error", onError)
402 readable.off("end", onEnd)
403 if (closeOnDone && "closed" in options.readable && !options.readable.closed) {
404 options.readable.destroy()
405 }
406 })
407 ),
408 pull
409 )
411​
412class StreamAdapter<E, R> extends Readable {
413 private readonly readLatch: Latch.Latch
414 private fiber: Fiber.Fiber<void, E> | undefined = undefined
415​
416 constructor(
417 context: Context.Context<R>,
418 stream: Stream.Stream<Uint8Array | string, E, R>
419 ) {
420 super({})
421 this.readLatch = Latch.makeUnsafe(false)
422 this.fiber = Stream.runForEachArray(stream, (chunk) =>
423 this.readLatch.whenOpen(Effect.sync(() => {
424 this.readLatch.closeUnsafe()
425 for (let i = 0; i < chunk.length; i++) {
426 const item = chunk[i]
427 if (typeof item === "string") {
428 this.push(item, "utf8")
429 } else {
430 this.push(item)
431 }
432 }
433 }))).pipe(
434 this.readLatch.whenOpen,
435 Effect.provideContext(context),
436 Effect.runFork
437 )
438 this.fiber.addObserver((exit) => {
439 this.fiber = undefined
440 if (Exit.isSuccess(exit)) {
441 this.push(null)
442 } else {
443 this.destroy(Cause.squash(exit.cause) as any)
444 }
445 })
446 }
447​
448 override _read(_size: number): void {
449 this.readLatch.openUnsafe()
450 }
451​
452 override _destroy(error: Error | null, callback: (error?: Error | null | undefined) => void): void {
453 if (!this.fiber) {
454 return callback(error)
455 }
456 Effect.runFork(Fiber.interrupt(this.fiber)).addObserver((exit) => {
457 callback(exit._tag === "Failure" ? Cause.squash(exit.cause) as any : error)
458 })
459 }
461​
462const defaultOnError = (error: unknown): Cause.UnknownError => new Cause.UnknownError(error)