@@ -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,19 +55,28 @@ 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 }
6565
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 if ( this . abort ) {
71+ this . abort ( this . signal . reason )
72+ }
73+ } )
74+ }
6775 }
6876
6977 onConnect ( abort , context ) {
70- if ( this . reason ) {
71- abort ( this . reason )
78+ if ( this . signal && this . signal . aborted ) {
79+ abort ( this . signal . reason )
7280 return
7381 }
7482
@@ -95,6 +103,13 @@ 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+ // TODO (fix): 'close' is sufficient but breaks tests.
108+ body
109+ . on ( 'end' , this . removeAbortListener )
110+ . on ( 'error' , this . removeAbortListener )
111+ }
112+
98113 this . callback = null
99114 this . res = body
100115 if ( callback !== null ) {
@@ -123,8 +138,6 @@ class RequestHandler extends AsyncResource {
123138 onComplete ( trailers ) {
124139 const { res } = this
125140
126- removeSignal ( this )
127-
128141 util . parseHeaders ( trailers , this . trailers )
129142
130143 res . push ( null )
@@ -133,8 +146,6 @@ class RequestHandler extends AsyncResource {
133146 onError ( err ) {
134147 const { res, callback, body, opaque } = this
135148
136- removeSignal ( this )
137-
138149 if ( callback ) {
139150 // TODO: Does this need queueMicrotask?
140151 this . callback = null
@@ -149,6 +160,8 @@ class RequestHandler extends AsyncResource {
149160 queueMicrotask ( ( ) => {
150161 util . destroy ( res , err )
151162 } )
163+ } else if ( this . removeAbortListener ) {
164+ this . removeAbortListener ( )
152165 }
153166
154167 if ( body ) {
0 commit comments