Skip to content

Commit e46ef6e

Browse files
committed
Remove Stale connections that have not been used for idletimeout period of time. mysqljs#962
1 parent 5c60778 commit e46ef6e

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

lib/Pool.js

+42
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,39 @@ function Pool(options) {
1717
this._freeConnections = [];
1818
this._connectionQueue = [];
1919
this._closed = false;
20+
this._recycleTimer = null;
21+
}
22+
23+
function recycleStaleConnections() {
24+
var now = Date.now();
25+
var min = null;
26+
for(var i=0 ;i<this._freeConnections.length; i++ ) {
27+
var lastused = this._freeConnections[i]._usedTimestamp;
28+
29+
if(lastused != undefined) {
30+
if((now - lastused) >= this.config.idleTimeout) {
31+
this._freeConnections[i].destroy();
32+
i--;
33+
} else {
34+
if(min == null) {
35+
min = now - lastused
36+
} else {
37+
if((now - lastused) < min) {
38+
min = now - lastused;
39+
}
40+
}
41+
}
42+
}
43+
}
44+
if(min != null) {
45+
if(min > 0) {
46+
clearInterval(this._recycleTimer);
47+
this._recycleTimer = setInterval(recycleStaleConnections.bind(this),this.config.idleTimeout);
48+
}
49+
} else {
50+
clearInterval(this._recycleTimer);
51+
this._recycleTimer = null;
52+
}
2053
}
2154

2255
Pool.prototype.getConnection = function (cb) {
@@ -138,6 +171,11 @@ Pool.prototype.releaseConnection = function releaseConnection(connection) {
138171
throw new Error('Connection already released');
139172
} else {
140173
// add connection to end of free queue
174+
if(this.config.idleTimeout > 0 && this._recycleTimer == null) {
175+
this._recycleTimer = setInterval(recycleStaleConnections.bind(this),this.config.idleTimeout);
176+
}
177+
178+
connection._usedTimestamp = Date.now();
141179
this._freeConnections.push(connection);
142180
this.emit('release', connection);
143181
}
@@ -160,6 +198,10 @@ Pool.prototype.releaseConnection = function releaseConnection(connection) {
160198

161199
Pool.prototype.end = function (cb) {
162200
this._closed = true;
201+
if(this._recycleTimer) {
202+
clearInterval(this._recycleTimer);
203+
this._recycleTimer = null;
204+
}
163205

164206
if (typeof cb !== 'function') {
165207
cb = function (err) {

lib/PoolConfig.js

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ function PoolConfig(options) {
2020
this.queueLimit = (options.queueLimit === undefined)
2121
? 0
2222
: Number(options.queueLimit);
23+
this.idleTimeout = (options.idleTimeout === undefined)? 0 : Number(options.idleTimeout);
2324
}
2425

2526
PoolConfig.prototype.newConnectionConfig = function newConnectionConfig() {

0 commit comments

Comments
 (0)