Skip to content

Commit

Permalink
fix: Avoid error for stream() being aborted (#2355)
Browse files Browse the repository at this point in the history
Co-authored-by: BobNobrain <bobnobrain@yandex.ru>
  • Loading branch information
BobNobrain and BobNobrain committed Oct 18, 2023
1 parent 49254c3 commit daf349f
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/api/api-stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,10 @@ class StreamHandler extends AsyncResource {
{ callback, body: res, contentType, statusCode, statusMessage, headers }
)
} else {
if (factory === null) {
return
}

res = this.runInAsyncScope(factory, null, {
statusCode,
headers,
Expand Down Expand Up @@ -152,14 +156,18 @@ class StreamHandler extends AsyncResource {
onData (chunk) {
const { res } = this

return res.write(chunk)
return res ? res.write(chunk) : true
}

onComplete (trailers) {
const { res } = this

removeSignal(this)

if (!res) {
return
}

this.trailers = util.parseHeaders(trailers)

res.end()
Expand Down
53 changes: 53 additions & 0 deletions test/issue-2349.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
'use strict'

const { test, skip } = require('tap')
const { nodeMajor } = require('../lib/core/util')
const { Writable } = require('stream')
const { MockAgent, errors, stream } = require('..')

if (nodeMajor < 16) {
skip('only for node 16')
process.exit(0)
}

test('stream() does not fail after request has been aborted', async (t) => {
t.plan(1)

const mockAgent = new MockAgent()

mockAgent.disableNetConnect()
mockAgent
.get('http://localhost:3333')
.intercept({
path: '/'
})
.reply(200, 'ok')
.delay(10)

const parts = []
const ac = new AbortController()

setTimeout(() => ac.abort('nevermind'), 5)

try {
await stream(
'http://localhost:3333/',
{
opaque: { parts },
signal: ac.signal,
dispatcher: mockAgent
},
({ opaque: { parts } }) => {
return new Writable({
write (chunk, _encoding, callback) {
parts.push(chunk)
callback()
}
})
}
)
} catch (error) {
console.log(error)
t.equal(error instanceof errors.RequestAbortedError, true)
}
})

0 comments on commit daf349f

Please sign in to comment.