Skip to content
Open
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
42 changes: 42 additions & 0 deletions lib/Pool.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
}
Expand All @@ -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) {
Expand Down
3 changes: 3 additions & 0 deletions lib/PoolConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down