feat(streaming): implement `stream.onAbort` (#1871)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat: extend `StreamAPI` for response interception and adapt stream handler for it * chore: denoify
authored by Sor4chi · committed by GitHub · parent 773531e · Browse files · 10 files·+114 added−34 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+114 added−34 removed
- tests:+50 added−14 removed
- other:+64 added−20 removed
Provenance
- Commit
4dfcda8- Tree
69001b5- Author
Sor4chi <80559385+sor4chi@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
773531e
10 files changed+114 added−34 removed
modified:deno_dist/helper/streaming/sse.ts+4 added-4 removed
7 unmodified lines891011121312131415161721 unmodified lines3940414243434445454647484911 unmodified lines7 unmodified lines id?: string}
export class SSEStreamingApi extends StreamingApi { constructor(writable: WritableStream) { super(writable) constructor(writable: WritableStream, readable: ReadableStream) { super(writable, readable) }
async writeSSE(message: SSEMessage) { const data = message.data21 unmodified lines
export const streamSSE = (c: Context, cb: (stream: SSEStreamingApi) => Promise<void>) => { return stream(c, async (originalStream: StreamingApi) => { const { readable, writable } = new TransformStream() const stream = new SSEStreamingApi(writable) const stream = new SSEStreamingApi(writable, readable)
originalStream.pipe(readable).catch((err) => { originalStream.pipe(stream.responseReadable).catch((err) => { console.error('Error in stream piping: ', err) stream.close() })
11 unmodified linesmodified:deno_dist/helper/streaming/stream.ts+2 added-2 removed
12345667889import type { Context } from '../../context.ts'import { StreamingApi } from '../../utils/stream.ts'
export const stream = (c: Context, cb: (stream: StreamingApi) => Promise<void>): Response => { const { readable, writable } = new TransformStream() const stream = new StreamingApi(writable) const stream = new StreamingApi(writable, readable) cb(stream).finally(() => stream.close()) return c.newResponse(readable) return c.newResponse(stream.responseReadable)}modified:deno_dist/utils/stream.ts+23 added-1 removed
12345676891011121314151617181920212223242526272829303128 unmodified lines606162636465666768export class StreamingApi { private writer: WritableStreamDefaultWriter<Uint8Array> private encoder: TextEncoder private writable: WritableStream private abortSubscribers: (() => void | Promise<void>)[] = [] responseReadable: ReadableStream
constructor(writable: WritableStream) { constructor(writable: WritableStream, _readable: ReadableStream) { this.writable = writable this.writer = writable.getWriter() this.encoder = new TextEncoder()
const reader = _readable.getReader()
this.responseReadable = new ReadableStream({ async pull(controller) { const { done, value } = await reader.read() if (done) { controller.close() } else { controller.enqueue(value) } }, cancel: () => { this.abortSubscribers.forEach((subscriber) => subscriber()) }, }) }
async write(input: Uint8Array | string) { try {28 unmodified lines this.writer.releaseLock() await body.pipeTo(this.writable, { preventClose: true }) this.writer = this.writable.getWriter() }
async onAbort(listener: () => void | Promise<void>) { this.abortSubscribers.push(listener) }}modified:deno_dist/context.ts+3 added-3 removed
397 unmodified lines398 arg?: StatusCode | ResponseInit,399 headers?: HeaderRecord400 ): Response => {401 const { readable, writable } = new TransformStream()402- const stream = new StreamingApi(writable)402+ const stream = new StreamingApi(writable, readable)403 cb(stream).finally(() => stream.close())404 405 return typeof arg === 'number'406- ? this.newResponse(readable, arg, headers)407- : this.newResponse(readable, arg)406+ ? this.newResponse(stream.responseReadable, arg, headers)407+ : this.newResponse(stream.responseReadable, arg)408 }409 410 /** @deprecated411 * Use Cookie Middleware instead of `c.cookie()`. The `c.cookie()` will be removed in v4.68 unmodified linesmodified:src/helper/streaming/sse.ts+4 added-4 removed
7 unmodified lines891011121312131415161721 unmodified lines3940414243434445454647484911 unmodified lines7 unmodified lines id?: string}
export class SSEStreamingApi extends StreamingApi { constructor(writable: WritableStream) { super(writable) constructor(writable: WritableStream, readable: ReadableStream) { super(writable, readable) }
async writeSSE(message: SSEMessage) { const data = message.data21 unmodified lines
export const streamSSE = (c: Context, cb: (stream: SSEStreamingApi) => Promise<void>) => { return stream(c, async (originalStream: StreamingApi) => { const { readable, writable } = new TransformStream() const stream = new SSEStreamingApi(writable) const stream = new SSEStreamingApi(writable, readable)
originalStream.pipe(readable).catch((err) => { originalStream.pipe(stream.responseReadable).catch((err) => { console.error('Error in stream piping: ', err) stream.close() })
11 unmodified linesmodified:src/helper/streaming/stream.ts+2 added-2 removed
12345667889import type { Context } from '../../context'import { StreamingApi } from '../../utils/stream'
export const stream = (c: Context, cb: (stream: StreamingApi) => Promise<void>): Response => { const { readable, writable } = new TransformStream() const stream = new StreamingApi(writable) const stream = new StreamingApi(writable, readable) cb(stream).finally(() => stream.close()) return c.newResponse(readable) return c.newResponse(stream.responseReadable)}modified:src/utils/stream.test.ts+28 added-14 removed
1 unmodified line2 3 describe('StreamingApi', () => {4 it('write(string)', async () => {5 const { readable, writable } = new TransformStream()6- const api = new StreamingApi(writable)7- const reader = readable.getReader()6+ const api = new StreamingApi(writable, readable)7+ const reader = api.responseReadable.getReader()8 api.write('foo')9 expect((await reader.read()).value).toEqual(new TextEncoder().encode('foo'))10 api.write('bar')11 expect((await reader.read()).value).toEqual(new TextEncoder().encode('bar'))12 })13 14 it('write(Uint8Array)', async () => {15 const { readable, writable } = new TransformStream()16- const api = new StreamingApi(writable)17- const reader = readable.getReader()16+ const api = new StreamingApi(writable, readable)17+ const reader = api.responseReadable.getReader()18 api.write(new Uint8Array([1, 2, 3]))19 expect((await reader.read()).value).toEqual(new Uint8Array([1, 2, 3]))20 api.write(new Uint8Array([4, 5, 6]))21 expect((await reader.read()).value).toEqual(new Uint8Array([4, 5, 6]))22 })23 24 it('writeln(string)', async () => {25 const { readable, writable } = new TransformStream()26- const api = new StreamingApi(writable)27- const reader = readable.getReader()26+ const api = new StreamingApi(writable, readable)27+ const reader = api.responseReadable.getReader()28 api.writeln('foo')29 expect((await reader.read()).value).toEqual(new TextEncoder().encode('foo\n'))30 api.writeln('bar')31 expect((await reader.read()).value).toEqual(new TextEncoder().encode('bar\n'))11 unmodified lines43 })()44 45 const { readable: receiverReadable, writable: receiverWritable } = new TransformStream()46 47- const api = new StreamingApi(receiverWritable)47+ const api = new StreamingApi(receiverWritable, receiverReadable)48 49 // pipe readable to api in other scope50 ;(async () => {51 await api.pipe(senderReadable)52 })()53 54 // read data from api55- const reader = receiverReadable.getReader()55+ const reader = api.responseReadable.getReader()56 expect((await reader.read()).value).toEqual(new TextEncoder().encode('foo'))57 expect((await reader.read()).value).toEqual(new TextEncoder().encode('bar'))58 })59 60 it('close()', async () => {61 const { readable, writable } = new TransformStream()62- const api = new StreamingApi(writable)63- const reader = readable.getReader()62+ const api = new StreamingApi(writable, readable)63+ const reader = api.responseReadable.getReader()64 await api.close()65 expect((await reader.read()).done).toBe(true)66 })67 68 it('should not throw an error in write()', async () => {69- const { writable } = new TransformStream()70- const api = new StreamingApi(writable)69+ const { readable, writable } = new TransformStream()70+ const api = new StreamingApi(writable, readable)71 await api.close()72 const write = () => api.write('foo')73 expect(write).not.toThrow()74 })75 76 it('should not throw an error in close()', async () => {77- const { writable } = new TransformStream()78- const api = new StreamingApi(writable)77+ const { readable, writable } = new TransformStream()78+ const api = new StreamingApi(writable, readable)79 const close = async () => {80 await api.close()81 await api.close()82 }83 expect(close).not.toThrow()84 })85+86+ it('onAbort()', async () => {87+ const { readable, writable } = new TransformStream()88+ const handleAbort1 = vi.fn()89+ const handleAbort2 = vi.fn()90+ const api = new StreamingApi(writable, readable)91+ api.onAbort(handleAbort1)92+ api.onAbort(handleAbort2)93+ expect(handleAbort1).not.toBeCalled()94+ expect(handleAbort2).not.toBeCalled()95+ await api.responseReadable.cancel()96+ expect(handleAbort1).toBeCalled()97+ expect(handleAbort2).toBeCalled()98+ })99 })modified:src/utils/stream.ts+23 added-1 removed
1 export class StreamingApi {2 private writer: WritableStreamDefaultWriter<Uint8Array>3 private encoder: TextEncoder4 private writable: WritableStream5+ private abortSubscribers: (() => void | Promise<void>)[] = []6+ responseReadable: ReadableStream7 6- constructor(writable: WritableStream) {8+ constructor(writable: WritableStream, _readable: ReadableStream) {9 this.writable = writable10 this.writer = writable.getWriter()11 this.encoder = new TextEncoder()12+13+ const reader = _readable.getReader()14+15+ this.responseReadable = new ReadableStream({16+ async pull(controller) {17+ const { done, value } = await reader.read()18+ if (done) {19+ controller.close()20+ } else {21+ controller.enqueue(value)22+ }23+ },24+ cancel: () => {25+ this.abortSubscribers.forEach((subscriber) => subscriber())26+ },27+ })28 }29 30 async write(input: Uint8Array | string) {31 try {28 unmodified lines60 this.writer.releaseLock()61 await body.pipeTo(this.writable, { preventClose: true })62 this.writer = this.writable.getWriter()63 }64+65+ async onAbort(listener: () => void | Promise<void>) {66+ this.abortSubscribers.push(listener)67+ }68 }modified:src/context.test.ts+22 added
340 unmodified lines341 const res = await c.render('<h1>content</h1>', { title: 'title' })342 expect(res.headers.get('foo')).toBe('bar')343 expect(await res.text()).toBe('<html><head>title</head><body><h1>content</h1></body></html>')344 })345+346+ it('c.stream() - with aborted during writing', async () => {347+ let aborted = false348+ const res = c.stream(async (stream) => {349+ stream.onAbort(() => {350+ aborted = true351+ })352+ for (let i = 0; i < 3; i++) {353+ await stream.write(new Uint8Array([i]))354+ await stream.sleep(1)355+ }356+ })357+ if (!res.body) {358+ throw new Error('Body is null')359+ }360+ const reader = res.body.getReader()361+ for (let i = 0; i < 2; i++) {362+ await reader.read()363+ await reader.cancel()364+ }365+ expect(aborted).toBe(true)366+ })367 })modified:src/context.ts+3 added-3 removed
397 unmodified lines398 arg?: StatusCode | ResponseInit,399 headers?: HeaderRecord400 ): Response => {401 const { readable, writable } = new TransformStream()402- const stream = new StreamingApi(writable)402+ const stream = new StreamingApi(writable, readable)403 cb(stream).finally(() => stream.close())404 405 return typeof arg === 'number'406- ? this.newResponse(readable, arg, headers)407- : this.newResponse(readable, arg)406+ ? this.newResponse(stream.responseReadable, arg, headers)407+ : this.newResponse(stream.responseReadable, arg)408 }409 410 /** @deprecated411 * Use Cookie Middleware instead of `c.cookie()`. The `c.cookie()` will be removed in v4.68 unmodified lines