Skip to content

Commit

Permalink
http: refactor ClientRequest destroy
Browse files Browse the repository at this point in the history
PR-URL: #36863
Reviewed-By: Benjamin Gruenbaum <[email protected]>
  • Loading branch information
ronag authored and ruyadorno committed Jan 21, 2021
1 parent 80051ab commit aa7243e
Showing 1 changed file with 26 additions and 33 deletions.
59 changes: 26 additions & 33 deletions lib/_http_client.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ const {
DTRACE_HTTP_CLIENT_RESPONSE
} = require('internal/dtrace');

const { addAbortSignal } = require('stream');
const { addAbortSignal, finished } = require('stream');

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

// In the event that we don't have a socket, we will pop out of
// the request queue through handling in onSocket.
if (this.socket) {
_destroy(this, this.socket, err);
} else if (err) {
this[kError] = err;
}
this[kError] = err;
this.socket?.destroy(err);

return this;
};

function _destroy(req, socket, err) {
// TODO (ronag): Check if socket was used at all (e.g. headersSent) and
// re-use it in that case. `req.socket` just checks whether the socket was
// assigned to the request and *might* have been used.
if (socket && (!req.agent || req.socket)) {
socket.destroy(err);
} else {
if (socket) {
socket.emit('free');
}
if (!req.aborted && !err) {
err = connResetException('socket hang up');
}
if (err) {
req.emit('error', err);
}
req._closed = true;
req.emit('close');
}
}

function emitAbortNT(req) {
req.emit('abort');
}
Expand Down Expand Up @@ -830,11 +804,30 @@ ClientRequest.prototype.onSocket = function onSocket(socket, err) {
};

function onSocketNT(req, socket, err) {
if (req.destroyed) {
_destroy(req, socket, req[kError]);
} else if (err) {
if (req.destroyed || err) {
req.destroyed = true;
_destroy(req, null, err);

function _destroy(req, err) {
if (!req.aborted && !err) {
err = connResetException('socket hang up');
}
if (err) {
req.emit('error', err);
}
req._closed = true;
req.emit('close');
}

if (!err && req.agent) {
socket?.emit('free');
} else if (socket) {
finished(socket.destroy(err || req[kError]), (er) => {
_destroy(req, er || err);
});
return;
}

_destroy(req, err || req[kError]);
} else {
tickOnSocket(req, socket);
req._flush();
Expand Down

0 comments on commit aa7243e

Please sign in to comment.