Skip to content

Commit 821e473

Browse files
committed
fix: remove abort handler on close
1 parent 9f26aff commit 821e473

File tree

2 files changed

+15
-12
lines changed

2 files changed

+15
-12
lines changed

lib/api/api-request.js

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -70,15 +70,18 @@ class RequestHandler extends AsyncResource {
7070
this.reason = this.signal.reason ?? new RequestAbortedError()
7171
} else {
7272
this.removeAbortListener = util.addAbortListener(this.signal, () => {
73-
this.removeAbortListener?.()
74-
this.removeAbortListener = null
75-
7673
this.reason = this.signal.reason ?? new RequestAbortedError()
7774
if (this.res) {
7875
util.destroy(this.res, this.reason)
7976
} else if (this.abort) {
8077
this.abort(this.reason)
8178
}
79+
80+
if (this.removeAbortListener) {
81+
this.res?.off('close', this.removeAbortListener)
82+
this.removeAbortListener()
83+
this.removeAbortListener = null
84+
}
8285
})
8386
}
8487
}
@@ -114,10 +117,7 @@ class RequestHandler extends AsyncResource {
114117
const body = new Readable({ resume, abort, contentType, contentLength, highWaterMark })
115118

116119
if (this.removeAbortListener) {
117-
// TODO (fix): 'close' is sufficient but breaks tests.
118-
body
119-
.on('end', this.removeAbortListener)
120-
.on('error', this.removeAbortListener)
120+
body.on('close', this.removeAbortListener)
121121
}
122122

123123
this.callback = null
@@ -156,9 +156,6 @@ class RequestHandler extends AsyncResource {
156156
onError (err) {
157157
const { res, callback, body, opaque } = this
158158

159-
this.removeAbortListener?.()
160-
this.removeAbortListener = null
161-
162159
if (callback) {
163160
// TODO: Does this need queueMicrotask?
164161
this.callback = null
@@ -179,6 +176,12 @@ class RequestHandler extends AsyncResource {
179176
this.body = null
180177
util.destroy(body, err)
181178
}
179+
180+
if (this.removeAbortListener) {
181+
res?.off('close', this.removeAbortListener)
182+
this.removeAbortListener()
183+
this.removeAbortListener = null
184+
}
182185
}
183186
}
184187

test/client.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ test('basic get', async (t) => {
6363
body.on('data', (buf) => {
6464
bufs.push(buf)
6565
})
66-
body.on('end', () => {
66+
body.on('close', () => {
6767
t.strictEqual(signal.listenerCount('abort'), 0)
6868
t.strictEqual('hello', Buffer.concat(bufs).toString('utf8'))
6969
})
@@ -135,7 +135,7 @@ test('basic get with custom request.reset=true', async (t) => {
135135
body.on('data', (buf) => {
136136
bufs.push(buf)
137137
})
138-
body.on('end', () => {
138+
body.on('close', () => {
139139
t.strictEqual(signal.listenerCount('abort'), 0)
140140
t.strictEqual('hello', Buffer.concat(bufs).toString('utf8'))
141141
})

0 commit comments

Comments
 (0)