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

close free sockets #18

Merged
merged 1 commit into from
Jul 5, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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