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

NodeStream.ts

447 lines14.4 KB

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