@@ -6,7 +6,6 @@ const { InvalidArgumentError } = require('../core/errors')
66const util = require ( '../core/util' )
77const { getResolveErrorBodyCallback } = require ( './util' )
88const { AsyncResource } = require ( 'node:async_hooks' )
9- const { addSignal, removeSignal } = require ( './abort-signal' )
109
1110class RequestHandler extends AsyncResource {
1211 constructor ( opts , callback ) {
@@ -56,26 +55,35 @@ class RequestHandler extends AsyncResource {
5655 this . onInfo = onInfo || null
5756 this . throwOnError = throwOnError
5857 this . highWaterMark = highWaterMark
58+ this . signal = signal
5959
6060 if ( util . isStream ( body ) ) {
6161 body . on ( 'error' , ( err ) => {
6262 this . onError ( err )
6363 } )
6464 }
65-
66- addSignal ( this , signal )
6765 }
6866
6967 onConnect ( abort , context ) {
70- if ( this . reason ) {
71- abort ( this . reason )
72- return
73- }
74-
7568 assert ( this . callback )
7669
7770 this . abort = abort
7871 this . context = context
72+
73+ if ( this . signal ) {
74+ if ( this . signal . aborted ) {
75+ abort ( this . signal . reason )
76+ return
77+ }
78+
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+ }
7987 }
8088
8189 onHeaders ( statusCode , rawHeaders , resume , statusMessage ) {
@@ -95,6 +103,10 @@ class RequestHandler extends AsyncResource {
95103 const contentLength = parsedHeaders [ 'content-length' ]
96104 const body = new Readable ( { resume, abort, contentType, contentLength, highWaterMark } )
97105
106+ if ( this . removeAbortListener ) {
107+ body . on ( 'close' , this . removeAbortListener )
108+ }
109+
98110 this . callback = null
99111 this . res = body
100112 if ( callback !== null ) {
@@ -123,8 +135,6 @@ class RequestHandler extends AsyncResource {
123135 onComplete ( trailers ) {
124136 const { res } = this
125137
126- removeSignal ( this )
127-
128138 util . parseHeaders ( trailers , this . trailers )
129139
130140 res . push ( null )
@@ -133,8 +143,6 @@ class RequestHandler extends AsyncResource {
133143 onError ( err ) {
134144 const { res, callback, body, opaque } = this
135145
136- removeSignal ( this )
137-
138146 if ( callback ) {
139147 // TODO: Does this need queueMicrotask?
140148 this . callback = null
@@ -149,6 +157,8 @@ class RequestHandler extends AsyncResource {
149157 queueMicrotask ( ( ) => {
150158 util . destroy ( res , err )
151159 } )
160+ } else if ( this . removeAbortListener ) {
161+ this . removeAbortListener ( )
152162 }
153163
154164 if ( body ) {
0 commit comments