Skip to content

Commit

Permalink
Use domain.bind to preserve domain context
Browse files Browse the repository at this point in the history
  • Loading branch information
LewisJEllis committed Oct 12, 2016
1 parent b89166b commit a6f86f0
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/generic-pool.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
45 changes: 45 additions & 0 deletions test/generic-pool.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -747,5 +747,50 @@ 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.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)
})
}
}

0 comments on commit a6f86f0

Please sign in to comment.