Skip to content

Commit 8168669

Browse files
DaveFishrock123
Dave
authored andcommitted
http: remove excess calls to removeSocket
socket.destroy() triggers a 'close' event from the socket which triggers the onClose handler of HTTPAgent which calls self.removeSocket(). So by calling self.removeSocket() prior to socket.destroy() we end up with two calls to self.removeSocket(). If there are pending requests, removeSocket ends up creating a new socket. So if there are pending requests, each time a request completes, we tear down one socket and create two more. So the total number of sockets grows exponentially and without regard for any maxSockets settings. This was noticed in nodejs#4050. Let's get rid of the extra calls to removeSocket so we only call it once per completed request. PR-URL: nodejs#4172 Reviewed-By: Brian White <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Fedor Indutny <[email protected]>
1 parent dd935c2 commit 8168669

File tree

2 files changed

+43
-2
lines changed

2 files changed

+43
-2
lines changed

lib/_http_agent.js

-2
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,6 @@ function Agent(options) {
6666
count += self.sockets[name].length;
6767

6868
if (count > self.maxSockets || freeLen >= self.maxFreeSockets) {
69-
self.removeSocket(socket, options);
7069
socket.destroy();
7170
} else {
7271
freeSockets = freeSockets || [];
@@ -78,7 +77,6 @@ function Agent(options) {
7877
freeSockets.push(socket);
7978
}
8079
} else {
81-
self.removeSocket(socket, options);
8280
socket.destroy();
8381
}
8482
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const http = require('http');
5+
6+
const MAX_SOCKETS = 2;
7+
8+
const agent = new http.Agent({
9+
keepAlive: true,
10+
keepAliveMsecs: 1000,
11+
maxSockets: MAX_SOCKETS,
12+
maxFreeSockets: 2
13+
});
14+
15+
const server = http.createServer(function(req, res) {
16+
res.end('hello world');
17+
});
18+
19+
function get(path, callback) {
20+
return http.get({
21+
host: 'localhost',
22+
port: common.PORT,
23+
agent: agent,
24+
path: path
25+
}, callback);
26+
}
27+
28+
server.listen(common.PORT, function() {
29+
var finished = 0;
30+
const num_requests = 6;
31+
for (var i = 0; i < num_requests; i++) {
32+
const request = get('/1', function() {
33+
});
34+
request.on('response', function() {
35+
request.abort();
36+
const sockets = agent.sockets[Object.keys(agent.sockets)[0]];
37+
assert(sockets.length <= MAX_SOCKETS);
38+
if (++finished === num_requests) {
39+
server.close();
40+
}
41+
});
42+
}
43+
});

0 commit comments

Comments
 (0)