diff --git a/index.js b/index.js index 9690340..7f8c27a 100644 --- a/index.js +++ b/index.js @@ -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 @@ -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; @@ -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; } @@ -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); }); } } diff --git a/test/jackpot.test.js b/test/jackpot.test.js index d395e5e..de8bbb1 100644 --- a/test/jackpot.test.js +++ b/test/jackpot.test.js @@ -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();