forked from laverdet/node-fibers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
future.js
348 lines (326 loc) · 7.87 KB
/
future.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
"use strict";
require('./fibers');
var util = require('util');
module.exports = Future;
Function.prototype.future = function() {
var fn = this;
var ret = function() {
return new FiberFuture(fn, this, arguments);
};
ret.toString = function() {
return '<<Future '+ fn+ '.future()>>';
};
return ret;
};
function Future() {}
/**
* Wrap a node-style async function to return a future in place of using a callback.
*/
Future.wrap = function(fn, idx) {
idx = idx === undefined ? fn.length - 1 : idx;
return function() {
var args = Array.prototype.slice.call(arguments);
if (args.length > idx) {
throw new Error('function expects no more than '+ idx+ ' arguments');
}
var future = new Future;
args[idx] = future.resolver();
fn.apply(this, args);
return future;
};
};
/**
* Wait on a series of futures and then return. If the futures throw an exception this function
* /won't/ throw it back. You can get the value of the future by calling get() on it directly. If
* you want to wait on a single future you're better off calling future.wait() on the instance.
*/
Future.wait = function wait(/* ... */) {
// Normalize arguments + pull out a FiberFuture for reuse if possible
var futures = [], singleFiberFuture;
for (var ii = 0; ii < arguments.length; ++ii) {
var arg = arguments[ii];
if (arg instanceof Future) {
// Ignore already resolved fibers
if (arg.isResolved()) {
continue;
}
// Look for fiber reuse
if (!singleFiberFuture && arg instanceof FiberFuture && !arg.started) {
singleFiberFuture = arg;
continue;
}
futures.push(arg);
} else if (arg instanceof Array) {
for (var jj = 0; jj < arg.length; ++jj) {
var aarg = arg[jj];
if (aarg instanceof Future) {
// Ignore already resolved fibers
if (aarg.isResolved()) {
continue;
}
// Look for fiber reuse
if (!singleFiberFuture && aarg instanceof FiberFuture && !aarg.started) {
singleFiberFuture = aarg;
continue;
}
futures.push(aarg);
} else {
throw new Error(aarg+ ' is not a future');
}
}
} else {
throw new Error(arg+ ' is not a future');
}
}
// Resumes current fiber
var fiber = Fiber.current;
if (!fiber) {
throw new Error('Can\'t wait without a fiber');
}
// Resolve all futures
var pending = futures.length + (singleFiberFuture ? 1 : 0);
function cb() {
if (!--pending) {
fiber.run();
}
}
for (var ii = 0; ii < futures.length; ++ii) {
futures[ii].resolve(cb);
}
// Reusing a fiber?
if (singleFiberFuture) {
singleFiberFuture.started = true;
try {
singleFiberFuture.return(
singleFiberFuture.fn.apply(singleFiberFuture.context, singleFiberFuture.args));
} catch(e) {
singleFiberFuture.throw(e);
}
--pending;
}
// Yield this fiber
if (pending) {
Fiber.yield();
}
};
Future.prototype = {
/**
* Return the value of this future. If the future hasn't resolved yet this will throw an error.
*/
get: function() {
if (!this.resolved) {
throw new Error('Future must resolve before value is ready');
} else if (this.error) {
// Link the stack traces up
var stack = {}, error = this.error instanceof Object ? this.error : new Error(this.error);
var longError = Object.create(error);
Error.captureStackTrace(stack, Future.prototype.get);
Object.defineProperty(longError, 'stack', {
get: function() {
var baseStack = error.stack;
if (baseStack) {
baseStack = baseStack.split('\n');
return [baseStack[0]]
.concat(stack.stack.split('\n').slice(1))
.concat(' - - - - -')
.concat(baseStack.slice(1))
.join('\n');
} else {
return stack.stack;
}
},
enumerable: true,
});
throw longError;
} else {
return this.value;
}
},
/**
* Mark this future as returned. All pending callbacks will be invoked immediately.
*/
"return": function(value) {
if (this.resolved) {
throw new Error('Future resolved more than once');
}
this.value = value;
this.resolved = true;
var callbacks = this.callbacks;
if (callbacks) {
delete this.callbacks;
for (var ii = 0; ii < callbacks.length; ++ii) {
try {
var ref = callbacks[ii];
if (ref[1]) {
ref[1](value);
} else {
ref[0](undefined, value);
}
} catch(ex) {
console.log(String(ex.stack || ex.message || ex));
process.exit(1);
}
}
}
},
/**
* Throw from this future as returned. All pending callbacks will be invoked immediately.
*/
"throw": function(error) {
if (this.resolved) {
throw new Error('Future resolved more than once');
} else if (!error) {
throw new Error('Must throw non-empty error');
}
this.error = error;
this.resolved = true;
var callbacks = this.callbacks;
if (callbacks) {
delete this.callbacks;
for (var ii = 0; ii < callbacks.length; ++ii) {
try {
var ref = callbacks[ii];
if (ref[1]) {
ref[0].throw(error);
} else {
ref[0](error);
}
} catch(ex) {
console.log(ex.stack || ex);
process.exit(1);
}
}
}
},
/**
* "detach" this future. Basically this is useful if you want to run a task in a future, you
* aren't interested in its return value, but if it throws you don't want the exception to be
* lost. If this fiber throws, an exception will be thrown to the event loop and node will
* probably fall down.
*/
detach: function() {
this.resolve(function(err) {
if (err) {
throw err;
}
});
},
/**
* Returns whether or not this future has resolved yet.
*/
isResolved: function() {
return this.resolved === true;
},
/**
* Returns a node-style function which will mark this future as resolved when called.
*/
resolver: function() {
return function(err, val) {
if (err) {
this.throw(err);
} else {
this.return(val);
}
}.bind(this);
},
/**
* Waits for this future to resolve and then invokes a callback.
*
* If two arguments are passed, the first argument is a future which will be thrown to in the case
* of error, and the second is a function(val){} callback.
*
* If only one argument is passed it is a standard function(err, val){} callback.
*/
resolve: function(arg1, arg2) {
if (this.resolved) {
if (arg2) {
if (this.error) {
arg1.throw(this.error);
} else {
arg2(this.value);
}
} else {
arg1(this.error, this.value);
}
} else {
(this.callbacks = this.callbacks || []).push([arg1, arg2]);
}
return this;
},
/**
* Resolve only in the case of success
*/
resolveSuccess: function(cb) {
this.resolve(function(err, val) {
if (err) {
return;
}
cb(val);
});
return this;
},
/**
* Propogate results to another future.
*/
proxy: function(future) {
this.resolve(function(err, val) {
if (err) {
future.throw(err);
} else {
future.return(val);
}
});
},
/**
* Propogate only errors to an another future or array of futures.
*/
proxyErrors: function(futures) {
this.resolve(function(err) {
if (!err) {
return;
}
if (futures instanceof Array) {
for (var ii = 0; ii < futures.length; ++ii) {
futures[ii].throw(err);
}
} else {
futures.throw(err);
}
});
return this;
},
/**
* Differs from its functional counterpart in that it actually resolves the future. Thus if the
* future threw, future.wait() will throw.
*/
wait: function() {
if (this.isResolved()) {
return this.get();
}
Future.wait(this);
return this.get();
},
};
/**
* A function call which loads inside a fiber automatically and returns a future.
*/
function FiberFuture(fn, context, args) {
this.fn = fn;
this.context = context;
this.args = args;
this.started = false;
var that = this;
process.nextTick(function() {
if (!that.started) {
that.started = true;
Fiber(function() {
try {
that.return(fn.apply(context, args));
} catch(e) {
that.throw(e);
}
}).run();
}
});
}
util.inherits(FiberFuture, Future);