diff --git a/lib/Pool.js b/lib/Pool.js index 87a40114a..0641342f8 100644 --- a/lib/Pool.js +++ b/lib/Pool.js @@ -17,6 +17,39 @@ function Pool(options) { this._freeConnections = []; this._connectionQueue = []; this._closed = false; + this._recycleTimer = null; +} + +function recycleStaleConnections() { + var now = Date.now(); + var min = null; + for (var i = 0; i < this._freeConnections.length; i++ ) { + var lastused = this._freeConnections[i]._usedTimestamp; + + if (lastused !== undefined) { + if ((now - lastused) >= this.config.idleTimeout) { + this._freeConnections[i].destroy(); + i--; + } else { + if (min == null) { + min = now - lastused; + } else { + if ((now - lastused) < min) { + min = now - lastused; + } + } + } + } + } + if (min != null) { + if (min > 0) { + clearInterval(this._recycleTimer); + this._recycleTimer = setInterval(recycleStaleConnections.bind(this),this.config.idleTimeout); + } + } else { + clearInterval(this._recycleTimer); + this._recycleTimer = null; + } } Pool.prototype.getConnection = function (cb) { @@ -138,6 +171,11 @@ Pool.prototype.releaseConnection = function releaseConnection(connection) { throw new Error('Connection already released'); } else { // add connection to end of free queue + if (this.config.idleTimeout > 0 && this._recycleTimer == null) { + this._recycleTimer = setInterval(recycleStaleConnections.bind(this),this.config.idleTimeout); + } + + connection._usedTimestamp = Date.now(); this._freeConnections.push(connection); this.emit('release', connection); } @@ -160,6 +198,10 @@ Pool.prototype.releaseConnection = function releaseConnection(connection) { Pool.prototype.end = function (cb) { this._closed = true; + if (this._recycleTimer) { + clearInterval(this._recycleTimer); + this._recycleTimer = null; + } if (typeof cb !== 'function') { cb = function (err) { diff --git a/lib/PoolConfig.js b/lib/PoolConfig.js index 8c5017a27..3580967c6 100644 --- a/lib/PoolConfig.js +++ b/lib/PoolConfig.js @@ -20,6 +20,9 @@ function PoolConfig(options) { this.queueLimit = (options.queueLimit === undefined) ? 0 : Number(options.queueLimit); + this.idleTimeout = (options.idleTimeout === undefined) + ? 0 + : Number(options.idleTimeout); } PoolConfig.prototype.newConnectionConfig = function newConnectionConfig() {