Browse files

Broken: use a counter for entering a domain multiple times

  • Loading branch information...
1 parent a3011b8 commit 6007534eb4e4c2c09a67c7c3fc8d966455e35a76 @isaacs committed Apr 11, 2012
Showing with 28 additions and 12 deletions.
  1. +28 −12 lib/domain.js
View
40 lib/domain.js
@@ -69,26 +69,42 @@ inherits(Domain, EventEmitter);
function Domain() {
EventEmitter.apply(this);
+ this._entered = 0;
this.members = [];
}
Domain.prototype.enter = function() {
+ // cannot enter disposed domains
if (this._disposed) return;
- // note that this might be a no-op, but we still need
- // to push it onto the stack so that we can pop it later.
- exports.active = process.domain = this;
+ // if we're already in this one, then no need to
+ // push it onto the stack. However, we do need to track
+ // that we're entering it again, so that we don't inadvertenly
+ // exit() it prematurely later.
+ this._entered++;
+ if (exports.active === this) return;
+
+ // not already the active domain, so push onto the stack.
exports.stack.push(this);
};
Domain.prototype.exit = function() {
if (this._disposed) return;
- // exit all domains until this one.
- var d;
- do {
- d = exports.stack.pop();
- } while (d && d !== this);
+ // if we're not currently entered, then this is spurious
+ if (this._entered <= 0) return;
+
+ // if we're not the active, then pop everything in front
+ var d = exports.stack.length - 1;
+ while (exports.stack[d] && exports.stack[d] !== this) {
+ exports.stack[d]._entered = 0;
+ exports.stack.pop();
+ d--;
+ }
+
+ // now we're definitely the top of the stack.
+ this._entered--;
+ if (this._entered <= 0) exports.stack.pop();
exports.active = exports.stack[exports.stack.length - 1];
process.domain = exports.active;
@@ -100,10 +116,10 @@ Domain.prototype.add = function(ee) {
if (this._disposed) return;
// already added to this domain.
- if (ee._domain === this) return;
-
- // has a domain already - remove it first.
- if (ee._domain) {
+ if (ee._domain === this) {
+ if (-1 !== this.members.indexOf(ee)) return;
+ } else if (ee._domain) {
+ // has a domain already - remove it first.
ee._domain.remove(ee);
}

0 comments on commit 6007534

Please sign in to comment.