-
Notifications
You must be signed in to change notification settings - Fork 57
/
sync.js
374 lines (338 loc) · 12 KB
/
sync.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
/*jshint node: true, indent:2, loopfunc: true, asi: true, undef:true*/
var Fiber = require('fibers')
// Takes function and returns its synchronized version, it's still backward compatible and
// can be used as asynchronous `syncFn = sync(asyncFn)`.
//
// Or You can provide object and it will synchronize its functions `sync(obj, fname1, fname2, ...)`.
//
// New synchronized version of function is backward compatible and You may call it as usual with
// explicit callback or inside of `fiber` with `aware` and `defer` keywords.
var sync = module.exports = function(){
if(arguments.length > 1){
// Synchronizing functions of object.
var obj = arguments[0]
for(var i = 1; i < arguments.length; i++){
var fname = arguments[i]
var fn = obj[fname]
if(!fn) throw new Error("object doesn't have '" + fname + "' function!")
obj[fname] = sync(fn)
}
}else{
return sync.syncFn(arguments[0])
}
}
var nextTick = global.setImmediate || process.nextTick || function(cb) { setTimeout(cb, 0) }
// Sometimes `Fiber` needed outside of `sync`.
sync.Fiber = Fiber
// Takes function and returns its synchronized version, it's still backward compatible and can
// be used as asynchronous.
sync.syncFn = function(fn){
// Preventing function to be synchronized twice.
if(fn._synchronized) return fn
var syncFn = function(){
// Using fibers only if there's active fiber and callback not provided explicitly.
if(Fiber.current && (typeof arguments[arguments.length-1] !== 'function')){
// Calling asynchronous function with our special fiber-aware callback.
Array.prototype.push.call(arguments, sync.defer())
fn.apply(this, arguments)
// Waiting for asynchronous result.
return sync.await()
}else{
// If there's no active fiber or callback provided explicitly we call original version.
return fn.apply(this, arguments)
}
}
// Marking function as synchronized.
syncFn._synchronized = true
return syncFn
}
// Use it to wait for asynchronous callback.
sync.await = Fiber.yield
// Creates fiber-aware asynchronous callback resuming current fiber when it will be finished.
sync.defer = function(){
if(!Fiber.current) throw new Error("no current Fiber, defer can't be used without Fiber!")
if(Fiber.current._syncParallel) return sync.deferParallel()
else return sync.deferSerial()
}
// Exactly the same as defer, but additionally it triggers an error if there's no response
// on time.
sync.deferWithTimeout = function(timeout, message){
if(!Fiber.current) throw new Error("no current Fiber, deferWithTimeout can't be used without Fiber!")
if(!timeout) throw new Error("no timeout provided!")
if(Fiber.current._syncParallel) throw new Error("deferWithTimeout can't be used in parallel!")
var defer = this.defer()
var error = new Error(message || "defer timed out!")
var called = false
var d = setTimeout(function(){
if(called) return
called = true
defer(error)
}, timeout)
return function(){
if(called) return
called = true
clearTimeout(d)
return defer.apply(this, arguments)
}
}
//
sync.deferSerial = function(){
var fiber = Fiber.current
if(!fiber) throw new Error("no current Fiber, defer can't be used without Fiber!")
// if(fiber._defered) throw new Error("invalid usage, should be clear previous defer!")
// fiber._defered = true
// Prevent recursive call
var called = false
// Returning asynchronous callback.
return function(err, result){
if (called) throw new Error("defer can't be used twice!")
called = true
// Wrapping in nextTick as a safe measure against not asynchronous usage.
nextTick(function(){
// fiber._defered = false
if(fiber._syncIsTerminated) return
if(err){
// Resuming fiber and throwing error.
fiber.throwInto(err)
}else{
// Resuming fiber and returning result.
fiber.run(result)
}
})
}
}
sync.deferParallel = function(){
var fiber = Fiber.current
if(!fiber) throw new Error("no current Fiber, defer can't be used without Fiber!")
if(!fiber._syncParallel) throw new Error("invalid usage, should be called in parallel mode!")
var data = fiber._syncParallel
// Counting amount of `defer` calls.
data.called += 1
var resultIndex = data.called - 1
// Returning asynchronous callback.
return function(err, result){
// Wrapping in nextTick as a safe measure against not asynchronous usage.
nextTick(function(){
if(fiber._syncIsTerminated) return
// Error in any of parallel call will result in aborting all of the calls.
if(data.errorHasBeenThrown) return
if(err){
data.errorHasBeenThrown = true
// Resuming fiber and throwing error.
fiber.throwInto(err)
}else{
data.returned += 1
data.results[resultIndex] = result
// Resuming fiber and returning result when all callbacks finished.
if(data.returned == data.called) fiber.run(data.results)
}
})
}
}
sync.defers = function(){
if(!Fiber.current) throw new Error("no current Fiber, defer can't be used without Fiber!")
if(Fiber.current._syncParallel) return sync.defersParallel.apply(sync, arguments)
else return sync.defersSerial.apply(sync, arguments)
}
sync.defersSerial = function(){
var fiber = Fiber.current;
if(!fiber) throw new Error("no current Fiber, defer can't be used without Fiber!")
// if(fiber._defered) throw new Error("invalid usage, should be clear previous defer!")
// fiber._defered = true
var kwds = Array.prototype.slice.call(arguments)
// Prevent recursive call
var called = false
// Returning asynchronous callback.
return function(err) {
if (called) throw new Error("defer can't be used twice!")
called = true
// Wrapping in nextTick as a safe measure against not asynchronous usage.
var args = Array.prototype.slice.call(arguments, 1)
nextTick(function(){
// fiber._defered = false
if(fiber._syncIsTerminated) return
if (err) {
// Resuming fiber and throwing error.
fiber.throwInto(err)
} else {
var results;
if(!kwds.length){
results = args
} else {
results = {}
kwds.forEach(function(kwd, i){
results[kwd]=args[i]
})
}
fiber.run(results)
}
})
}
}
sync.defersParallel = function(){
var fiber = Fiber.current
if(!fiber) throw new Error("no current Fiber, defer can't be used without Fiber!")
if(!fiber._syncParallel) throw new Error("invalid usage, should be called in parallel mode!")
var data = fiber._syncParallel
// Counting amount of `defer` calls.
data.called += 1
var resultIndex = data.called - 1
var kwds = Array.prototype.slice.call(arguments)
// Returning asynchronous callback.
return function(err) {
// Wrapping in nextTick as a safe measure against not asynchronous usage.
var args = Array.prototype.slice.call(arguments, 1)
nextTick(function(){
if(fiber._syncIsTerminated) return
// Error in any of parallel call will result in aborting all of the calls.
if(data.errorHasBeenThrown) return
if (err) {
data.errorHasBeenThrown = true
// Resuming fiber and throwing error.
fiber.throwInto(err)
}
var results;
if(!kwds.length){
results = args
} else {
results = {}
kwds.forEach(function(kwd, i){
results[kwd]=args[i]
})
}
data.returned += 1
data.results[resultIndex] = results
if(data.returned == data.called) fiber.run(data.results)
})
}
}
// Support for parallel calls, all `defer` calls within callback will be
// performed in parallel.
sync.parallel = function(cb){
var fiber = Fiber.current
if(!fiber) throw new Error("no current Fiber, defer can't be used without Fiber!")
// Enabling `defer` calls to be performed in parallel.
// There's an important note - error in any parallel call will result in aborting
// all of the parallel calls.
fiber._syncParallel = {called: 0, returned: 0, results: [], errorHasBeenThrown: false}
try{
cb.call(this)
}finally{
// If neither `defer` nor `defers` were called within the callback, we need
// to run the fiber ourselves or else the fiber will unwind when `await` is called.
// This might happen if the user intended to enumerate an array within the
// callback, calling `defer` once per array item, but the array was empty.
if (!fiber._syncParallel.called) {
nextTick(function(){
// Return an empty array to represent that there were no results.
if(!fiber._syncIsTerminated) fiber.run([])
})
}
delete fiber._syncParallel
}
}
function decorateError(error, callStack){
if (typeof error === 'object') {
var errorStack = error.stack;
Object.defineProperties(error, {
stack: {
configurable: true,
get: function () {
if (!callStack) {
return errorStack;
}
return [errorStack, callStack.substring(callStack.indexOf('\n') + 1)].join('\n')
}
}
});
}
return error;
}
// Executes `cb` within `Fiber`, when it finish it will call `done` callback.
// If error will be thrown during execution, this error will be catched and passed to `done`,
// if `done` not provided it will be just rethrown.
sync.fiber = function(cb, done){
var that = this
var fiber = Fiber(function(){
// Prevent restart fiber
if (Fiber.current._started) return
if (done) {
var result
try {
result = cb.call(that)
Fiber.current._syncIsTerminated = true
} catch (error) {
return done(decorateError(error, Fiber.current._callStack.stack))
}
done(null, result)
} else {
// Don't catch errors if done not provided!
cb.call(that)
Fiber.current._syncIsTerminated = true
}
})
if (done) {
fiber._callStack = {}
Error.captureStackTrace(fiber._callStack, this.fiber)
}
fiber.run()
fiber._started = true
}
// Asynchronous wrapper for mocha.js tests.
//
// async = sync.asyncIt
// it('should pass', async(function(){
// ...
// }))
//
sync.asyncIt = function(cb){
if(!cb) throw "no callback for async spec helper!"
return function(done){sync.fiber(cb.bind(this), done)}
}
// Same as `sync` but with verbose logging for every method invocation.
// Ignore this method, it shouldn't be used unless you want to track down
// tricky and complex bugs and need full information abouth how and when all
// this async stuff has been called.
var fiberIdCounter = 1
sync.syncWithDebug = function(){
if(arguments.length > 1){
// Synchronizing functions of object.
var obj = arguments[0]
for(var i = 1; i < arguments.length; i++){
(function(fname){
var fn = obj[fname]
if(!fn) throw new Error("object doesn't have '" + fname + "' function!")
var syncedFn = sync(fn)
obj[fname] = function(){
if(Fiber.current && Fiber.current._fiberId === undefined){
Fiber.current._fiberId = fiberIdCounter
fiberIdCounter = fiberIdCounter + 1
Fiber.current._callbackLevel = 0
}
var fiberId = '-'
if(Fiber.current){
fiberId = Fiber.current._fiberId
Fiber.current._callbackLevel = Fiber.current._callbackLevel + 1
}
var indent = ' '
if(Fiber.current)
for(var j = 0; j < Fiber.current._callbackLevel; j++) indent = indent + ' '
console.log(fiberId + indent + this.constructor.name + '.' +
fname + " called", JSON.stringify(arguments))
var result
try{
result = syncedFn.apply(this, arguments)
}finally{
console.log(fiberId + indent + this.constructor.name + '.' +
fname + " finished")
if(Fiber.current)
Fiber.current._callbackLevel = Fiber.current._callbackLevel - 1
}
return result
}
})(arguments[i])
}
}else{
return sync.syncFn(arguments[0])
}
}