@@ -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
}
@@ -830,11 +804,30 @@ ClientRequest.prototype.onSocket = function onSocket(socket, err) {
830
804
} ;
831
805
832
806
function onSocketNT ( req , socket , err ) {
833
- if ( req . destroyed ) {
834
- _destroy ( req , socket , req [ kError ] ) ;
835
- } else if ( err ) {
807
+ if ( req . destroyed || err ) {
836
808
req . destroyed = true ;
837
- _destroy ( req , null , err ) ;
809
+
810
+ function _destroy ( req , err ) {
811
+ if ( ! req . aborted && ! err ) {
812
+ err = connResetException ( 'socket hang up' ) ;
813
+ }
814
+ if ( err ) {
815
+ req . emit ( 'error' , err ) ;
816
+ }
817
+ req . _closed = true ;
818
+ req . emit ( 'close' ) ;
819
+ }
820
+
821
+ if ( ! err && req . agent ) {
822
+ socket ?. emit ( 'free' ) ;
823
+ } else if ( socket ) {
824
+ finished ( socket . destroy ( err || req [ kError ] ) , ( er ) => {
825
+ _destroy ( req , er || err ) ;
826
+ } ) ;
827
+ return ;
828
+ }
829
+
830
+ _destroy ( req , err || req [ kError ] ) ;
838
831
} else {
839
832
tickOnSocket ( req , socket ) ;
840
833
req . _flush ( ) ;
0 commit comments