Skip to content

Commit d995ce3

Browse files
Fix ReadableStream controller double-close crash
Guard against calling controller.close() when the stream has already been closed by an external cancellation. This can happen when the SDK cancels the stream before the underlying Node stream emits its 'end' event. - Add `closed` flag to track controller state - Guard all controller operations with closed check - Add `cancel()` callback to handle external cancellation - Properly destroy the Node stream on cancellation
1 parent 6a86c19 commit d995ce3

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

server/src/index.ts

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -241,18 +241,31 @@ const authMiddleware = (
241241
* This is necessary for the EventSource polyfill which expects web streams
242242
*/
243243
const createWebReadableStream = (nodeStream: any): ReadableStream => {
244+
let closed = false;
244245
return new ReadableStream({
245246
start(controller) {
246247
nodeStream.on("data", (chunk: any) => {
247-
controller.enqueue(chunk);
248+
if (!closed) {
249+
controller.enqueue(chunk);
250+
}
248251
});
249252
nodeStream.on("end", () => {
250-
controller.close();
253+
if (!closed) {
254+
closed = true;
255+
controller.close();
256+
}
251257
});
252258
nodeStream.on("error", (err: any) => {
253-
controller.error(err);
259+
if (!closed) {
260+
closed = true;
261+
controller.error(err);
262+
}
254263
});
255264
},
265+
cancel() {
266+
closed = true;
267+
nodeStream.destroy();
268+
},
256269
});
257270
};
258271

0 commit comments

Comments
 (0)