Skip to content

Commit

Permalink
http: simplify timeout handling
Browse files Browse the repository at this point in the history
Avoids allocating and registering extra listeners for 'timeout'.

PR-URL: #29200
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
  • Loading branch information
ronag authored and BridgeAR committed Sep 4, 2019
1 parent 2efd72f commit e5a9a85
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions lib/_http_client.js
Original file line number Diff line number Diff line change
Expand Up @@ -625,6 +625,10 @@ function responseOnEnd() {
const res = this;
const req = this.req;

if (req.socket && req.timeoutCb) {
req.socket.removeListener('timeout', emitRequestTimeout);
}

req._ended = true;
if (!req.shouldKeepAlive || req.finished)
responseKeepAlive(res, req);
Expand Down Expand Up @@ -680,11 +684,17 @@ function tickOnSocket(req, socket) {
req.emit('socket', socket);
}

function emitRequestTimeout() {
const req = this._httpMessage;
if (req) {
req.emit('timeout');
}
}

function listenSocketTimeout(req) {
if (req.timeoutCb) {
return;
}
const emitRequestTimeout = () => req.emit('timeout');
// Set timeoutCb so it will get cleaned up on request end.
req.timeoutCb = emitRequestTimeout;
// Delegate socket timeout event.
Expand All @@ -695,12 +705,6 @@ function listenSocketTimeout(req) {
socket.once('timeout', emitRequestTimeout);
});
}
// Remove socket timeout listener after response end.
req.once('response', (res) => {
res.once('end', () => {
req.socket.removeListener('timeout', emitRequestTimeout);
});
});
}

ClientRequest.prototype.onSocket = function onSocket(socket) {
Expand Down

0 comments on commit e5a9a85

Please sign in to comment.