@@ -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,26 +55,35 @@ 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
-
66
- addSignal ( this , signal )
67
65
}
68
66
69
67
onConnect ( abort , context ) {
70
- if ( this . reason ) {
71
- abort ( this . reason )
68
+ if ( this . signal . aborted ) {
69
+ abort ( this . signal . reason )
72
70
return
73
71
}
74
72
75
73
assert ( this . callback )
76
74
77
75
this . abort = abort
78
76
this . context = context
77
+
78
+ if ( this . signal ) {
79
+ this . removeAbortListener = util . addAbortListener ( this . signal , ( ) => {
80
+ if ( this . res ) {
81
+ this . res . destroy ( this . signal . reason )
82
+ } else {
83
+ this . abort ( this . signal . reason )
84
+ }
85
+ } )
86
+ }
79
87
}
80
88
81
89
onHeaders ( statusCode , rawHeaders , resume , statusMessage ) {
@@ -95,6 +103,10 @@ 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
+ body . on ( 'close' , this . removeAbortListener )
108
+ }
109
+
98
110
this . callback = null
99
111
this . res = body
100
112
if ( callback !== null ) {
@@ -123,8 +135,6 @@ class RequestHandler extends AsyncResource {
123
135
onComplete ( trailers ) {
124
136
const { res } = this
125
137
126
- removeSignal ( this )
127
-
128
138
util . parseHeaders ( trailers , this . trailers )
129
139
130
140
res . push ( null )
@@ -133,8 +143,6 @@ class RequestHandler extends AsyncResource {
133
143
onError ( err ) {
134
144
const { res, callback, body, opaque } = this
135
145
136
- removeSignal ( this )
137
-
138
146
if ( callback ) {
139
147
// TODO: Does this need queueMicrotask?
140
148
this . callback = null
@@ -149,6 +157,8 @@ class RequestHandler extends AsyncResource {
149
157
queueMicrotask ( ( ) => {
150
158
util . destroy ( res , err )
151
159
} )
160
+ } else if ( this . removeAbortListener ) {
161
+ this . removeAbortListener ( )
152
162
}
153
163
154
164
if ( body ) {
0 commit comments