diff --git a/index.js b/index.js index cfe377c..7789bb5 100644 --- a/index.js +++ b/index.js @@ -44,8 +44,9 @@ function release (client, err) { this._remove(client) }, this.options.idleTimeoutMillis) } - this._idle.push(new IdleItem(client, tid)) + this._active.splice(this._active.indexOf(client), 1) + this.emit('release', client) this._pulseQueue() } @@ -94,6 +95,7 @@ class Pool extends EventEmitter { this._clients = [] this._idle = [] + this._active = [] this._pendingQueue = [] this._endCallback = undefined this.ending = false @@ -250,6 +252,7 @@ class Pool extends EventEmitter { } else { this.log('new client connected') client.release = release.bind(this, client) + this._active.push(client) this.emit('connect', client) this.emit('acquire', client) if (!pendingItem.timedOut) { @@ -328,5 +331,9 @@ class Pool extends EventEmitter { get totalCount () { return this._clients.length } + + get activeCount () { + return this._active.length + } } module.exports = Pool diff --git a/test/events.js b/test/events.js index a2da481..82b1e0d 100644 --- a/test/events.js +++ b/test/events.js @@ -60,6 +60,30 @@ describe('events', function () { }, 100) }) + it('emits release every time a client is released', function (done) { + const pool = new Pool() + let releaseCount = 0 + pool.on('release', function (client) { + expect(client).to.be.ok() + releaseCount++ + }) + for (let releases = [], i = 0; i < 10; i++) { + pool.connect(function (err, client, release) { + if (err) return done(err) + releases.push(release) + expect(pool.activeCount).to.be(releases.length) + if (releases.length === 10) { + while (releases.length > 0) releases.pop()() + } + }) + } + setTimeout(function () { + expect(releaseCount).to.be(10) + expect(pool.activeCount).to.be(0) + pool.end(done) + }, 100) + }) + it('emits error and client if an idle client in the pool hits an error', function (done) { const pool = new Pool() pool.connect(function (err, client) {