Skip to content
This repository has been archived by the owner on May 5, 2023. It is now read-only.

Commit

Permalink
Close free sockets (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
tareksha authored and TooTallNate committed Jul 5, 2018
1 parent f5fcafd commit 783e956
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
10 changes: 10 additions & 0 deletions index.js
Expand Up @@ -94,6 +94,7 @@ Agent.prototype.addRequest = function addRequest(req, _opts) {
let timeout;
let timedOut = false;
const timeoutMs = this.timeout;
const freeSocket = this.freeSocket;

function onerror(err) {
if (req._hadError) return;
Expand Down Expand Up @@ -133,6 +134,10 @@ Agent.prototype.addRequest = function addRequest(req, _opts) {
// responsibility for this `req` to the Agent from here on
socket.addRequest(req, opts);
} else if (socket) {
function onfree() {
freeSocket(socket, opts);
}
socket.on('free', onfree);
req.onSocket(socket);
} else {
const err = new Error(
Expand All @@ -158,3 +163,8 @@ Agent.prototype.addRequest = function addRequest(req, _opts) {
Promise.reject(err).catch(callbackError);
}
};

Agent.prototype.freeSocket = function freeSocket(socket, opts) {
// TODO reuse sockets
socket.destroy();
};
24 changes: 24 additions & 0 deletions test/test.js
Expand Up @@ -398,6 +398,30 @@ describe('"http" module', function() {
});
});

it('should free sockets after use', function(done) {
var agent = new Agent(function(req, opts, fn) {
var socket = net.connect(opts);
fn(null, socket);
});

// add HTTP server "request" listener
var gotReq = false;
server.once('request', function(req, res) {
gotReq = true;
res.end();
});

var info = url.parse('http://127.0.0.1:' + port + '/foo');
info.agent = agent;
http.get(info, function(res) {
res.socket.emit('free');
assert.equal(true, res.socket.destroyed);
assert(gotReq);
done();
});
});


describe('PassthroughAgent', function() {
it('should pass through to `http.globalAgent`', function(done) {
// add HTTP server "request" listener
Expand Down

0 comments on commit 783e956

Please sign in to comment.