This repository has been archived by the owner on Oct 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
promise_server.js
229 lines (187 loc) · 5.82 KB
/
promise_server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
var assert = require("assert");
var fiberPool = require("./fiber_pool.js").makePool();
exports.makeCompatible = function (Promise, Fiber) {
var es6PromiseThen = Promise.prototype.then;
if (typeof Fiber === "function") {
Promise.Fiber = Fiber;
}
if (es6PromiseThen.name === "meteorPromiseThen") {
return; // Already compatible.
}
function meteorPromiseThen(onResolved, onRejected) {
var Promise = this.constructor;
var Fiber = Promise.Fiber;
if (typeof Fiber === "function" &&
! this._meteorPromiseAlreadyWrapped) {
onResolved = wrapCallback(onResolved, Promise);
onRejected = wrapCallback(onRejected, Promise);
// Just in case we're wrapping a .then method defined by an older
// version of this library, make absolutely sure it doesn't attempt
// to rewrap the callbacks, and instead calls its own original
// es6PromiseThen function.
Promise.Fiber = null;
try {
return es6PromiseThen.call(this, onResolved, onRejected);
} finally {
Promise.Fiber = Fiber;
}
}
return es6PromiseThen.call(this, onResolved, onRejected);
}
// Replace Promise.prototype.then with a wrapper that ensures the
// onResolved and onRejected callbacks always run in a Fiber.
Object.defineProperty(Promise.prototype, "then", {
value: meteorPromiseThen,
enumerable: true,
// Don't let older versions of the meteor-promise library overwrite
// this version of Promise.prototype.then...
writable: false,
// ... unless they also call Object.defineProperty.
configurable: true
});
Promise.awaitAll = function (args) {
return awaitPromise(this.all(args));
};
Promise.await = function (arg) {
return awaitPromise(this.resolve(arg));
};
Promise.prototype.await = function () {
return awaitPromise(this);
};
// Yield the current Fiber until the given Promise has been fulfilled.
function awaitPromise(promise) {
var Promise = promise.constructor;
var Fiber = Promise.Fiber;
assert.strictEqual(
typeof Fiber, "function",
"Cannot await unless Promise.Fiber is defined"
);
var fiber = Fiber.current;
assert.ok(
fiber instanceof Fiber,
"Cannot await without a Fiber"
);
var run = fiber.run;
var throwInto = fiber.throwInto;
if (process.domain) {
run = process.domain.bind(run);
throwInto = process.domain.bind(throwInto);
}
// The overridden es6PromiseThen function is adequate here because these
// two callbacks do not need to run in a Fiber.
es6PromiseThen.call(promise, function (result) {
tryCatchNextTick(fiber, run, [result]);
}, function (error) {
tryCatchNextTick(fiber, throwInto, [error]);
});
return stackSafeYield(Fiber, awaitPromise);
}
function stackSafeYield(Fiber, caller) {
try {
return Fiber.yield();
} catch (thrown) {
if (thrown) {
var e = new Error;
Error.captureStackTrace(e, caller);
thrown.stack += e.stack.replace(/^.*?\n/, "\n => awaited here:\n");
}
throw thrown;
}
}
// Return a wrapper function that returns a Promise for the eventual
// result of the original function.
Promise.async = function (fn, allowReuseOfCurrentFiber) {
var Promise = this;
return function () {
return Promise.asyncApply(
fn, this, arguments,
allowReuseOfCurrentFiber
);
};
};
Promise.asyncApply = function (
fn, context, args, allowReuseOfCurrentFiber
) {
var Promise = this;
var Fiber = Promise.Fiber;
var fiber = Fiber && Fiber.current;
if (fiber && allowReuseOfCurrentFiber) {
return this.resolve(fn.apply(context, args));
}
return fiberPool.run({
callback: fn,
context: context,
args: args,
dynamics: cloneFiberOwnProperties(fiber)
}, Promise);
};
};
function wrapCallback(callback, Promise) {
if (! callback) {
return callback;
}
// Don't wrap callbacks that are flagged as not wanting to be called in a
// fiber.
if (callback._meteorPromiseAlreadyWrapped) {
return callback;
}
var dynamics = cloneFiberOwnProperties(Promise.Fiber.current);
var result = function (arg) {
var promise = fiberPool.run({
callback: callback,
args: [arg], // Avoid dealing with arguments objects.
dynamics: dynamics
}, Promise);
// Avoid wrapping the native resolver functions that will be attached
// to this promise per https://github.com/meteor/promise/issues/18.
promise._meteorPromiseAlreadyWrapped = true;
return promise;
};
// Flag this callback as not wanting to be called in a fiber because it is
// already creating a fiber.
result._meteorPromiseAlreadyWrapped = true;
return result;
}
function cloneFiberOwnProperties(fiber) {
if (fiber) {
var dynamics = {};
Object.keys(fiber).forEach(function (key) {
dynamics[key] = shallowClone(fiber[key]);
});
return dynamics;
}
}
function shallowClone(value) {
if (Array.isArray(value)) {
return value.slice(0);
}
if (!value || typeof value !== "object") {
return value;
}
if (value instanceof Map) {
return new Map(value);
}
if (value instanceof Set) {
return new Set(value);
}
const copy = Object.create(Object.getPrototypeOf(value));
const keys = Object.keys(value);
const keyCount = keys.length;
for (var i = 0; i < keyCount; ++i) {
const key = keys[i];
copy[key] = value[key];
}
return copy;
}
// Invoke method with args against object in a try-catch block,
// re-throwing any exceptions in the next tick of the event loop, so that
// they won't get captured/swallowed by the caller.
function tryCatchNextTick(object, method, args) {
try {
return method.apply(object, args);
} catch (error) {
process.nextTick(function () {
throw error;
});
}
}