-
Notifications
You must be signed in to change notification settings - Fork 2
/
workflo.js
999 lines (790 loc) · 37.4 KB
/
workflo.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
/**
* workflo.js
* ----------
*
* @description provides a schema centric framework for managing and running your aws SWF workflows
* @author Mike MacMillan ([email protected])
*/
var Q = require('q'),
_ = require('lodash'),
aws = require('aws-sdk'),
events = require('events'),
util = require('util'),
_workflows = {};
var workflow = {
/**
* @class workflow
*/
define: function(name, opts) {
if(!opts) return;
var lib = this;
var workflowObj = {
name: name,
domain: this.swfDomain,
tasks: opts.tasks||[],
handlers: opts.handlers||{},
//** defines the aws swf specific config/defaults, inheriting any settings from the options
swf: _.assign({
version: '1.0',
defaultTaskStartToCloseTimeout: '5', //** 5 second limit on tasks to finish, within this workflow, if none specified @ the task level
defaultExecutionStartToCloseTimeout: ''+ ((60*60*24)*180), //** 180 days default, task limits will eliminate bottlenecks, but some workflows may require waiting weeks
defaultChildPolicy: 'TERMINATE', //** by default, when terminated, child processes will also be terminated
defaultTaskList: lib.defaultTaskList
}, opts.swf||{}),
//** defines some workflo specific config/defaults
config: _.assign({
maxFailures: 5,
maxDecisionTimeouts: 5,
maxActivityTimeouts: 5
}, opts.config||{}),
verify: function() {
var def = Q.defer();
//** asynchronously verify each of the activityTypes that are included in this workflow
function verifyTasks() {
var actions = _.map(workflowObj.tasks, function(obj) { return obj.verify() });
Q.all(actions).then(def.resolve, def.reject);
}
//** see if the workflow exists already, with this name/version
lib.workflow.exists(workflowObj.name, workflowObj.swf.version)
.then(verifyTasks)
.catch(function() {
var obj = _.extend({
name: workflowObj.name,
domain: workflowObj.domain,
}, workflowObj.swf||{});
//** create it otherwise
lib.emit('workflow:create', workflowObj);
lib.workflow.create(workflowObj.name, workflowObj.swf.version, obj)
.then(verifyTasks)
.catch(def.reject);
}.bind(this))
.catch(def.reject);
return def.promise;
},
evaluate: function(p, context) {
var data = {},
history = context.history,
config = context.workflow && context.workflow.config,
lastFailed = history.lastFailedActivity(),
lastCompleted = history.lastCompletedActivity(),
lastScheduled = history.lastScheduledActivity(),
previousFail = false;
//** see if the workflow was cancelled
//**** add here
//** if we have a failed task, but no completed tasks, we need to retry the same task again
if(lastFailed && !lastCompleted)
previousFail = true;
//** since our last event could be many things other than a fail or complete event for an activity, compare the
//** last failed activity with the last completed activity; if the last completed activity comes after the failure
//** we can safely assume the failure was recovered; if the failure came after, we need to recover from that failure
if(!previousFail && (lastFailed && lastCompleted)) {
var lastFailId = lastFailed.args().scheduledEventId,
lastCompletedId = lastCompleted.args().scheduledEventId;
if(parseInt(lastFailId) >= parseInt(lastCompletedId))
previousFail = true;
}
if(previousFail) {
var details = lastFailed.args().details,
activity = null;
//** see if the last failed task specified that the workflow should be marked as failed
if(!!details.workflowFailed) {
context.failWorkflow(details, lastFailed.args().reason);
return p.resolve();
}
//** see if the task that failed specified what its next step should be
if (!!details.next)
activity = this.getTask(details.next);
else {
//** otherwise, attempt to retrieve the last task scheduled to be run
if (lastScheduled) {
var args = lastScheduled.args(),
name = args && args.activityType && args.activityType.name;
//** if found, assign the activity so its scheduled to be run
name && (activity = this.getTask(name));
}
}
//** before scheduling a new activity, see if we've hit our maximum failures allowed for this workflow
if (this.config && this.config.maxFailures) {
var failed = history.eventsByType('ActivityTaskFailed').length;
if (failed >= parseInt(this.config.maxFailures)) {
context.failWorkflow(details, 'maximum failures reached');
return p.resolve();
}
}
//** if a fail activity was found, run it
if(activity) {
context.schedule(activity);
return p.resolve();
}
}
//** if no tasks have been completed yet, schedule the first activity for execution
if(!history.hasCompletedActivity()) {
var activity = this.tasks[0];
context.schedule(activity);
return p.resolve();
}
//** before we potentially schedule another activity, we need to evaluate if the previous resulted in a timeout that caused our threshold to be exceeded; this prevents tasks doomed to fail, from looping indefinitely
var activityTimeouts = history.eventsByType('ActivityTaskTimedOut');
if(activityTimeouts.length >= config.maxActivityTimeouts)
context.failWorkflow('Max ActivityTaskTimedOut events encountered');
//** get the last completed activity, extract the result data. by deciding what task to run based on the last *completed* task,
//** that means we will always be running the correct next task, regardless if a thousand failed iterations of the next task ran before this decision
if(lastCompleted)
data = lastCompleted.args().result;
//** 3) see if the last step's data indicates the next step
if(!context.decided() && data.next) {
var nextStep = _.find(this.tasks, function(act) {
return act.name == data.next;
});
//** if we found the step by name, schedule it to be run
nextStep && context.schedule(nextStep);
}
//** 4) if we haven't decided yet...
if(!context.decided()) {
//** see if the last step's data indicates the workflow is complete
if (!!data.workflowComplete)
context.completeWorkflow(data);
//** otherwise, this could mean we're stuck; no decision has been made, the "next" step couldn't be easily determined; find out
else {
//** see if we're in a "timeout loop", where a decision can't be made, and its continually rescheduling a decision
var decisionTimeouts = history.eventsByType('DecisionTaskTimedOut');
//** if we've exceeded the max timeouts, fail the workflow
if(decisionTimeouts.length >= config.maxDecisionTimeouts)
context.failWorkflow('Max DecisionTaskTimedOut events encountered');
}
}
//** 5) let the workflow itself evaluate these decisions and provide any modifications
this.onEvaluate && this.onEvaluate(context);
//** 6) finally, let any consumers evaluate the context and decisions
lib.emit('workflow:evaluate', this, context);
p.resolve();
},
getTask: function(name) {
return _.find(this.tasks, function(act) { return act.name == name; });
},
//** returns the next step, given a tasks name
getNextTask: function(name) {
var nextIdx;
_.each(this.tasks, function(obj, idx) {
if(obj.name == name)
nextIdx = idx+1;
});
if(!nextIdx) return;
nextIdx >= this.tasks.length && (nextIdx = this.tasks.length - 1);
return this.tasks[nextIdx];
},
runTask: function(name, context) {
var def = Q.defer(),
prm = def.promise;
//** get a reference to the workflows handler for this task
var activityHandler = this.handlers[name];
//** ensure there's a handler for this workflow activity
if(!activityHandler)
def.reject('There is no handler available for the activity: '+ this.name +'/'+ name);
//** trigger the handler; if it returns a promise, this is an async operation...handle it accordingly. otherwise,
//** it is synchronous, and we resolve() it immediately; any errors will bubble up to the parent catch()
lib.emit('activity:run', this, name);
var promise = activityHandler(context);
!!promise
? promise.then(def.resolve, def.reject)
: def.resolve();
return prm;
}
};
//** if the default task list was provided by the workflow, but as a string, convert it to an object
var dfltTaskList = workflowObj.swf.defaultTaskList;
typeof(dfltTaskList) == 'string' && (workflowObj.swf.defaultTaskList = { name: dfltTaskList });
//** parse the tasks defined as activityType objects
workflowObj.tasks = _.map(workflowObj.tasks||[], function(obj) {
obj.workflow = workflowObj;
//** if the task hasn't specified a default task list, use the taskList from the workflow, if defined, falling back on the configured default task list
if(!obj.defaultTaskList)
obj.defaultTaskList = workflowObj.swf.defaultTaskList;
return this.activity.define(obj.name, obj);
}.bind(this));
_workflows[name] = workflowObj;
return workflowObj;
},
exists: function(name, version) {
return this.svc.describeWorkflowType({
domain: this.swfDomain,
workflowType: {
name: name,
version: version||'1.0'
}
});
},
create: function(name, version, opts) {
opts = opts||{};
opts.name = name;
!!version && (opts.version = version);
return this.svc.registerWorkflowType(opts);
},
load: function(workflowId, runId) {
return this.svc.describeWorkflowExecution({
domain: this.swfDomain,
execution: {
runId: runId,
workflowId: workflowId
}
});
},
execute: function(name, version, data, opts) {
//** when firing off multiple workflows, using Date.now() as the unique identifier, its not uncommon to trigger an exception related
//** to using the same workflowId twice (WorkflowExecutionAlreadyStartedFault), so add a simple bit of randomness to it
var rnd = (Math.random().toFixed(5)*10000).toFixed(0);
//** provide the default options for starting a workflow, if not specified
opts = _.defaults(opts||{}, {
domain: this.swfDomain,
taskList: this.defaultTaskList,
workflowId: name +'-'+ Date.now() + rnd,
workflowType: {
name: name,
version: version||'1.0'
}
});
//** serialize the data, send the request to execute the workflow
!!data && typeof(data) === 'object' && (opts.input = JSON.stringify(data));
this.emit('workflow:start', opts);
return this.svc.startWorkflowExecution(opts);
}
};
var activity = {
/**
* @class activity
*/
defaults: function(opts) {
return (opts = _.defaults({}, opts||{}, {
domain: this.swfDomain,
version: '1.0',
defaultTaskStartToCloseTimeout: '30',
defaultTaskHeartbeatTimeout: '30',
defaultTaskScheduleToStartTimeout: 'NONE', //** this indicates how long tasks can wait to be scheduled; defaulting to unlimited
defaultTaskScheduleToCloseTimeout: 'NONE' //** this indicates how long tasks can exist period; defaulting to unlimited
}));
},
/**
* http://docs.aws.amazon.com/amazonswf/latest/apireference/API_RegisterActivityType.html
* http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SWF.html#registerActivityType-property
*/
define: function(name, opts) {
var obj = _.extend(this.activity.defaults(opts), {
name: name,
verify: function() {
var def = Q.defer();
//** see if the activity type exists already, with this name/version
this.activity.exists(obj.name, obj.version)
.then(def.resolve)
.catch(function() {
//** clone the options and remove the workflow field
var data = _.clone(opts);
delete data['workflow'];
//** create it otherwise
this.emit('activity:create', obj);
this.activity.create(data).then(def.resolve, def.reject);
}.bind(this));
return def.promise;
}.bind(this)
});
return obj;
},
exists: function(name, version) {
return this.svc.describeActivityType({
domain: this.swfDomain,
activityType: {
name: name,
version: version||'1.0'
}
});
},
create: function(opts) {
opt = this.activity.defaults(opts);
return this.svc.registerActivityType(opt);
},
complete: function(taskToken, result) {
return this.svc.respondActivityTaskCompleted({ taskToken: taskToken, result: result });
},
cancel: function(taskToken, details) {
return this.svc.respondActivityTaskCancelled({ taskToken: taskToken, details: details });
},
fail: function(taskToken, details, reason) {
return this.svc.respondActivityTaskFailed({ taskToken: taskToken, details: details, reason: reason });
},
startChildWorkflow: function(name, data, opts) {
//** provide the default options for starting a workflow, if not specified
opts = _.defaults(opts||{}, {
workflowId: name +'-'+ Date.now(),
workflowType: {
name: name,
version: '1.0'
}
});
//** serialize the data, send the decision to start the child workflow
!!data && typeof(data) === 'object' && (opts.input = JSON.stringify(data));
return this.svc.respondActivity(opts);
}
};
var poll = {
/**
* @class poll
*/
//** opts: maximumPageSize, <add more>
decision: function(opts) {
typeof(opts) == 'string' && (opts = { taskList: { name: opts }});
opts = _.defaults(opts||{}, {
domain: this.swfDomain,
taskList: this.defaultTaskList
});
function handleTask(data) {
if(!!data.taskToken) {
//** get a execution context, grabbing the ref to the workflow object we're executing
var decision = new decisionContext(data, this),
lib = this;
//** fire a general decision event for receiving the task
this.emit('decision:receive', decision);
//** make sure we've loaded the full event history for this workflow...in the future this could be optional
decision.loadFullHistory().then(function() {
var flow = decision.workflow,
def = Q.defer(),
prm = def.promise;
//** let the workflow definition evaluate the context and decide on the next action
flow.evaluate(def, decision);
//** if a decision has been made, send it
prm.then(function () {
if (decision.decided()) {
lib.svc.respondDecisionTaskCompleted({
taskToken: decision.context.taskToken,
decisions: decision.decisions
});
}
//** fire a general decision event
lib.emit('decision:complete', decision);
//** fire events to consumer based on the workflows outcome
if(decision.isWorkflowComplete())
lib.emit('workflow:complete', decision);
else if(decision.isWorkflowFailed())
lib.emit('workflow:fail', decision);
else if(decision.isWorkflowCancelled())
lib.emit('workflow:cancel', decision);
});
})
//** report any errors
.catch(this.emit.bind(lib, 'decision:error', decision));
}
//** continue polling...always polling
setTimeout(this.poll.decision.bind(this, opts), 0);
}
this.emit('poll:decider', opts);
this.svc.pollForDecisionTask(opts).done(handleTask.bind(this));
return this;
},
activity: function(opts) {
typeof(opts) == 'string' && (opts = { taskList: { name: opts }});
opts = _.defaults(opts||{}, {
domain: this.swfDomain,
taskList: this.defaultTaskList
});
function handleTask(data) {
if(!!data.taskToken) {
//** get a execution context, grabbing the ref to the workflow object we're executing
var activity = new activityContext(data, this);
//** fire a general decision event for receiving the task
this.emit('activity:receive', activity);
//** run the activity via its parent workflow
activity.workflow.runTask(activity.context.activityType.name, activity)
.then(done.bind(this, true))
.catch(done.bind(this, false));
function done(success) {
this.emit('activity:'+ (!!success?'success':'fail'), activity);
}
//** if we do nothing, it will time out and run the task again...
}
setTimeout(this.poll.activity.bind(this, opts), 0);
}
this.emit('poll:worker', opts);
this.svc.pollForActivityTask(opts).done(handleTask.bind(this));
return this;
}
};
var decisions = {
/**
* provides methods to generate the args for each of the decisions a decider can respond with, in their most minimal form; see
* the docs for more info:
* http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SWF.html#respondDecisionTaskCompleted-property
* and
* http://docs.aws.amazon.com/amazonswf/latest/apireference/API_RespondDecisionTaskCompleted.html
* and (best)
* http://docs.aws.amazon.com/amazonswf/latest/apireference/API_Decision.html
*
* @class decisions
*/
scheduleActivityTask: function(name, version, id, opt) {
return {
decisionType: 'ScheduleActivityTask',
scheduleActivityTaskDecisionAttributes: _.assign((opt=opt||{}), {
activityId: opt.activityId || (id || name + '-' + Date.now()),
activityType: opt.activityType || {
name: name,
version: version || '1.0'
},
input: typeof(opt.input) === 'string' && opt.input || JSON.stringify(opt.input||{})
})
};
},
completeWorkflow: function(result) {
result = result||{};
typeof(result) == 'object' && (result = JSON.stringify(result));
return {
decisionType: 'CompleteWorkflowExecution',
completeWorkflowExecutionDecisionAttributes: { result: result }
}
},
failWorkflow: function(details, reason) {
details = details||{};
typeof(details) == 'object' && (details = JSON.stringify(details));
return {
decisionType: 'FailWorkflowExecution',
failWorkflowExecutionDecisionAttributes: { details: details, reason: reason }
}
},
cancelWorkflow: function(details) {
details = details||{};
typeof(details) == 'object' && (details = JSON.stringify(details));
return {
decisionType: 'CancelWorkflowExecution',
cancelWorkflowExecutionDecisionAttributes: { details: details }
}
}
};
function decisionContext(data, lib) {
function loadHistory(nextPageToken) {
var started = this.history.workflowStartedActivity(),
taskList = {},
def = Q.defer();
//** find the tasklist from the workflow execution started event
if(!!started)
taskList = started.args().taskList;
lib.svc.pollForDecisionTask({
domain: lib.swfDomain,
taskList: taskList,
nextPageToken: nextPageToken
})
.then(function(res) {
//** add the history events
res = res||{};
this.history.addEvents(res.events||[]);
//** if there is a next page token, keep following the token...otherwise, resolve the promise, indicating history is "good"
!!res.nextPageToken
? loadHistory.call(this, res.nextPageToken).then(def.resolve)
: def.resolve();
}.bind(this))
.catch(def.reject);
return def.promise;
}
_.extend(this, {
//** provide a reference to the workflow being executed, along with an eventHistory collection for access events
context: data,
lib: lib,
decisions: [],
workflow: data.workflowType && _workflows[data.workflowType.name],
history: new eventHistory(data.events),
loadFullHistory: function() {
var def = Q.defer();
!!data.nextPageToken
? loadHistory.call(this, data.nextPageToken).then(def.resolve)
: def.resolve();
return def.promise;
}
});
//** a decision is always based on a workflow, so make sure we've been able to dereference the workflow requested
if(!this.workflow)
throw new Error('The decision context doesnt have a valid workflow');
//** get the last scheduled activity, last completed activity, and the activity for when the workflow started
var current = this.history.lastScheduledActivity(),
completed = this.history.lastCompletedActivity(),
start = this.history.workflowStartedActivity();
//** create an aggregate data object for this decision, based on the data passed to the tasks/workflow
this.data = _.assign(
{ workflow: this.workflow.name },
start && start.args().input||{},
completed && completed.args().result||{},
current && current.args().input||{}
);
};
_.extend(decisionContext.prototype, {
decided: function() { return this.decisions.length > 0; },
//** a helper to determine if there's a decision in the queue for completing the workflow
isWorkflowComplete: function() {
return !!_.find(this.decisions, function(dec) { return dec.decisionType == 'CompleteWorkflowExecution' });
},
isWorkflowFailed: function() {
return !!_.find(this.decisions, function(dec) { return dec.decisionType == 'FailWorkflowExecution' });
},
isWorkflowCancelled: function() {
return !!_.find(this.decisions, function(dec) { return dec.decisionType == 'CancelWorkflowExecution' });
},
//** for scheduling an activity task using the activity object from the workflow
schedule: function(activity, opts) {
opts = opts||{};
var taskList = opts.taskList || activity.defaultTaskList;
_.defaults(opts, {
//** use the task list for the workflow, if none specified specifically at the task level
taskList: taskList || this.workflow.swf.defaultTaskList,
//** if input was provided for the activity, combine it with the existing data context
input: _.assign(this.data, opts.input||{})
});
this.decisions.push(decisions.scheduleActivityTask(activity.name, activity.version, null, opts));
},
//** for scheduling an activity task by name/version; this method enforces the version passed by setting it on the activity
scheduleActivity: function(name, version, opts) {
var activity = _.clone(this.workflow.getTask('name'));
activity.version = version||'1.0';
this.schedule(activity, opts);
},
//** queue a complete workflow decision, with the given result; if an object, it will be serialized to json
completeWorkflow: function(result) {
this.decisions.push(decisions.completeWorkflow(result));
},
failWorkflow: function(details, reason) {
this.decisions.push(decisions.failWorkflow(details, reason));
},
cancelWorkflow: function(details) {
this.decisions.push(decisions.cancelWorkflow(details));
}
});
function activityContext(data, lib) {
this._defer = Q.defer();
this.lib = lib;
this.context = data;
this.data = {};
//** try to deserialize the input as a json message
try {
data.input && (this.data = JSON.parse(data.input));
} catch(e) {}
//** if this task's data carries the name of the workflow, try and get the actual workflow reference for the context
if(!!this.data.workflow)
this.workflow = _workflows[this.data.workflow];
//** an activity is always based on a workflow, so make sure we've been able to dereference the workflow requested
if(!this.workflow)
throw new Error('The activity context doesnt have a valid workflow');
};
_.extend(activityContext.prototype, {
//** return .async() from handler methods if you want them to be run asynchronously using a promise...this just returns the promise for this response
async: function() { return this._defer.promise; },
//** accepts a result as a string or an object. if the result is a string, it is assumed to be the next steps name. this allows
//** an easy way to indicate to the decider what the next step should be.
complete: function(result, nextStep) {
result = result||{};
//** if the result is a string, and the nextStep isn't defined, assume it to be the name of the next step
if(typeof(result) == 'string' && !nextStep)
result = { next: result };
else
!!nextStep && (result.next = nextStep);
//** if we weren't able to determine the next step, get the next step in order from the workflow
if(!result.next) {
var next = this.workflow.getNextTask(this.context.activityType.name);
if(next)
result.next = next.name;
}
//** we resolve/reject this responses promise for any consumers of the handler task that was run for this execution
var prm = this.lib.activity.complete(this.context.taskToken, JSON.stringify(result));
prm.then(this._defer.resolve, this._defer.reject);
return prm;
},
fail: function(details, reason) {
//** allow details to be an object, but pass a string to the api. if no reason is provided, assume details are the "reason"
details = details||{};
if(typeof(details) == 'string') {
if(!reason) {
reason = details;
details = {};
} else
details = { next: details };
}
var prm = this.lib.activity.fail(this.context.taskToken, JSON.stringify(details), reason);
prm.then(this._defer.resolve, this._defer.reject);
return prm;
},
cancel: function(details) {
//** allow details to be an object, but pass a string to the api
typeof(details) == 'object' && (details = JSON.stringify(details));
var prm = this.lib.activity.cancel(this.context.taskToken, details);
prm.then(this._defer.resolve, this._defer.reject);
return prm;
},
startChildWorkflow: function(name, data, opts) {
var prm = this.lib.activity.startChildWorkflow(name, data, opts);
prm.then(this._defer.resolve, this._defer.reject);
return prm;
},
completeWorkflow: function(result) {
result = result||{};
//** if the result is a string, do not assume it is serialized, pass it as the result
if(typeof(result) == 'string')
result = { result: result };
//** indicate the workflow is complete
result.workflowComplete = true;
var prm = this.lib.activity.complete(this.context.taskToken, JSON.stringify(result));
prm.then(this._defer.resolve, this._defer.reject);
return prm;
},
failWorkflow: function(details, reason) {
details = details||{};
if(typeof(details) === 'string') {
reason = details;
details = {};
}
//** indicate the workflow has failed, before failing the task
details.workflowFailed = true;
return this.fail(details, reason);
},
cancelWorkflow: function(details) {
//** indicate the workflow has been cancelled
details = details||{};
details.workflowCancelled = true;
return this.cancel(details);
}
});
/**
* an event history collection object; wraps the events for an execution context, providing some helpers
*/
function eventHistory(events, opts) {
this.events = events||[];
this.options = opts||{};
this.sorted = this.sortBy(function(evt) { return evt.eventTimestamp });
}
//** add some helpers to the eventHistory courtesy of lodash
['contains', 'each', 'find', 'filter', 'map', 'reduce', 'sortBy', 'where'].forEach(function(key) {
eventHistory.prototype[key] = function() {
var args = [this.events].concat(_.toArray(arguments));
return _[key].apply(_, args);
}
});
//** add some additional helpers to the eventHistory
_.assign(eventHistory.prototype, {
current: function() { return this.wrapEvent(this.sorted[this.sorted.length > 0 && this.sorted.length - 1 || 0]); },
previous: function() { return this.wrapEvent(this.sorted[this.sorted.length - (this.sorted.length >= 2 ? 2 : 1)]); },
addEvents: function(events) {
!Array.isArray(events) && (events = [events]);
this.events = this.events.concat(events);
this.sorted = this.sortBy(function(evt) { return evt.eventTimestamp });
},
workflowStartedActivity: function() {
return this.eventsByType('WorkflowExecutionStarted').pop();
},
lastActivity: function() {
return this.eventsByType('ActivityTaskStarted').pop();
},
lastScheduledActivity: function() {
return this.eventsByType('ActivityTaskScheduled').pop();
},
lastCompletedActivity: function() {
return this.eventsByType('ActivityTaskCompleted').pop();
},
lastFailedActivity: function() {
return this.eventsByType('ActivityTaskFailed').pop();
},
//** returns a filtered listed of the event history based on event type
eventsByType: function(type) {
return this.filter(function(evt) {
if(evt.eventType.toLowerCase() == (type||'').toLowerCase())
return !!this.wrapEvent(evt);
}.bind(this));
},
//** is this the first decision we're making for this particular execution of this workflow
isFirstDecision: function() {
var evt = this.eventsByType('DecisionTaskStarted');
return !!evt.length && this.events.length <= 3;
},
hasRunActivity: function() {
return !!this.lastScheduledActivity();
},
hasCompletedActivity: function() {
return !!this.lastCompletedActivity();
},
wrapEvent: function(evt) {
if(!!evt.args) return evt;
//** wraps and extends the event object with helpers
_.assign(evt, {
//** provides easy access to the event args. they are commonly stored as <EventTypeName>EventAttributes
args: function() {
var name = evt.eventType[0].toLowerCase() + evt.eventType.slice(1);
return this[name +'EventAttributes'] || {};
}
});
//** try to parse the fields that may hold json data
var args = evt.args();
try {
if(args.input && typeof(args.input) == 'string')
args.input = JSON.parse(args.input);
if(args.details && typeof(args.details) == 'string')
args.details = JSON.parse(args.details);
if(args.result && typeof(args.result) == 'string')
args.result = JSON.parse(args.result);
} catch(e) {}
return evt;
}
});
var workflo = module.exports = function(opt) {
events.EventEmitter.call(this);
//** proxy the options unchanged to the aws-sns sdk for creation
this.swf = new aws.SWF((opt = opt || {}));
this.swfDomain = opt.domain;
this.svc = {};
this.defaultTaskList = (typeof(opt.defaultTaskList) === 'string' ? { name: opt.defaultTaskList } : opt.defaultTaskList);
//** if a string was provided for the default task list, convert it to an object; this is how the swf api expects it
if(this.defaultTaskList == 'string')
this.defaultTaskList = { name: this.defaultTaskList };
//** create a curried version of each swf sdk api function, introducing a promise interface, hoisting it to a service object
_.each(this.swf.constructor.prototype, function (fn, key) {
if (typeof(fn) !== 'function' || key == 'constructor') return;
this.svc[key] = Q.nbind(fn, this.swf);
}.bind(this));
var scope = function (ctx, fn, key) {
ctx[key] = fn.bind(this);
return ctx;
}.bind(this);
//** scope each of the individual service libs
this.workflow = _.reduce(workflow, scope, {});
this.activity = _.reduce(activity, scope, {});
this.poll = _.reduce(poll, scope, {});
this.decisions = _.reduce(decisions, scope, {});
//** simple helper function to execute a workflow, using the syntax: workflo.run('some-test-workflow')
this.run = function (name, data, taskList, opts) {
opts = opts || {};
var def = Q.defer();
//** get the workflow we're trying to run
var wkflow = _workflows[name];
if(!wkflow) {
def.reject('Could not find the target workflow: '+ name);
} else {
//** use the version of the workflow we're running (in case multiple versions exist in swf)
var version = opts.version || wkflow.swf.version,
taskList = (typeof(taskList) === 'string' ? { name: taskList } : taskList) || wkflow.swf.defaultTaskList;
//** use the default tasklist for workflo if none specified for the target workflow, or method invocation
if(!taskList) taskList = this.defaultTaskList;
!!taskList && (opts.taskList = taskList);
//** execute the tasklist
this.workflow.execute(name, version, data, opts).done();
}
return def.promise;
}.bind(this);
this.define = function(name, opts) {
//** see if the workflow already exists
if(!!_workflows[name])
return;
return this.workflow.define(name, opts);
}
this.get = function(name) { return _workflows[name] }
//** a helper to asynchronously verify all the workflows and their tasks with SWF
this.verifyWorkflows = function() {
var def = Q.defer();
//** call the verify() method of each workflow, waiting for them all to finish verifying before continuing
var actions = _.map(_workflows, function(obj) { return obj.verify(); });
Q.all(actions)
.then(def.resolve)
.catch(def.reject);
return def.promise;
}
};
util.inherits(workflo, events.EventEmitter);