Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Avoid error for stream() being aborted #2355

Merged
merged 1 commit into from
Oct 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
})
Loading