/
historyEngine.go
2317 lines (2018 loc) · 81.1 KB
/
historyEngine.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 history
import (
ctx "context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/pborman/uuid"
h "github.com/uber/cadence/.gen/go/history"
workflow "github.com/uber/cadence/.gen/go/shared"
hc "github.com/uber/cadence/client/history"
"github.com/uber/cadence/client/matching"
"github.com/uber/cadence/common"
"github.com/uber/cadence/common/cache"
"github.com/uber/cadence/common/clock"
"github.com/uber/cadence/common/cluster"
"github.com/uber/cadence/common/definition"
ce "github.com/uber/cadence/common/errors"
"github.com/uber/cadence/common/log"
"github.com/uber/cadence/common/log/tag"
"github.com/uber/cadence/common/messaging"
"github.com/uber/cadence/common/metrics"
"github.com/uber/cadence/common/persistence"
warchiver "github.com/uber/cadence/service/worker/archiver"
"go.uber.org/cadence/.gen/go/cadence/workflowserviceclient"
)
const (
conditionalRetryCount = 5
activityCancellationMsgActivityIDUnknown = "ACTIVITY_ID_UNKNOWN"
activityCancellationMsgActivityNotStarted = "ACTIVITY_ID_NOT_STARTED"
timerCancellationMsgTimerIDUnknown = "TIMER_ID_UNKNOWN"
)
type (
historyEngineImpl struct {
currentClusterName string
shard ShardContext
timeSource clock.TimeSource
decisionHandler decisionHandler
clusterMetadata cluster.Metadata
historyMgr persistence.HistoryManager
historyV2Mgr persistence.HistoryV2Manager
executionManager persistence.ExecutionManager
visibilityMgr persistence.VisibilityManager
txProcessor transferQueueProcessor
timerProcessor timerQueueProcessor
taskAllocator taskAllocator
replicator *historyReplicator
replicatorProcessor queueProcessor
historyEventNotifier historyEventNotifier
tokenSerializer common.TaskTokenSerializer
historyCache *historyCache
metricsClient metrics.Client
logger log.Logger
throttledLogger log.Logger
config *Config
archivalClient warchiver.Client
resetor workflowResetor
}
)
var _ Engine = (*historyEngineImpl)(nil)
var (
// ErrTaskDiscarded is the error indicating that the timer / transfer task is pending for too long and discarded.
ErrTaskDiscarded = errors.New("passive task pending for too long")
// ErrTaskRetry is the error indicating that the timer / transfer task should be retried.
ErrTaskRetry = errors.New("passive task should retry due to condition in mutable state is not met")
// ErrDuplicate is exported temporarily for integration test
ErrDuplicate = errors.New("Duplicate task, completing it")
// ErrConflict is exported temporarily for integration test
ErrConflict = errors.New("Conditional update failed")
// ErrMaxAttemptsExceeded is exported temporarily for integration test
ErrMaxAttemptsExceeded = errors.New("Maximum attempts exceeded to update history")
// ErrStaleState is the error returned during state update indicating that cached mutable state could be stale
ErrStaleState = errors.New("Cache mutable state could potentially be stale")
// ErrActivityTaskNotFound is the error to indicate activity task could be duplicate and activity already completed
ErrActivityTaskNotFound = &workflow.EntityNotExistsError{Message: "Activity task not found."}
// ErrWorkflowCompleted is the error to indicate workflow execution already completed
ErrWorkflowCompleted = &workflow.EntityNotExistsError{Message: "Workflow execution already completed."}
// ErrWorkflowParent is the error to parent execution is given and mismatch
ErrWorkflowParent = &workflow.EntityNotExistsError{Message: "Workflow parent does not match."}
// ErrDeserializingToken is the error to indicate task token is invalid
ErrDeserializingToken = &workflow.BadRequestError{Message: "Error deserializing task token."}
// ErrSignalOverSize is the error to indicate signal input size is > 256K
ErrSignalOverSize = &workflow.BadRequestError{Message: "Signal input size is over 256K."}
// ErrCancellationAlreadyRequested is the error indicating cancellation for target workflow is already requested
ErrCancellationAlreadyRequested = &workflow.CancellationAlreadyRequestedError{Message: "Cancellation already requested for this workflow execution."}
// ErrSignalsLimitExceeded is the error indicating limit reached for maximum number of signal events
ErrSignalsLimitExceeded = &workflow.LimitExceededError{Message: "Exceeded workflow execution limit for signal events"}
// ErrEventsAterWorkflowFinish is the error indicating server error trying to write events after workflow finish event
ErrEventsAterWorkflowFinish = &workflow.InternalServiceError{Message: "error validating last event being workflow finish event."}
// FailedWorkflowCloseState is a set of failed workflow close states, used for start workflow policy
// for start workflow execution API
FailedWorkflowCloseState = map[int]bool{
persistence.WorkflowCloseStatusFailed: true,
persistence.WorkflowCloseStatusCanceled: true,
persistence.WorkflowCloseStatusTerminated: true,
persistence.WorkflowCloseStatusTimedOut: true,
}
)
// NewEngineWithShardContext creates an instance of history engine
func NewEngineWithShardContext(
shard ShardContext,
visibilityMgr persistence.VisibilityManager,
matching matching.Client,
historyClient hc.Client,
publicClient workflowserviceclient.Interface,
historyEventNotifier historyEventNotifier,
publisher messaging.Producer,
config *Config,
) Engine {
currentClusterName := shard.GetService().GetClusterMetadata().GetCurrentClusterName()
logger := shard.GetLogger()
executionManager := shard.GetExecutionManager()
historyManager := shard.GetHistoryManager()
historyV2Manager := shard.GetHistoryV2Manager()
historyCache := newHistoryCache(shard)
historyEngImpl := &historyEngineImpl{
currentClusterName: currentClusterName,
shard: shard,
clusterMetadata: shard.GetClusterMetadata(),
timeSource: shard.GetTimeSource(),
historyMgr: historyManager,
historyV2Mgr: historyV2Manager,
executionManager: executionManager,
visibilityMgr: visibilityMgr,
tokenSerializer: common.NewJSONTaskTokenSerializer(),
historyCache: historyCache,
logger: logger.WithTags(tag.ComponentHistoryEngine),
throttledLogger: shard.GetThrottledLogger().WithTags(tag.ComponentHistoryEngine),
metricsClient: shard.GetMetricsClient(),
historyEventNotifier: historyEventNotifier,
config: config,
archivalClient: warchiver.NewClient(
shard.GetMetricsClient(),
logger,
publicClient,
shard.GetConfig().NumArchiveSystemWorkflows,
shard.GetConfig().ArchiveRequestRPS,
shard.GetService().GetArchiverProvider(),
),
}
txProcessor := newTransferQueueProcessor(shard, historyEngImpl, visibilityMgr, matching, historyClient, logger)
historyEngImpl.timerProcessor = newTimerQueueProcessor(shard, historyEngImpl, matching, logger)
historyEngImpl.txProcessor = txProcessor
// Only start the replicator processor if valid publisher is passed in
if publisher != nil {
replicatorProcessor := newReplicatorQueueProcessor(shard, historyEngImpl.historyCache, publisher, executionManager, historyManager, historyV2Manager, logger)
historyEngImpl.replicatorProcessor = replicatorProcessor
historyEngImpl.replicator = newHistoryReplicator(shard, clock.NewRealTimeSource(), historyEngImpl, historyCache, shard.GetDomainCache(), historyManager, historyV2Manager,
logger)
}
historyEngImpl.resetor = newWorkflowResetor(historyEngImpl)
historyEngImpl.decisionHandler = newDecisionHandler(historyEngImpl)
shard.SetEngine(historyEngImpl)
return historyEngImpl
}
// Start will spin up all the components needed to start serving this shard.
// Make sure all the components are loaded lazily so start can return immediately. This is important because
// ShardController calls start sequentially for all the shards for a given host during startup.
func (e *historyEngineImpl) Start() {
e.logger.Info("", tag.LifeCycleStarting)
defer e.logger.Info("", tag.LifeCycleStarted)
e.registerDomainFailoverCallback()
e.txProcessor.Start()
e.timerProcessor.Start()
if e.replicatorProcessor != nil {
e.replicatorProcessor.Start()
}
}
// Stop the service.
func (e *historyEngineImpl) Stop() {
e.logger.Info("", tag.LifeCycleStopping)
defer e.logger.Info("", tag.LifeCycleStopped)
e.txProcessor.Stop()
e.timerProcessor.Stop()
if e.replicatorProcessor != nil {
e.replicatorProcessor.Stop()
}
// unset the failover callback
e.shard.GetDomainCache().UnregisterDomainChangeCallback(e.shard.GetShardID())
}
func (e *historyEngineImpl) registerDomainFailoverCallback() {
// NOTE: READ BEFORE MODIFICATION
//
// Tasks, e.g. transfer tasks and timer tasks, are created when holding the shard lock
// meaning tasks -> release of shard lock
//
// Domain change notification follows the following steps, order matters
// 1. lock all task processing.
// 2. domain changes visible to everyone (Note: lock of task processing prevents task processing logic seeing the domain changes).
// 3. failover min and max task levels are calaulated, then update to shard.
// 4. failover start & task processing unlock & shard domain version notification update. (order does not matter for this discussion)
//
// The above guarantees that task created during the failover will be processed.
// If the task is created after domain change:
// then active processor will handle it. (simple case)
// If the task is created before domain change:
// task -> release of shard lock
// failover min / max task levels calculated & updated to shard (using shard lock) -> failover start
// above 2 guarantees that failover start is after persistence of the task.
failoverPredicate := func(shardNotificationVersion int64, nextDomain *cache.DomainCacheEntry, action func()) {
domainFailoverNotificationVersion := nextDomain.GetFailoverNotificationVersion()
domainActiveCluster := nextDomain.GetReplicationConfig().ActiveClusterName
if nextDomain.IsGlobalDomain() &&
domainFailoverNotificationVersion >= shardNotificationVersion &&
domainActiveCluster == e.currentClusterName {
action()
}
}
// first set the failover callback
e.shard.GetDomainCache().RegisterDomainChangeCallback(
e.shard.GetShardID(),
e.shard.GetDomainNotificationVersion(),
func() {
e.txProcessor.LockTaskPrrocessing()
e.timerProcessor.LockTaskPrrocessing()
},
func(prevDomains []*cache.DomainCacheEntry, nextDomains []*cache.DomainCacheEntry) {
defer func() {
e.txProcessor.UnlockTaskPrrocessing()
e.timerProcessor.UnlockTaskPrrocessing()
}()
if len(nextDomains) == 0 {
return
}
shardNotificationVersion := e.shard.GetDomainNotificationVersion()
failoverDomainIDs := map[string]struct{}{}
for _, nextDomain := range nextDomains {
failoverPredicate(shardNotificationVersion, nextDomain, func() {
failoverDomainIDs[nextDomain.GetInfo().ID] = struct{}{}
})
}
if len(failoverDomainIDs) > 0 {
e.logger.Info("Domain Failover Start.", tag.WorkflowDomainIDs(failoverDomainIDs))
e.txProcessor.FailoverDomain(failoverDomainIDs)
e.timerProcessor.FailoverDomain(failoverDomainIDs)
now := e.shard.GetTimeSource().Now()
// the fake tasks will not be actually used, we just need to make sure
// its length > 0 and has correct timestamp, to trigger a db scan
fakeDecisionTask := []persistence.Task{&persistence.DecisionTask{}}
fakeDecisionTimeoutTask := []persistence.Task{&persistence.DecisionTimeoutTask{VisibilityTimestamp: now}}
e.txProcessor.NotifyNewTask(e.currentClusterName, fakeDecisionTask)
e.timerProcessor.NotifyNewTimers(e.currentClusterName, fakeDecisionTimeoutTask)
}
e.shard.UpdateDomainNotificationVersion(nextDomains[len(nextDomains)-1].GetNotificationVersion() + 1)
},
)
}
func (e *historyEngineImpl) createMutableState(
clusterMetadata cluster.Metadata,
domainEntry *cache.DomainCacheEntry,
) mutableState {
var msBuilder mutableState
if clusterMetadata.IsGlobalDomainEnabled() && domainEntry.IsGlobalDomain() {
// all workflows within a global domain should have replication state, no matter whether it will be replicated to multiple
// target clusters or not
msBuilder = newMutableStateBuilderWithReplicationState(
e.shard,
e.shard.GetEventsCache(),
e.logger,
domainEntry.GetFailoverVersion(),
domainEntry.GetReplicationPolicy(),
domainEntry.GetInfo().Name,
)
} else {
msBuilder = newMutableStateBuilder(
e.shard,
e.shard.GetEventsCache(),
e.logger,
domainEntry.GetInfo().Name,
)
}
return msBuilder
}
func (e *historyEngineImpl) generateFirstDecisionTask(
domainID string,
msBuilder mutableState,
parentInfo *h.ParentExecutionInfo,
taskListName string,
cronBackoffSeconds int32,
) ([]persistence.Task, *decisionInfo, error) {
di := &decisionInfo{
TaskList: taskListName,
Version: common.EmptyVersion,
ScheduleID: common.EmptyEventID,
StartedID: common.EmptyEventID,
DecisionTimeout: int32(0),
}
var transferTasks []persistence.Task
var err error
if parentInfo == nil {
// RecordWorkflowStartedTask is only created when it is not a Child Workflow
transferTasks = append(transferTasks, &persistence.RecordWorkflowStartedTask{})
if cronBackoffSeconds == 0 {
// DecisionTask is only created when it is not a Child Workflow and no backoff is needed
di, err = msBuilder.AddDecisionTaskScheduledEvent()
if err != nil {
return nil, nil, &workflow.InternalServiceError{Message: "Failed to add decision scheduled event."}
}
transferTasks = append(transferTasks, &persistence.DecisionTask{
DomainID: domainID, TaskList: taskListName, ScheduleID: di.ScheduleID,
})
}
}
return transferTasks, di, nil
}
// StartWorkflowExecution starts a workflow execution
func (e *historyEngineImpl) StartWorkflowExecution(
ctx ctx.Context,
startRequest *h.StartWorkflowExecutionRequest,
) (resp *workflow.StartWorkflowExecutionResponse, retError error) {
domainEntry, err := e.getActiveDomainEntry(startRequest.DomainUUID)
if err != nil {
return nil, err
}
domainID := domainEntry.GetInfo().ID
request := startRequest.StartRequest
err = validateStartWorkflowExecutionRequest(request, e.config.MaxIDLengthLimit())
if err != nil {
return nil, err
}
e.overrideStartWorkflowExecutionRequest(domainEntry, request)
workflowID := request.GetWorkflowId()
// grab the current context as a lock, nothing more
_, currentRelease, err := e.historyCache.getOrCreateCurrentWorkflowExecution(
ctx,
domainID,
workflowID,
)
if err != nil {
return nil, err
}
defer func() { currentRelease(retError) }()
execution := workflow.WorkflowExecution{
WorkflowId: common.StringPtr(workflowID),
RunId: common.StringPtr(uuid.New()),
}
clusterMetadata := e.shard.GetService().GetClusterMetadata()
msBuilder := e.createMutableState(clusterMetadata, domainEntry)
var eventStoreVersion int32
if e.config.EnableEventsV2(request.GetDomain()) {
eventStoreVersion = persistence.EventStoreVersionV2
}
if eventStoreVersion == persistence.EventStoreVersionV2 {
// NOTE: except for fork(reset), we use runID as treeID for simplicity
if retError = msBuilder.SetHistoryTree(execution.GetRunId()); retError != nil {
return
}
}
_, err = msBuilder.AddWorkflowExecutionStartedEvent(domainEntry, execution, startRequest)
if err != nil {
return nil, &workflow.InternalServiceError{Message: "Failed to add workflow execution started event."}
}
taskList := request.TaskList.GetName()
cronBackoffSeconds := startRequest.GetFirstDecisionTaskBackoffSeconds()
// Generate first decision task event if not child WF and no first decision task backoff
transferTasks, _, err := e.generateFirstDecisionTask(domainID, msBuilder, startRequest.ParentExecutionInfo, taskList, cronBackoffSeconds)
if err != nil {
return nil, err
}
// Generate first timer task : WF timeout task
cronBackoffDuration := time.Duration(cronBackoffSeconds) * time.Second
timeoutDuration := time.Duration(*request.ExecutionStartToCloseTimeoutSeconds)*time.Second + cronBackoffDuration
timerTasks := []persistence.Task{&persistence.WorkflowTimeoutTask{
VisibilityTimestamp: e.shard.GetTimeSource().Now().Add(timeoutDuration),
}}
// Only schedule the backoff timer task if not child WF and there's first decision task backoff
if cronBackoffSeconds != 0 && startRequest.ParentExecutionInfo == nil {
timerTasks = append(timerTasks, &persistence.WorkflowBackoffTimerTask{
VisibilityTimestamp: e.shard.GetTimeSource().Now().Add(cronBackoffDuration),
TimeoutType: persistence.WorkflowBackoffTimeoutTypeCron,
})
}
context := newWorkflowExecutionContext(domainID, execution, e.shard, e.executionManager, e.logger)
msBuilder.AddTransferTasks(transferTasks...)
msBuilder.AddTimerTasks(timerTasks...)
now := e.timeSource.Now()
newWorkflow, newWorkflowEventsSeq, err := msBuilder.CloseTransactionAsSnapshot(
now,
transactionPolicyActive,
)
if err != nil {
return nil, err
}
historySize, err := context.persistFirstWorkflowEvents(newWorkflowEventsSeq[0])
if err != nil {
return nil, err
}
// create as brand new
createMode := persistence.CreateWorkflowModeBrandNew
prevRunID := ""
prevLastWriteVersion := int64(0)
err = context.createWorkflowExecution(
newWorkflow, historySize, now,
createMode, prevRunID, prevLastWriteVersion,
)
if err != nil {
if t, ok := err.(*persistence.WorkflowExecutionAlreadyStartedError); ok {
if t.StartRequestID == *request.RequestId {
return &workflow.StartWorkflowExecutionResponse{
RunId: common.StringPtr(t.RunID),
}, nil
// delete history is expected here because duplicate start request will create history with different rid
}
if msBuilder.GetCurrentVersion() < t.LastWriteVersion {
return nil, ce.NewDomainNotActiveError(
*request.Domain,
clusterMetadata.GetCurrentClusterName(),
clusterMetadata.ClusterNameForFailoverVersion(t.LastWriteVersion),
)
}
// create as ID reuse
createMode = persistence.CreateWorkflowModeWorkflowIDReuse
prevRunID = t.RunID
prevLastWriteVersion = t.LastWriteVersion
if err = e.applyWorkflowIDReusePolicyHelper(
t.StartRequestID,
prevRunID,
t.State,
t.CloseStatus,
domainID,
execution,
startRequest.StartRequest.GetWorkflowIdReusePolicy(),
); err != nil {
return nil, err
}
err = context.createWorkflowExecution(
newWorkflow, historySize, now,
createMode, prevRunID, prevLastWriteVersion,
)
}
}
if err != nil {
return nil, err
}
return &workflow.StartWorkflowExecutionResponse{
RunId: execution.RunId,
}, nil
}
// GetMutableState retrieves the mutable state of the workflow execution
func (e *historyEngineImpl) GetMutableState(
ctx ctx.Context,
request *h.GetMutableStateRequest,
) (*h.GetMutableStateResponse, error) {
domainID, err := validateDomainUUID(request.DomainUUID)
if err != nil {
return nil, err
}
execution := workflow.WorkflowExecution{
WorkflowId: request.Execution.WorkflowId,
RunId: request.Execution.RunId,
}
response, err := e.getMutableState(ctx, domainID, execution)
if err != nil {
return nil, err
}
// set the run id in case query the current running workflow
execution.RunId = response.Execution.RunId
// expectedNextEventID is 0 when caller want to get the current next event ID without blocking
expectedNextEventID := common.FirstEventID
if request.ExpectedNextEventId != nil {
expectedNextEventID = request.GetExpectedNextEventId()
}
// if caller decide to long poll on workflow execution
// and the event ID we are looking for is smaller than current next event ID
if expectedNextEventID >= response.GetNextEventId() && response.GetIsWorkflowRunning() {
subscriberID, channel, err := e.historyEventNotifier.WatchHistoryEvent(definition.NewWorkflowIdentifier(domainID, execution.GetWorkflowId(), execution.GetRunId()))
if err != nil {
return nil, err
}
defer e.historyEventNotifier.UnwatchHistoryEvent(definition.NewWorkflowIdentifier(domainID, execution.GetWorkflowId(), execution.GetRunId()), subscriberID)
// check again in case the next event ID is updated
response, err = e.getMutableState(ctx, domainID, execution)
if err != nil {
return nil, err
}
if expectedNextEventID < response.GetNextEventId() || !response.GetIsWorkflowRunning() {
return response, nil
}
domainCache, err := e.shard.GetDomainCache().GetDomainByID(domainID)
if err != nil {
return nil, err
}
timer := time.NewTimer(e.shard.GetConfig().LongPollExpirationInterval(domainCache.GetInfo().Name))
defer timer.Stop()
for {
select {
case event := <-channel:
response.LastFirstEventId = common.Int64Ptr(event.lastFirstEventID)
response.NextEventId = common.Int64Ptr(event.nextEventID)
response.IsWorkflowRunning = common.BoolPtr(event.isWorkflowRunning)
response.PreviousStartedEventId = common.Int64Ptr(event.previousStartedEventID)
if expectedNextEventID < response.GetNextEventId() || !response.GetIsWorkflowRunning() {
return response, nil
}
case <-timer.C:
return response, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
return response, nil
}
func (e *historyEngineImpl) getMutableState(
ctx ctx.Context,
domainID string,
execution workflow.WorkflowExecution,
) (retResp *h.GetMutableStateResponse, retError error) {
context, release, retError := e.historyCache.getOrCreateWorkflowExecution(ctx, domainID, execution)
if retError != nil {
return
}
defer func() { release(retError) }()
msBuilder, retError := context.loadWorkflowExecution()
if retError != nil {
return
}
executionInfo := msBuilder.GetExecutionInfo()
execution.RunId = context.getExecution().RunId
retResp = &h.GetMutableStateResponse{
Execution: &execution,
WorkflowType: &workflow.WorkflowType{Name: common.StringPtr(executionInfo.WorkflowTypeName)},
LastFirstEventId: common.Int64Ptr(msBuilder.GetLastFirstEventID()),
NextEventId: common.Int64Ptr(msBuilder.GetNextEventID()),
PreviousStartedEventId: common.Int64Ptr(msBuilder.GetPreviousStartedEventID()),
TaskList: &workflow.TaskList{Name: common.StringPtr(executionInfo.TaskList)},
ClientLibraryVersion: common.StringPtr(executionInfo.ClientLibraryVersion),
ClientFeatureVersion: common.StringPtr(executionInfo.ClientFeatureVersion),
ClientImpl: common.StringPtr(executionInfo.ClientImpl),
IsWorkflowRunning: common.BoolPtr(msBuilder.IsWorkflowExecutionRunning()),
EventStoreVersion: common.Int32Ptr(msBuilder.GetEventStoreVersion()),
BranchToken: msBuilder.GetCurrentBranch(),
}
if msBuilder.IsStickyTaskListEnabled() {
retResp.StickyTaskList = &workflow.TaskList{Name: common.StringPtr(executionInfo.StickyTaskList)}
retResp.StickyTaskListScheduleToStartTimeout = common.Int32Ptr(executionInfo.StickyScheduleToStartTimeout)
}
replicationState := msBuilder.GetReplicationState()
if replicationState != nil {
retResp.ReplicationInfo = map[string]*workflow.ReplicationInfo{}
for k, v := range replicationState.LastReplicationInfo {
retResp.ReplicationInfo[k] = &workflow.ReplicationInfo{
Version: common.Int64Ptr(v.Version),
LastEventId: common.Int64Ptr(v.LastEventID),
}
}
}
return
}
func (e *historyEngineImpl) DescribeMutableState(
ctx ctx.Context,
request *h.DescribeMutableStateRequest,
) (retResp *h.DescribeMutableStateResponse, retError error) {
domainID, err := validateDomainUUID(request.DomainUUID)
if err != nil {
return nil, err
}
execution := workflow.WorkflowExecution{
WorkflowId: request.Execution.WorkflowId,
RunId: request.Execution.RunId,
}
cacheCtx, dbCtx, release, cacheHit, err := e.historyCache.getAndCreateWorkflowExecution(ctx, domainID, execution)
if err != nil {
return nil, err
}
defer func() { release(retError) }()
retResp = &h.DescribeMutableStateResponse{}
if cacheHit && cacheCtx.(*workflowExecutionContextImpl).msBuilder != nil {
msb := cacheCtx.(*workflowExecutionContextImpl).msBuilder
retResp.MutableStateInCache, retError = e.toMutableStateJSON(msb)
}
msb, retError := dbCtx.loadWorkflowExecution()
retResp.MutableStateInDatabase, retError = e.toMutableStateJSON(msb)
return
}
func (e *historyEngineImpl) toMutableStateJSON(msb mutableState) (*string, error) {
ms := msb.CopyToPersistence()
jsonBytes, err := json.Marshal(ms)
if err != nil {
return nil, err
}
return common.StringPtr(string(jsonBytes)), nil
}
// ResetStickyTaskList reset the volatile information in mutable state of a given workflow.
// Volatile information are the information related to client, such as:
// 1. StickyTaskList
// 2. StickyScheduleToStartTimeout
// 3. ClientLibraryVersion
// 4. ClientFeatureVersion
// 5. ClientImpl
func (e *historyEngineImpl) ResetStickyTaskList(
ctx ctx.Context,
resetRequest *h.ResetStickyTaskListRequest,
) (*h.ResetStickyTaskListResponse, error) {
domainID, err := validateDomainUUID(resetRequest.DomainUUID)
if err != nil {
return nil, err
}
err = e.updateWorkflowExecution(ctx, domainID, *resetRequest.Execution, false, false,
func(msBuilder mutableState, tBuilder *timerBuilder) ([]persistence.Task, error) {
if !msBuilder.IsWorkflowExecutionRunning() {
return nil, ErrWorkflowCompleted
}
msBuilder.ClearStickyness()
return nil, nil
},
)
if err != nil {
return nil, err
}
return &h.ResetStickyTaskListResponse{}, nil
}
// DescribeWorkflowExecution returns information about the specified workflow execution.
func (e *historyEngineImpl) DescribeWorkflowExecution(
ctx ctx.Context,
request *h.DescribeWorkflowExecutionRequest,
) (retResp *workflow.DescribeWorkflowExecutionResponse, retError error) {
domainID, err := validateDomainUUID(request.DomainUUID)
if err != nil {
return nil, err
}
execution := *request.Request.Execution
context, release, err0 := e.historyCache.getOrCreateWorkflowExecution(ctx, domainID, execution)
if err0 != nil {
return nil, err0
}
defer func() { release(retError) }()
msBuilder, err1 := context.loadWorkflowExecution()
if err1 != nil {
return nil, err1
}
executionInfo := msBuilder.GetExecutionInfo()
result := &workflow.DescribeWorkflowExecutionResponse{
ExecutionConfiguration: &workflow.WorkflowExecutionConfiguration{
TaskList: &workflow.TaskList{Name: common.StringPtr(executionInfo.TaskList)},
ExecutionStartToCloseTimeoutSeconds: common.Int32Ptr(executionInfo.WorkflowTimeout),
TaskStartToCloseTimeoutSeconds: common.Int32Ptr(executionInfo.DecisionTimeoutValue),
ChildPolicy: common.ChildPolicyPtr(workflow.ChildPolicyTerminate),
},
WorkflowExecutionInfo: &workflow.WorkflowExecutionInfo{
Execution: &workflow.WorkflowExecution{
WorkflowId: common.StringPtr(executionInfo.WorkflowID),
RunId: common.StringPtr(executionInfo.RunID),
},
Type: &workflow.WorkflowType{Name: common.StringPtr(executionInfo.WorkflowTypeName)},
StartTime: common.Int64Ptr(executionInfo.StartTimestamp.UnixNano()),
HistoryLength: common.Int64Ptr(msBuilder.GetNextEventID() - common.FirstEventID),
AutoResetPoints: executionInfo.AutoResetPoints,
SearchAttributes: &workflow.SearchAttributes{IndexedFields: executionInfo.SearchAttributes},
},
}
// TODO: we need to consider adding execution time to mutable state
// For now execution time will be calculated based on start time and cron schedule/retry policy
// each time DescribeWorkflowExecution is called.
backoffDuration := time.Duration(0)
startEvent, ok := msBuilder.GetStartEvent()
if ok {
backoffDuration = time.Duration(startEvent.GetWorkflowExecutionStartedEventAttributes().GetFirstDecisionTaskBackoffSeconds()) * time.Second
}
result.WorkflowExecutionInfo.ExecutionTime = common.Int64Ptr(result.WorkflowExecutionInfo.GetStartTime() + backoffDuration.Nanoseconds())
if executionInfo.ParentRunID != "" {
result.WorkflowExecutionInfo.ParentExecution = &workflow.WorkflowExecution{
WorkflowId: common.StringPtr(executionInfo.ParentWorkflowID),
RunId: common.StringPtr(executionInfo.ParentRunID),
}
result.WorkflowExecutionInfo.ParentDomainId = common.StringPtr(executionInfo.ParentDomainID)
}
if executionInfo.State == persistence.WorkflowStateCompleted {
// for closed workflow
closeStatus := getWorkflowExecutionCloseStatus(executionInfo.CloseStatus)
result.WorkflowExecutionInfo.CloseStatus = &closeStatus
completionEvent, ok := msBuilder.GetCompletionEvent()
if !ok {
return nil, &workflow.InternalServiceError{Message: "Unable to get workflow completion event."}
}
result.WorkflowExecutionInfo.CloseTime = common.Int64Ptr(completionEvent.GetTimestamp())
}
if len(msBuilder.GetPendingActivityInfos()) > 0 {
for _, ai := range msBuilder.GetPendingActivityInfos() {
p := &workflow.PendingActivityInfo{
ActivityID: common.StringPtr(ai.ActivityID),
}
state := workflow.PendingActivityStateScheduled
if ai.CancelRequested {
state = workflow.PendingActivityStateCancelRequested
} else if ai.StartedID != common.EmptyEventID {
state = workflow.PendingActivityStateStarted
}
p.State = &state
lastHeartbeatUnixNano := ai.LastHeartBeatUpdatedTime.UnixNano()
if lastHeartbeatUnixNano > 0 {
p.LastHeartbeatTimestamp = common.Int64Ptr(lastHeartbeatUnixNano)
p.HeartbeatDetails = ai.Details
}
// TODO: move to mutable state instead of loading it from event
scheduledEvent, ok := msBuilder.GetActivityScheduledEvent(ai.ScheduleID)
if !ok {
return nil, &workflow.InternalServiceError{Message: "Unable to get activity schedule event."}
}
p.ActivityType = scheduledEvent.ActivityTaskScheduledEventAttributes.ActivityType
if state == workflow.PendingActivityStateScheduled {
p.ScheduledTimestamp = common.Int64Ptr(ai.ScheduledTime.UnixNano())
} else {
p.LastStartedTimestamp = common.Int64Ptr(ai.StartedTime.UnixNano())
}
if ai.HasRetryPolicy {
p.Attempt = common.Int32Ptr(ai.Attempt)
p.ExpirationTimestamp = common.Int64Ptr(ai.ExpirationTime.UnixNano())
if ai.MaximumAttempts != 0 {
p.MaximumAttempts = common.Int32Ptr(ai.MaximumAttempts)
}
if ai.LastFailureReason != "" {
p.LastFailureReason = common.StringPtr(ai.LastFailureReason)
}
if ai.LastWorkerIdentity != "" {
p.LastWorkerIdentity = common.StringPtr(ai.LastWorkerIdentity)
}
}
result.PendingActivities = append(result.PendingActivities, p)
}
}
if len(msBuilder.GetPendingChildExecutionInfos()) > 0 {
for _, ch := range msBuilder.GetPendingChildExecutionInfos() {
p := &workflow.PendingChildExecutionInfo{
WorkflowID: common.StringPtr(ch.StartedWorkflowID),
RunID: common.StringPtr(ch.StartedRunID),
WorkflowTypName: common.StringPtr(ch.WorkflowTypeName),
InitiatedID: common.Int64Ptr(ch.InitiatedID),
}
result.PendingChildren = append(result.PendingChildren, p)
}
}
return result, nil
}
func (e *historyEngineImpl) RecordActivityTaskStarted(
ctx ctx.Context,
request *h.RecordActivityTaskStartedRequest,
) (*h.RecordActivityTaskStartedResponse, error) {
domainEntry, err := e.getActiveDomainEntry(request.DomainUUID)
if err != nil {
return nil, err
}
domainInfo := domainEntry.GetInfo()
domainID := domainInfo.ID
domainName := domainInfo.Name
execution := workflow.WorkflowExecution{
WorkflowId: request.WorkflowExecution.WorkflowId,
RunId: request.WorkflowExecution.RunId,
}
response := &h.RecordActivityTaskStartedResponse{}
err = e.updateWorkflowExecution(ctx, domainID, execution, false, false,
func(msBuilder mutableState, tBuilder *timerBuilder) ([]persistence.Task, error) {
if !msBuilder.IsWorkflowExecutionRunning() {
return nil, ErrWorkflowCompleted
}
scheduleID := request.GetScheduleId()
requestID := request.GetRequestId()
ai, isRunning := msBuilder.GetActivityInfo(scheduleID)
// First check to see if cache needs to be refreshed as we could potentially have stale workflow execution in
// some extreme cassandra failure cases.
if !isRunning && scheduleID >= msBuilder.GetNextEventID() {
e.metricsClient.IncCounter(metrics.HistoryRecordActivityTaskStartedScope, metrics.StaleMutableStateCounter)
return nil, ErrStaleState
}
// Check execution state to make sure task is in the list of outstanding tasks and it is not yet started. If
// task is not outstanding than it is most probably a duplicate and complete the task.
if !isRunning {
// Looks like ActivityTask already completed as a result of another call.
// It is OK to drop the task at this point.
e.logger.Debug("Potentially duplicate task.", tag.TaskID(request.GetTaskId()), tag.WorkflowScheduleID(scheduleID), tag.TaskType(persistence.TransferTaskTypeActivityTask))
return nil, ErrActivityTaskNotFound
}
scheduledEvent, ok := msBuilder.GetActivityScheduledEvent(scheduleID)
if !ok {
return nil, &workflow.InternalServiceError{Message: "Unable to get activity schedule event."}
}
response.ScheduledEvent = scheduledEvent
response.ScheduledTimestampOfThisAttempt = common.Int64Ptr(ai.ScheduledTime.UnixNano())
if ai.StartedID != common.EmptyEventID {
// If activity is started as part of the current request scope then return a positive response
if ai.RequestID == requestID {
response.StartedTimestamp = common.Int64Ptr(ai.StartedTime.UnixNano())
response.Attempt = common.Int64Ptr(int64(ai.Attempt))
return nil, nil
}
// Looks like ActivityTask already started as a result of another call.
// It is OK to drop the task at this point.
e.logger.Debug("Potentially duplicate task.", tag.TaskID(request.GetTaskId()), tag.WorkflowScheduleID(scheduleID), tag.TaskType(persistence.TransferTaskTypeActivityTask))
return nil, &h.EventAlreadyStartedError{Message: "Activity task already started."}
}
if _, err := msBuilder.AddActivityTaskStartedEvent(
ai, scheduleID, requestID, request.PollRequest.GetIdentity(),
); err != nil {
return nil, err
}
response.StartedTimestamp = common.Int64Ptr(ai.StartedTime.UnixNano())
response.Attempt = common.Int64Ptr(int64(ai.Attempt))
response.HeartbeatDetails = ai.Details
response.WorkflowType = msBuilder.GetWorkflowType()
response.WorkflowDomain = common.StringPtr(domainName)
// Start a timer for the activity task.
timerTasks := []persistence.Task{}
if tt := tBuilder.GetActivityTimerTaskIfNeeded(msBuilder); tt != nil {
timerTasks = append(timerTasks, tt)
}
return timerTasks, nil
})
if err != nil {
return nil, err
}
return response, err
}
// ScheduleDecisionTask schedules a decision if no outstanding decision found
func (e *historyEngineImpl) ScheduleDecisionTask(
ctx ctx.Context,
req *h.ScheduleDecisionTaskRequest,
) error {
return e.decisionHandler.handleDecisionTaskScheduled(ctx, req)
}
// RecordDecisionTaskStarted starts a decision
func (e *historyEngineImpl) RecordDecisionTaskStarted(
ctx ctx.Context,
request *h.RecordDecisionTaskStartedRequest,
) (*h.RecordDecisionTaskStartedResponse, error) {
return e.decisionHandler.handleDecisionTaskStarted(ctx, request)
}
// RespondDecisionTaskCompleted completes a decision task
func (e *historyEngineImpl) RespondDecisionTaskCompleted(
ctx ctx.Context,
req *h.RespondDecisionTaskCompletedRequest,
) (*h.RespondDecisionTaskCompletedResponse, error) {
return e.decisionHandler.handleDecisionTaskCompleted(ctx, req)
}
// RespondDecisionTaskFailed fails a decision
func (e *historyEngineImpl) RespondDecisionTaskFailed(
ctx ctx.Context,
req *h.RespondDecisionTaskFailedRequest,
) error {
return e.decisionHandler.handleDecisionTaskFailed(ctx, req)
}
// RespondActivityTaskCompleted completes an activity task.
func (e *historyEngineImpl) RespondActivityTaskCompleted(
ctx ctx.Context,
req *h.RespondActivityTaskCompletedRequest,
) error {
domainEntry, err := e.getActiveDomainEntry(req.DomainUUID)
if err != nil {
return err
}
domainID := domainEntry.GetInfo().ID
request := req.CompleteRequest
token, err0 := e.tokenSerializer.Deserialize(request.TaskToken)
if err0 != nil {
return ErrDeserializingToken
}
workflowExecution := workflow.WorkflowExecution{
WorkflowId: common.StringPtr(token.WorkflowID),
RunId: common.StringPtr(token.RunID),
}
return e.updateWorkflowExecution(ctx, domainID, workflowExecution, false, true,
func(msBuilder mutableState, tBuilder *timerBuilder) ([]persistence.Task, error) {