Skip to content
Myr

stream.ts

This file

Path

src/utils/stream.ts

96 lines · 2.4 KiB · TypeScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than 82bdc4d point at it.

4.9.0Yusuke Wadabefore adoption82bdc4d

lines 1–96why, one step back
1/**
2 * @module3 * Stream utility.4 */56export class StreamingApi {7 private writer: WritableStreamDefaultWriter<Uint8Array>8 private encoder: TextEncoder9 private writable: WritableStream10 private abortSubscribers: (() => void | Promise<void>)[] = []11 responseReadable: ReadableStream12 /**13 * Whether the stream has been aborted.14 */15 aborted: boolean = false16 /**17 * Whether the stream has been closed normally.18 */19 closed: boolean = false2021 constructor(writable: WritableStream, _readable: ReadableStream) {22 this.writable = writable23 this.writer = writable.getWriter()24 this.encoder = new TextEncoder()2526 const reader = _readable.getReader()2728 // in case the user disconnects, let the reader know to cancel29 // this in-turn results in responseReadable being closed30 // and writeSSE method no longer blocks indefinitely31 this.abortSubscribers.push(async () => {32 await reader.cancel()33 })3435 this.responseReadable = new ReadableStream({36 async pull(controller) {37 const { done, value } = await reader.read()38 done ? controller.close() : controller.enqueue(value)39 },40 cancel: () => {41 this.abort()42 },43 })44 }4546 async write(input: Uint8Array | string): Promise<StreamingApi> {47 try {48 if (typeof input === 'string') {49 input = this.encoder.encode(input)50 }51 await this.writer.write(input)52 } catch {53 // Do nothing. If you want to handle errors, create a stream by yourself.54 }55 return this56 }5758 async writeln(input: string): Promise<StreamingApi> {59 await this.write(input + '\n')60 return this61 }6263 sleep(ms: number): Promise<unknown> {64 return new Promise((res) => setTimeout(res, ms))65 }6667 async close() {68 try {69 await this.writer.close()70 } catch {71 // Do nothing. If you want to handle errors, create a stream by yourself.72 }73 this.closed = true74 }7576 async pipe(body: ReadableStream) {77 this.writer.releaseLock()78 await body.pipeTo(this.writable, { preventClose: true })79 this.writer = this.writable.getWriter()80 }8182 onAbort(listener: () => void | Promise<void>) {83 this.abortSubscribers.push(listener)84 }8586 /**87 * Abort the stream.88 * You can call this method when stream is aborted by external event.89 */90 abort() {91 if (!this.aborted) {92 this.aborted = true93 this.abortSubscribers.forEach((subscriber) => subscriber())94 }95 }96}