@@ -6,7 +6,6 @@ const { InvalidArgumentError } = require('../core/errors')
6
6
const util = require ( '../core/util' )
7
7
const { getResolveErrorBodyCallback } = require ( './util' )
8
8
const { AsyncResource } = require ( 'node:async_hooks' )
9
- const { addSignal, removeSignal } = require ( './abort-signal' )
10
9
11
10
class RequestHandler extends AsyncResource {
12
11
constructor ( opts , callback ) {
@@ -56,19 +55,28 @@ class RequestHandler extends AsyncResource {
56
55
this . onInfo = onInfo || null
57
56
this . throwOnError = throwOnError
58
57
this . highWaterMark = highWaterMark
58
+ this . signal = signal
59
59
60
60
if ( util . isStream ( body ) ) {
61
61
body . on ( 'error' , ( err ) => {
62
62
this . onError ( err )
63
63
} )
64
64
}
65
65
66
- addSignal ( this , signal )
66
+ if ( this . signal ) {
67
+ this . removeAbortListener = util . addAbortListener ( this . signal , ( ) => {
68
+ if ( this . res ) {
69
+ this . res . destroy ( this . signal . reason )
70
+ } else {
71
+ this . abort ( this . signal . reason )
72
+ }
73
+ } )
74
+ }
67
75
}
68
76
69
77
onConnect ( abort , context ) {
70
- if ( this . reason ) {
71
- abort ( this . reason )
78
+ if ( this . signal && this . signal . aborted ) {
79
+ abort ( this . signal . reason )
72
80
return
73
81
}
74
82
@@ -95,6 +103,13 @@ class RequestHandler extends AsyncResource {
95
103
const contentLength = parsedHeaders [ 'content-length' ]
96
104
const body = new Readable ( { resume, abort, contentType, contentLength, highWaterMark } )
97
105
106
+ if ( this . removeAbortListener ) {
107
+ // TODO (fix): 'close' is sufficient but breaks tests.
108
+ body
109
+ . on ( 'end' , this . removeAbortListener )
110
+ . on ( 'error' , this . removeAbortListener )
111
+ }
112
+
98
113
this . callback = null
99
114
this . res = body
100
115
if ( callback !== null ) {
@@ -123,8 +138,6 @@ class RequestHandler extends AsyncResource {
123
138
onComplete ( trailers ) {
124
139
const { res } = this
125
140
126
- removeSignal ( this )
127
-
128
141
util . parseHeaders ( trailers , this . trailers )
129
142
130
143
res . push ( null )
@@ -133,8 +146,6 @@ class RequestHandler extends AsyncResource {
133
146
onError ( err ) {
134
147
const { res, callback, body, opaque } = this
135
148
136
- removeSignal ( this )
137
-
138
149
if ( callback ) {
139
150
// TODO: Does this need queueMicrotask?
140
151
this . callback = null
@@ -149,6 +160,8 @@ class RequestHandler extends AsyncResource {
149
160
queueMicrotask ( ( ) => {
150
161
util . destroy ( res , err )
151
162
} )
163
+ } else if ( this . removeAbortListener ) {
164
+ this . removeAbortListener ( )
152
165
}
153
166
154
167
if ( body ) {
0 commit comments