forked from uber-go/cadence-client
/
internal_task_handlers.go
1764 lines (1539 loc) · 59.1 KB
/
internal_task_handlers.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 internal
// All code in this file is private to the package.
import (
"bytes"
"context"
"errors"
"fmt"
"math"
"reflect"
"strings"
"sync"
"time"
"github.com/opentracing/opentracing-go"
"go.uber.org/cadence/.gen/go/cadence/workflowserviceclient"
s "go.uber.org/cadence/.gen/go/shared"
"go.uber.org/cadence/internal/common"
"go.uber.org/cadence/internal/common/backoff"
"go.uber.org/cadence/internal/common/cache"
"go.uber.org/cadence/internal/common/metrics"
"go.uber.org/cadence/internal/common/util"
"go.uber.org/zap"
)
const (
defaultHeartBeatIntervalInSec = 10 * 60
defaultStickyCacheSize = 10000
noRetryBackoff = time.Duration(-1)
)
type (
// workflowExecutionEventHandler process a single event.
workflowExecutionEventHandler interface {
// Process a single event and return the assosciated decisions.
// Return List of decisions made, any error.
ProcessEvent(event *s.HistoryEvent, isReplay bool, isLast bool) error
// ProcessQuery process a query request.
ProcessQuery(queryType string, queryArgs []byte) ([]byte, error)
StackTrace() string
// Close for cleaning up resources on this event handler
Close()
}
// workflowTask wraps a decision task.
workflowTask struct {
task *s.PollForDecisionTaskResponse
historyIterator HistoryIterator
doneCh chan struct{}
laResultCh chan *localActivityResult
}
// activityTask wraps a activity task.
activityTask struct {
task *s.PollForActivityTaskResponse
pollStartTime time.Time
}
// resetStickinessTask wraps a ResetStickyTaskListRequest.
resetStickinessTask struct {
task *s.ResetStickyTaskListRequest
}
// workflowExecutionContextImpl is the cached workflow state for sticky execution
workflowExecutionContextImpl struct {
mutex sync.Mutex
workflowStartTime time.Time
workflowInfo *WorkflowInfo
wth *workflowTaskHandlerImpl
eventHandler *workflowExecutionEventHandlerImpl
isWorkflowCompleted bool
result []byte
err error
previousStartedEventID int64
newDecisions []*s.Decision
currentDecisionTask *s.PollForDecisionTaskResponse
laTunnel *localActivityTunnel
decisionStartTime time.Time
}
// workflowTaskHandlerImpl is the implementation of WorkflowTaskHandler
workflowTaskHandlerImpl struct {
domain string
metricsScope *metrics.TaggedScope
ppMgr pressurePointMgr
logger *zap.Logger
identity string
enableLoggingInReplay bool
disableStickyExecution bool
hostEnv *hostEnvImpl
laTunnel *localActivityTunnel
nonDeterministicWorkflowPolicy NonDeterministicWorkflowPolicy
dataConverter DataConverter
contextPropagators []ContextPropagator
tracer opentracing.Tracer
}
activityProvider func(name string) activity
// activityTaskHandlerImpl is the implementation of ActivityTaskHandler
activityTaskHandlerImpl struct {
taskListName string
identity string
service workflowserviceclient.Interface
metricsScope *metrics.TaggedScope
logger *zap.Logger
userContext context.Context
hostEnv *hostEnvImpl
activityProvider activityProvider
dataConverter DataConverter
workerStopCh <-chan struct{}
contextPropagators []ContextPropagator
tracer opentracing.Tracer
}
// history wrapper method to help information about events.
history struct {
workflowTask *workflowTask
eventsHandler *workflowExecutionEventHandlerImpl
loadedEvents []*s.HistoryEvent
currentIndex int
next []*s.HistoryEvent
}
decisionHeartbeatError struct {
Message string
}
)
func newHistory(task *workflowTask, eventsHandler *workflowExecutionEventHandlerImpl) *history {
result := &history{
workflowTask: task,
eventsHandler: eventsHandler,
loadedEvents: task.task.History.Events,
currentIndex: 0,
}
return result
}
func (e decisionHeartbeatError) Error() string {
return e.Message
}
// Get workflow start event.
func (eh *history) GetWorkflowStartedEvent() (*s.HistoryEvent, error) {
events := eh.workflowTask.task.History.Events
if len(events) == 0 || events[0].GetEventType() != s.EventTypeWorkflowExecutionStarted {
return nil, errors.New("unable to find WorkflowExecutionStartedEventAttributes in the history")
}
return events[0], nil
}
func (eh *history) IsReplayEvent(event *s.HistoryEvent) bool {
return event.GetEventId() <= eh.workflowTask.task.GetPreviousStartedEventId() || isDecisionEvent(event.GetEventType())
}
func (eh *history) IsNextDecisionFailed() (bool, error) {
nextIndex := eh.currentIndex + 1
if nextIndex >= len(eh.loadedEvents) && eh.hasMoreEvents() { // current page ends and there is more pages
if err := eh.loadMoreEvents(); err != nil {
return false, err
}
}
if nextIndex < len(eh.loadedEvents) {
nextEventType := eh.loadedEvents[nextIndex].GetEventType()
isFailed := nextEventType == s.EventTypeDecisionTaskTimedOut || nextEventType == s.EventTypeDecisionTaskFailed
return isFailed, nil
}
return false, nil
}
func (eh *history) loadMoreEvents() error {
historyPage, err := eh.getMoreEvents()
if err != nil {
return err
}
eh.loadedEvents = append(eh.loadedEvents, historyPage.Events...)
return nil
}
func isDecisionEvent(eventType s.EventType) bool {
switch eventType {
case s.EventTypeWorkflowExecutionCompleted,
s.EventTypeWorkflowExecutionFailed,
s.EventTypeWorkflowExecutionCanceled,
s.EventTypeWorkflowExecutionContinuedAsNew,
s.EventTypeActivityTaskScheduled,
s.EventTypeActivityTaskCancelRequested,
s.EventTypeTimerStarted,
s.EventTypeTimerCanceled,
s.EventTypeCancelTimerFailed,
s.EventTypeMarkerRecorded,
s.EventTypeStartChildWorkflowExecutionInitiated,
s.EventTypeRequestCancelExternalWorkflowExecutionInitiated,
s.EventTypeSignalExternalWorkflowExecutionInitiated,
s.EventTypeUpsertWorkflowSearchAttributes:
return true
default:
return false
}
}
// NextDecisionEvents returns events that there processed as new by the next decision.
func (eh *history) NextDecisionEvents() (result []*s.HistoryEvent, markers []*s.HistoryEvent, err error) {
if eh.next == nil {
eh.next, _, err = eh.nextDecisionEvents()
if err != nil {
return result, markers, err
}
}
result = eh.next
if len(result) > 0 {
eh.next, markers, err = eh.nextDecisionEvents()
}
return result, markers, err
}
func (eh *history) hasMoreEvents() bool {
historyIterator := eh.workflowTask.historyIterator
return historyIterator != nil && historyIterator.HasNextPage()
}
func (eh *history) getMoreEvents() (*s.History, error) {
return eh.workflowTask.historyIterator.GetNextPage()
}
func (eh *history) nextDecisionEvents() (nextEvents []*s.HistoryEvent, markers []*s.HistoryEvent, err error) {
if eh.currentIndex == len(eh.loadedEvents) && !eh.hasMoreEvents() {
return []*s.HistoryEvent{}, []*s.HistoryEvent{}, nil
}
// Process events
OrderEvents:
for {
// load more history events if needed
for eh.currentIndex == len(eh.loadedEvents) {
if !eh.hasMoreEvents() {
break OrderEvents
}
if err1 := eh.loadMoreEvents(); err1 != nil {
err = err1
return
}
}
event := eh.loadedEvents[eh.currentIndex]
switch event.GetEventType() {
case s.EventTypeDecisionTaskStarted:
isFailed, err1 := eh.IsNextDecisionFailed()
if err1 != nil {
err = err1
return
}
if !isFailed {
eh.currentIndex++
nextEvents = append(nextEvents, event)
break OrderEvents
}
case s.EventTypeDecisionTaskCompleted,
s.EventTypeDecisionTaskScheduled,
s.EventTypeDecisionTaskTimedOut,
s.EventTypeDecisionTaskFailed:
// Skip
default:
if isPreloadMarkerEvent(event) {
markers = append(markers, event)
}
nextEvents = append(nextEvents, event)
}
eh.currentIndex++
}
// shrink loaded events so it can be GCed
eh.loadedEvents = eh.loadedEvents[eh.currentIndex:]
eh.currentIndex = 0
return nextEvents, markers, nil
}
func isPreloadMarkerEvent(event *s.HistoryEvent) bool {
return event.GetEventType() == s.EventTypeMarkerRecorded
}
// newWorkflowTaskHandler returns an implementation of workflow task handler.
func newWorkflowTaskHandler(
domain string,
params workerExecutionParameters,
ppMgr pressurePointMgr,
hostEnv *hostEnvImpl,
) WorkflowTaskHandler {
ensureRequiredParams(¶ms)
return &workflowTaskHandlerImpl{
domain: domain,
logger: params.Logger,
ppMgr: ppMgr,
metricsScope: metrics.NewTaggedScope(params.MetricsScope),
identity: params.Identity,
enableLoggingInReplay: params.EnableLoggingInReplay,
disableStickyExecution: params.DisableStickyExecution,
hostEnv: hostEnv,
nonDeterministicWorkflowPolicy: params.NonDeterministicWorkflowPolicy,
dataConverter: params.DataConverter,
contextPropagators: params.ContextPropagators,
tracer: params.Tracer,
}
}
// TODO: need a better eviction policy based on memory usage
var workflowCache cache.Cache
var stickyCacheSize = defaultStickyCacheSize
var initCacheOnce sync.Once
var stickyCacheLock sync.Mutex
// SetStickyWorkflowCacheSize sets the cache size for sticky workflow cache. Sticky workflow execution is the affinity
// between decision tasks of a specific workflow execution to a specific worker. The affinity is set if sticky execution
// is enabled via Worker.Options (It is enabled by default unless disabled explicitly). The benefit of sticky execution
// is that workflow does not have to reconstruct the state by replaying from beginning of history events. But the cost
// is it consumes more memory as it rely on caching workflow execution's running state on the worker. The cache is shared
// between workers running within same process. This must be called before any worker is started. If not called, the
// default size of 10K (might change in future) will be used.
func SetStickyWorkflowCacheSize(cacheSize int) {
stickyCacheLock.Lock()
defer stickyCacheLock.Unlock()
if workflowCache != nil {
panic("cache already created, please set cache size before worker starts.")
}
stickyCacheSize = cacheSize
}
func getWorkflowCache() cache.Cache {
initCacheOnce.Do(func() {
stickyCacheLock.Lock()
defer stickyCacheLock.Unlock()
workflowCache = cache.New(stickyCacheSize, &cache.Options{
RemovedFunc: func(cachedEntity interface{}) {
wc := cachedEntity.(*workflowExecutionContextImpl)
wc.onEviction()
},
})
})
return workflowCache
}
func getWorkflowContext(runID string) *workflowExecutionContextImpl {
o := getWorkflowCache().Get(runID)
if o == nil {
return nil
}
wc := o.(*workflowExecutionContextImpl)
return wc
}
func putWorkflowContext(runID string, wc *workflowExecutionContextImpl) (*workflowExecutionContextImpl, error) {
existing, err := getWorkflowCache().PutIfNotExist(runID, wc)
if err != nil {
return nil, err
}
return existing.(*workflowExecutionContextImpl), nil
}
func removeWorkflowContext(runID string) {
getWorkflowCache().Delete(runID)
}
func (w *workflowExecutionContextImpl) Lock() {
w.mutex.Lock()
}
func (w *workflowExecutionContextImpl) Unlock(err error) {
if err != nil || w.err != nil || w.isWorkflowCompleted || (w.wth.disableStickyExecution && !w.hasPendingLocalActivityWork()) {
// TODO: in case of closed, it asumes the close decision always succeed. need server side change to return
// error to indicate the close failure case. This should be rear case. For now, always remove the cache, and
// if the close decision failed, the next decision will have to rebuild the state.
if getWorkflowCache().Exist(w.workflowInfo.WorkflowExecution.RunID) {
removeWorkflowContext(w.workflowInfo.WorkflowExecution.RunID)
} else {
// sticky is disabled, manually clear the workflow state.
w.clearState()
}
}
w.mutex.Unlock()
}
func (w *workflowExecutionContextImpl) completeWorkflow(result []byte, err error) {
w.isWorkflowCompleted = true
w.result = result
w.err = err
}
func (w *workflowExecutionContextImpl) shouldResetStickyOnEviction() bool {
// Not all evictions from the cache warrant a call to the server
// to reset stickiness.
// Cases when this is redundant or unnecessary include
// when an error was encountered during execution
// or workflow simply completed successfully.
return w.err == nil && !w.isWorkflowCompleted
}
func (w *workflowExecutionContextImpl) onEviction() {
// onEviction is run by LRU cache's removeFunc in separate goroutinue
w.mutex.Lock()
// Queue a ResetStickiness request *BEFORE* calling clearState
// because once destroyed, no sensible information
// may be ascertained about the execution context's state,
// nor should any of its methods be invoked.
if w.shouldResetStickyOnEviction() {
w.queueResetStickinessTask()
}
w.clearState()
w.mutex.Unlock()
}
func (w *workflowExecutionContextImpl) IsDestroyed() bool {
return w.eventHandler == nil
}
func (w *workflowExecutionContextImpl) queueResetStickinessTask() {
var task resetStickinessTask
task.task = &s.ResetStickyTaskListRequest{
Domain: common.StringPtr(w.workflowInfo.Domain),
Execution: &s.WorkflowExecution{
WorkflowId: common.StringPtr(w.workflowInfo.WorkflowExecution.ID),
RunId: common.StringPtr(w.workflowInfo.WorkflowExecution.RunID),
},
}
// w.laTunnel could be nil for worker.ReplayHistory() because there is no worker started, in that case we don't
// care about resetStickinessTask.
if w.laTunnel != nil && w.laTunnel.resultCh != nil {
w.laTunnel.resultCh <- &task
}
}
func (w *workflowExecutionContextImpl) clearState() {
w.clearCurrentTask()
w.isWorkflowCompleted = false
w.result = nil
w.err = nil
w.previousStartedEventID = 0
w.newDecisions = nil
if w.eventHandler != nil {
// Set isReplay to true to prevent user code in defer guarded by !isReplaying() from running
w.eventHandler.isReplay = true
w.eventHandler.Close()
w.eventHandler = nil
}
}
func (w *workflowExecutionContextImpl) createEventHandler() {
w.clearState()
w.eventHandler = newWorkflowExecutionEventHandler(
w.workflowInfo,
w.completeWorkflow,
w.wth.logger,
w.wth.enableLoggingInReplay,
w.wth.metricsScope,
w.wth.hostEnv,
w.wth.dataConverter,
w.wth.contextPropagators,
w.wth.tracer,
).(*workflowExecutionEventHandlerImpl)
}
func resetHistory(task *s.PollForDecisionTaskResponse, historyIterator HistoryIterator) (*s.History, error) {
historyIterator.Reset()
firstPageHistory, err := historyIterator.GetNextPage()
if err != nil {
return nil, err
}
task.History = firstPageHistory
return firstPageHistory, nil
}
func (wth *workflowTaskHandlerImpl) createWorkflowContext(task *s.PollForDecisionTaskResponse) (*workflowExecutionContextImpl, error) {
h := task.History
attributes := h.Events[0].WorkflowExecutionStartedEventAttributes
if attributes == nil {
return nil, errors.New("first history event is not WorkflowExecutionStarted")
}
taskList := attributes.TaskList
if taskList == nil {
return nil, errors.New("nil TaskList in WorkflowExecutionStarted event")
}
runID := task.WorkflowExecution.GetRunId()
workflowID := task.WorkflowExecution.GetWorkflowId()
// Setup workflow Info
var parentWorkflowExecution *WorkflowExecution
if attributes.ParentWorkflowExecution != nil {
parentWorkflowExecution = &WorkflowExecution{
ID: attributes.ParentWorkflowExecution.GetWorkflowId(),
RunID: attributes.ParentWorkflowExecution.GetRunId(),
}
}
workflowInfo := &WorkflowInfo{
WorkflowExecution: WorkflowExecution{
ID: workflowID,
RunID: runID,
},
WorkflowType: flowWorkflowTypeFrom(*task.WorkflowType),
TaskListName: taskList.GetName(),
ExecutionStartToCloseTimeoutSeconds: attributes.GetExecutionStartToCloseTimeoutSeconds(),
TaskStartToCloseTimeoutSeconds: attributes.GetTaskStartToCloseTimeoutSeconds(),
Domain: wth.domain,
Attempt: attributes.GetAttempt(),
lastCompletionResult: attributes.LastCompletionResult,
CronSchedule: attributes.CronSchedule,
ContinuedExecutionRunID: attributes.ContinuedExecutionRunId,
ParentWorkflowDomain: attributes.ParentWorkflowDomain,
ParentWorkflowExecution: parentWorkflowExecution,
Memo: attributes.Memo,
SearchAttributes: attributes.SearchAttributes,
}
wfStartTime := time.Unix(0, h.Events[0].GetTimestamp())
workflowContext := &workflowExecutionContextImpl{workflowStartTime: wfStartTime, workflowInfo: workflowInfo, wth: wth}
workflowContext.createEventHandler()
return workflowContext, nil
}
func (wth *workflowTaskHandlerImpl) getOrCreateWorkflowContext(
task *s.PollForDecisionTaskResponse,
historyIterator HistoryIterator,
) (workflowContext *workflowExecutionContextImpl, err error) {
metricsScope := wth.metricsScope.GetTaggedScope(tagWorkflowType, task.WorkflowType.GetName())
defer func() {
if err == nil && workflowContext != nil && workflowContext.laTunnel == nil {
workflowContext.laTunnel = wth.laTunnel
}
metricsScope.Gauge(metrics.StickyCacheSize).Update(float64(getWorkflowCache().Size()))
}()
runID := task.WorkflowExecution.GetRunId()
history := task.History
isFullHistory := isFullHistory(history)
workflowContext = nil
if task.Query == nil || (task.Query != nil && !isFullHistory) {
workflowContext = getWorkflowContext(runID)
}
if workflowContext != nil {
workflowContext.Lock()
if task.Query != nil && !isFullHistory {
// query task and we have a valid cached state
metricsScope.Counter(metrics.StickyCacheHit).Inc(1)
} else if history.Events[0].GetEventId() == workflowContext.previousStartedEventID+1 {
// non query task and we have a valid cached state
metricsScope.Counter(metrics.StickyCacheHit).Inc(1)
} else {
// non query task and cached state is missing events, we need to discard the cached state and rebuild one.
workflowContext.ResetIfStale(task, historyIterator)
}
} else {
if !isFullHistory {
// we are getting partial history task, but cached state was already evicted.
// we need to reset history so we get events from beginning to replay/rebuild the state
metricsScope.Counter(metrics.StickyCacheMiss).Inc(1)
if history, err = resetHistory(task, historyIterator); err != nil {
return
}
}
if workflowContext, err = wth.createWorkflowContext(task); err != nil {
return
}
if !wth.disableStickyExecution && task.Query == nil {
workflowContext, _ = putWorkflowContext(runID, workflowContext)
}
workflowContext.Lock()
}
err = workflowContext.resetStateIfDestroyed(task, historyIterator)
if err != nil {
workflowContext.Unlock(err)
}
return
}
func isFullHistory(history *s.History) bool {
if len(history.Events) == 0 || history.Events[0].GetEventType() != s.EventTypeWorkflowExecutionStarted {
return false
}
return true
}
func (w *workflowExecutionContextImpl) resetStateIfDestroyed(task *s.PollForDecisionTaskResponse, historyIterator HistoryIterator) error {
// It is possible that 2 threads (one for decision task and one for query task) that both are getting this same
// cached workflowContext. If one task finished with err, it would destroy the cached state. In that case, the
// second task needs to reset the cache state and start from beginning of the history.
if w.IsDestroyed() {
w.createEventHandler()
// reset history events if necessary
if !isFullHistory(task.History) {
if _, err := resetHistory(task, historyIterator); err != nil {
return err
}
}
}
return nil
}
// ProcessWorkflowTask processes all the events of the workflow task.
func (wth *workflowTaskHandlerImpl) ProcessWorkflowTask(
workflowTask *workflowTask,
heartbeatFunc decisionHeartbeatFunc,
) (completeRequest interface{}, errRet error) {
if workflowTask == nil || workflowTask.task == nil {
return nil, errors.New("nil workflow task provided")
}
task := workflowTask.task
if task.History == nil || len(task.History.Events) == 0 {
task.History = &s.History{
Events: []*s.HistoryEvent{},
}
}
if task.Query == nil && len(task.History.Events) == 0 {
return nil, errors.New("nil or empty history")
}
runID := task.WorkflowExecution.GetRunId()
workflowID := task.WorkflowExecution.GetWorkflowId()
traceLog(func() {
wth.logger.Debug("Processing new workflow task.",
zap.String(tagWorkflowType, task.WorkflowType.GetName()),
zap.String(tagWorkflowID, workflowID),
zap.String(tagRunID, runID),
zap.Int64("PreviousStartedEventId", task.GetPreviousStartedEventId()))
})
workflowContext, err := wth.getOrCreateWorkflowContext(task, workflowTask.historyIterator)
if err != nil {
return nil, err
}
defer func() {
workflowContext.Unlock(errRet)
}()
var response interface{}
process_Workflow_Loop:
for {
startTime := time.Now()
response, err = workflowContext.ProcessWorkflowTask(workflowTask)
if err == nil && response == nil {
wait_LocalActivity_Loop:
for {
deadlineToTrigger := time.Duration(float32(ratioToForceCompleteDecisionTaskComplete) * float32(workflowContext.GetDecisionTimeout()))
delayDuration := startTime.Add(deadlineToTrigger).Sub(time.Now())
select {
case <-time.After(delayDuration):
// force complete, call the decision heartbeat function
workflowTask, err = heartbeatFunc(
workflowContext.CompleteDecisionTask(workflowTask, false),
startTime,
)
if err != nil {
return nil, &decisionHeartbeatError{Message: fmt.Sprintf("error sending decision heartbeat %v", err)}
}
if workflowTask == nil {
return nil, nil
}
continue process_Workflow_Loop
case lar := <-workflowTask.laResultCh:
// local activity result ready
response, err = workflowContext.ProcessLocalActivityResult(workflowTask, lar)
if err == nil && response == nil {
// decision task is not done yet, still waiting for more local activities
continue wait_LocalActivity_Loop
}
break process_Workflow_Loop
}
}
} else {
break process_Workflow_Loop
}
}
return response, err
}
func (w *workflowExecutionContextImpl) ProcessWorkflowTask(workflowTask *workflowTask) (interface{}, error) {
task := workflowTask.task
historyIterator := workflowTask.historyIterator
if err := w.ResetIfStale(task, historyIterator); err != nil {
return nil, err
}
w.SetCurrentTask(task)
eventHandler := w.eventHandler
reorderedHistory := newHistory(workflowTask, eventHandler)
var replayDecisions []*s.Decision
var respondEvents []*s.HistoryEvent
skipReplayCheck := w.skipReplayCheck()
// Process events
ProcessEvents:
for {
reorderedEvents, markers, err := reorderedHistory.NextDecisionEvents()
if err != nil {
return nil, err
}
if len(reorderedEvents) == 0 {
break ProcessEvents
}
// Markers are from the events that are produced from the current decision
for _, m := range markers {
if m.MarkerRecordedEventAttributes.GetMarkerName() != localActivityMarkerName {
// local activity marker needs to be applied after decision task started event
err := eventHandler.ProcessEvent(m, true, false)
if err != nil {
return nil, err
}
if w.isWorkflowCompleted {
break ProcessEvents
}
}
}
for i, event := range reorderedEvents {
isInReplay := reorderedHistory.IsReplayEvent(event)
isLast := !isInReplay && i == len(reorderedEvents)-1
if !skipReplayCheck && isDecisionEvent(event.GetEventType()) {
respondEvents = append(respondEvents, event)
}
if isPreloadMarkerEvent(event) {
// marker events are processed separately
continue
}
// Any pressure points.
err := w.wth.executeAnyPressurePoints(event, isInReplay)
if err != nil {
return nil, err
}
err = eventHandler.ProcessEvent(event, isInReplay, isLast)
if err != nil {
return nil, err
}
if w.isWorkflowCompleted {
break ProcessEvents
}
}
// now apply local activity markers
for _, m := range markers {
if m.MarkerRecordedEventAttributes.GetMarkerName() == localActivityMarkerName {
err := eventHandler.ProcessEvent(m, true, false)
if err != nil {
return nil, err
}
if w.isWorkflowCompleted {
break ProcessEvents
}
}
}
isReplay := len(reorderedEvents) > 0 && reorderedHistory.IsReplayEvent(reorderedEvents[len(reorderedEvents)-1])
if isReplay {
eventDecisions := eventHandler.decisionsHelper.getDecisions(true)
if len(eventDecisions) > 0 && !skipReplayCheck {
replayDecisions = append(replayDecisions, eventDecisions...)
}
}
}
// Non-deterministic error could happen in 2 different places:
// 1) the replay decisions does not match to history events. This is usually due to non backwards compatible code
// change to decider logic. For example, change calling one activity to a different activity.
// 2) the decision state machine is trying to make illegal state transition while replay a history event (like
// activity task completed), but the corresponding decider code that start the event has been removed. In that case
// the replay of that event will panic on the decision state machine and the workflow will be marked as completed
// with the panic error.
var nonDeterministicErr error
if !skipReplayCheck && !w.isWorkflowCompleted {
// check if decisions from reply matches to the history events
if err := matchReplayWithHistory(replayDecisions, respondEvents); err != nil {
nonDeterministicErr = err
}
}
if nonDeterministicErr == nil && w.err != nil {
if panicErr, ok := w.err.(*PanicError); ok && panicErr.value != nil {
if _, isStateMachinePanic := panicErr.value.(stateMachineIllegalStatePanic); isStateMachinePanic {
nonDeterministicErr = panicErr
}
}
}
if nonDeterministicErr != nil {
w.wth.metricsScope.GetTaggedScope(tagWorkflowType, task.WorkflowType.GetName()).Counter(metrics.NonDeterministicError).Inc(1)
w.wth.logger.Error("non-deterministic-error",
zap.String(tagWorkflowType, task.WorkflowType.GetName()),
zap.String(tagWorkflowID, task.WorkflowExecution.GetWorkflowId()),
zap.String(tagRunID, task.WorkflowExecution.GetRunId()),
zap.Error(nonDeterministicErr))
switch w.wth.nonDeterministicWorkflowPolicy {
case NonDeterministicWorkflowPolicyFailWorkflow:
// complete workflow with custom error will fail the workflow
eventHandler.Complete(nil, NewCustomError("NonDeterministicWorkflowPolicyFailWorkflow", nonDeterministicErr.Error()))
case NonDeterministicWorkflowPolicyBlockWorkflow:
// return error here will be convert to DecisionTaskFailed for the first time, and ignored for subsequent
// attempts which will cause DecisionTaskTimeout and server will retry forever until issue got fixed or
// workflow timeout.
return nil, nonDeterministicErr
default:
panic(fmt.Sprintf("unknown mismatched workflow history policy."))
}
}
return w.CompleteDecisionTask(workflowTask, true), nil
}
func (w *workflowExecutionContextImpl) ProcessLocalActivityResult(workflowTask *workflowTask, lar *localActivityResult) (interface{}, error) {
if lar.err != nil && w.retryLocalActivity(lar) {
return nil, nil // nothing to do here as we are retrying...
}
err := w.eventHandler.ProcessLocalActivityResult(lar)
if err != nil {
return nil, err
}
return w.CompleteDecisionTask(workflowTask, true), nil
}
func (w *workflowExecutionContextImpl) retryLocalActivity(lar *localActivityResult) bool {
if lar.task.retryPolicy == nil || lar.err == nil || lar.err == ErrCanceled {
return false
}
backoff := getRetryBackoff(lar, time.Now())
if backoff > 0 && backoff <= w.GetDecisionTimeout() {
// we need a local retry
time.AfterFunc(backoff, func() {
if _, ok := w.eventHandler.pendingLaTasks[lar.task.activityID]; !ok {
return
}
lar.task.attempt++
w.laTunnel.sendTask(lar.task)
})
return true
}
// Backoff could be large and potentially much larger than DecisionTaskTimeout. We cannot just sleep locally for
// retry. Because it will delay the local activity from complete which keeps the decision task open. In order to
// keep decision task open, we have to keep "heartbeating" current decision task.
// In that case, it is more efficient to create a server timer with backoff duration and retry when that backoff
// timer fires. So here we will return false to indicate we don't need local retry anymore. However, we have to
// store the current attempt and backoff to the same LocalActivityResultMarker so the replay can do the right thing.
// The backoff timer will be created by workflow.ExecuteLocalActivity().
lar.backoff = backoff
return false
}
func getRetryBackoff(lar *localActivityResult, now time.Time) time.Duration {
p := lar.task.retryPolicy
var errReason string
if len(p.NonRetriableErrorReasons) > 0 {
if lar.err == ErrDeadlineExceeded {
errReason = "timeout:" + s.TimeoutTypeScheduleToClose.String()
} else {
errReason, _ = getErrorDetails(lar.err, nil)
}
}
return getRetryBackoffWithNowTime(p, lar.task.attempt, errReason, now, lar.task.expireTime)
}
func getRetryBackoffWithNowTime(p *RetryPolicy, attempt int32, errReason string, now, expireTime time.Time) time.Duration {
if p.MaximumAttempts == 0 && p.ExpirationInterval == 0 {
return noRetryBackoff
}
if p.MaximumAttempts > 0 && attempt > p.MaximumAttempts-1 {
return noRetryBackoff // max attempt reached
}
backoffInterval := time.Duration(float64(p.InitialInterval) * math.Pow(p.BackoffCoefficient, float64(attempt)))
if backoffInterval <= 0 {
// math.Pow() could overflow
if p.MaximumInterval > 0 {
backoffInterval = p.MaximumInterval
} else {
return noRetryBackoff
}
}
if p.MaximumInterval > 0 && backoffInterval > p.MaximumInterval {
// cap next interval to MaxInterval
backoffInterval = p.MaximumInterval
}
nextScheduleTime := now.Add(backoffInterval)
if !expireTime.IsZero() && nextScheduleTime.After(expireTime) {
return noRetryBackoff
}
// check if error is non-retriable
for _, er := range p.NonRetriableErrorReasons {
if er == errReason {
return noRetryBackoff
}
}
return backoffInterval
}
func (w *workflowExecutionContextImpl) CompleteDecisionTask(workflowTask *workflowTask, waitLocalActivities bool) interface{} {
if w.currentDecisionTask == nil {
return nil
}
// w.laTunnel could be nil for worker.ReplayHistory() because there is no worker started, in that case we don't
// care about the pending local activities, and just return because the result is ignored anyway by the caller.
if w.hasPendingLocalActivityWork() && w.laTunnel != nil {
if len(w.eventHandler.unstartedLaTasks) > 0 {
// start new local activity tasks
for activityID := range w.eventHandler.unstartedLaTasks {
task := w.eventHandler.pendingLaTasks[activityID]
task.wc = w
task.workflowTask = workflowTask
w.laTunnel.sendTask(task)
}
w.eventHandler.unstartedLaTasks = make(map[string]struct{})
}
// cannot complete decision task as there are pending local activities
if waitLocalActivities {
return nil
}
}
eventDecisions := w.eventHandler.decisionsHelper.getDecisions(true)
if len(eventDecisions) > 0 {
w.newDecisions = append(w.newDecisions, eventDecisions...)
}
completeRequest := w.wth.completeWorkflow(w.eventHandler, w.currentDecisionTask, w, w.newDecisions, !waitLocalActivities)
w.clearCurrentTask()
return completeRequest
}
func (w *workflowExecutionContextImpl) hasPendingLocalActivityWork() bool {
return !w.isWorkflowCompleted &&
w.currentDecisionTask != nil &&
w.currentDecisionTask.Query == nil && // don't run local activity for query task
w.eventHandler != nil &&
len(w.eventHandler.pendingLaTasks) > 0
}
func (w *workflowExecutionContextImpl) clearCurrentTask() {
w.newDecisions = nil
w.currentDecisionTask = nil
}
func (w *workflowExecutionContextImpl) skipReplayCheck() bool {
return w.currentDecisionTask.Query != nil || !isFullHistory(w.currentDecisionTask.History)