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
This commit is contained in:
Felix Weinberger 2025-11-27 21:57:17 +00:00
commit d995ce3bbd
No known key found for this signature in database

View file

@ -241,18 +241,31 @@ const authMiddleware = (
* This is necessary for the EventSource polyfill which expects web streams
*/
const createWebReadableStream = (nodeStream: any): ReadableStream => {
let closed = false;
return new ReadableStream({
start(controller) {
nodeStream.on("data", (chunk: any) => {
controller.enqueue(chunk);
if (!closed) {
controller.enqueue(chunk);
}
});
nodeStream.on("end", () => {
controller.close();
if (!closed) {
closed = true;
controller.close();
}
});
nodeStream.on("error", (err: any) => {
controller.error(err);
if (!closed) {
closed = true;
controller.error(err);
}
});
},
cancel() {
closed = true;
nodeStream.destroy();
},
});
};