-
Notifications
You must be signed in to change notification settings - Fork 787
/
task_handler.go
1095 lines (967 loc) · 34.5 KB
/
task_handler.go
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
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package decision
import (
"context"
"fmt"
"github.com/pborman/uuid"
"github.com/uber/cadence/common"
"github.com/uber/cadence/common/backoff"
"github.com/uber/cadence/common/cache"
"github.com/uber/cadence/common/log"
"github.com/uber/cadence/common/log/tag"
"github.com/uber/cadence/common/metrics"
"github.com/uber/cadence/common/types"
"github.com/uber/cadence/service/history/config"
"github.com/uber/cadence/service/history/execution"
"github.com/uber/cadence/service/history/workflow"
)
const (
activityCancellationMsgActivityIDUnknown = "ACTIVITY_ID_UNKNOWN"
activityCancellationMsgActivityNotStarted = "ACTIVITY_ID_NOT_STARTED"
)
type (
attrValidationFn func() error
taskHandlerImpl struct {
identity string
decisionTaskCompletedID int64
domainEntry *cache.DomainCacheEntry
// internal state
hasUnhandledEventsBeforeDecisions bool
failDecision bool
failDecisionCause *types.DecisionTaskFailedCause
failMessage *string
activityNotStartedCancelled bool
continueAsNewBuilder execution.MutableState
stopProcessing bool // should stop processing any more decisions
mutableState execution.MutableState
// validation
attrValidator *attrValidator
sizeLimitChecker *workflowSizeChecker
tokenSerializer common.TaskTokenSerializer
logger log.Logger
domainCache cache.DomainCache
metricsClient metrics.Client
config *config.Config
activityCountToDispatch int
}
decisionResult struct {
activityDispatchInfo *types.ActivityLocalDispatchInfo
}
)
func newDecisionTaskHandler(
identity string,
decisionTaskCompletedID int64,
domainEntry *cache.DomainCacheEntry,
mutableState execution.MutableState,
attrValidator *attrValidator,
sizeLimitChecker *workflowSizeChecker,
tokenSerializer common.TaskTokenSerializer,
logger log.Logger,
domainCache cache.DomainCache,
metricsClient metrics.Client,
config *config.Config,
) *taskHandlerImpl {
return &taskHandlerImpl{
identity: identity,
decisionTaskCompletedID: decisionTaskCompletedID,
domainEntry: domainEntry,
// internal state
hasUnhandledEventsBeforeDecisions: mutableState.HasBufferedEvents(),
failDecision: false,
failDecisionCause: nil,
failMessage: nil,
activityNotStartedCancelled: false,
continueAsNewBuilder: nil,
stopProcessing: false,
mutableState: mutableState,
// validation
attrValidator: attrValidator,
sizeLimitChecker: sizeLimitChecker,
tokenSerializer: tokenSerializer,
logger: logger,
domainCache: domainCache,
metricsClient: metricsClient,
config: config,
activityCountToDispatch: config.MaxActivityCountDispatchByDomain(domainEntry.GetInfo().Name),
}
}
func (handler *taskHandlerImpl) handleDecisions(
ctx context.Context,
executionContext []byte,
decisions []*types.Decision,
) ([]*decisionResult, error) {
// overall workflow size / count check
failWorkflow, err := handler.sizeLimitChecker.failWorkflowSizeExceedsLimit()
if err != nil || failWorkflow {
return nil, err
}
var results []*decisionResult
for _, decision := range decisions {
result, err := handler.handleDecisionWithResult(ctx, decision)
if err != nil || handler.stopProcessing {
return nil, err
} else if result != nil {
results = append(results, result)
}
}
handler.mutableState.GetExecutionInfo().ExecutionContext = executionContext
return results, nil
}
func (handler *taskHandlerImpl) handleDecisionWithResult(
ctx context.Context,
decision *types.Decision,
) (*decisionResult, error) {
switch decision.GetDecisionType() {
case types.DecisionTypeScheduleActivityTask:
return handler.handleDecisionScheduleActivity(ctx, decision.ScheduleActivityTaskDecisionAttributes)
default:
return nil, handler.handleDecision(ctx, decision)
}
}
func (handler *taskHandlerImpl) handleDecision(
ctx context.Context,
decision *types.Decision,
) error {
switch decision.GetDecisionType() {
case types.DecisionTypeCompleteWorkflowExecution:
return handler.handleDecisionCompleteWorkflow(ctx, decision.CompleteWorkflowExecutionDecisionAttributes)
case types.DecisionTypeFailWorkflowExecution:
return handler.handleDecisionFailWorkflow(ctx, decision.FailWorkflowExecutionDecisionAttributes)
case types.DecisionTypeCancelWorkflowExecution:
return handler.handleDecisionCancelWorkflow(ctx, decision.CancelWorkflowExecutionDecisionAttributes)
case types.DecisionTypeStartTimer:
return handler.handleDecisionStartTimer(ctx, decision.StartTimerDecisionAttributes)
case types.DecisionTypeRequestCancelActivityTask:
return handler.handleDecisionRequestCancelActivity(ctx, decision.RequestCancelActivityTaskDecisionAttributes)
case types.DecisionTypeCancelTimer:
return handler.handleDecisionCancelTimer(ctx, decision.CancelTimerDecisionAttributes)
case types.DecisionTypeRecordMarker:
return handler.handleDecisionRecordMarker(ctx, decision.RecordMarkerDecisionAttributes)
case types.DecisionTypeRequestCancelExternalWorkflowExecution:
return handler.handleDecisionRequestCancelExternalWorkflow(ctx, decision.RequestCancelExternalWorkflowExecutionDecisionAttributes)
case types.DecisionTypeSignalExternalWorkflowExecution:
return handler.handleDecisionSignalExternalWorkflow(ctx, decision.SignalExternalWorkflowExecutionDecisionAttributes)
case types.DecisionTypeContinueAsNewWorkflowExecution:
return handler.handleDecisionContinueAsNewWorkflow(ctx, decision.ContinueAsNewWorkflowExecutionDecisionAttributes)
case types.DecisionTypeStartChildWorkflowExecution:
return handler.handleDecisionStartChildWorkflow(ctx, decision.StartChildWorkflowExecutionDecisionAttributes)
case types.DecisionTypeUpsertWorkflowSearchAttributes:
return handler.handleDecisionUpsertWorkflowSearchAttributes(ctx, decision.UpsertWorkflowSearchAttributesDecisionAttributes)
default:
return &types.BadRequestError{Message: fmt.Sprintf("Unknown decision type: %v", decision.GetDecisionType())}
}
}
func (handler *taskHandlerImpl) handleDecisionScheduleActivity(
ctx context.Context,
attr *types.ScheduleActivityTaskDecisionAttributes,
) (*decisionResult, error) {
handler.metricsClient.IncCounter(
metrics.HistoryRespondDecisionTaskCompletedScope,
metrics.DecisionTypeScheduleActivityCounter,
)
executionInfo := handler.mutableState.GetExecutionInfo()
domainID := executionInfo.DomainID
targetDomainID := domainID
if attr.GetDomain() != "" {
targetDomainEntry, err := handler.domainCache.GetDomain(attr.GetDomain())
if err != nil {
return nil, &types.InternalServiceError{
Message: fmt.Sprintf("Unable to schedule activity across domain %v.", attr.GetDomain()),
}
}
targetDomainID = targetDomainEntry.GetInfo().ID
}
if err := handler.validateDecisionAttr(
func() error {
return handler.attrValidator.validateActivityScheduleAttributes(
domainID,
targetDomainID,
attr,
executionInfo.WorkflowTimeout,
metrics.HistoryRespondDecisionTaskCompletedScope,
)
},
types.DecisionTaskFailedCauseBadScheduleActivityAttributes,
); err != nil || handler.stopProcessing {
return nil, err
}
failWorkflow, err := handler.sizeLimitChecker.failWorkflowIfBlobSizeExceedsLimit(
metrics.DecisionTypeTag(types.DecisionTypeScheduleActivityTask.String()),
attr.Input,
"ScheduleActivityTaskDecisionAttributes.Input exceeds size limit.",
)
if err != nil || failWorkflow {
handler.stopProcessing = true
return nil, err
}
event, ai, activityDispatchInfo, dispatched, started, err := handler.mutableState.AddActivityTaskScheduledEvent(
ctx, handler.decisionTaskCompletedID, attr, handler.activityCountToDispatch > 0)
if dispatched {
handler.activityCountToDispatch--
}
switch err.(type) {
case nil:
if activityDispatchInfo != nil || started {
if _, err1 := handler.mutableState.AddActivityTaskStartedEvent(ai, event.ID, uuid.New(), handler.identity); err1 != nil {
return nil, err1
}
if started {
return nil, nil
}
token := &common.TaskToken{
DomainID: executionInfo.DomainID,
WorkflowID: executionInfo.WorkflowID,
WorkflowType: executionInfo.WorkflowTypeName,
RunID: executionInfo.RunID,
ScheduleID: ai.ScheduleID,
ScheduleAttempt: 0,
ActivityID: ai.ActivityID,
ActivityType: attr.ActivityType.GetName(),
}
activityDispatchInfo.TaskToken, err = handler.tokenSerializer.Serialize(token)
if err != nil {
return nil, workflow.ErrSerializingToken
}
activityDispatchInfo.ScheduledTimestamp = common.Int64Ptr(ai.ScheduledTime.UnixNano())
activityDispatchInfo.ScheduledTimestampOfThisAttempt = common.Int64Ptr(ai.ScheduledTime.UnixNano())
activityDispatchInfo.StartedTimestamp = common.Int64Ptr(ai.StartedTime.UnixNano())
return &decisionResult{activityDispatchInfo: activityDispatchInfo}, nil
}
return nil, nil
case *types.BadRequestError:
return nil, handler.handlerFailDecision(
types.DecisionTaskFailedCauseScheduleActivityDuplicateID, "",
)
default:
return nil, err
}
}
func (handler *taskHandlerImpl) handleDecisionRequestCancelActivity(
ctx context.Context,
attr *types.RequestCancelActivityTaskDecisionAttributes,
) error {
handler.metricsClient.IncCounter(
metrics.HistoryRespondDecisionTaskCompletedScope,
metrics.DecisionTypeCancelActivityCounter,
)
if err := handler.validateDecisionAttr(
func() error {
return handler.attrValidator.validateActivityCancelAttributes(
attr,
metrics.HistoryRespondDecisionTaskCompletedScope,
handler.domainEntry.GetInfo().Name)
},
types.DecisionTaskFailedCauseBadRequestCancelActivityAttributes,
); err != nil || handler.stopProcessing {
return err
}
activityID := attr.GetActivityID()
actCancelReqEvent, ai, err := handler.mutableState.AddActivityTaskCancelRequestedEvent(
handler.decisionTaskCompletedID,
activityID,
handler.identity,
)
switch err.(type) {
case nil:
if ai.StartedID == common.EmptyEventID {
// We haven't started the activity yet, we can cancel the activity right away and
// schedule a decision task to ensure the workflow makes progress.
_, err = handler.mutableState.AddActivityTaskCanceledEvent(
ai.ScheduleID,
ai.StartedID,
actCancelReqEvent.ID,
[]byte(activityCancellationMsgActivityNotStarted),
handler.identity,
)
if err != nil {
return err
}
handler.activityNotStartedCancelled = true
}
return nil
case *types.BadRequestError:
_, err = handler.mutableState.AddRequestCancelActivityTaskFailedEvent(
handler.decisionTaskCompletedID,
activityID,
activityCancellationMsgActivityIDUnknown,
)
return err
default:
return err
}
}
func (handler *taskHandlerImpl) handleDecisionStartTimer(
ctx context.Context,
attr *types.StartTimerDecisionAttributes,
) error {
handler.metricsClient.IncCounter(
metrics.HistoryRespondDecisionTaskCompletedScope,
metrics.DecisionTypeStartTimerCounter,
)
if err := handler.validateDecisionAttr(
func() error {
return handler.attrValidator.validateTimerScheduleAttributes(
attr,
metrics.HistoryRespondDecisionTaskCompletedScope,
handler.domainEntry.GetInfo().Name)
},
types.DecisionTaskFailedCauseBadStartTimerAttributes,
); err != nil || handler.stopProcessing {
return err
}
_, _, err := handler.mutableState.AddTimerStartedEvent(handler.decisionTaskCompletedID, attr)
switch err.(type) {
case nil:
return nil
case *types.BadRequestError:
return handler.handlerFailDecision(
types.DecisionTaskFailedCauseStartTimerDuplicateID, "",
)
default:
return err
}
}
func (handler *taskHandlerImpl) handleDecisionCompleteWorkflow(
ctx context.Context,
attr *types.CompleteWorkflowExecutionDecisionAttributes,
) error {
handler.metricsClient.IncCounter(
metrics.HistoryRespondDecisionTaskCompletedScope,
metrics.DecisionTypeCompleteWorkflowCounter,
)
if handler.hasUnhandledEventsBeforeDecisions {
return handler.handlerFailDecision(
types.DecisionTaskFailedCauseUnhandledDecision,
"cannot complete workflow, new pending decisions were scheduled while this decision was processing",
)
}
if err := handler.validateDecisionAttr(
func() error {
return handler.attrValidator.validateCompleteWorkflowExecutionAttributes(attr)
},
types.DecisionTaskFailedCauseBadCompleteWorkflowExecutionAttributes,
); err != nil || handler.stopProcessing {
return err
}
failWorkflow, err := handler.sizeLimitChecker.failWorkflowIfBlobSizeExceedsLimit(
metrics.DecisionTypeTag(types.DecisionTypeCompleteWorkflowExecution.String()),
attr.Result,
"CompleteWorkflowExecutionDecisionAttributes.Result exceeds size limit.",
)
if err != nil || failWorkflow {
handler.stopProcessing = true
return err
}
// If the decision has more than one completion event than just pick the first one
if !handler.mutableState.IsWorkflowExecutionRunning() {
handler.metricsClient.IncCounter(
metrics.HistoryRespondDecisionTaskCompletedScope,
metrics.MultipleCompletionDecisionsCounter,
)
handler.logger.Warn(
"Multiple completion decisions",
tag.WorkflowDecisionType(int64(types.DecisionTypeCompleteWorkflowExecution)),
tag.ErrorTypeMultipleCompletionDecisions,
)
return nil
}
// event ID is not relevant
isCanceled, _ := handler.mutableState.IsCancelRequested()
// check if this is a cron workflow
cronBackoff, err := handler.mutableState.GetCronBackoffDuration(ctx)
if err != nil {
handler.stopProcessing = true
return err
}
if isCanceled || cronBackoff == backoff.NoBackoff {
// canceled or not cron, so complete this workflow execution
if _, err := handler.mutableState.AddCompletedWorkflowEvent(handler.decisionTaskCompletedID, attr); err != nil {
return &types.InternalServiceError{Message: "Unable to add complete workflow event."}
}
return nil
}
// this is a cron workflow
startEvent, err := handler.mutableState.GetStartEvent(ctx)
if err != nil {
return err
}
startAttributes := startEvent.WorkflowExecutionStartedEventAttributes
return handler.retryCronContinueAsNew(
ctx,
startAttributes,
int32(cronBackoff.Seconds()),
types.ContinueAsNewInitiatorCronSchedule.Ptr(),
nil,
nil,
attr.Result,
)
}
func (handler *taskHandlerImpl) handleDecisionFailWorkflow(
ctx context.Context,
attr *types.FailWorkflowExecutionDecisionAttributes,
) error {
handler.metricsClient.IncCounter(
metrics.HistoryRespondDecisionTaskCompletedScope,
metrics.DecisionTypeFailWorkflowCounter,
)
if handler.hasUnhandledEventsBeforeDecisions {
return handler.handlerFailDecision(
types.DecisionTaskFailedCauseUnhandledDecision,
"cannot complete workflow, new pending decisions were scheduled while this decision was processing",
)
}
if err := handler.validateDecisionAttr(
func() error {
return handler.attrValidator.validateFailWorkflowExecutionAttributes(attr)
},
types.DecisionTaskFailedCauseBadFailWorkflowExecutionAttributes,
); err != nil || handler.stopProcessing {
return err
}
failWorkflow, err := handler.sizeLimitChecker.failWorkflowIfBlobSizeExceedsLimit(
metrics.DecisionTypeTag(types.DecisionTypeFailWorkflowExecution.String()),
attr.Details,
"FailWorkflowExecutionDecisionAttributes.Details exceeds size limit.",
)
if err != nil || failWorkflow {
handler.stopProcessing = true
return err
}
// If the decision has more than one completion event than just pick the first one
if !handler.mutableState.IsWorkflowExecutionRunning() {
handler.metricsClient.IncCounter(
metrics.HistoryRespondDecisionTaskCompletedScope,
metrics.MultipleCompletionDecisionsCounter,
)
handler.logger.Warn(
"Multiple completion decisions",
tag.WorkflowDecisionType(int64(types.DecisionTypeFailWorkflowExecution)),
tag.ErrorTypeMultipleCompletionDecisions,
)
return nil
}
if is, _ := handler.mutableState.IsCancelRequested(); is {
// cancellation must be sticky, as it's telling things to stop.
// this is particularly important for child workflows, as if they restart themselves after the parent
// cancels its context, there is no way for the parent to cancel the new run.
cancelAttrs := types.CancelWorkflowExecutionDecisionAttributes{
// TODO: serialize reason somehow, may deserve a new field / wrapped errors
Details: attr.Details,
}
if _, err := handler.mutableState.AddWorkflowExecutionCanceledEvent(handler.decisionTaskCompletedID, &cancelAttrs); err != nil {
return err
}
return nil
}
// below will check whether to do continue as new based on backoff & backoff or cron
backoffInterval := handler.mutableState.GetRetryBackoffDuration(attr.GetReason())
continueAsNewInitiator := types.ContinueAsNewInitiatorRetryPolicy
// first check the backoff retry
if backoffInterval == backoff.NoBackoff {
// if no backoff retry, set the backoffInterval using cron schedule
backoffInterval, err = handler.mutableState.GetCronBackoffDuration(ctx)
if err != nil {
handler.stopProcessing = true
return err
}
continueAsNewInitiator = types.ContinueAsNewInitiatorCronSchedule
}
// second check the backoff / cron schedule
if backoffInterval == backoff.NoBackoff {
// no retry or cron
if _, err := handler.mutableState.AddFailWorkflowEvent(handler.decisionTaskCompletedID, attr); err != nil {
return err
}
return nil
}
// this is a cron / backoff workflow
startEvent, err := handler.mutableState.GetStartEvent(ctx)
if err != nil {
return err
}
startAttributes := startEvent.WorkflowExecutionStartedEventAttributes
return handler.retryCronContinueAsNew(
ctx,
startAttributes,
int32(backoffInterval.Seconds()),
continueAsNewInitiator.Ptr(),
attr.Reason,
attr.Details,
startAttributes.LastCompletionResult,
)
}
func (handler *taskHandlerImpl) handleDecisionCancelTimer(
ctx context.Context,
attr *types.CancelTimerDecisionAttributes,
) error {
handler.metricsClient.IncCounter(
metrics.HistoryRespondDecisionTaskCompletedScope,
metrics.DecisionTypeCancelTimerCounter,
)
if err := handler.validateDecisionAttr(
func() error {
return handler.attrValidator.validateTimerCancelAttributes(
attr,
metrics.HistoryRespondDecisionTaskCompletedScope,
handler.domainEntry.GetInfo().Name)
},
types.DecisionTaskFailedCauseBadCancelTimerAttributes,
); err != nil || handler.stopProcessing {
return err
}
_, err := handler.mutableState.AddTimerCanceledEvent(
handler.decisionTaskCompletedID,
attr,
handler.identity)
switch err.(type) {
case nil:
// timer deletion is a success, we may have deleted a fired timer in
// which case we should reset hasBufferedEvents
// TODO deletion of timer fired event refreshing hasUnhandledEventsBeforeDecisions
// is not entirely correct, since during these decisions processing, new event may appear
handler.hasUnhandledEventsBeforeDecisions = handler.mutableState.HasBufferedEvents()
return nil
case *types.BadRequestError:
_, err = handler.mutableState.AddCancelTimerFailedEvent(
handler.decisionTaskCompletedID,
attr,
handler.identity,
)
return err
default:
return err
}
}
func (handler *taskHandlerImpl) handleDecisionCancelWorkflow(
ctx context.Context,
attr *types.CancelWorkflowExecutionDecisionAttributes,
) error {
handler.metricsClient.IncCounter(metrics.HistoryRespondDecisionTaskCompletedScope,
metrics.DecisionTypeCancelWorkflowCounter)
if handler.hasUnhandledEventsBeforeDecisions {
return handler.handlerFailDecision(
types.DecisionTaskFailedCauseUnhandledDecision,
"cannot process cancellation, new pending decisions were scheduled while this decision was processing",
)
}
if err := handler.validateDecisionAttr(
func() error {
return handler.attrValidator.validateCancelWorkflowExecutionAttributes(attr)
},
types.DecisionTaskFailedCauseBadCancelWorkflowExecutionAttributes,
); err != nil || handler.stopProcessing {
return err
}
// If the decision has more than one completion event than just pick the first one
if !handler.mutableState.IsWorkflowExecutionRunning() {
handler.metricsClient.IncCounter(
metrics.HistoryRespondDecisionTaskCompletedScope,
metrics.MultipleCompletionDecisionsCounter,
)
handler.logger.Warn(
"Multiple completion decisions",
tag.WorkflowDecisionType(int64(types.DecisionTypeCancelWorkflowExecution)),
tag.ErrorTypeMultipleCompletionDecisions,
)
return nil
}
_, err := handler.mutableState.AddWorkflowExecutionCanceledEvent(handler.decisionTaskCompletedID, attr)
return err
}
func (handler *taskHandlerImpl) handleDecisionRequestCancelExternalWorkflow(
ctx context.Context,
attr *types.RequestCancelExternalWorkflowExecutionDecisionAttributes,
) error {
handler.metricsClient.IncCounter(
metrics.HistoryRespondDecisionTaskCompletedScope,
metrics.DecisionTypeCancelExternalWorkflowCounter,
)
executionInfo := handler.mutableState.GetExecutionInfo()
domainID := executionInfo.DomainID
targetDomainID := domainID
if attr.GetDomain() != "" {
targetDomainEntry, err := handler.domainCache.GetDomain(attr.GetDomain())
if err != nil {
return &types.InternalServiceError{
Message: fmt.Sprintf("Unable to cancel workflow across domain: %v.", attr.GetDomain()),
}
}
targetDomainID = targetDomainEntry.GetInfo().ID
}
if err := handler.validateDecisionAttr(
func() error {
return handler.attrValidator.validateCancelExternalWorkflowExecutionAttributes(
domainID,
targetDomainID,
attr,
metrics.HistoryRespondDecisionTaskCompletedScope,
)
},
types.DecisionTaskFailedCauseBadRequestCancelExternalWorkflowExecutionAttributes,
); err != nil || handler.stopProcessing {
return err
}
cancelRequestID := uuid.New()
_, _, err := handler.mutableState.AddRequestCancelExternalWorkflowExecutionInitiatedEvent(
handler.decisionTaskCompletedID, cancelRequestID, attr,
)
return err
}
func (handler *taskHandlerImpl) handleDecisionRecordMarker(
ctx context.Context,
attr *types.RecordMarkerDecisionAttributes,
) error {
handler.metricsClient.IncCounter(
metrics.HistoryRespondDecisionTaskCompletedScope,
metrics.DecisionTypeRecordMarkerCounter,
)
if err := handler.validateDecisionAttr(
func() error {
return handler.attrValidator.validateRecordMarkerAttributes(
attr,
metrics.HistoryRespondDecisionTaskCompletedScope,
handler.domainEntry.GetInfo().Name)
},
types.DecisionTaskFailedCauseBadRecordMarkerAttributes,
); err != nil || handler.stopProcessing {
return err
}
failWorkflow, err := handler.sizeLimitChecker.failWorkflowIfBlobSizeExceedsLimit(
metrics.DecisionTypeTag(types.DecisionTypeRecordMarker.String()),
attr.Details,
"RecordMarkerDecisionAttributes.Details exceeds size limit.",
)
if err != nil || failWorkflow {
handler.stopProcessing = true
return err
}
_, err = handler.mutableState.AddRecordMarkerEvent(handler.decisionTaskCompletedID, attr)
return err
}
func (handler *taskHandlerImpl) handleDecisionContinueAsNewWorkflow(
ctx context.Context,
attr *types.ContinueAsNewWorkflowExecutionDecisionAttributes,
) error {
handler.metricsClient.IncCounter(
metrics.HistoryRespondDecisionTaskCompletedScope,
metrics.DecisionTypeContinueAsNewCounter,
)
if handler.hasUnhandledEventsBeforeDecisions {
return handler.handlerFailDecision(
types.DecisionTaskFailedCauseUnhandledDecision,
"cannot complete workflow, new pending decisions were scheduled while this decision was processing",
)
}
executionInfo := handler.mutableState.GetExecutionInfo()
if err := handler.validateDecisionAttr(
func() error {
return handler.attrValidator.validateContinueAsNewWorkflowExecutionAttributes(
attr,
executionInfo,
metrics.HistoryRespondDecisionTaskCompletedScope,
handler.domainEntry.GetInfo().Name,
)
},
types.DecisionTaskFailedCauseBadContinueAsNewAttributes,
); err != nil || handler.stopProcessing {
return err
}
failWorkflow, err := handler.sizeLimitChecker.failWorkflowIfBlobSizeExceedsLimit(
metrics.DecisionTypeTag(types.DecisionTypeContinueAsNewWorkflowExecution.String()),
attr.Input,
"ContinueAsNewWorkflowExecutionDecisionAttributes. Input exceeds size limit.",
)
if err != nil || failWorkflow {
handler.stopProcessing = true
return err
}
// If the decision has more than one completion event than just pick the first one
if !handler.mutableState.IsWorkflowExecutionRunning() {
handler.metricsClient.IncCounter(
metrics.HistoryRespondDecisionTaskCompletedScope,
metrics.MultipleCompletionDecisionsCounter,
)
handler.logger.Warn(
"Multiple completion decisions",
tag.WorkflowDecisionType(int64(types.DecisionTypeContinueAsNewWorkflowExecution)),
tag.ErrorTypeMultipleCompletionDecisions,
)
return nil
}
if is, _ := handler.mutableState.IsCancelRequested(); is {
// cancellation must be sticky, as it's telling things to stop.
// this is particularly important for child workflows, as if they restart themselves after the parent
// cancels its context, there is no way for the parent to cancel the new run.
cancelAttrs := types.CancelWorkflowExecutionDecisionAttributes{
Details: nil, // TODO: serialize continue-as-new data somehow, may deserve a new field
}
if _, err := handler.mutableState.AddWorkflowExecutionCanceledEvent(handler.decisionTaskCompletedID, &cancelAttrs); err != nil {
return err
}
return nil
}
// Extract parentDomainName so it can be passed down to next run of workflow execution
var parentDomainName string
if handler.mutableState.HasParentExecution() {
parentDomainID := executionInfo.ParentDomainID
parentDomainName, err = handler.domainCache.GetDomainName(parentDomainID)
if err != nil {
return err
}
}
_, newStateBuilder, err := handler.mutableState.AddContinueAsNewEvent(
ctx,
handler.decisionTaskCompletedID,
handler.decisionTaskCompletedID,
parentDomainName,
attr,
)
if err != nil {
return err
}
handler.continueAsNewBuilder = newStateBuilder
return nil
}
func (handler *taskHandlerImpl) handleDecisionStartChildWorkflow(
ctx context.Context,
attr *types.StartChildWorkflowExecutionDecisionAttributes,
) error {
handler.metricsClient.IncCounter(
metrics.HistoryRespondDecisionTaskCompletedScope,
metrics.DecisionTypeChildWorkflowCounter,
)
executionInfo := handler.mutableState.GetExecutionInfo()
domainID := executionInfo.DomainID
targetDomainID := domainID
if attr.GetDomain() != "" {
targetDomainEntry, err := handler.domainCache.GetDomain(attr.GetDomain())
if err != nil {
return &types.InternalServiceError{
Message: fmt.Sprintf("Unable to schedule child execution across domain %v.", attr.GetDomain()),
}
}
targetDomainID = targetDomainEntry.GetInfo().ID
}
if err := handler.validateDecisionAttr(
func() error {
return handler.attrValidator.validateStartChildExecutionAttributes(
domainID,
targetDomainID,
attr,
executionInfo,
metrics.HistoryRespondDecisionTaskCompletedScope,
)
},
types.DecisionTaskFailedCauseBadStartChildExecutionAttributes,
); err != nil || handler.stopProcessing {
return err
}
failWorkflow, err := handler.sizeLimitChecker.failWorkflowIfBlobSizeExceedsLimit(
metrics.DecisionTypeTag(types.DecisionTypeStartChildWorkflowExecution.String()),
attr.Input,
"StartChildWorkflowExecutionDecisionAttributes.Input exceeds size limit.",
)
if err != nil || failWorkflow {
handler.stopProcessing = true
return err
}
enabled := handler.config.EnableParentClosePolicy(handler.domainEntry.GetInfo().Name)
if attr.ParentClosePolicy == nil {
// for old clients, this field is empty. If they enable the feature, make default as terminate
if enabled {
attr.ParentClosePolicy = types.ParentClosePolicyTerminate.Ptr()
} else {
attr.ParentClosePolicy = types.ParentClosePolicyAbandon.Ptr()
}
} else {
// for domains that haven't enabled the feature yet, need to use Abandon for backward-compatibility
if !enabled {
attr.ParentClosePolicy = types.ParentClosePolicyAbandon.Ptr()
}
}
requestID := uuid.New()
_, _, err = handler.mutableState.AddStartChildWorkflowExecutionInitiatedEvent(
handler.decisionTaskCompletedID, requestID, attr,
)
return err
}
func (handler *taskHandlerImpl) handleDecisionSignalExternalWorkflow(
ctx context.Context,
attr *types.SignalExternalWorkflowExecutionDecisionAttributes,
) error {
handler.metricsClient.IncCounter(
metrics.HistoryRespondDecisionTaskCompletedScope,
metrics.DecisionTypeSignalExternalWorkflowCounter,
)
executionInfo := handler.mutableState.GetExecutionInfo()
domainID := executionInfo.DomainID
targetDomainID := domainID
if attr.GetDomain() != "" {
targetDomainEntry, err := handler.domainCache.GetDomain(attr.GetDomain())
if err != nil {
return &types.InternalServiceError{
Message: fmt.Sprintf("Unable to signal workflow across domain: %v.", attr.GetDomain()),
}
}
targetDomainID = targetDomainEntry.GetInfo().ID
}
if err := handler.validateDecisionAttr(
func() error {
return handler.attrValidator.validateSignalExternalWorkflowExecutionAttributes(
domainID,
targetDomainID,
attr,
metrics.HistoryRespondDecisionTaskCompletedScope,
)
},
types.DecisionTaskFailedCauseBadSignalWorkflowExecutionAttributes,
); err != nil || handler.stopProcessing {
return err
}
failWorkflow, err := handler.sizeLimitChecker.failWorkflowIfBlobSizeExceedsLimit(
metrics.DecisionTypeTag(types.DecisionTypeSignalExternalWorkflowExecution.String()),
attr.Input,
"SignalExternalWorkflowExecutionDecisionAttributes.Input exceeds size limit.",
)
if err != nil || failWorkflow {
handler.stopProcessing = true
return err
}
signalRequestID := uuid.New() // for deduplicate
_, _, err = handler.mutableState.AddSignalExternalWorkflowExecutionInitiatedEvent(
handler.decisionTaskCompletedID, signalRequestID, attr,
)
return err
}
func (handler *taskHandlerImpl) handleDecisionUpsertWorkflowSearchAttributes(
ctx context.Context,
attr *types.UpsertWorkflowSearchAttributesDecisionAttributes,
) error {
handler.metricsClient.IncCounter(
metrics.HistoryRespondDecisionTaskCompletedScope,
metrics.DecisionTypeUpsertWorkflowSearchAttributesCounter,
)
// get domain name
executionInfo := handler.mutableState.GetExecutionInfo()
domainID := executionInfo.DomainID
domainName, err := handler.domainCache.GetDomainName(domainID)
if err != nil {
return &types.InternalServiceError{
Message: fmt.Sprintf("Unable to get domain for domainID: %v.", domainID),
}
}
// valid search attributes for upsert
if err := handler.validateDecisionAttr(
func() error {
return handler.attrValidator.validateUpsertWorkflowSearchAttributes(
domainName,
attr,
)
},
types.DecisionTaskFailedCauseBadSearchAttributes,
); err != nil || handler.stopProcessing {
return err
}