forked from laverdet/node-fibers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
future.js
475 lines (450 loc) · 11.4 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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
"use strict";
var Fiber = require('./fibers');
var util = require('util');
module.exports = Future;
Function.prototype.future = function(detach) {
var fn = this;
var ret = function() {
var future = new FiberFuture(fn, this, arguments);
if (detach) {
future.detach();
}
return future;
};
ret.toString = function() {
return '<<Future '+ fn+ '.future()>>';
};
return ret;
};
function Future() {}
/**
* Run a function(s) in a future context, and return a future to their return value. This is useful
* for instances where you want a closure to be able to `.wait()`. This also lets you wait for
* mulitple parallel opertions to run.
*/
Future.task = function(fn) {
if (arguments.length === 1) {
return fn.future()();
} else {
var future = new Future, pending = arguments.length, error, values = new Array(arguments.length);
for (var ii = 0; ii < arguments.length; ++ii) {
arguments[ii].future()().resolve(function(ii, err, val) {
if (err) {
error = err;
}
values[ii] = val;
if (--pending === 0) {
if (error) {
future.throw(error);
} else {
future.return(values);
}
}
}.bind(null, ii));
}
return future;
}
};
/**
* Wrap node-style async functions to instead return futures. This assumes that the last parameter
* of the function is a callback.
*
* If a single function is passed a future-returning function is created. If an object is passed a
* new object is returned with all functions wrapped.
*
* The value that is returned from the invocation of the underlying function is assigned to the
* property `_` on the future. This is useful for functions like `execFile` which take a callback,
* but also return meaningful information.
*
* `multi` indicates that this callback will return more than 1 argument after `err`. For example,
* `child_process.exec()`
*
* `suffix` will append a string to every method that was overridden, if you pass an object to
* `Future.wrap()`. Default is 'Future'.
*
* var readFileFuture = Future.wrap(require('fs').readFile);
* var fs = Future.wrap(require('fs'));
* fs.readFileFuture('example.txt').wait();
*/
Future.wrap = function(fnOrObject, multi, suffix, stop) {
if (typeof fnOrObject === 'object') {
var wrapped = Object.create(fnOrObject);
for (var ii in fnOrObject) {
if (wrapped[ii] instanceof Function) {
wrapped[suffix === undefined ? ii+ 'Future' : ii+ suffix] = Future.wrap(wrapped[ii], multi, suffix, stop);
}
}
return wrapped;
} else if (typeof fnOrObject === 'function') {
var fn = function() {
var future = new Future;
var args = Array.prototype.slice.call(arguments);
if (multi) {
var cb = future.resolver();
args.push(function(err) {
cb(err, Array.prototype.slice.call(arguments, 1));
});
} else {
args.push(future.resolver());
}
future._ = fnOrObject.apply(this, args);
return future;
}
// Modules like `request` return a function that has more functions as properties. Handle this
// in some kind of reasonable way.
if (!stop) {
var proto = Object.create(fnOrObject);
for (var ii in fnOrObject) {
if (fnOrObject.hasOwnProperty(ii) && fnOrObject[ii] instanceof Function) {
proto[ii] = proto[ii];
}
}
fn.__proto__ = Future.wrap(proto, multi, suffix, true);
}
return fn;
}
};
/**
* 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();
}
};
/**
* Return a Future that waits on an ES6 Promise.
*/
Future.fromPromise = function(promise) {
var future = new Future;
promise.then(function(val) {
future.return(val);
}, function(err) {
future.throw(err);
});
return future;
};
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 error = this.error;
var localStack = {};
Error.captureStackTrace(localStack, Future.prototype.get);
var futureStack = Object.getOwnPropertyDescriptor(error, 'futureStack');
if (!futureStack) {
futureStack = Object.getOwnPropertyDescriptor(error, 'stack');
if (futureStack) {
Object.defineProperty(error, 'futureStack', futureStack);
}
}
if (futureStack && futureStack.get) {
Object.defineProperty(error, 'stack', {
get: function() {
var stack = futureStack.get.apply(error);
if (stack) {
stack = stack.split('\n');
return [stack[0]]
.concat(localStack.stack.split('\n').slice(1))
.concat(' - - - - -')
.concat(stack.slice(1))
.join('\n');
} else {
return localStack.stack;
}
},
set: function(stack) {
Object.defineProperty(error, 'stack', {
value: stack,
configurable: true,
enumerable: false,
writable: true,
});
},
configurable: true,
enumerable: false,
});
}
throw error;
} 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('Resolve cb threw', String(ex.stack || ex.message || ex));
process.nextTick(function() {
throw(ex);
});
}
}
}
},
/**
* 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('Resolve cb threw', String(ex.stack || ex.message || ex));
process.nextTick(function() {
throw(ex);
});
}
}
}
},
/**
* "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;
},
/**
* Returns an ES6 Promise
*/
promise: function() {
var that = this;
return new Promise(function(resolve, reject) {
that.resolve(function(err, val) {
if (err) {
reject(err);
} else {
resolve(val);
}
});
});
},
/**
* 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);