@@ -77,7 +77,7 @@ const {
77
77
DTRACE_HTTP_CLIENT_RESPONSE
78
78
} = require ( 'internal/dtrace' ) ;
79
79
80
- const { addAbortSignal } = require ( 'stream' ) ;
80
+ const { addAbortSignal, finished } = require ( 'stream' ) ;
81
81
82
82
const INVALID_PATH_REGEX = / [ ^ \u0021 - \u00ff ] / ;
83
83
const kError = Symbol ( 'kError' ) ;
@@ -370,38 +370,12 @@ ClientRequest.prototype.destroy = function destroy(err) {
370
370
this . res . _dump ( ) ;
371
371
}
372
372
373
- // In the event that we don't have a socket, we will pop out of
374
- // the request queue through handling in onSocket.
375
- if ( this . socket ) {
376
- _destroy ( this , this . socket , err ) ;
377
- } else if ( err ) {
378
- this [ kError ] = err ;
379
- }
373
+ this [ kError ] = err ;
374
+ this . socket ?. destroy ( err ) ;
380
375
381
376
return this ;
382
377
} ;
383
378
384
- function _destroy ( req , socket , err ) {
385
- // TODO (ronag): Check if socket was used at all (e.g. headersSent) and
386
- // re-use it in that case. `req.socket` just checks whether the socket was
387
- // assigned to the request and *might* have been used.
388
- if ( socket && ( ! req . agent || req . socket ) ) {
389
- socket . destroy ( err ) ;
390
- } else {
391
- if ( socket ) {
392
- socket . emit ( 'free' ) ;
393
- }
394
- if ( ! req . aborted && ! err ) {
395
- err = connResetException ( 'socket hang up' ) ;
396
- }
397
- if ( err ) {
398
- req . emit ( 'error' , err ) ;
399
- }
400
- req . _closed = true ;
401
- req . emit ( 'close' ) ;
402
- }
403
- }
404
-
405
379
function emitAbortNT ( req ) {
406
380
req . emit ( 'abort' ) ;
407
381
}
@@ -813,11 +787,30 @@ ClientRequest.prototype.onSocket = function onSocket(socket, err) {
813
787
} ;
814
788
815
789
function onSocketNT ( req , socket , err ) {
816
- if ( req . destroyed ) {
817
- _destroy ( req , socket , req [ kError ] ) ;
818
- } else if ( err ) {
790
+ if ( req . destroyed || err ) {
819
791
req . destroyed = true ;
820
- _destroy ( req , null , err ) ;
792
+
793
+ function _destroy ( req , err ) {
794
+ if ( ! req . aborted && ! err ) {
795
+ err = connResetException ( 'socket hang up' ) ;
796
+ }
797
+ if ( err ) {
798
+ req . emit ( 'error' , err ) ;
799
+ }
800
+ req . _closed = true ;
801
+ req . emit ( 'close' ) ;
802
+ }
803
+
804
+ if ( ! err && req . agent ) {
805
+ socket ?. emit ( 'free' ) ;
806
+ } else if ( socket ) {
807
+ finished ( socket . destroy ( err || req [ kError ] ) , ( er ) => {
808
+ _destroy ( req , er || err ) ;
809
+ } ) ;
810
+ return ;
811
+ }
812
+
813
+ _destroy ( req , err || req [ kError ] ) ;
821
814
} else {
822
815
tickOnSocket ( req , socket ) ;
823
816
req . _flush ( ) ;
0 commit comments