Skip to content

Commit

Permalink
fix(streaming): call stream.abort() explicitly when request is aborted
Browse files Browse the repository at this point in the history
  • Loading branch information
usualoma committed Jun 25, 2024
1 parent 21c94b0 commit 9f5a78c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/helper/streaming/sse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,15 @@ export const streamSSE = (
const { readable, writable } = new TransformStream()
const stream = new SSEStreamingApi(writable, readable)

// bun does not cancel response stream when request is canceled, so detect abort by signal
c.req.raw.signal.addEventListener('abort', () => {
// "referencing a `c` that is never null in a condition" is a work around for bun (maybe JIT).
// If `c` is not referenced in this closure, this event will not fire.
if (c) {
stream.abort()
}

Check warning on line 75 in src/helper/streaming/sse.ts

View check run for this annotation

Codecov / codecov/patch

src/helper/streaming/sse.ts#L71-L75

Added lines #L71 - L75 were not covered by tests
})

c.header('Transfer-Encoding', 'chunked')
c.header('Content-Type', 'text/event-stream')
c.header('Cache-Control', 'no-cache')
Expand Down
9 changes: 9 additions & 0 deletions src/helper/streaming/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@ export const stream = (
): Response => {
const { readable, writable } = new TransformStream()
const stream = new StreamingApi(writable, readable)

// bun does not cancel response stream when request is canceled, so detect abort by signal
c.req.raw.signal.addEventListener('abort', () => {
// "referencing a `c` that is never null in a condition" is a work around for bun (maybe JIT).
// If `c` is not referenced in this closure, this event will not fire.
if (c) {
stream.abort()
}

Check warning on line 18 in src/helper/streaming/stream.ts

View check run for this annotation

Codecov / codecov/patch

src/helper/streaming/stream.ts#L14-L18

Added lines #L14 - L18 were not covered by tests
})
;(async () => {
try {
await cb(stream)
Expand Down

0 comments on commit 9f5a78c

Please sign in to comment.