Skip to content

Commit 9f9a41c

Browse files
fix(sse): close sse stream on end (#2529)
* 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 <[email protected]>
1 parent c83d80f commit 9f9a41c

File tree

3 files changed

+10
-1
lines changed

3 files changed

+10
-1
lines changed

deno_dist/helper/streaming/sse.ts

+2
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ const run = async (
5353
} else {
5454
console.error(e)
5555
}
56+
} finally {
57+
stream.close()
5658
}
5759
}
5860

src/helper/streaming/sse.test.ts

+6-1
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,17 @@ describe('SSE Streaming helper', () => {
1010
})
1111

1212
it('Check streamSSE Response', async () => {
13+
let spy
1314
const res = streamSSE(c, async (stream) => {
15+
spy = vi.spyOn(stream, 'close').mockImplementation(async () => {})
16+
1417
let id = 0
1518
const maxIterations = 5
1619

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

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

4954
it('Check streamSSE Response if aborted by client', async () => {

src/helper/streaming/sse.ts

+2
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ const run = async (
5353
} else {
5454
console.error(e)
5555
}
56+
} finally {
57+
stream.close()
5658
}
5759
}
5860

0 commit comments

Comments
 (0)