Skip to content
Myr

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

10 files+114 added−34 removed

modified:deno_dist/helper/streaming/sse.ts+4 added-4 removed
modified:deno_dist/helper/streaming/stream.ts+2 added-2 removed
modified:deno_dist/utils/stream.ts+23 added-1 removed
modified:deno_dist/context.ts+3 added-3 removed
397 unmodified lines
398 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())404405 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 }409410 /** @deprecated411 * Use Cookie Middleware instead of `c.cookie()`. The `c.cookie()` will be removed in v4.
68 unmodified lines
modified:src/helper/streaming/sse.ts+4 added-4 removed
modified:src/helper/streaming/stream.ts+2 added-2 removed
modified:src/utils/stream.test.ts+28 added-14 removed
1 unmodified line
23describe('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 })1314 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 })2324 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 lines
43 })()4445 const { readable: receiverReadable, writable: receiverWritable } = new TransformStream()4647 const api = new StreamingApi(receiverWritable)47 const api = new StreamingApi(receiverWritable, receiverReadable)4849 // pipe readable to api in other scope50 ;(async () => {51 await api.pipe(senderReadable)52 })()5354 // 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 })5960 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 })6768 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 })7576 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 })8586 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
1export class StreamingApi {2 private writer: WritableStreamDefaultWriter<Uint8Array>3 private encoder: TextEncoder4 private writable: WritableStream5 private abortSubscribers: (() => void | Promise<void>)[] = []6 responseReadable: ReadableStream76 constructor(writable: WritableStream) {8 constructor(writable: WritableStream, _readable: ReadableStream) {9 this.writable = writable10 this.writer = writable.getWriter()11 this.encoder = new TextEncoder()1213 const reader = _readable.getReader()1415 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 }2930 async write(input: Uint8Array | string) {31 try {
28 unmodified lines
60 this.writer.releaseLock()61 await body.pipeTo(this.writable, { preventClose: true })62 this.writer = this.writable.getWriter()63 }6465 async onAbort(listener: () => void | Promise<void>) {66 this.abortSubscribers.push(listener)67 }68}
modified:src/context.test.ts+22 added
340 unmodified lines
341 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 })345346 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 lines
398 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())404405 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 }409410 /** @deprecated411 * Use Cookie Middleware instead of `c.cookie()`. The `c.cookie()` will be removed in v4.
68 unmodified lines