/
l8.js
2116 lines (1965 loc) · 64.4 KB
/
l8.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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// l8.js
// a modern multi-tasker for javascript
// https://github.com/JeanHuguesRobert/l8
//
// 2012/10/24, JHR, create
// 2013/02/03, JHR, browserify
//
// (c) Jean Hugues Robert
// Licensed under the MIT license.
"use strict";
// There should be single l8 object, application wide. A true singleton.
var l8;
if( global.l8 ){
l8 = global.l8;
}else{
/* ----------------------------------------------------------------------------
* Debug. The one painful thing that we want to cure.
*/
// DEBUG mode currently defaults to "on". Please use l8.debug() to change it
var DEBUG = true
var NoOp = function noop(){}
var TraceStartTask = !DEBUG ? 0 : 0
// When debugging test cases, this tells when to start outputting traces.
// Ugly but useful.
// In node.js, "util" module defines puts(), among others
var Util = null
//var Bugsnag = null
try{
Util = require( "util")
// Bugsnag = require( "bugsnag")
// Bugsnag.register( "your-api-key-goes-here")
// ToDo: https://bugsnag.com/docs/notifiers/node
DEBUG && console.log( "entering l8.js")
}catch( e ){}
var slice = [].slice
var inspect = function(){
// Return a string representation of its parameter in a format that is
// useful to log.
var buf = []
// Output message will have a "l8" prefix so that you know who did it
var args = ["l8"]
var only_strings = true
// If single array argument, just add "l8" prefix
if( arguments.length === 1 && arguments[0] instanceof Array){
args = args.concat( arguments[0])
// Or else make array using arguments, still with "l8" prefix
}else{
args = args.concat( slice.call( arguments, 0))
}
// For each item to display
var item
var stack
for( var ii = 0 ; ii < args.length ; ii++ ){
item = args[ii]
// Unless empty, skipped
if( item ){
// When item is object with a nice .toLabel() method, keep it short
if( item.toLabel ){
item = item.toLabel()
// When item is a string or something we cannot handle client side
}else if( typeof item === 'string' || !Util ){
item = item
// When item is complex and Util.inspect() can help
}else{
stack = item.stack
item = Util.inspect( item)
}
// When we have only string, better concat them
if( only_strings && typeof item !== "string" ){
only_strings = false
}
if( item ){
buf.push( item)
if( stack ){
if( Util ){
buf.push( Util.inspect( stack))
}else{
buf.push( stack)
}
stack = null
}
}
}
}
if( Util ){
if( only_strings ){
buf = buf.join( ", ")
}else{
buf = Util.inspect( buf)
}
}else{
buf = buf.join( ", ")
}
return buf
}
// l8.logger( null ) restores the default logger for traces.
// This is the function that returns the default log() function that l8.trace()
// uses. That returned function must have the signature of console.log()
var DefaultGetLogger = function(){
return console.log;
}
// User can redefine what logger l8.trace() uses, see l8.logger().
var GetLogger = DefaultGetLogger
var trace = function(){
// l8#trace()
// Print trace. Offer an easy breakpoint when output contains "DEBUG".
// Note: when using native console.log(), it's better to output objects
// instead of strings because modern debuggers understand objects and can
// display them intelligently.
// The function returns a string version of the message that was logged.
GetLogger || (GetLogger = DefaultGetLogger)
var l = GetLogger()
var msg = inspect.apply( this, arguments)
try{
if( console && l === console.log ){
console.log.apply( console, arguments)
}else{
l.call( l, msg)
}
}catch( e ){
// ToDo: host adapted tracing
}
if( msg.indexOf( "DEBUG") >= 0 ){
// please set breakpoint here to debug
try{ debugger }catch( e ){}
}
return msg
}
var assert = function( cond ){
// l8#assert()
// Throw an error if condition is not satisfied.
// ToDo: https://github.com/visionmedia/better-assert
if( !cond ){
trace.apply( this, arguments )
trace( "DEBUG assert failure" )
throw new Error( "Assert failure" )
}
}
var de = DEBUG, bug = trace, mand = assert
// That's my de&&bug darling, also de&&mand()
/* ----------------------------------------------------------------------------
* Task & Step
*/
var NextTaskId = 0
var Task = function f_Task(){
// Tasks are like function call activation records, but with a spaghetti stack
// because more than one child task can be active at the same time.
// See also http://en.wikipedia.org/wiki/Spaghetti_stack
// Forked tasks's parent task collect the multiple results, one per fork.
// Special "spawn" tasks don't block their parent and don't provide a result.
// this.nextFree = void null // Task allocator reuse objects
return this
}
var ProtoTask = Task.prototype
var task_init = function( task, parent, is_fork, is_spawn ){
task.current = task // root task l8 defines it differently
task.id = NextTaskId++ // unique id. .toString() uses it too
if( DEBUG ){
task.stepCount = 0 // Step ids generator
}
// Note: initializing properties to undefined helps some JIT compilers
// any it is needed anyways because objects get reused by Task allocator
task.firstStep = void null
task.isSingleStep = false
task.currentStep = void null // What step the task is on, aka "IP"
task.insertionStep = void null // Where steps are usually added
task.pausedStep = void null // What step the task is paused on
task.isFork = !!is_fork
task.wasSpawn = !!is_spawn
task.stepResult = parent.stepResult
task.stepError = void null
task.isDone = false // False while task is pending
task.subtasks = void null // a set, keys are task.id
task.subtasksCount = void null // size of that set
task.parentTask = parent // aka "caller"
task.forkedTasks = void null // Subtask(s) that block this task
task.forkedTasksCount = void null // Number of such tasks
task.forkResults = void null // Array of these task's result
task.forkResultsCount = void null // Number of entries in that array
task.forkResultsIndex = void null // in parent's forkResults array
task.data = void null // bindings for task local variables
task.optional = {} // Some JIT compilers prefer that
/*
task.optional.wasCanceled = false // "brutal cancel" flag
task.optional.shouldStop = false // "gentle cancel" flag
task.optional.deferredSteps = null // Go lang style "defer"
task.optional.deferredResult = null
task.optional.deferredError = null
task.optional.successBlock = null
task.optional.failureBlock = null
task.optional.finalBlock = null
task.optional.donePromise = null
task.optional.generator = null
*/
if( TraceStartTask && NextTaskId > TraceStartTask )trace( "DEBUG New", task)
// Add new task to it's parent's list of pending subtasks
de&&mand( !parent.isDone )
// Parent remembers all pending subtasks, both forked & spawn ones
// ToDo: find a way to optimize this for the frequent case where there is
// only one sub task.
if( !parent.subtasks ){
de&&mand( !parent.subtasksCount, parent.subtasksCount)
parent.subtasks = {}
parent.subtasksCount = 1
}else{
parent.subtasksCount++
}
parent.subtasks[task.id] = task
// not spawn sub tasks also block their parent
if( !is_spawn ){
if( !parent.forkedTasks ){
// When only one member, direct link, efficient because frequent
parent.forkedTasks = task
parent.forkedTasksCount = 1
}else{
de&&mand( is_fork || parent === l8 )
parent.forkedTasksCount++
// With two members, mutate into an array
if( parent.forkedTasksCount === 2 ){
parent.forkedTasks = [parent.forkedTasks,task]
// More members, push them
}else{
parent.forkedTasks.push( task)
}
}
// Allocate entry for forked tasks results, set to undefined for now
if( is_fork ){
if( !parent.forkResults ){
parent.forkResults = [void null]
parent.forkResultsCount = 1
task.forkResultsIndex = 0 // this task's result in parent.forkResults
}else{
parent.forkResults[
task.forkResultsIndex = parent.forkResultsCount++
] = void null
}
}
}
// Please see what happens in Task.subtaskDoneEvent(), ie "destructor"
if( TraceStartTask && NextTaskId > TraceStartTask )trace( "New", task)
}
var Step = function f_Step(){
// Tasks execute steps, some steps may queue additional steps to execute.
// Forked steps run in parallel whereas regular steps are sequential. Steps
// that cannot execute immediately can block and terminate later when some
// asynchronous event occurs. When a forked step is blocked, the other forked
// steps are still executed whereas when a regular step blocks, the next
// steps are blocked too.
return this
}
var ProtoStep = Step.prototype
// Step allocator. Attempt to reuse some previous steps
var NextFreeStep = null
var MakeStep = function l8_MakeStep( task, block, is_fork, is_repeat ){
var step = NextFreeStep
if( step ){
NextFreeStep = step.next
}else{
step = new Step()
}
step_init( step, task, block, is_fork, is_repeat )
return step
}
ProtoStep.free = function(){
//_ When possible, I reuse step objects to avoid building new ones. This is a
// speed optimization.
this.next = NextFreeStep
NextFreeStep = this
}
var step_init = function( step, task, block, is_fork, is_repeat ){
if( DEBUG ){
step.id = ++task.stepCount
step.wasQueued = false
step.wasExecuted = false
}
de&&mand( !task.isDone )
step.task = task
if( block ){
// If step is a promise, step will block until that promise delivers
if( !(block instanceof Function) ){
block = function(){ task.interpret( block ) }
}
step.block = block
}else{
step.block = NoOp
}
step.isFork = is_fork
step.isRepeat = is_repeat
step.wasSpawn = false
step.isBlocking = false // When task is paused on this step
// enqueue/dequeue list management
var previous = task.insertionStep
task.insertionStep = step
// When inserting at head of queue
if( !previous ){
step.next = task.firstStep
task.firstStep = task.currentStep = step
// When inserting after the head of the queue
}else{
step.next = previous.next
previous.next = step
}
if( TraceStartTask && NextTaskId > TraceStartTask ){
trace(
"New", step,
step === task.firstStep ? "first" : ""
)
}
}
// Bootstrap root task, id 0
var l8 = new Task();
task_init( l8, {} /*dummy parent*/ );
l8.parentTask = null
l8.data = {task:l8}
// l8.proto makes it easy for module to export a new mmm method by adding it
// to the prototype of all the task objects. As a result this.mmm() will be
// directly accessible in the code body of all tasks, ie where "this" is bound
// to the current task.
l8.proto = ProtoTask
// this.l8 is the root task in all code where "this" is bound to the current
// task.
l8.proto.l8 = l8
//_ this defines the body to the root task, an infinite blocked empty loop
var CurrentStep = MakeStep( l8, NoOp, false, true /* empty loop */ )
CurrentStep.isBlocking = true
l8.currentStep = l8.pausedStep = CurrentStep
// l8.now provides a fast access to the time in millisec. That value is
// sample whenever the l8 scheduler wakes up. As a result, it can be
// useful to correlate sub events that pertain to the same event that
// woke up the scheduler.
l8.now = null
// l8.dateNow is the Date object sampled when l8.now was last sampled.
l8.dateNow = null
// Provide initial value for .now & .dateNow
l8.update_now = function(){
return l8.now = (l8.dateNow = new Date()).getTime();
};
l8.update_now();
// Browser & nodejs way to schedule code execution in the event loop.
// Note: you can provide yours if you get an efficient one.
try{
l8.tick = process.nextTick
l8.tick( function(){} )
l8.module = module
}catch( e ){
// Use setTimeout( x, 0 ) or faster Internet Explorer's setImmediate()
if( window.setImmediate ){
l8.tick = window.setImmediate
}else{
// Nota: even when using 0 there is a minimum delay, browser dependent
// See https://github.com/NobleJS/setImmediate
l8.tick = function next_tick( block ){ setTimeout( block, 0 ) }
}
l8.tick( function(){} )
l8.module = this
}
// l8.tick( fn ) is a low level function that schedules the execution of a
// function by the javascript event loop. It is the equivalent to setTimeout()
// with a true 0 delay.
var L8_Tick = ProtoTask.tick = l8.tick
// Some special errors are used to build control structures.
// l8.cancelEvent is the value of the parameter for the l8.failure() specified
// function when the failure is due to a cancellation.
l8.cancelEvent = ["cancel"]
l8.breakEvent = ["break"]
l8.continueEvent = ["continue"]
l8.returnEvent = ["return"]
l8.failureEvent = ["failure"]
l8.closeEvent = ["close"]
// l8.debug() returns true of false depending on the debug flag setting.
// l8.debug( v ) sets that flag to true or false.
ProtoTask.debug = function( on ){
if( arguments.length ){
de = DEBUG = !!on
}
return DEBUG
}
//_ init debug based on global DEBUG flag.
// ToDo: design a way to enable/disable this flag from the command line
// or from some ENV variable.
l8.debug( DEBUG )
ProtoTask.trace = trace
// l8.bug() is an alias for l8.trace() that enables the de&&bug() pattern.
ProtoTask.bug = trace
// l8.assert( cond ) raises an error when cond is satisfied.
ProtoTask.assert = assert
// l8.mand( cond ) is an alias for l8.trace() that enable the de&&mand()
// pattern for asserts that can be disabled with very little overhead left.
ProtoTask.mand = assert
// l8.inspect( obj ) returns a string representation for the specified object
// that can be useful to output traces.
ProtoTask.inspect = inspect
ProtoTask.logger = function( get_logger ){
// Change the way l8.trace() outputs messages.
//
// Usage:
// var save = l8.logger()
// l8.logger( function(){ return function(){
// console.log.apply( console, arguments )
// })
//
// Parameter "get_logger" is a function returning a logger, ie a
// function called to log messages, like console.log(). l8.trace() will use it.
// To restore it to its default value, use l8.logger( null ).
// To read the current value, use l8.logger()
// Usage: l8.logger( function(){ return console.log } }
// Note: because "get_logger" is a function that returns the logger function,
// ie because of this added level of indirection, user can fine tune logging
// using information available in the context of the application when the
// logger function is necessary, versus the information available when the
// logger is installed.
var previous = GetLogger
arguments.length && (GetLogger = get_logger || DefaultGetLogger )
return previous
}
// True when running inside a browser. Opposite to l8.server.
l8.client = typeof window !== "undefined"
// True when running inside node.js. Opposite to l8.client.
// Note: detection is currently based on definition of global "window" variable
l8.server = !l8.client
l8.clientize = function(){
// Act as if client. Override l8.client/l8.server auto-detection.
l8.client = true;
l8.server = false;
}
l8.serverize = function(){
// Act as if server. Override l8.client/l8.server auto-detection.
if( !Util )throw new Error( "Cannot l8.serverize(), not a server")
l8.server = true
l8.client = false
}
l8._getDebugFlag = function(){ return de }
// l8.de&&bug( ... ), where "l8.de" changes according to l8.debug()
l8.__defineGetter__( "de", l8._getDebugFlag )
/* ----------------------------------------------------------------------------
* Scheduler, aka "step walker"
* process.nextTick() or setTimeout() can do the job but I do some buffering
* and that runs faster.
*/
var L8_Execute //_ ProtoStep.execute, see below
var L8_QueuedStep = null
var L8_StepQueue = []
var L8_IsScheduled = false
var L8_Tock = function(){
// Update l8.now & l8.dateNow, called often enough.
// Fast and somehow usefull to correlate traces about the same event.
// ToDo: Use V8/Mozilla Date.now() ?
l8.now = (l8.dateNow = new Date()).getTime()
var step
while( step = L8_QueuedStep ){
L8_QueuedStep = L8_StepQueue.shift()
//step.execute()
L8_Execute( step )
}
L8_IsScheduled = false
// When done, assume code runs from within the "root" task
CurrentStep = l8.currentStep
}
var L8_Scheduler = function(){
// Inject the scheduler in the global event loop.
// It executes queued steps and their next ones.
if( !L8_IsScheduled ){
de&&mand( L8_QueuedStep )
L8_IsScheduled = true
L8_Tick( L8_Tock )
}
}
var L8_EnqueueStep = function( step ){
// Schedule step to execute. Restart scheduler if it is not started.
if( DEBUG ){
assert( !step.wasQueued || step.isRepeat )
step.wasQueued = true
}
// Store step, efficiently if only one exist, in an array if more is needed
if( L8_QueuedStep ){
L8_StepQueue.push( step )
}else{
L8_QueuedStep = step
}
de&&mand( !step.isBlocking )
// Wake up scheduler if necessary, it will eventually execute this step
if( !L8_IsScheduled ){
L8_IsScheduled = true
L8_Tick( L8_Tock )
}
// Debug traces
if( TraceStartTask && NextTaskId > TraceStartTask ){
if( L8_QueuedStep ){
L8_QueuedStep.trace( "queued step" )
var item
for( var ii = 0 ; ii < L8_StepQueue.length ; ii++ ){
item = L8_StepQueue[ii].trace( "queued step[" + ii + "]" )
}
}
}
}
ProtoStep.trace = function step_trace(){
//_ displays a trace about a step. Useful to debug l8 itself.
var args = slice.call( arguments, 0)
var task = this.task
trace( [this].concat( args).concat([
task.isDone ? "task done" : "",
this === task.firstStep ? "first" : "",
this.isRepeat ? "repeat" : "",
this.isFork ? "fork" : "",
this.isBlocking ? "pause" : ""
]))
}
ProtoStep.execute = L8_Execute = function step_execute( that ){
//_ to execute a step is mainly about executing the associated block, using
// the current task result as input and changing that result if a new one is
// provided by the block.
if( TraceStartTask && NextTaskId > TraceStartTask ){
that.trace( "DEBUG execute")
}
if( false && DEBUG ){
assert( !that.wasExecuted || that.isRepeat )
that.wasExecuted = true
}
var task = that.task
if( DEBUG && task.isDone )throw new Error( "BUG, exec done l8 step: " + that)
de&&mand( !task.parentTask || task.parentTask.subtasksCount > 0 )
if( that.isBlocking ){
de&&mand( task.pausedStep === that )
return
}
task.currentStep = that
CurrentStep = that
// Steps created by this step are queued after the insertionStep
task.insertionStep = that
var block = that.block
// Previous result cannot be a promise because promises pause the task
de&&mand( !task.stepResult || !task.stepResult.then || task.stepResult.parentTask )
var result
// Consume previous fork results if any unless step is a fork itself
var results = !that.isFork && task.forkResults
if( results ){
de&&mand( !task.forkedTasks )
task.forkResults = null
task.forkResultsCount = 0
}
// Execute block, set "this" to the current task
try{
// If step(), don't provide any parameter
if( !block.length ){
result = block.call( task)
// If step( r), provide forks results or last result as a single parameter
}else if( block.length === 1 ){
if( results ){
result = block.call( task, results)
}else{
result = block.call( task, task.stepResult)
}
// If step( a, b, ...), use fork results or assume last result is an array
}else{
result = block.apply(
task,
(results && results.length > 1)
? results
: task.stepResult
)
}
de&&mand( !task.parentTask || task.parentTask.subtasksCount > 0 )
// Update last result only when block returned something defined.
// Result can be set asynchronously using proceed(), see below
if( result !== void null ){
task.stepResult = result
// If result is a promise, block until promise is done, unless rslt is a
// task (waiting for a task must be explicit)
if( result.then && !result.parentTask ){
return task.wait( result)
}
}
}catch( e ){
// scheduleNext() will handle the error propagation
task.stepError = e
if( DEBUG ){
that.trace( "task failure", e)
if( TraceStartTask && NextTaskId > TraceStartTask ){
that.trace( "DEBUG execute failed" + e)
}
}
}
// task.insertionStep = null
that.scheduleNext()
}
ProtoStep.scheduleNext = function schedule_next(){
//_ this private method is called after a step is executed, it determines
// what to do next.
// Handles progression from step to step, error propagation, task termination
var task = this.task
if( task.isDone )throw new Error( "Bug, schedule a done l8 task: " + this)
de&&mand( !task.parentTask || task.parentTask.subtasksCount > 0 )
if( this.isBlocking ){
de&&mand( task.pausedStep === this, task.pausedStep)
return
}
var redo = this.isRepeat
// Handle "continue" and "break" in loops
if( redo && task.stepError ){
if( task.stepError === l8.continueEvent ){
task.stepError = void null
}else if( task.stepError === l8.breakEvent ){
redo = false
}
}
// When no error, wait for subtasks if any, else move to next step or loop
if( !task.stepError ){
// Previous step result cannot be a promise because promises pause the task
de&&mand( !task.stepResult || !task.stepResult.then || task.stepResult.parentTask )
var next_step = redo ? this : this.next
if( next_step ){
if( !this.isFork || !next_step.isFork || redo ){
// Regular steps wait for forked tasks, fork steps don't
if( task.forkedTasks ){
this.isBlocking = true
task.pausedStep = this
return
}
}
if( redo ){
if( task === l8 ){
this.isBlocking = true
task.pausedStep = this
return
}
}
L8_EnqueueStep( next_step )
de&&mand( task.parentTask || task.parentTask.subtasksCount > 0 )
return
}else{
if( task.forkedTasks ){
this.isBlocking = true
task.pausedStep = this
return
}
}
// When error, cancel all remaining subtasks
}else{
var subtasks = task.subtasks
if( subtasks ){
for( var subtask_id in subtasks ){
subtasks[subtask_id].cancel()
}
de&&mand( !task.parentTask || task.parentTask.subtasksCount > 0 )
}
if( task.forkedTasks ){
this.isBlocking = true
task.pausedStep = this
return
}
}
// Handle deferred steps
var steps = task.optional.deferredSteps
if( task.optional.deferredSteps ){
var step = steps.pop()
if( step ){
// Save task result before running first deferred step
if( !task.optional.deferredResult ){
task.optional.deferredResult = task.stepResult
task.optional.deferredError = task.stepError
}
// Schedule the deferred step
//task.firstStep = null
step = MakeStep( task, step[0] ) // ToDo: handle args
L8_EnqueueStep( step)
return
// Restore "pre-deferred" task result
}else{
task.stepResult = task.optional.deferredResult
task.stepError = task.optional.deferredError
}
}
// When nothing more, handle task termination
de&&mand( !task.forkedTasks )
this.isBlocking = true
task.pausedStep = null
// ToDo: let success/failure block run asynch, then done, not before
task.isDone = true
var exit_repeat = false
var is_return = false
var block
if( task.stepError === l8.returnEvent ){
is_return = true
task.stepError = void null
}else if( task.stepError === l8.breakEvent ){
task.stepError = void null
exit_repeat = true
}
var err = task.stepError
de&&mand( !task.parentTask || task.parentTask.subtasksCount > 0 )
if( err ){
if( block = task.optional.failureBlock ){
try{
block.call( task, err)
err = task.stepError = void null
}catch( e ){
task.stepError = e
}
}
}else{
if( block = task.optional.successBlock ){
try{
block.call( task, task.stepResult)
}catch( e ){
err = task.stepError = e
}
}
}
if( block = task.optional.finalBlock ){
try{
block.call( task, err, task.stepResult)
}catch( e ){
err = task.stepError = e
}
}
var promise = task.optional.donePromise
if( promise ){
if( err ){
promise.reject( err)
}else{
promise.resolve( task.stepResult)
}
}
var parent = task.parentTask
if( exit_repeat ){
//if( parent ){
if( parent.currentStep.isRepeat ){
parent.currentStep.isRepeat = false
}else{
// task.parentTask.raise( l8.breakEvent)
task.stepError = l8.breakEvent
}
//}
}else if( is_return && !task.optional.wasCanceled ){
task.optional.wasCanceled
task.stepError = l8.returnEvent
}
//if( parent ){ // all tasks (but inactive root one) have a parent
de&&mand( parent.subtasksCount > 0 )
parent.subtaskDoneEvent( task)
//}
// Ask the Step allocator to reuse this now done task's steps
if( !task.data ){
// ToDo: I could free task when binding contains only references, not defs
task.firstStep.free()
}
}
ProtoTask.subtaskDoneEvent = function( subtask ){
//_ Private. Called by Step.scheduleNextStep() when a subtask is done
if( DEBUG && TraceStartTask && NextTaskId > TraceStartTask ){
trace( "DEBUG Done subtask", subtask)
}
// One less pending subtask
de&&mand( !this.parentTask || this.parentTask.subtasksCount > 0 )
de&&mand( !subtask.forkedTasks )
de&&mand( this.subtasksCount > 0, this.subtasksCount)
de&&mand( this.subtasks)
de&&mand( this.subtasks[subtask.id] === subtask )
delete this.subtasks[subtask.id]
// Parent task inherits spawn subtasks, unix does the same with processes
var list = subtask.subtasks
if( list ){
subtask.subtasks = null
subtask.subtasksCount = 0
var item
for( var ii in list ){
item = list[ii]
item.parentTask = this
this.subtasks[item.id] = item
this.subtasksCount++
}
}
if( --this.subtasksCount === 0 ){
this.subtasks = null
}
// When a sub task is done, resume blocked parent and remember result
if( !subtask.wasSpawn ){ // && this.parentTast ){
// When sub task failed, parent will cancel the other forks
var err = subtask.stepError
if( err ){
this.stepError = err
if( !this.parentTask ){
trace( "Unhandled exception", subtask, err, err.stack );
}
// When
}else if( subtask.isFork ){
// Accumulate forked results, stored at the appropriate index
this.forkResults[subtask.forkResultsIndex] = subtask.stepResult
}
// When all sub tasks succeed, resume blocked parent task
// Ditto if sub task failed
if( --this.forkedTasksCount <= 0 || err ){
// Clear this.forkedTasks when it is empty, code elsewhere expect this
if( !this.forkedTasksCount ){
this.forkedTasks = null
}
// As a bonus, deblocking task's result is made available for next step
if( !err ){ this.stepResult = subtask.stepResult }
// Unless fork terminated early there should be a blocked step
var paused_step = this.pausedStep
if( paused_step && this !== l8 ){
de&&mand( paused_step.task === this )
paused_step.isBlocking = false
this.pausedStep = null
paused_step.scheduleNext()
// But if task has no more steps, make task result using forked results
}else if( subtask.isFork ){
var list = this.forkedTasksResults
var len = list ? this.forkedTasksResults.length : 0
// ToDo: I need a isTask flag to handle length 1 result lists
if( list && len > 1 ){
var buf = []
var item
for( var ii = 0 ; ii < len ; ii++ ){
item = list[ii]
if( !item.stepError ){
buf.push( item.stepResult)
}else{
buf.push( void null)
}
}
this.stepResult = buf
}
}
}
// Some task objects are reuseable. If a reference to the task was held
// somewhere, using it is when the task is done is a bug
// However, references to long lived spawn tasks are legit
subtask.free()
}
}
ProtoTask.step = function( block ){
// Queue a step in the task's step queue.
//
// Usage:
// l8.task( function(){
// l8.step( function(){
// console.log( "first step" );
// return ["hello", "world"];
// }).step( function( h, w ){
// console.log( h, w )
// })
// })
//
// The output, ie result, of a step is the input, ie parameters, of the next
// one. Steps can block, using l8.pause() && l8.resume().
//
// When the output of a step is a promise, the step is blocked until the
// promise is resolved. The promise's value becomes the new value for the
// output of the step.
//
// l8.task(), l8.fork() and l8.repeat() queue "special" steps in the current
// task.
//
// The new step is inserted in the task step queue. It is inserted after the
// current step for that task. If multiple steps are inserted, they are
// inserted in FIFO order, ie the last inserted step will be executed last.
//
// Note: l8.step(...) inserts a step in the "current" task, not the l8 task.
// The l8 task is the root task, it is the ultimate "parent" task of all tasks.
// The returned value of the .step() function is the actual task whose queue
// was augmented.
// Attempts to queue a step in a "done" task will be redirected to a not
// yet done parent task (this may change).
var task = this.current
// Add step to some parent task if current task is done
while( task.isDone ){
task = task.parentTask
// ToDo: maybe I could create a task "on the fly"?
if( task === l8 )throw new Error( "Cannot add step to root l8 task")
}
// If arguments are provided, assume this is a call to a blocking function
if( arguments.length !== 1 ){
var args = slice.call( arguments, 1 )
// Assume that last param of called function is expected to be a callback
args.push( this.proceed() )
var fn = block
block = function(){ fn.apply( task, args ) }
}
MakeStep( task, block )
return task
}
ProtoTask._step = function( block, is_fork, is_repeat ){
var task = this.current
// Add step to some parent task if current task is done
while( task.isDone ){
task = task.parentTask
// ToDo: maybe I could create a task "on the fly"?
if( task === l8 )throw new Error( "Cannot add step to root l8 task")
}
MakeStep( task, block, is_fork, is_repeat)
return task
}
ProtoTask.proceed = function( block ){
// l8.proceed( fn ) is used to pause/resume a task when dealing with async
// functions. The fn function is called with the parameters provided by the
// async function. The returned value of that fn function, unless undefined,
// provide the output for the step, an output that will be input for the next
// step. See also l8.walk and l8.flow that are simpler to use in most cases.
// Usage:
// l8.step( function(){ fs.readFile( "xx", "utf8",
// l8.proceed( function( err, content ){ return [err,content]; })
// Pauses current task and returns a callback to be called to resume execution.
var task = this.current
var step = task.currentStep
if( step.isBlocking ){
// ToDo: test/allow multiple next()
// throw new Error( "Can't walk, not running")
}
step.isBlocking = true
task.pausedStep = step
return function walk_cb(){
if( task.currentStep !== step ){
// ToDo: quid if multiple proceed() fire?
throw new Error( "Cannot walk same step again")
}
var previous_step = CurrentStep
CurrentStep = step
var result = arguments
try{
// ToDo: block should run as if from next step ?
// ToDo: block should run as a new step ?
if( block ){
result = block.apply( task, result )
}
// Only resume the task if it is still block on the same step.
// If, for example, task was cancelled, the current step changed.
if( task.currentStep === step ){
if( step.isBlocking ){
de&&mand( task.pausedStep === step )