fix(streaming): call stream.abort() explicitly when request is aborted (#3042)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(utils/stream): enable to abort streaming manually * feat(utils/stream): prevent multiple aborts, and enable to get the abort status * fix(streaming): call `stream.abort()` explicitly when request is aborted * test: add tests for streaming * docs(stream): add comments * test: add --allow-net to deno test command in ci.yml * test(streaming): update test code * test(stream): retry flaky test up to 3 times at "bun" * test(streaming): refactor test to use afterEach * fix(streaming): in bun, `c` is destroyed when the request is returned, so hold it until the end of streaming * refactor(streaming): tweaks code layout
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+318 added−4 removed
- tests:+283 added−1 removed
- other:+35 added−3 removed
Provenance
- Commit
2d3bc55- Tree
bff0a4c- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
a6ad42d
11 files changed+318 added−4 removed
modified:.github/workflows/ci.yml+1 added-1 removed
75 unmodified lines7677787980808182838495 unmodified lines75 unmodified lines - uses: actions/checkout@v4 - uses: denoland/setup-deno@v1 with: deno-version: v1.x - run: env NAME=Deno deno test --coverage=coverage/raw/deno-runtime --allow-read --allow-env --allow-write -c runtime_tests/deno/deno.json runtime_tests/deno - run: env NAME=Deno deno test --coverage=coverage/raw/deno-runtime --allow-read --allow-env --allow-write --allow-net -c runtime_tests/deno/deno.json runtime_tests/deno - run: deno test -c runtime_tests/deno-jsx/deno.precompile.json --coverage=coverage/raw/deno-precompile-jsx runtime_tests/deno-jsx - run: deno test -c runtime_tests/deno-jsx/deno.react-jsx.json --coverage=coverage/raw/deno-react-jsx runtime_tests/deno-jsx - uses: actions/upload-artifact@v4 with:95 unmodified linesmodified:runtime_tests/bun/index.test.tsx+73 added-1 removed
1-import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'1+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'2 import { serveStatic, toSSG } from '../../src/adapter/bun'3 import { createBunWebSocket } from '../../src/adapter/bun/websocket'4 import type { BunWebSocketData } from '../../src/adapter/bun/websocket'5 import { Context } from '../../src/context'4 unmodified lines10 import { jsx } from '../../src/jsx'11 import { basicAuth } from '../../src/middleware/basic-auth'12 import { jwt } from '../../src/middleware/jwt'13 import { HonoRequest } from '../../src/request'14+import { stream, streamSSE } from '../..//src/helper/streaming'15 16 // Test just only minimal patterns.17 // Because others are tested well in Cloudflare Workers environment already.18 297 unmodified lines316 } else {317 await fs.unlink(dirPath)318 }319 }320+321+describe('streaming', () => {322+ const app = new Hono()323+ let server: ReturnType<typeof Bun.serve>324+ let aborted = false325+326+ app.get('/stream', (c) => {327+ return stream(c, async (stream) => {328+ stream.onAbort(() => {329+ aborted = true330+ })331+ return new Promise<void>((resolve) => {332+ stream.onAbort(resolve)333+ })334+ })335+ })336+ app.get('/streamSSE', (c) => {337+ return streamSSE(c, async (stream) => {338+ stream.onAbort(() => {339+ aborted = true340+ })341+ return new Promise<void>((resolve) => {342+ stream.onAbort(resolve)343+ })344+ })345+ })346+347+ beforeEach(() => {348+ aborted = false349+ server = Bun.serve({ port: 0, fetch: app.fetch })350+ })351+352+ afterEach(() => {353+ server.stop()354+ })355+356+ describe('stream', () => {357+ it('Should call onAbort', async () => {358+ const ac = new AbortController()359+ const req = new Request(`http://localhost:${server.port}/stream`, {360+ signal: ac.signal,361+ })362+ expect(aborted).toBe(false)363+ const res = fetch(req).catch(() => {})364+ await new Promise((resolve) => setTimeout(resolve, 10))365+ ac.abort()366+ await res367+ while (!aborted) {368+ await new Promise((resolve) => setTimeout(resolve))369+ }370+ expect(aborted).toBe(true)371+ })372+ })373+374+ describe('streamSSE', () => {375+ it('Should call onAbort', async () => {376+ const ac = new AbortController()377+ const req = new Request(`http://localhost:${server.port}/streamSSE`, {378+ signal: ac.signal,379+ })380+ const res = fetch(req).catch(() => {})381+ await new Promise((resolve) => setTimeout(resolve, 10))382+ ac.abort()383+ await res384+ while (!aborted) {385+ await new Promise((resolve) => setTimeout(resolve))386+ }387+ expect(aborted).toBe(true)388+ })389+ })390+})added:runtime_tests/deno/stream.test.ts+69 added
1+import { Hono } from '../../src/hono.ts'2+import { assertEquals } from './deps.ts'3+import { stream, streamSSE } from '../../src/helper/streaming/index.ts'4+5+Deno.test('Shuld call onAbort via stream', async () => {6+ const app = new Hono()7+ let aborted = false8+ app.get('/stream', (c) => {9+ return stream(c, async (stream) => {10+ stream.onAbort(() => {11+ aborted = true12+ })13+ return new Promise<void>((resolve) => {14+ stream.onAbort(resolve)15+ })16+ })17+ })18+19+ const server = Deno.serve({ port: 0 }, app.fetch)20+ const ac = new AbortController()21+ const req = new Request(`http://localhost:${server.addr.port}/stream`, {22+ signal: ac.signal,23+ })24+ assertEquals25+ const res = fetch(req).catch(() => {})26+ assertEquals(aborted, false)27+ await new Promise((resolve) => setTimeout(resolve, 10))28+ ac.abort()29+ await res30+ while (!aborted) {31+ await new Promise((resolve) => setTimeout(resolve))32+ }33+ assertEquals(aborted, true)34+35+ await server.shutdown()36+})37+38+Deno.test('Shuld call onAbort via streamSSE', async () => {39+ const app = new Hono()40+ let aborted = false41+ app.get('/stream', (c) => {42+ return streamSSE(c, async (stream) => {43+ stream.onAbort(() => {44+ aborted = true45+ })46+ return new Promise<void>((resolve) => {47+ stream.onAbort(resolve)48+ })49+ })50+ })51+52+ const server = Deno.serve({ port: 0 }, app.fetch)53+ const ac = new AbortController()54+ const req = new Request(`http://localhost:${server.addr.port}/stream`, {55+ signal: ac.signal,56+ })57+ assertEquals58+ const res = fetch(req).catch(() => {})59+ assertEquals(aborted, false)60+ await new Promise((resolve) => setTimeout(resolve, 10))61+ ac.abort()62+ await res63+ while (!aborted) {64+ await new Promise((resolve) => setTimeout(resolve))65+ }66+ assertEquals(aborted, true)67+68+ await server.shutdown()69+})modified:runtime_tests/node/index.test.ts+67 added
4 unmodified lines5 import { env, getRuntimeKey } from '../../src/helper/adapter'6 import { basicAuth } from '../../src/middleware/basic-auth'7 import { jwt } from '../../src/middleware/jwt'8 import { HonoRequest } from '../../src/request'9+import { stream, streamSSE } from '../../src/helper/streaming'10 11 // Test only minimal patterns.12 // See <https://github.com/honojs/node-server> for more tests and information.13 82 unmodified lines96 expect(res.status).toBe(200)97 expect(res.text).toBe('auth')98 })99 })100+101+describe('stream', () => {102+ const app = new Hono()103+104+ let aborted = false105+106+ app.get('/stream', (c) => {107+ return stream(c, async (stream) => {108+ stream.onAbort(() => {109+ aborted = true110+ })111+ return new Promise<void>((resolve) => {112+ stream.onAbort(resolve)113+ })114+ })115+ })116+117+ const server = createAdaptorServer(app)118+119+ it('Should call onAbort', async () => {120+ const req = request(server)121+ .get('/stream')122+ .end(() => {})123+124+ expect(aborted).toBe(false)125+ await new Promise((resolve) => setTimeout(resolve, 10))126+ req.abort()127+ while (!aborted) {128+ await new Promise((resolve) => setTimeout(resolve))129+ }130+ expect(aborted).toBe(true)131+ })132+})133+134+describe('streamSSE', () => {135+ const app = new Hono()136+137+ let aborted = false138+139+ app.get('/stream', (c) => {140+ return streamSSE(c, async (stream) => {141+ stream.onAbort(() => {142+ aborted = true143+ })144+ return new Promise<void>((resolve) => {145+ stream.onAbort(resolve)146+ })147+ })148+ })149+150+ const server = createAdaptorServer(app)151+152+ it('Should call onAbort', async () => {153+ const req = request(server)154+ .get('/stream')155+ .end(() => {})156+157+ expect(aborted).toBe(false)158+ await new Promise((resolve) => setTimeout(resolve, 10))159+ req.abort()160+ while (!aborted) {161+ await new Promise((resolve) => setTimeout(resolve))162+ }163+ expect(aborted).toBe(true)164+ })165+})modified:src/helper/streaming/sse.test.ts+27 added
71 unmodified lines72 reader.cancel()73 expect(aborted).toBeTruthy()74 })75 76+ it('Check streamSSE Response if aborted by abort signal', async () => {77+ const ac = new AbortController()78+ const req = new Request('http://localhost/', { signal: ac.signal })79+ const c = new Context(req)80+81+ let aborted = false82+ const res = streamSSE(c, async (stream) => {83+ stream.onAbort(() => {84+ aborted = true85+ })86+ for (let i = 0; i < 3; i++) {87+ await stream.writeSSE({88+ data: `Message ${i}`,89+ })90+ await stream.sleep(1)91+ }92+ })93+ if (!res.body) {94+ throw new Error('Body is null')95+ }96+ const reader = res.body.getReader()97+ const { value } = await reader.read()98+ expect(value).toEqual(new TextEncoder().encode('data: Message 0\n\n'))99+ ac.abort()100+ expect(aborted).toBeTruthy()101+ })102+103 it('Should include retry in the SSE message', async () => {104 const retryTime = 3000 // 3 seconds105 const res = streamSSE(c, async (stream) => {106 await stream.writeSSE({42 unmodified linesmodified:src/helper/streaming/sse.ts+8 added
56 unmodified lines57 stream.close()58 }59 }60 61+const contextStash = new WeakMap<ReadableStream, Context>()62 export const streamSSE = (63 c: Context,64 cb: (stream: SSEStreamingApi) => Promise<void>,65 onError?: (e: Error, stream: SSEStreamingApi) => Promise<void>66 ): Response => {67 const { readable, writable } = new TransformStream()68 const stream = new SSEStreamingApi(writable, readable)69 70+ // bun does not cancel response stream when request is canceled, so detect abort by signal71+ c.req.raw.signal.addEventListener('abort', () => {72+ stream.abort()73+ })74+ // in bun, `c` is destroyed when the request is returned, so hold it until the end of streaming75+ contextStash.set(stream.responseReadable, c)76+77 c.header('Transfer-Encoding', 'chunked')78 c.header('Content-Type', 'text/event-stream')79 c.header('Cache-Control', 'no-cache')80 c.header('Connection', 'keep-alive')5 unmodified linesmodified:src/helper/streaming/stream.test.ts+25 added
44 unmodified lines45 reader.cancel()46 expect(aborted).toBeTruthy()47 })48 49+ it('Check stream Response if aborted by abort signal', async () => {50+ const ac = new AbortController()51+ const req = new Request('http://localhost/', { signal: ac.signal })52+ const c = new Context(req)53+54+ let aborted = false55+ const res = stream(c, async (stream) => {56+ stream.onAbort(() => {57+ aborted = true58+ })59+ for (let i = 0; i < 3; i++) {60+ await stream.write(new Uint8Array([i]))61+ await stream.sleep(1)62+ }63+ })64+ if (!res.body) {65+ throw new Error('Body is null')66+ }67+ const reader = res.body.getReader()68+ const { value } = await reader.read()69+ expect(value).toEqual(new Uint8Array([0]))70+ ac.abort()71+ expect(aborted).toBeTruthy()72+ })73+74 it('Check stream Response if error occurred', async () => {75 const onError = vi.fn()76 const res = stream(77 c,15 unmodified linesmodified:src/helper/streaming/stream.ts+9 added
1 import type { Context } from '../../context'2 import { StreamingApi } from '../../utils/stream'3 4+const contextStash = new WeakMap<ReadableStream, Context>()5 export const stream = (6 c: Context,7 cb: (stream: StreamingApi) => Promise<void>,8 onError?: (e: Error, stream: StreamingApi) => Promise<void>9 ): Response => {10 const { readable, writable } = new TransformStream()11 const stream = new StreamingApi(writable, readable)12+13+ // bun does not cancel response stream when request is canceled, so detect abort by signal14+ c.req.raw.signal.addEventListener('abort', () => {15+ stream.abort()16+ })17+ // in bun, `c` is destroyed when the request is returned, so hold it until the end of streaming18+ contextStash.set(stream.responseReadable, c)19 ;(async () => {20 try {21 await cb(stream)22 } catch (e) {5 unmodified lines28 } finally {29 stream.close()30 }31 })()32+33 return c.newResponse(stream.responseReadable)34 }modified:src/utils/stream.test.ts+22 added
94 unmodified lines95 await api.responseReadable.cancel()96 expect(handleAbort1).toBeCalled()97 expect(handleAbort2).toBeCalled()98 })99+100+ it('abort()', async () => {101+ const { readable, writable } = new TransformStream()102+ const handleAbort1 = vi.fn()103+ const handleAbort2 = vi.fn()104+ const api = new StreamingApi(writable, readable)105+ api.onAbort(handleAbort1)106+ api.onAbort(handleAbort2)107+ expect(handleAbort1).not.toBeCalled()108+ expect(handleAbort2).not.toBeCalled()109+ expect(api.aborted).toBe(false)110+111+ api.abort()112+ expect(handleAbort1).toHaveBeenCalledOnce()113+ expect(handleAbort2).toHaveBeenCalledOnce()114+ expect(api.aborted).toBe(true)115+116+ api.abort()117+ expect(handleAbort1).toHaveBeenCalledOnce()118+ expect(handleAbort2).toHaveBeenCalledOnce()119+ expect(api.aborted).toBe(true)120+ })121 })modified:src/utils/stream.ts+16 added-1 removed
7 unmodified lines8 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 constructor(writable: WritableStream, _readable: ReadableStream) {18 this.writable = writable19 this.writer = writable.getWriter()13 unmodified lines33 const { done, value } = await reader.read()34 done ? controller.close() : controller.enqueue(value)35 },36 cancel: () => {33- this.abortSubscribers.forEach((subscriber) => subscriber())37+ this.abort()38 },39 })40 }41 34 unmodified lines76 77 onAbort(listener: () => void | Promise<void>) {78 this.abortSubscribers.push(listener)79 }80+81+ /**82+ * Abort the stream.83+ * You can call this method when stream is aborted by external event.84+ */85+ abort() {86+ if (!this.aborted) {87+ this.aborted = true88+ this.abortSubscribers.forEach((subscriber) => subscriber())89+ }90+ }91 }modified:package.json+1 added-1 removed
10 unmodified lines11 ],12 "scripts": {13 "test": "tsc --noEmit && vitest --run && vitest -c .vitest.config/jsx-runtime-default.ts --run && vitest -c .vitest.config/jsx-runtime-dom.ts --run",14 "test:watch": "vitest --watch",15- "test:deno": "deno test --allow-read --allow-env --allow-write -c runtime_tests/deno/deno.json runtime_tests/deno && deno test --no-lock -c runtime_tests/deno-jsx/deno.precompile.json runtime_tests/deno-jsx && deno test --no-lock -c runtime_tests/deno-jsx/deno.react-jsx.json runtime_tests/deno-jsx",15+ "test:deno": "deno test --allow-read --allow-env --allow-write --allow-net -c runtime_tests/deno/deno.json runtime_tests/deno && deno test --no-lock -c runtime_tests/deno-jsx/deno.precompile.json runtime_tests/deno-jsx && deno test --no-lock -c runtime_tests/deno-jsx/deno.react-jsx.json runtime_tests/deno-jsx",16 "test:bun": "bun test --jsx-import-source ../../src/jsx runtime_tests/bun/index.test.tsx",17 "test:fastly": "vitest --run --config ./runtime_tests/fastly/vitest.config.ts",18 "test:node": "vitest --run --config ./runtime_tests/node/vitest.config.ts",19 "test:workerd": "vitest --run --config ./runtime_tests/workerd/vitest.config.ts",584 unmodified lines