-
Notifications
You must be signed in to change notification settings - Fork 226
/
Copy pathinternal_event_handlers.go
2067 lines (1793 loc) · 73.8 KB
/
internal_event_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
// The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 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 (
"errors"
"fmt"
"reflect"
"sync"
"time"
commandpb "go.temporal.io/api/command/v1"
commonpb "go.temporal.io/api/common/v1"
enumspb "go.temporal.io/api/enums/v1"
failurepb "go.temporal.io/api/failure/v1"
historypb "go.temporal.io/api/history/v1"
protocolpb "go.temporal.io/api/protocol/v1"
taskqueuepb "go.temporal.io/api/taskqueue/v1"
"go.temporal.io/api/workflowservice/v1"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/durationpb"
"go.temporal.io/sdk/converter"
"go.temporal.io/sdk/internal/common/metrics"
ilog "go.temporal.io/sdk/internal/log"
"go.temporal.io/sdk/internal/protocol"
"go.temporal.io/sdk/log"
)
const (
queryResultSizeLimit = 2000000 // 2MB
changeVersionSearchAttrSizeLimit = 2048
)
// Assert that structs do indeed implement the interfaces
var (
_ WorkflowEnvironment = (*workflowEnvironmentImpl)(nil)
_ workflowExecutionEventHandler = (*workflowExecutionEventHandlerImpl)(nil)
)
type (
// completionHandler Handler to indicate completion result
completionHandler func(result *commonpb.Payloads, err error)
// workflowExecutionEventHandlerImpl handler to handle workflowExecutionEventHandler
workflowExecutionEventHandlerImpl struct {
*workflowEnvironmentImpl
workflowDefinition WorkflowDefinition
}
scheduledTimer struct {
callback ResultHandler
handled bool
}
scheduledActivity struct {
callback ResultHandler
waitForCancelRequest bool
handled bool
activityType ActivityType
}
scheduledNexusOperation struct {
startedCallback func(operationID string, err error)
completedCallback func(result *commonpb.Payload, err error)
endpoint string
service string
operation string
}
scheduledChildWorkflow struct {
resultCallback ResultHandler
startedCallback func(r WorkflowExecution, e error)
waitForCancellation bool
handled bool
}
scheduledCancellation struct {
callback ResultHandler
handled bool
}
scheduledSignal struct {
callback ResultHandler
handled bool
}
sendCfg struct {
addCmd bool
pred func(*historypb.HistoryEvent) bool
}
msgSendOpt func(so *sendCfg)
outboxEntry struct {
eventPredicate func(*historypb.HistoryEvent) bool
msg *protocolpb.Message
}
// workflowEnvironmentImpl an implementation of WorkflowEnvironment represents a environment for workflow execution.
workflowEnvironmentImpl struct {
workflowInfo *WorkflowInfo
commandsHelper *commandsHelper
outbox []outboxEntry
sideEffectResult map[int64]*commonpb.Payloads
changeVersions map[string]Version
pendingLaTasks map[string]*localActivityTask
completedLaAttemptsThisWFT uint32
// mutableSideEffect is a map for each mutable side effect ID where each key is the
// number of times the mutable side effect was called in a workflow
// execution per ID.
mutableSideEffect map[string]map[int]*commonpb.Payloads
unstartedLaTasks map[string]struct{}
openSessions map[string]*SessionInfo
// Set of mutable side effect IDs that are recorded on the next task for use
// during replay to determine whether a command should be created. The keys
// are the user-provided IDs + "_" + the command counter.
mutableSideEffectsRecorded map[string]bool
// Records the number of times a mutable side effect was called per ID over the
// life of the workflow. Used to help distinguish multiple calls to MutableSideEffect in the same
// WorkflowTask.
mutableSideEffectCallCounter map[string]int
// LocalActivities have a separate, individual counter instead of relying on actual commandEventIDs.
// This is because command IDs are only incremented on activity completion, which breaks
// local activities that are spawned in parallel as they would all share the same command ID
localActivityCounterID int64
sideEffectCounterID int64
currentReplayTime time.Time // Indicates current replay time of the command.
currentLocalTime time.Time // Local time when currentReplayTime was updated.
completeHandler completionHandler // events completion handler
cancelHandler func() // A cancel handler to be invoked on a cancel notification
signalHandler func(name string, input *commonpb.Payloads, header *commonpb.Header) error // A signal handler to be invoked on a signal event
queryHandler func(queryType string, queryArgs *commonpb.Payloads, header *commonpb.Header) (*commonpb.Payloads, error)
updateHandler func(name string, id string, args *commonpb.Payloads, header *commonpb.Header, callbacks UpdateCallbacks)
logger log.Logger
isReplay bool // flag to indicate if workflow is in replay mode
enableLoggingInReplay bool // flag to indicate if workflow should enable logging in replay mode
metricsHandler metrics.Handler
registry *registry
dataConverter converter.DataConverter
failureConverter converter.FailureConverter
contextPropagators []ContextPropagator
deadlockDetectionTimeout time.Duration
sdkFlags *sdkFlags
sdkVersionUpdated bool
sdkVersion string
sdkNameUpdated bool
sdkName string
// Any update requests received in a workflow task before we have registered
// any handlers are not scheduled and are queued here until either their
// handler is registered or the event loop runs out of work and they are rejected.
bufferedUpdateRequests map[string][]func()
protocols *protocol.Registry
}
localActivityTask struct {
sync.Mutex
workflowTask *workflowTask
activityID string
params *ExecuteLocalActivityParams
callback LocalActivityResultHandler
wc *workflowExecutionContextImpl
canceled bool
cancelFunc func()
attempt int32 // attempt starting from 1
attemptsThisWFT uint32 // Number of attempts started during this workflow task
pastFirstWFT bool // Set true once this LA has lived for more than one workflow task
retryPolicy *RetryPolicy
expireTime time.Time
scheduledTime time.Time // Time the activity was scheduled initially.
header *commonpb.Header
}
localActivityMarkerData struct {
ActivityID string
ActivityType string
ReplayTime time.Time
Attempt int32 // record attempt, starting from 1.
Backoff time.Duration // retry backoff duration.
}
)
var (
// ErrUnknownMarkerName is returned if there is unknown marker name in the history.
ErrUnknownMarkerName = errors.New("unknown marker name")
// ErrMissingMarkerDetails is returned when marker details are nil.
ErrMissingMarkerDetails = errors.New("marker details are nil")
// ErrMissingMarkerDataKey is returned when marker details doesn't have data key.
ErrMissingMarkerDataKey = errors.New("marker key is missing in details")
// ErrUnknownHistoryEvent is returned if there is an unknown event in history and the SDK needs to handle it
ErrUnknownHistoryEvent = errors.New("unknown history event")
)
func newWorkflowExecutionEventHandler(
workflowInfo *WorkflowInfo,
completeHandler completionHandler,
logger log.Logger,
enableLoggingInReplay bool,
metricsHandler metrics.Handler,
registry *registry,
dataConverter converter.DataConverter,
failureConverter converter.FailureConverter,
contextPropagators []ContextPropagator,
deadlockDetectionTimeout time.Duration,
capabilities *workflowservice.GetSystemInfoResponse_Capabilities,
) workflowExecutionEventHandler {
context := &workflowEnvironmentImpl{
workflowInfo: workflowInfo,
commandsHelper: newCommandsHelper(),
sideEffectResult: make(map[int64]*commonpb.Payloads),
mutableSideEffect: make(map[string]map[int]*commonpb.Payloads),
changeVersions: make(map[string]Version),
pendingLaTasks: make(map[string]*localActivityTask),
unstartedLaTasks: make(map[string]struct{}),
openSessions: make(map[string]*SessionInfo),
completeHandler: completeHandler,
enableLoggingInReplay: enableLoggingInReplay,
registry: registry,
dataConverter: dataConverter,
failureConverter: failureConverter,
contextPropagators: contextPropagators,
deadlockDetectionTimeout: deadlockDetectionTimeout,
protocols: protocol.NewRegistry(),
mutableSideEffectCallCounter: make(map[string]int),
sdkFlags: newSDKFlags(capabilities),
bufferedUpdateRequests: make(map[string][]func()),
}
// Attempt to skip 1 log level to remove the ReplayLogger from the stack.
context.logger = log.Skip(ilog.NewReplayLogger(
log.With(logger,
tagWorkflowType, workflowInfo.WorkflowType.Name,
tagWorkflowID, workflowInfo.WorkflowExecution.ID,
tagRunID, workflowInfo.WorkflowExecution.RunID,
tagAttempt, workflowInfo.Attempt,
),
&context.isReplay,
&context.enableLoggingInReplay), 1)
if metricsHandler != nil {
context.metricsHandler = metrics.NewReplayAwareHandler(&context.isReplay, metricsHandler).
WithTags(metrics.WorkflowTags(workflowInfo.WorkflowType.Name))
}
return &workflowExecutionEventHandlerImpl{context, nil}
}
func (s *scheduledTimer) handle(result *commonpb.Payloads, err error) {
if s.handled {
panic(fmt.Sprintf("timer already handled %v", s))
}
s.handled = true
s.callback(result, err)
}
func (s *scheduledActivity) handle(result *commonpb.Payloads, err error) {
if s.handled {
panic(fmt.Sprintf("activity already handled %v", s))
}
s.handled = true
s.callback(result, err)
}
func (s *scheduledChildWorkflow) handle(result *commonpb.Payloads, err error) {
if s.handled {
panic(fmt.Sprintf("child workflow already handled %v", s))
}
s.handled = true
s.resultCallback(result, err)
}
func (s *scheduledChildWorkflow) handleFailedToStart(result *commonpb.Payloads, err error) {
if s.handled {
panic(fmt.Sprintf("child workflow already handled %v", s))
}
s.handled = true
s.resultCallback(result, err)
s.startedCallback(WorkflowExecution{}, err)
}
func (t *localActivityTask) cancel() {
t.Lock()
t.canceled = true
if t.cancelFunc != nil {
t.cancelFunc()
}
t.Unlock()
}
func (s *scheduledCancellation) handle(result *commonpb.Payloads, err error) {
if s.handled {
panic(fmt.Sprintf("cancellation already handled %v", s))
}
s.handled = true
s.callback(result, err)
}
func (s *scheduledSignal) handle(result *commonpb.Payloads, err error) {
if s.handled {
panic(fmt.Sprintf("signal already handled %v", s))
}
s.handled = true
s.callback(result, err)
}
func (wc *workflowEnvironmentImpl) takeOutgoingMessages() []*protocolpb.Message {
retval := make([]*protocolpb.Message, 0, len(wc.outbox))
for _, entry := range wc.outbox {
retval = append(retval, entry.msg)
}
wc.outbox = nil
return retval
}
func (wc *workflowEnvironmentImpl) ScheduleUpdate(name string, id string, args *commonpb.Payloads, hdr *commonpb.Header, callbacks UpdateCallbacks) {
wc.updateHandler(name, id, args, hdr, callbacks)
}
func withExpectedEventPredicate(pred func(*historypb.HistoryEvent) bool) msgSendOpt {
return func(so *sendCfg) {
so.addCmd = true
so.pred = pred
}
}
func (wc *workflowEnvironmentImpl) Send(msg *protocolpb.Message, opts ...msgSendOpt) {
sendCfg := sendCfg{
pred: func(*historypb.HistoryEvent) bool { return false },
}
for _, opt := range opts {
opt(&sendCfg)
}
canSendCmd := wc.sdkFlags.tryUse(SDKFlagProtocolMessageCommand, !wc.isReplay)
if canSendCmd && sendCfg.addCmd {
wc.commandsHelper.addProtocolMessage(msg.Id)
}
wc.outbox = append(wc.outbox, outboxEntry{msg: msg, eventPredicate: sendCfg.pred})
}
func (wc *workflowEnvironmentImpl) getNewSdkNameAndReset() string {
if wc.sdkNameUpdated {
wc.sdkNameUpdated = false
return wc.sdkName
}
return ""
}
func (wc *workflowEnvironmentImpl) getNewSdkVersionAndReset() string {
if wc.sdkVersionUpdated {
wc.sdkVersionUpdated = false
return wc.sdkVersion
}
return ""
}
func (wc *workflowEnvironmentImpl) getNextLocalActivityID() string {
wc.localActivityCounterID++
return getStringID(wc.localActivityCounterID)
}
func (wc *workflowEnvironmentImpl) getNextSideEffectID() int64 {
wc.sideEffectCounterID++
return wc.sideEffectCounterID
}
func (wc *workflowEnvironmentImpl) WorkflowInfo() *WorkflowInfo {
return wc.workflowInfo
}
func (wc *workflowEnvironmentImpl) TypedSearchAttributes() SearchAttributes {
return convertToTypedSearchAttributes(wc.logger, wc.workflowInfo.SearchAttributes.GetIndexedFields())
}
func (wc *workflowEnvironmentImpl) Complete(result *commonpb.Payloads, err error) {
wc.completeHandler(result, err)
}
func (wc *workflowEnvironmentImpl) RequestCancelChildWorkflow(namespace string, workflowID string) {
// For cancellation of child workflow only, we do not use cancellation ID and run ID
wc.commandsHelper.requestCancelExternalWorkflowExecution(namespace, workflowID, "", "", true)
}
func (wc *workflowEnvironmentImpl) RequestCancelExternalWorkflow(namespace, workflowID, runID string, callback ResultHandler) {
// for cancellation of external workflow, we have to use cancellation ID and set isChildWorkflowOnly to false
cancellationID := wc.GenerateSequenceID()
command := wc.commandsHelper.requestCancelExternalWorkflowExecution(namespace, workflowID, runID, cancellationID, false)
command.setData(&scheduledCancellation{callback: callback})
}
func (wc *workflowEnvironmentImpl) SignalExternalWorkflow(
namespace string,
workflowID string,
runID string,
signalName string,
input *commonpb.Payloads,
_ /* THIS IS FOR TEST FRAMEWORK. DO NOT USE HERE. */ interface{},
header *commonpb.Header,
childWorkflowOnly bool,
callback ResultHandler,
) {
signalID := wc.GenerateSequenceID()
command := wc.commandsHelper.signalExternalWorkflowExecution(namespace, workflowID, runID, signalName, input,
header, signalID, childWorkflowOnly)
command.setData(&scheduledSignal{callback: callback})
}
func (wc *workflowEnvironmentImpl) UpsertSearchAttributes(attributes map[string]interface{}) error {
// This has to be used in WorkflowEnvironment implementations instead of in Workflow for testsuite mock purpose.
attr, err := validateAndSerializeSearchAttributes(attributes)
if err != nil {
return err
}
var upsertID string
if changeVersion, ok := attributes[TemporalChangeVersion]; ok {
// to ensure backward compatibility on searchable GetVersion, use latest changeVersion as upsertID
upsertID = changeVersion.([]string)[0]
} else {
upsertID = wc.GenerateSequenceID()
}
wc.commandsHelper.upsertSearchAttributes(upsertID, attr)
wc.updateWorkflowInfoWithSearchAttributes(attr) // this is for getInfo correctness
return nil
}
func (wc *workflowEnvironmentImpl) UpsertTypedSearchAttributes(attributes SearchAttributes) error {
rawSearchAttributes, err := serializeTypedSearchAttributes(attributes.untypedValue)
if err != nil {
return err
}
if _, ok := rawSearchAttributes.GetIndexedFields()[TemporalChangeVersion]; ok {
return errors.New("TemporalChangeVersion is a reserved key that cannot be set, please use other key")
}
attr := make(map[string]interface{})
for k, v := range rawSearchAttributes.GetIndexedFields() {
attr[k] = v
}
return wc.UpsertSearchAttributes(attr)
}
func (wc *workflowEnvironmentImpl) updateWorkflowInfoWithSearchAttributes(attributes *commonpb.SearchAttributes) {
wc.workflowInfo.SearchAttributes = mergeSearchAttributes(wc.workflowInfo.SearchAttributes, attributes)
}
func mergeSearchAttributes(current, upsert *commonpb.SearchAttributes) *commonpb.SearchAttributes {
if current == nil || len(current.IndexedFields) == 0 {
if upsert == nil || len(upsert.IndexedFields) == 0 {
return nil
}
current = &commonpb.SearchAttributes{
IndexedFields: make(map[string]*commonpb.Payload),
}
}
fields := current.IndexedFields
for k, v := range upsert.IndexedFields {
fields[k] = v
}
return current
}
func validateAndSerializeSearchAttributes(attributes map[string]interface{}) (*commonpb.SearchAttributes, error) {
if len(attributes) == 0 {
return nil, errSearchAttributesNotSet
}
attr, err := serializeUntypedSearchAttributes(attributes)
if err != nil {
return nil, err
}
return attr, nil
}
func (wc *workflowEnvironmentImpl) UpsertMemo(memoMap map[string]interface{}) error {
// This has to be used in WorkflowEnvironment implementations instead of in Workflow for testsuite mock purpose.
memo, err := validateAndSerializeMemo(memoMap, wc.dataConverter)
if err != nil {
return err
}
changeID := wc.GenerateSequenceID()
wc.commandsHelper.modifyProperties(changeID, memo)
wc.updateWorkflowInfoWithMemo(memo) // this is for getInfo correctness
return nil
}
func (wc *workflowEnvironmentImpl) updateWorkflowInfoWithMemo(memo *commonpb.Memo) {
wc.workflowInfo.Memo = mergeMemo(wc.workflowInfo.Memo, memo)
}
func mergeMemo(current, upsert *commonpb.Memo) *commonpb.Memo {
if current == nil || len(current.Fields) == 0 {
if upsert == nil || len(upsert.Fields) == 0 {
return nil
}
current = &commonpb.Memo{
Fields: make(map[string]*commonpb.Payload),
}
}
fields := current.Fields
for k, v := range upsert.Fields {
if v.Data == nil {
delete(fields, k)
} else {
fields[k] = v
}
}
return current
}
func validateAndSerializeMemo(memoMap map[string]interface{}, dc converter.DataConverter) (*commonpb.Memo, error) {
if len(memoMap) == 0 {
return nil, errMemoNotSet
}
return getWorkflowMemo(memoMap, dc)
}
func (wc *workflowEnvironmentImpl) RegisterCancelHandler(handler func()) {
wrappedHandler := func() {
handler()
}
wc.cancelHandler = wrappedHandler
}
func (wc *workflowEnvironmentImpl) ExecuteChildWorkflow(
params ExecuteWorkflowParams, callback ResultHandler, startedHandler func(r WorkflowExecution, e error),
) {
if params.WorkflowID == "" {
params.WorkflowID = wc.workflowInfo.WorkflowExecution.RunID + "_" + wc.GenerateSequenceID()
}
memo, err := getWorkflowMemo(params.Memo, wc.dataConverter)
if err != nil {
if wc.sdkFlags.tryUse(SDKFlagChildWorkflowErrorExecution, !wc.isReplay) {
startedHandler(WorkflowExecution{}, &ChildWorkflowExecutionAlreadyStartedError{})
}
callback(nil, err)
return
}
searchAttr, err := serializeSearchAttributes(params.SearchAttributes, params.TypedSearchAttributes)
if err != nil {
if wc.sdkFlags.tryUse(SDKFlagChildWorkflowErrorExecution, !wc.isReplay) {
startedHandler(WorkflowExecution{}, &ChildWorkflowExecutionAlreadyStartedError{})
}
callback(nil, err)
return
}
attributes := &commandpb.StartChildWorkflowExecutionCommandAttributes{}
attributes.Namespace = params.Namespace
attributes.TaskQueue = &taskqueuepb.TaskQueue{Name: params.TaskQueueName, Kind: enumspb.TASK_QUEUE_KIND_NORMAL}
attributes.WorkflowId = params.WorkflowID
attributes.WorkflowExecutionTimeout = durationpb.New(params.WorkflowExecutionTimeout)
attributes.WorkflowRunTimeout = durationpb.New(params.WorkflowRunTimeout)
attributes.WorkflowTaskTimeout = durationpb.New(params.WorkflowTaskTimeout)
attributes.Input = params.Input
attributes.WorkflowType = &commonpb.WorkflowType{Name: params.WorkflowType.Name}
attributes.WorkflowIdReusePolicy = params.WorkflowIDReusePolicy
attributes.ParentClosePolicy = params.ParentClosePolicy
attributes.RetryPolicy = params.RetryPolicy
attributes.Header = params.Header
attributes.Memo = memo
attributes.SearchAttributes = searchAttr
if len(params.CronSchedule) > 0 {
attributes.CronSchedule = params.CronSchedule
}
attributes.InheritBuildId = determineInheritBuildIdFlagForCommand(
params.VersioningIntent, wc.workflowInfo.TaskQueueName, params.TaskQueueName)
command, err := wc.commandsHelper.startChildWorkflowExecution(attributes)
if _, ok := err.(*childWorkflowExistsWithId); ok {
if wc.sdkFlags.tryUse(SDKFlagChildWorkflowErrorExecution, !wc.isReplay) {
startedHandler(WorkflowExecution{}, &ChildWorkflowExecutionAlreadyStartedError{})
}
callback(nil, &ChildWorkflowExecutionAlreadyStartedError{})
return
}
command.setData(&scheduledChildWorkflow{
resultCallback: callback,
startedCallback: startedHandler,
waitForCancellation: params.WaitForCancellation,
})
wc.logger.Debug("ExecuteChildWorkflow",
tagChildWorkflowID, params.WorkflowID,
tagWorkflowType, params.WorkflowType.Name)
}
func (wc *workflowEnvironmentImpl) ExecuteNexusOperation(params executeNexusOperationParams, callback func(*commonpb.Payload, error), startedHandler func(opID string, e error)) int64 {
seq := wc.GenerateSequence()
scheduleTaskAttr := &commandpb.ScheduleNexusOperationCommandAttributes{
Endpoint: params.client.Endpoint(),
Service: params.client.Service(),
Operation: params.operation,
Input: params.input,
ScheduleToCloseTimeout: durationpb.New(params.options.ScheduleToCloseTimeout),
NexusHeader: params.nexusHeader,
}
command := wc.commandsHelper.scheduleNexusOperation(seq, scheduleTaskAttr)
command.setData(&scheduledNexusOperation{
startedCallback: startedHandler,
completedCallback: callback,
endpoint: params.client.Endpoint(),
service: params.client.Service(),
operation: params.operation,
})
wc.logger.Debug("ScheduleNexusOperation",
tagNexusEndpoint, params.client.Endpoint(),
tagNexusService, params.client.Service(),
tagNexusOperation, params.operation,
)
return command.seq
}
func (wc *workflowEnvironmentImpl) RequestCancelNexusOperation(seq int64) {
command := wc.commandsHelper.requestCancelNexusOperation(seq)
data := command.getData().(*scheduledNexusOperation)
// Make sure to unblock the futures.
if command.getState() == commandStateCreated || command.getState() == commandStateCommandSent {
if data.startedCallback != nil {
data.startedCallback("", ErrCanceled)
data.startedCallback = nil
}
if data.completedCallback != nil {
data.completedCallback(nil, ErrCanceled)
data.completedCallback = nil
}
}
wc.logger.Debug("RequestCancelNexusOperation",
tagNexusEndpoint, data.endpoint,
tagNexusService, data.service,
tagNexusOperation, data.operation,
)
}
func (wc *workflowEnvironmentImpl) RegisterSignalHandler(
handler func(name string, input *commonpb.Payloads, header *commonpb.Header) error,
) {
wc.signalHandler = handler
}
func (wc *workflowEnvironmentImpl) RegisterQueryHandler(
handler func(string, *commonpb.Payloads, *commonpb.Header) (*commonpb.Payloads, error),
) {
wc.queryHandler = handler
}
func (wc *workflowEnvironmentImpl) RegisterUpdateHandler(
handler func(string, string, *commonpb.Payloads, *commonpb.Header, UpdateCallbacks),
) {
wc.updateHandler = handler
}
func (wc *workflowEnvironmentImpl) GetLogger() log.Logger {
return wc.logger
}
func (wc *workflowEnvironmentImpl) GetMetricsHandler() metrics.Handler {
return wc.metricsHandler
}
func (wc *workflowEnvironmentImpl) GetDataConverter() converter.DataConverter {
return wc.dataConverter
}
func (wc *workflowEnvironmentImpl) GetFailureConverter() converter.FailureConverter {
return wc.failureConverter
}
func (wc *workflowEnvironmentImpl) GetContextPropagators() []ContextPropagator {
return wc.contextPropagators
}
func (wc *workflowEnvironmentImpl) IsReplaying() bool {
return wc.isReplay
}
func (wc *workflowEnvironmentImpl) GenerateSequenceID() string {
return getStringID(wc.GenerateSequence())
}
func (wc *workflowEnvironmentImpl) GenerateSequence() int64 {
return wc.commandsHelper.getNextID()
}
func (wc *workflowEnvironmentImpl) CreateNewCommand(commandType enumspb.CommandType) *commandpb.Command {
return &commandpb.Command{
CommandType: commandType,
}
}
func (wc *workflowEnvironmentImpl) ExecuteActivity(parameters ExecuteActivityParams, callback ResultHandler) ActivityID {
scheduleTaskAttr := &commandpb.ScheduleActivityTaskCommandAttributes{}
scheduleID := wc.GenerateSequence()
if parameters.ActivityID == "" {
scheduleTaskAttr.ActivityId = getStringID(scheduleID)
} else {
scheduleTaskAttr.ActivityId = parameters.ActivityID
}
activityID := scheduleTaskAttr.GetActivityId()
scheduleTaskAttr.ActivityType = &commonpb.ActivityType{Name: parameters.ActivityType.Name}
scheduleTaskAttr.TaskQueue = &taskqueuepb.TaskQueue{Name: parameters.TaskQueueName, Kind: enumspb.TASK_QUEUE_KIND_NORMAL}
scheduleTaskAttr.Input = parameters.Input
scheduleTaskAttr.ScheduleToCloseTimeout = durationpb.New(parameters.ScheduleToCloseTimeout)
scheduleTaskAttr.StartToCloseTimeout = durationpb.New(parameters.StartToCloseTimeout)
scheduleTaskAttr.ScheduleToStartTimeout = durationpb.New(parameters.ScheduleToStartTimeout)
scheduleTaskAttr.HeartbeatTimeout = durationpb.New(parameters.HeartbeatTimeout)
scheduleTaskAttr.RetryPolicy = parameters.RetryPolicy
scheduleTaskAttr.Header = parameters.Header
// We set this as true if not disabled on the params knowing it will be set as
// false just before request by the eager activity executor if eager activity
// execution is otherwise disallowed
scheduleTaskAttr.RequestEagerExecution = !parameters.DisableEagerExecution
scheduleTaskAttr.UseWorkflowBuildId = determineInheritBuildIdFlagForCommand(
parameters.VersioningIntent, wc.workflowInfo.TaskQueueName, parameters.TaskQueueName)
command := wc.commandsHelper.scheduleActivityTask(scheduleID, scheduleTaskAttr)
command.setData(&scheduledActivity{
callback: callback,
waitForCancelRequest: parameters.WaitForCancellation,
activityType: parameters.ActivityType,
})
wc.logger.Debug("ExecuteActivity",
tagActivityID, activityID,
tagActivityType, scheduleTaskAttr.ActivityType.GetName())
return ActivityID{id: activityID}
}
func (wc *workflowEnvironmentImpl) RequestCancelActivity(activityID ActivityID) {
command := wc.commandsHelper.requestCancelActivityTask(activityID.id)
activity := command.getData().(*scheduledActivity)
if activity.handled {
return
}
if command.isDone() || !activity.waitForCancelRequest {
activity.handle(nil, ErrCanceled)
}
wc.logger.Debug("RequestCancelActivity", tagActivityID, activityID)
}
func (wc *workflowEnvironmentImpl) ExecuteLocalActivity(params ExecuteLocalActivityParams, callback LocalActivityResultHandler) LocalActivityID {
activityID := wc.getNextLocalActivityID()
task := newLocalActivityTask(params, callback, activityID)
wc.pendingLaTasks[activityID] = task
wc.unstartedLaTasks[activityID] = struct{}{}
return LocalActivityID{id: activityID}
}
func newLocalActivityTask(params ExecuteLocalActivityParams, callback LocalActivityResultHandler, activityID string) *localActivityTask {
task := &localActivityTask{
activityID: activityID,
params: ¶ms,
callback: callback,
retryPolicy: params.RetryPolicy,
attempt: params.Attempt,
header: params.Header,
scheduledTime: time.Now(),
}
if params.ScheduleToCloseTimeout > 0 {
task.expireTime = params.ScheduledTime.Add(params.ScheduleToCloseTimeout)
}
return task
}
func (wc *workflowEnvironmentImpl) RequestCancelLocalActivity(activityID LocalActivityID) {
if task, ok := wc.pendingLaTasks[activityID.id]; ok {
task.cancel()
}
}
func (wc *workflowEnvironmentImpl) SetCurrentReplayTime(replayTime time.Time) {
if replayTime.Before(wc.currentReplayTime) {
return
}
wc.currentReplayTime = replayTime
wc.currentLocalTime = time.Now()
}
func (wc *workflowEnvironmentImpl) Now() time.Time {
return wc.currentReplayTime
}
func (wc *workflowEnvironmentImpl) NewTimer(d time.Duration, callback ResultHandler) *TimerID {
if d < 0 {
callback(nil, fmt.Errorf("negative duration provided %v", d))
return nil
}
if d == 0 {
callback(nil, nil)
return nil
}
timerID := wc.GenerateSequenceID()
startTimerAttr := &commandpb.StartTimerCommandAttributes{}
startTimerAttr.TimerId = timerID
startTimerAttr.StartToFireTimeout = durationpb.New(d)
command := wc.commandsHelper.startTimer(startTimerAttr)
command.setData(&scheduledTimer{callback: callback})
wc.logger.Debug("NewTimer",
tagTimerID, startTimerAttr.GetTimerId(),
"Duration", d)
return &TimerID{id: timerID}
}
func (wc *workflowEnvironmentImpl) RequestCancelTimer(timerID TimerID) {
command := wc.commandsHelper.cancelTimer(timerID)
timer := command.getData().(*scheduledTimer)
if timer != nil {
if timer.handled {
return
}
timer.handle(nil, ErrCanceled)
}
wc.logger.Debug("RequestCancelTimer", tagTimerID, timerID)
}
func validateVersion(changeID string, version, minSupported, maxSupported Version) {
if version < minSupported {
panicIllegalState(fmt.Sprintf("[TMPRL1100] Workflow code removed support of version %v. "+
"for \"%v\" changeID. The oldest supported version is %v",
version, changeID, minSupported))
}
if version > maxSupported {
panicIllegalState(fmt.Sprintf("[TMPRL1100] Workflow code is too old to support version %v "+
"for \"%v\" changeID. The maximum supported version is %v",
version, changeID, maxSupported))
}
}
func (wc *workflowEnvironmentImpl) GetVersion(changeID string, minSupported, maxSupported Version) Version {
if version, ok := wc.changeVersions[changeID]; ok {
validateVersion(changeID, version, minSupported, maxSupported)
return version
}
var version Version
if wc.isReplay {
// GetVersion for changeID is called first time in replay mode, use DefaultVersion
version = DefaultVersion
} else {
// GetVersion for changeID is called first time (non-replay mode), generate a marker command for it.
// Also upsert search attributes to enable ability to search by changeVersion.
version = maxSupported
changeVersionSA := createSearchAttributesForChangeVersion(changeID, version, wc.changeVersions)
attr, err := validateAndSerializeSearchAttributes(changeVersionSA)
if err != nil {
wc.logger.Warn(fmt.Sprintf("Failed to seralize %s search attribute with: %v", TemporalChangeVersion, err))
} else {
// Server has a limit for the max size of a single search attribute value. If we exceed the default limit
// do not try to upsert as it will cause the workflow to fail.
updateSearchAttribute := true
if wc.sdkFlags.tryUse(SDKFlagLimitChangeVersionSASize, !wc.isReplay) && len(attr.IndexedFields[TemporalChangeVersion].GetData()) >= changeVersionSearchAttrSizeLimit {
wc.logger.Warn(fmt.Sprintf("Serialized size of %s search attribute update would "+
"exceed the maximum value size. Skipping this upsert. Be aware that your "+
"visibility records will not include the following patch: %s", TemporalChangeVersion, getChangeVersion(changeID, version)),
)
updateSearchAttribute = false
}
wc.commandsHelper.recordVersionMarker(changeID, version, wc.GetDataConverter(), updateSearchAttribute)
if updateSearchAttribute {
_ = wc.UpsertSearchAttributes(changeVersionSA)
}
}
}
validateVersion(changeID, version, minSupported, maxSupported)
wc.changeVersions[changeID] = version
return version
}
func createSearchAttributesForChangeVersion(changeID string, version Version, existingChangeVersions map[string]Version) map[string]interface{} {
return map[string]interface{}{
TemporalChangeVersion: getChangeVersions(changeID, version, existingChangeVersions),
}
}
func getChangeVersions(changeID string, version Version, existingChangeVersions map[string]Version) []string {
res := []string{getChangeVersion(changeID, version)}
for k, v := range existingChangeVersions {
res = append(res, getChangeVersion(k, v))
}
return res
}
func getChangeVersion(changeID string, version Version) string {
return fmt.Sprintf("%s-%v", changeID, version)
}
func (wc *workflowEnvironmentImpl) SideEffect(f func() (*commonpb.Payloads, error), callback ResultHandler) {
sideEffectID := wc.getNextSideEffectID()
var result *commonpb.Payloads
if wc.isReplay {
var ok bool
result, ok = wc.sideEffectResult[sideEffectID]
if !ok {
keys := make([]int64, 0, len(wc.sideEffectResult))
for k := range wc.sideEffectResult {
keys = append(keys, k)
}
panicIllegalState(fmt.Sprintf("[TMPRL1100] No cached result found for side effectID=%v. KnownSideEffects=%v",
sideEffectID, keys))
}
// Once the SideEffect has been consumed, we can free the referenced payload
// to reduce memory pressure
delete(wc.sideEffectResult, sideEffectID)
wc.logger.Debug("SideEffect returning already calculated result.",
tagSideEffectID, sideEffectID)
} else {
var err error
result, err = f()
if err != nil {
callback(result, err)
return
}
}
wc.commandsHelper.recordSideEffectMarker(sideEffectID, result, wc.dataConverter)
callback(result, nil)
wc.logger.Debug("SideEffect Marker added", tagSideEffectID, sideEffectID)
}
func (wc *workflowEnvironmentImpl) TryUse(flag sdkFlag) bool {
return wc.sdkFlags.tryUse(flag, !wc.isReplay)
}
func (wc *workflowEnvironmentImpl) QueueUpdate(name string, f func()) {
wc.bufferedUpdateRequests[name] = append(wc.bufferedUpdateRequests[name], f)
}
func (wc *workflowEnvironmentImpl) HandleQueuedUpdates(name string) {
if bufferedUpdateRequests, ok := wc.bufferedUpdateRequests[name]; ok {
for _, request := range bufferedUpdateRequests {
request()
}
delete(wc.bufferedUpdateRequests, name)
}
}
func (wc *workflowEnvironmentImpl) DrainUnhandledUpdates() bool {
anyExecuted := false
// Check if any buffered update requests remain when we have no more coroutines to run and let them schedule so they are rejected.
// Generally iterating a map in workflow code is bad because it is non deterministic
// this case is fine since all these update handles will be rejected and not recorded in history.
for name, requests := range wc.bufferedUpdateRequests {
for _, request := range requests {
request()
anyExecuted = true
}
delete(wc.bufferedUpdateRequests, name)
}
return anyExecuted