Skip to content

Commit

Permalink
Merge pull request #9 from ianshward/callback-on-timeout
Browse files Browse the repository at this point in the history
handle timeout while trying to connect
  • Loading branch information
3rd-Eden committed Jul 31, 2013
2 parents 0beae67 + 53906de commit 8fbd250
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
18 changes: 14 additions & 4 deletions index.js
Expand Up @@ -146,10 +146,10 @@ Manager.prototype.allocate = function allocate(fn) {
}

/**
* Small helper function that allows us to correctly call the callback with
* Two helper functions that allows us to correctly call the callback with
* the correct arguments when we generate a new connection as the connection
* should be emitting 'connect' befor we can use it. But it can also emit
* error if it fails to connect.
* error if it fails to connect, or times in so doing.
*
* @param {Error} err Optional error argument.
* @api private
Expand All @@ -165,6 +165,12 @@ Manager.prototype.allocate = function allocate(fn) {
fn(err, this);
}

function timeout() {
this.removeListener('timeout', timeout);
self.pending--;
fn(new Error('Timed out while trying to establish connection'), this);
}

var probabilities = []
, self = this
, total, i, probability, connection;
Expand Down Expand Up @@ -206,7 +212,9 @@ Manager.prototype.allocate = function allocate(fn) {
if (connection) {
this.pending++;
this.listen(connection);
connection.on('error', either).on('connect', either);
connection.on('error', either)
.on('connect', either)
.on('timeout', timeout);

return this;
}
Expand All @@ -217,7 +225,9 @@ Manager.prototype.allocate = function allocate(fn) {

self.pending++;
self.listen(connection);
return connection.on('error', either).on('connect', either);
return connection.on('error', either)
.on('connect', either)
.on('timeout', timeout);
});
}
}
Expand Down
20 changes: 20 additions & 0 deletions test/jackpot.test.js
Expand Up @@ -116,6 +116,26 @@ describe('jackpot', function () {
});
});

it('should emit an error on timeout when trying to establish connection', function (done) {
var pool = new ConnectionPool(10, {
retries: 0
})
, unroutable = '10.255.255.255'
, S = new net.Socket;

pool.factory(function factory() {
S.connect(port, unroutable);
S.setTimeout(100);
return S;
});

pool.allocate(function allocate(err, connection) {
var fn = function() { throw err };
expect(fn).to.throw(/Timed out while trying to establish connection/);
done();
});
});

it('should NOT emit an error when we can establish a connection', function (done) {
var pool = new ConnectionPool();

Expand Down

0 comments on commit 8fbd250

Please sign in to comment.