diff --git a/lib/_http_agent.js b/lib/_http_agent.js index 86ad95fc9bd1f4..5a69a99489266a 100644 --- a/lib/_http_agent.js +++ b/lib/_http_agent.js @@ -488,6 +488,7 @@ Agent.prototype.keepSocketAlive = function keepSocketAlive(socket) { socket.unref(); let agentTimeout = this.options.timeout || 0; + let canKeepSocketAlive = true; if (socket._httpMessage?.res) { const keepAliveHint = socket._httpMessage.res.headers['keep-alive']; @@ -498,11 +499,15 @@ Agent.prototype.keepSocketAlive = function keepSocketAlive(socket) { if (hint) { // Let the timer expires before the announced timeout to reduce // the likelihood of ECONNRESET errors - let serverHintTimeout = ( NumberParseInt(hint) * 1000 ) - 1000; + let serverHintTimeout = (NumberParseInt(hint) * 1000) - 1000; serverHintTimeout = serverHintTimeout > 0 ? serverHintTimeout : 0; - - if (serverHintTimeout < agentTimeout) { - agentTimeout = serverHintTimeout; + if (serverHintTimeout === 0) { + // cannot safely reuse the socket because the server timeout is too short + canKeepSocketAlive = false; + } else { + if (serverHintTimeout < agentTimeout) { + agentTimeout = serverHintTimeout; + } } } } @@ -512,7 +517,7 @@ Agent.prototype.keepSocketAlive = function keepSocketAlive(socket) { socket.setTimeout(agentTimeout); } - return true; + return canKeepSocketAlive; }; Agent.prototype.reuseSocket = function reuseSocket(socket, req) {