Skip to content

Commit

Permalink
Merge pull request #8 from mgorven/poolbugs
Browse files Browse the repository at this point in the history
Fix various bugs with connection pool handling
  • Loading branch information
mikeal committed Apr 18, 2014
2 parents 0dabc3d + 3d979c3 commit 912a7a6
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,23 +81,29 @@ TunnelingAgent.prototype.addRequest = function addRequest(req, options) {

if (self.sockets.length >= this.maxSockets) {
// We are over limit so we'll add it to the queue.
self.requests.push({host: host, port: port, request: req})
self.requests.push({host: options.host, port: options.port, request: req})
return
}

// If we are under maxSockets create a new one.
self.createSocket({host: options.host, port: options.port, request: req}, function(socket) {
self.createConnection({host: options.host, port: options.port, request: req})
}

TunnelingAgent.prototype.createConnection = function createConnection(pending) {
var self = this

self.createSocket(pending, function(socket) {
socket.on('free', onFree)
socket.on('close', onCloseOrRemove)
socket.on('agentRemove', onCloseOrRemove)
req.onSocket(socket)
pending.request.onSocket(socket)

function onFree() {
self.emit('free', socket, options.host, options.port)
self.emit('free', socket, pending.host, pending.port)
}

function onCloseOrRemove(err) {
self.removeSocket()
self.removeSocket(socket)
socket.removeListener('free', onFree)
socket.removeListener('close', onCloseOrRemove)
socket.removeListener('agentRemove', onCloseOrRemove)
Expand Down Expand Up @@ -182,9 +188,7 @@ TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
if (pending) {
// If we have pending requests and a socket gets closed a new one
// needs to be created to take over in the pool for the one that closed.
this.createSocket(pending, function(socket) {
pending.request.onSocket(socket)
})
this.createConnection(pending)
}
}

Expand All @@ -197,6 +201,7 @@ function createSecureSocket(options, cb) {
, socket: socket
}
))
self.sockets[self.sockets.indexOf(socket)] = secureSocket
cb(secureSocket)
})
}
Expand Down

0 comments on commit 912a7a6

Please sign in to comment.