return
in a generator function crashes after iterating an @azure/core-sse
EventMessageStream
to the end #30414
Description
- Package Name: @azure/core-sse
- Package Version: 2.1.2
- Operating system: MacOS
- nodejs
- version: 20.10.0
- browser
- name/version:
- typescript
- version:
- Is the bug related to documentation in
- README.md
- source code documentation
- SDK API docs on https://learn.microsoft.com
Describe the bug
Returning from an iteration over an EventMessageStream
crashes if the entire stream has already been consumed.
To Reproduce
Steps to reproduce the behavior:
- obtain a stream with
createSseStream
(e.g. from an@azure-rest/ai-inference
response body) - iterate the stream in a generator function (with
for await (const event of stream)
) return
from the iterator when complete (e.g. withif (event.data === "[DONE]") return
)- observe exception:
TypeError: Cannot read properties of null (reading 'end')
at Object.cancel (file:///Users/jaked/repos/githubnext/vitale/node_modules/.pnpm/@azure+core-sse@2.1.2/node_modules/@azure/core-sse/dist/esm/utils.js:54:31)
at readableStreamDefaultControllerCancelSteps (node:internal/webstreams/readablestream:2383:39)
at ReadableStreamDefaultController.[kCancel] (node:internal/webstreams/readablestream:1079:12)
at ensureIsPromise (node:internal/webstreams/util:185:19)
at readableStreamCancel (node:internal/webstreams/readablestream:1984:5)
at readableStreamReaderGenericCancel (node:internal/webstreams/readablestream:2124:10)
at returnSteps (node:internal/webstreams/readablestream:524:24)
at Object.return (node:internal/webstreams/readablestream:568:11)
at main (/Users/jaked/repos/githubnext/vitale/packages/examples/azure-ai.vnb-cellId=fUdPs5uLJxWHELOq-T1-8.tsx:40:3)
at main.next (<anonymous>)
Expected behavior
Iteration completes normally without exception.
Screenshots
If applicable, add screenshots to help explain your problem.
Additional context
The exception is coming from the cancel
function in @azure/core-sse/utils.js
, which calls stream.socket.end()
when an EventMessageStream
iteration return
s in a generator function (since #28111). But Node sets stream.socket
to null
when the underlying message has been consumed (I think since nodejs/node#38505 / nodejs/undici#834), so the call fails.
Replacing stream.socket.end()
with stream.socket?.end()
fixes the issue for me.