Conversation
…error handling Add support for async iterables (async generators) as response bodies, filter ERR_STREAM_PREMATURE_CLOSE errors from client disconnects in the stream pipeline, and add comprehensive tests for the new functionality. Closes koajs#1864 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1928 +/- ##
=======================================
Coverage 99.90% 99.90%
=======================================
Files 9 9
Lines 2084 2098 +14
=======================================
+ Hits 2082 2096 +14
Misses 2 2 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
lib/is-stream.js
Outdated
| * @param {*} obj | ||
| * @return {boolean} | ||
| */ | ||
| const isAsyncIterable = (obj) => { |
There was a problem hiding this comment.
There is duplicative logic here. Claude, in this session, is having the isSteam function do the same calculations as its new isAsyncIterable on line 34. AKA, you could remove some lines of this function.
I think this function can be removed, and
typeof obj[Symbol.asyncIterator] === 'function' could be the if statement logic on line 230 of lib/response.js...?
The isAsyncIterable helper had redundant type exclusion checks since streams, ReadableStream, Blob, and Response are already handled by preceding branches in both the body setter and respond function. Inline the Symbol.asyncIterator check directly where needed.
|
Good call, yeah that function was doing unnecessary work since all those types (Stream, ReadableStream, Blob, Response) are already handled by the preceding branches. Removed |
Summary
Addresses #1864 - Improved stream handling in Koa.
ctx.bodynow accepts async iterables (e.g.async function*) as response bodies, converting them to Node.js readable streams viaStream.Readable.from(). This is useful for streaming responses from async data sources without manually creating streams.ERR_STREAM_PREMATURE_CLOSEerrors (caused by client disconnects) are now filtered out in thestream.pipelinecallback, preventing spurious error events on the application when clients simply close their connections.Changes
lib/is-stream.js: AddedisAsyncIterable()helper that detects async iterables while excluding types already handled (Node.js streams, ReadableStream, Blob, Response)lib/application.js: Added async iterable detection inrespond(), filteredERR_STREAM_PREMATURE_CLOSEin pipeline error callbacklib/response.js: Added async iterable handling in thebodysetter__tests__/application/respond.test.js: Added 9 new tests covering async generator responses, async iterable responses, buffer yields, content type handling, error propagation, and premature close filtering__tests__/response/body.test.js: Added 4 new tests for body setter behavior with async iterablesTest plan
ctx.body = asyncGenerator()ERR_STREAM_PREMATURE_CLOSEerrors🤖 Generated with Claude Code