Skip to content

Commit

Permalink
fix(sse): close sse stream on end (#2529)
Browse files Browse the repository at this point in the history
* close sse stream on end

Adds a finally block to the SSEStream class. Otherwise streamSSE will error whenever used in Cloudflare Workers.

* denoify

* add a test

---------

Co-authored-by: Yusuke Wada <yusuke@kamawada.com>
  • Loading branch information
domeccleston and yusukebe committed Apr 19, 2024
1 parent c83d80f commit 9f9a41c
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 1 deletion.
2 changes: 2 additions & 0 deletions deno_dist/helper/streaming/sse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ const run = async (
} else {
console.error(e)
}
} finally {
stream.close()
}
}

Expand Down
7 changes: 6 additions & 1 deletion src/helper/streaming/sse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,17 @@ describe('SSE Streaming helper', () => {
})

it('Check streamSSE Response', async () => {
let spy
const res = streamSSE(c, async (stream) => {
spy = vi.spyOn(stream, 'close').mockImplementation(async () => {})

let id = 0
const maxIterations = 5

while (id < maxIterations) {
const message = `Message\nIt is ${id}`
await stream.writeSSE({ data: message, event: 'time-update', id: String(id++) })
await stream.sleep(100)
await stream.sleep(10)
}
})

Expand All @@ -44,6 +47,8 @@ describe('SSE Streaming helper', () => {
expectedValue += `id: ${i}\n\n`
expect(decodedValue).toBe(expectedValue)
}
await new Promise((resolve) => setTimeout(resolve, 100))
expect(spy).toHaveBeenCalled()
})

it('Check streamSSE Response if aborted by client', async () => {
Expand Down
2 changes: 2 additions & 0 deletions src/helper/streaming/sse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ const run = async (
} else {
console.error(e)
}
} finally {
stream.close()
}
}

Expand Down

0 comments on commit 9f9a41c

Please sign in to comment.