diff --git a/lib/policy.js b/lib/policy.js index 396368f..d917766 100755 --- a/lib/policy.js +++ b/lib/policy.js @@ -39,6 +39,10 @@ internals.Policy.prototype.get = function (key, callback) { // key: string o var self = this; + if (process.domain) { + callback = process.domain.bind(callback); // Explicitly bind callback to its process.domain (_finalize might get called from a different active process.domain) + } + // Check if request is already pending var id = (key && typeof key === 'object') ? key.id : key; diff --git a/test/policy.js b/test/policy.js index ff031fc..719eb8d 100755 --- a/test/policy.js +++ b/test/policy.js @@ -4,7 +4,7 @@ var Catbox = require('..'); var Code = require('code'); var Lab = require('lab'); var Import = require('./import'); - +var Domain = require('domain'); // Declare internals @@ -18,7 +18,6 @@ var describe = lab.experiment; var it = lab.test; var expect = Code.expect; - describe('Policy', function () { it('returns cached item', function (done) { @@ -1281,6 +1280,90 @@ describe('Policy', function () { }); }); }); + + describe('get()', function(){ + it('it only binds if domain exists', function (done) { + var policy = new Catbox.Policy({ + expiresIn: 1000, + staleIn: 100, + generateFunc: function (id, next) { + setTimeout(function(){ + return next(null, true); + }, 20); + }, + staleTimeout: 50 + }, new Catbox.Client(Import), 'test'); + + var tests = 0; + var completed = 0; + + var checkAndDone = process.domain.bind(function (expected, actual) { // Bind back to the lab domain + expect(actual).to.not.exist(); + expect(expected).to.not.exist(); + expect(actual).to.not.equal(expected, process.domain); // This should be the lab domain + + if (tests === completed) { + done(); + } + }); + + var test = function(domain){ + tests++; + + Domain.create().run(function () { + process.domain = domain; + + policy.get('', function (err, result) { + completed++; + checkAndDone(domain, process.domain); + }); + }); + }; + + test(null); + }); + + it('it returns with the correct process domain', function (done) { + var policy = new Catbox.Policy({ + expiresIn: 1000, + staleIn: 100, + generateFunc: function (id, next) { + setTimeout(function(){ + return next(null, true); + }, 20); + }, + staleTimeout: 50 + }, new Catbox.Client(Import), 'test'); + + var tests = 0; + var completed = 0; + + var checkAndDone = process.domain.bind(function (expected, actual) { + expect(actual).to.equal(expected); + + if (tests === completed) { + done(); + } + }); + + var test = function(domain){ + tests++; + + Domain.create().run(function () { + process.domain.name = domain; + + policy.get('', function (err, result) { + completed++; + checkAndDone(domain, process.domain.name); + }); + }); + }; + + for (var i = 0; i < 10; ++i){ + test(i); + } + }); + }); }); describe('drop()', function () {