diff --git a/lib/generic-pool.js b/lib/generic-pool.js index eb9460c2..2b847b0e 100644 --- a/lib/generic-pool.js +++ b/lib/generic-pool.js @@ -384,6 +384,9 @@ Pool.prototype.acquire = function acquire (callback, priority) { if (this._draining) { throw new Error('pool is draining and cannot accept work') } + if (process.domain) { + callback = process.domain.bind(callback) + } this._waitingClients.enqueue(callback, priority) this._dispense() return (this._count < this._factory.max) diff --git a/test/generic-pool.test.js b/test/generic-pool.test.js index abecf156..66fe8321 100644 --- a/test/generic-pool.test.js +++ b/test/generic-pool.test.js @@ -747,5 +747,51 @@ module.exports = { assert.equal(pool.availableObjectsCount(), 0) assert.equal(pool.inUseObjectsCount(), 1) }) + }, + + 'domain context is preserved on acquire callback': function (beforeExit) { + var assertion_count = 0 + var pool = poolModule.Pool({ + name: 'test', + create: function (cb) { + cb(null, {}) + }, + destroy: function (client) {}, + max: 2, + idleTimeoutMillis: 1000 + }) + + // bail on old node versions because domains didn't exist until v0.8 + if (process.version < 'v0.8') { + return + } + + var domain = require('domain') + + function check (index) { + var wrapDomain = domain.create() + wrapDomain.index = index + + wrapDomain.run(function () { + pool.acquire(function (err, client) { + assert.ifError(err) + assert.equal(domain.active.index, index) + assertion_count++ + setTimeout(function () { + pool.release(client) + }, 50) + }) + }) + } + + // first two will work even without domain binding + check(1) + check(2) + // third and on will fail without domain binding + check(3) + + beforeExit(function () { + assert.equal(assertion_count, 3) + }) } }