Skip to content

Commit 73ba57c

Browse files
committed
better/safer EV set/withValue - must be used with >=5.0.2-5 of fibers
1 parent 63820a1 commit 73ba57c

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

packages/meteor/dynamics_nodejs.js

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,18 @@ Meteor._nodeCodeMustBeInFiber = function () {
2121

2222
Object.defineProperty(Fiber.prototype, '_meteor_dynamics', {
2323
get() {
24-
return __async_meteor_dynamics.getStore() || [];
24+
return __async_meteor_dynamics.getStore();
25+
},
26+
set(store) {
27+
// opinionated - but there are no situations I can think of where we want to set the root _meteor_dynamics.
28+
if (executionAsyncId() === 0) {
29+
throw new Error('Trying to call Fiber.current._meteor_dynamics = [...] at the global execution ID');
30+
}
31+
__async_meteor_dynamics.enterWith(store);
2532
}
2633
});
2734

35+
2836
/**
2937
* @memberOf Meteor
3038
* @summary Constructor for EnvironmentVariable
@@ -76,18 +84,12 @@ EVp.getOrNullIfOutsideFiber = function () {
7684
EVp.withValue = function (value, func) {
7785
const current = (__async_meteor_dynamics.getStore() || []).slice();
7886
current[this.slot] = value;
79-
if (!Fiber.current) {
80-
// this is necessary as if we aren't in a fiber, the current async scope may be poluted
81-
// particularly bad if this is the root async scope - which it often is inside a fiber
82-
// in the future we may loosen this restriction to only require there be a current fiber if
83-
// the current executionAsyncId == 0 (e.g., the root) - this will allow us to call withValue
84-
// after an await without poluting the root AsyncResource. However, this may not resolve the concerns
85-
// of poluting some other shared async resource.
87+
if (!Fiber.current && executionAsyncId() === 0) {
8688
// running the full meteor test suite (in particular, mongo and ddp*) multiple times in a single build
8789
// should expose any flaws with changes made here.
8890
throw new Error('You can\'t call withValue from outside a Fiber. Perhaps you awaited something before calling this?');
8991
}
90-
return Fiber.current.runInAsyncScope(() => __async_meteor_dynamics.run(current, func));
92+
return __async_meteor_dynamics.run(current, func);
9193
};
9294

9395
/**

0 commit comments

Comments
 (0)