Skip to content

Commit aa7243e

Browse files
ronagruyadorno
authored andcommitted
http: refactor ClientRequest destroy
PR-URL: #36863 Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
1 parent 80051ab commit aa7243e

File tree

1 file changed

+26
-33
lines changed

1 file changed

+26
-33
lines changed

lib/_http_client.js

+26-33
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ const {
7777
DTRACE_HTTP_CLIENT_RESPONSE
7878
} = require('internal/dtrace');
7979

80-
const { addAbortSignal } = require('stream');
80+
const { addAbortSignal, finished } = require('stream');
8181

8282
const INVALID_PATH_REGEX = /[^\u0021-\u00ff]/;
8383
const kError = Symbol('kError');
@@ -370,38 +370,12 @@ ClientRequest.prototype.destroy = function destroy(err) {
370370
this.res._dump();
371371
}
372372

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);
380375

381376
return this;
382377
};
383378

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-
405379
function emitAbortNT(req) {
406380
req.emit('abort');
407381
}
@@ -830,11 +804,30 @@ ClientRequest.prototype.onSocket = function onSocket(socket, err) {
830804
};
831805

832806
function onSocketNT(req, socket, err) {
833-
if (req.destroyed) {
834-
_destroy(req, socket, req[kError]);
835-
} else if (err) {
807+
if (req.destroyed || err) {
836808
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]);
838831
} else {
839832
tickOnSocket(req, socket);
840833
req._flush();

0 commit comments

Comments
 (0)