forked from uber-go/cadence-client
/
internal_workflow_testsuite.go
1457 lines (1275 loc) · 50.9 KB
/
internal_workflow_testsuite.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
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
"sync"
"time"
"github.com/facebookgo/clock"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/mock"
"github.com/uber-go/tally"
"go.uber.org/cadence/.gen/go/cadence/workflowserviceclient"
"go.uber.org/cadence/.gen/go/cadence/workflowservicetest"
"go.uber.org/cadence/.gen/go/shared"
"go.uber.org/cadence/encoded"
"go.uber.org/cadence/internal/common"
"go.uber.org/cadence/internal/common/metrics"
"go.uber.org/yarpc"
"go.uber.org/zap"
)
const (
defaultTestDomain = "default-test-domain"
defaultTestTaskList = "default-test-tasklist"
defaultTestWorkflowID = "default-test-workflow-id"
defaultTestRunID = "default-test-run-id"
)
type (
testTimerHandle struct {
env *testWorkflowEnvironmentImpl
callback resultHandler
timer *clock.Timer
wallTimer *clock.Timer
duration time.Duration
mockTimeToFire time.Time
wallTimeToFire time.Time
timerID int
}
testActivityHandle struct {
callback resultHandler
activityType string
}
testWorkflowHandle struct {
env *testWorkflowEnvironmentImpl
callback resultHandler
handled bool
options *workflowOptions
err error
}
testCallbackHandle struct {
callback func()
startDecisionTask bool // start a new decision task after callback() is handled.
env *testWorkflowEnvironmentImpl
}
activityExecutorWrapper struct {
*activityExecutor
env *testWorkflowEnvironmentImpl
}
workflowExecutorWrapper struct {
*workflowExecutor
env *testWorkflowEnvironmentImpl
}
mockWrapper struct {
env *testWorkflowEnvironmentImpl
name string
fn interface{}
isWorkflow bool
}
taskListSpecificActivity struct {
fn interface{}
taskLists map[string]struct{}
}
// testWorkflowEnvironmentShared is the shared data between parent workflow and child workflow test environments
testWorkflowEnvironmentShared struct {
locker sync.Mutex
testSuite *WorkflowTestSuite
taskListSpecificActivities map[string]*taskListSpecificActivity
mock *mock.Mock
service workflowserviceclient.Interface
workerOptions WorkerOptions
logger *zap.Logger
metricsScope *metrics.TaggedScope
mockClock *clock.Mock
wallClock clock.Clock
startTime time.Time
callbackChannel chan testCallbackHandle
testTimeout time.Duration
counterID int
activities map[string]*testActivityHandle
localActivities map[string]*localActivityTask
timers map[string]*testTimerHandle
runningWorkflows map[string]*testWorkflowHandle
runningCount int
expectedMockCalls map[string]struct{}
onActivityStartedListener func(activityInfo *ActivityInfo, ctx context.Context, args encoded.Values)
onActivityCompletedListener func(activityInfo *ActivityInfo, result encoded.Value, err error)
onActivityCanceledListener func(activityInfo *ActivityInfo)
onLocalActivityStartedListener func(activityInfo *ActivityInfo, ctx context.Context, args []interface{})
onLocalActivityCompletedListener func(activityInfo *ActivityInfo, result encoded.Value, err error)
onLocalActivityCanceledListener func(activityInfo *ActivityInfo)
onActivityHeartbeatListener func(activityInfo *ActivityInfo, details encoded.Values)
onChildWorkflowStartedListener func(workflowInfo *WorkflowInfo, ctx Context, args encoded.Values)
onChildWorkflowCompletedListener func(workflowInfo *WorkflowInfo, result encoded.Value, err error)
onChildWorkflowCanceledListener func(workflowInfo *WorkflowInfo)
onTimerScheduledListener func(timerID string, duration time.Duration)
onTimerFiredListener func(timerID string)
onTimerCancelledListener func(timerID string)
}
// testWorkflowEnvironmentImpl is the environment that runs the workflow/activity unit tests.
testWorkflowEnvironmentImpl struct {
*testWorkflowEnvironmentShared
parentEnv *testWorkflowEnvironmentImpl
workflowInfo *WorkflowInfo
workflowDef workflowDefinition
changeVersions map[string]Version
workflowCancelHandler func()
signalHandler func(name string, input []byte)
queryHandler func(string, []byte) ([]byte, error)
startedHandler func(r WorkflowExecution, e error)
isTestCompleted bool
testResult EncodedValue
testError error
doneChannel chan struct{}
}
)
func newTestWorkflowEnvironmentImpl(s *WorkflowTestSuite) *testWorkflowEnvironmentImpl {
env := &testWorkflowEnvironmentImpl{
testWorkflowEnvironmentShared: &testWorkflowEnvironmentShared{
testSuite: s,
taskListSpecificActivities: make(map[string]*taskListSpecificActivity),
logger: s.logger,
metricsScope: metrics.NewTaggedScope(nil),
mockClock: clock.NewMock(),
wallClock: clock.New(),
timers: make(map[string]*testTimerHandle),
activities: make(map[string]*testActivityHandle),
localActivities: make(map[string]*localActivityTask),
runningWorkflows: make(map[string]*testWorkflowHandle),
callbackChannel: make(chan testCallbackHandle, 1000),
testTimeout: time.Second * 3,
expectedMockCalls: make(map[string]struct{}),
},
workflowInfo: &WorkflowInfo{
Domain: defaultTestDomain,
WorkflowExecution: WorkflowExecution{
ID: defaultTestWorkflowID,
RunID: defaultTestRunID,
},
WorkflowType: WorkflowType{Name: "workflow-type-not-specified"},
TaskListName: defaultTestTaskList,
ExecutionStartToCloseTimeoutSeconds: 1,
TaskStartToCloseTimeoutSeconds: 1,
},
changeVersions: make(map[string]Version),
doneChannel: make(chan struct{}),
}
// move forward the mock clock to start time.
startTime := env.startTime
if startTime == time.Unix(0, 0) {
// if start time not set, use current clock time
startTime = env.wallClock.Now()
}
env.mockClock.Add(startTime.Sub(env.mockClock.Now()))
// put current workflow as a running workflow so child can send signal to parent
env.runningWorkflows[env.workflowInfo.WorkflowExecution.ID] = &testWorkflowHandle{env: env, callback: func(result []byte, err error) {}}
if env.logger == nil {
logger, _ := zap.NewDevelopment()
env.logger = logger
}
if env.metricsScope == nil {
env.metricsScope = metrics.NewTaggedScope(s.scope)
}
// setup mock service
mockCtrl := gomock.NewController(&testReporter{logger: env.logger})
mockService := workflowservicetest.NewMockClient(mockCtrl)
mockHeartbeatFn := func(c context.Context, r *shared.RecordActivityTaskHeartbeatRequest, opts ...yarpc.CallOption) error {
activityID := string(r.TaskToken)
env.locker.Lock() // need lock as this is running in activity worker's goroutinue
activityHandle, ok := env.activities[activityID]
env.locker.Unlock()
if !ok {
env.logger.Debug("RecordActivityTaskHeartbeat: ActivityID not found, could be already completed or cancelled.",
zap.String(tagActivityID, activityID))
return &shared.EntityNotExistsError{}
}
activityInfo := env.getActivityInfo(activityID, activityHandle.activityType)
env.postCallback(func() {
if env.onActivityHeartbeatListener != nil {
env.onActivityHeartbeatListener(activityInfo, EncodedValues(r.Details))
}
}, false)
env.logger.Debug("RecordActivityTaskHeartbeat", zap.String(tagActivityID, activityID))
return nil
}
var callOptions []interface{}
for range yarpcCallOptions {
callOptions = append(callOptions, gomock.Any())
}
em := mockService.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), gomock.Any(), callOptions...).
Return(&shared.RecordActivityTaskHeartbeatResponse{CancelRequested: common.BoolPtr(false)}, nil)
em.Do(func(ctx context.Context, r *shared.RecordActivityTaskHeartbeatRequest, opts ...yarpc.CallOption) {
// TODO: The following will hit a data race in the gomock code where the Do() action is executed outside
// the lock and setting return value from inside the action is going to run into races.
// err := mockHeartbeatFn(ctx, r, opts)
// em.Return(&shared.RecordActivityTaskHeartbeatResponse{CancelRequested: common.BoolPtr(false)}, err)
mockHeartbeatFn(ctx, r, opts...)
}).AnyTimes()
env.service = mockService
if env.workerOptions.Logger == nil {
env.workerOptions.Logger = env.logger
}
if env.workerOptions.MetricsScope == nil {
env.workerOptions.MetricsScope = env.metricsScope
}
return env
}
func (env *testWorkflowEnvironmentImpl) newTestWorkflowEnvironmentForChild(options *workflowOptions, callback resultHandler, startedHandler func(r WorkflowExecution, e error)) (*testWorkflowEnvironmentImpl, error) {
// create a new test env
childEnv := newTestWorkflowEnvironmentImpl(env.testSuite)
childEnv.parentEnv = env
childEnv.startedHandler = startedHandler
childEnv.testWorkflowEnvironmentShared = env.testWorkflowEnvironmentShared
if options.workflowID == "" {
options.workflowID = env.workflowInfo.WorkflowExecution.RunID + "_" + getStringID(env.nextID())
}
// set workflow info data for child workflow
childEnv.workflowInfo.WorkflowExecution.ID = options.workflowID
childEnv.workflowInfo.WorkflowExecution.RunID = options.workflowID + "_RunID"
childEnv.workflowInfo.Domain = *options.domain
childEnv.workflowInfo.TaskListName = *options.taskListName
childEnv.workflowInfo.ExecutionStartToCloseTimeoutSeconds = *options.executionStartToCloseTimeoutSeconds
childEnv.workflowInfo.TaskStartToCloseTimeoutSeconds = *options.taskStartToCloseTimeoutSeconds
if workflowHandler, ok := env.runningWorkflows[options.workflowID]; ok {
// duplicate workflow ID
if !workflowHandler.handled {
return nil, errors.New("child workflow already running")
}
if options.workflowIDReusePolicy == WorkflowIDReusePolicyRejectDuplicate {
return nil, errors.New("duplicate workflow id not allowed")
}
if workflowHandler.err == nil && options.workflowIDReusePolicy == WorkflowIDReusePolicyAllowDuplicateFailedOnly {
return nil, errors.New("child workflow with specified workflow id already completed")
}
}
env.runningWorkflows[options.workflowID] = &testWorkflowHandle{env: childEnv, callback: callback, options: options}
return childEnv, nil
}
func (env *testWorkflowEnvironmentImpl) setWorkerOptions(options WorkerOptions) {
if len(options.Identity) > 0 {
env.workerOptions.Identity = options.Identity
}
if options.BackgroundActivityContext != nil {
env.workerOptions.BackgroundActivityContext = options.BackgroundActivityContext
}
if options.MetricsScope != nil {
env.workerOptions.MetricsScope = options.MetricsScope
}
}
func (env *testWorkflowEnvironmentImpl) setActivityTaskList(tasklist string, activityFns ...interface{}) {
for _, activityFn := range activityFns {
fnName := getFunctionName(activityFn)
taskListActivity, ok := env.taskListSpecificActivities[fnName]
if !ok {
taskListActivity = &taskListSpecificActivity{fn: activityFn, taskLists: make(map[string]struct{})}
env.taskListSpecificActivities[fnName] = taskListActivity
}
taskListActivity.taskLists[tasklist] = struct{}{}
}
}
func (env *testWorkflowEnvironmentImpl) executeWorkflow(workflowFn interface{}, args ...interface{}) {
workflowType, input, err := getValidatedWorkflowFunction(workflowFn, args)
if err != nil {
panic(err)
}
env.executeWorkflowInternal(workflowType.Name, input)
}
func (env *testWorkflowEnvironmentImpl) executeWorkflowInternal(workflowType string, input []byte) {
env.workflowInfo.WorkflowType.Name = workflowType
workflowDefinition, err := env.getWorkflowDefinition(env.workflowInfo.WorkflowType)
if err != nil {
panic(err)
}
env.workflowDef = workflowDefinition
// env.workflowDef.Execute() method will execute dispatcher. We want the dispatcher to only run in main loop.
// In case of child workflow, this executeWorkflowInternal() is run in separate goroutinue, so use postCallback
// to make sure workflowDef.Execute() is run in main loop.
env.postCallback(func() {
if env.isChildWorkflow() {
// notify parent that child workflow is started
env.parentEnv.postCallback(func() {
env.startedHandler(env.workflowInfo.WorkflowExecution, nil)
}, true)
}
env.workflowDef.Execute(env, input)
}, false)
env.startMainLoop()
}
func (env *testWorkflowEnvironmentImpl) getWorkflowDefinition(wt WorkflowType) (workflowDefinition, error) {
hostEnv := getHostEnvironment()
wf, ok := hostEnv.getWorkflowFn(wt.Name)
if !ok {
supported := strings.Join(hostEnv.getRegisteredWorkflowTypes(), ", ")
return nil, fmt.Errorf("Unable to find workflow type: %v. Supported types: [%v]", wt.Name, supported)
}
wd := &workflowExecutorWrapper{
workflowExecutor: &workflowExecutor{name: wt.Name, fn: wf},
env: env,
}
return newWorkflowDefinition(wd), nil
}
func (env *testWorkflowEnvironmentImpl) executeActivity(
activityFn interface{},
args ...interface{},
) (encoded.Value, error) {
activityType, input, err := getValidatedActivityFunction(activityFn, args)
if err != nil {
panic(err)
}
params := executeActivityParameters{
ActivityType: *activityType,
Input: input,
ScheduleToCloseTimeoutSeconds: 600,
StartToCloseTimeoutSeconds: 600,
}
task := newTestActivityTask(
defaultTestWorkflowID,
defaultTestRunID,
"0",
params,
)
// ensure activityFn is registered to defaultTestTaskList
taskHandler := env.newTestActivityTaskHandler(defaultTestTaskList)
result, err := taskHandler.Execute(defaultTestTaskList, task)
if err != nil {
topLine := fmt.Sprintf("activity for %s [panic]:", defaultTestTaskList)
st := getStackTraceRaw(topLine, 7, 0)
return nil, newPanicError(err.Error(), st)
}
if result == ErrActivityResultPending {
return nil, ErrActivityResultPending
}
switch request := result.(type) {
case *shared.RespondActivityTaskCanceledRequest:
return nil, NewCanceledError(request.Details)
case *shared.RespondActivityTaskFailedRequest:
return nil, constructError(request.GetReason(), request.Details)
case *shared.RespondActivityTaskCompletedRequest:
return EncodedValue(request.Result), nil
default:
// will never happen
return nil, fmt.Errorf("unsupported respond type %T", result)
}
}
func (env *testWorkflowEnvironmentImpl) executeLocalActivity(
activityFn interface{},
args ...interface{},
) (encoded.Value, error) {
params := executeLocalActivityParams{
ActivityFn: activityFn,
InputArgs: args,
ScheduleToCloseTimeoutSeconds: common.Int32Ceil(env.testTimeout.Seconds()),
WorkflowInfo: env.workflowInfo,
}
task := &localActivityTask{
activityID: "test-local-activity",
params: ¶ms,
callback: func(result []byte, err error) {
},
}
taskHandler := localActivityTaskHandler{
userContext: env.workerOptions.BackgroundActivityContext,
metricsScope: env.metricsScope,
logger: env.logger,
}
result := taskHandler.executeLocalActivityTask(task)
return EncodedValue(result.result), result.err
}
func (env *testWorkflowEnvironmentImpl) startDecisionTask() {
if !env.isTestCompleted {
env.workflowDef.OnDecisionTaskStarted()
}
}
func (env *testWorkflowEnvironmentImpl) isChildWorkflow() bool {
return env.parentEnv != nil
}
func (env *testWorkflowEnvironmentImpl) startMainLoop() {
if env.isChildWorkflow() {
// child workflow rely on parent workflow's main loop to process events
<-env.doneChannel // wait until workflow is complete
return
}
for {
// use non-blocking-select to check if there is anything pending in the main thread.
select {
case c := <-env.callbackChannel:
// this will drain the callbackChannel
c.processCallback()
default:
// nothing to process, main thread is blocked at this moment, now check if we should auto fire next timer
if !env.autoFireNextTimer() {
if env.isTestCompleted {
return
}
// no timer to fire, wait for things to do or timeout.
select {
case c := <-env.callbackChannel:
c.processCallback()
case <-time.After(env.testTimeout):
// not able to complete workflow within test timeout, workflow likely stuck somewhere,
// check workflow stack for more details.
panicMsg := fmt.Sprintf("test timeout: %v, workflow stack: %v",
env.testTimeout, env.workflowDef.StackTrace())
panic(panicMsg)
}
}
}
}
}
func (env *testWorkflowEnvironmentImpl) registerDelayedCallback(f func(), delayDuration time.Duration) {
timerCallback := func(result []byte, err error) {
f()
}
mainLoopCallback := func() {
env.newTimer(delayDuration, timerCallback, false)
}
env.postCallback(mainLoopCallback, false)
}
func (c *testCallbackHandle) processCallback() {
c.env.locker.Lock()
defer c.env.locker.Unlock()
c.callback()
if c.startDecisionTask {
c.env.startDecisionTask()
}
}
func (env *testWorkflowEnvironmentImpl) autoFireNextTimer() bool {
if len(env.timers) == 0 {
return false
}
// find next timer
var nextTimer *testTimerHandle
for _, t := range env.timers {
if nextTimer == nil {
nextTimer = t
} else if t.mockTimeToFire.Before(nextTimer.mockTimeToFire) ||
(t.mockTimeToFire.Equal(nextTimer.mockTimeToFire) && t.timerID < nextTimer.timerID) {
nextTimer = t
}
}
// function to fire timer
fireTimer := func(th *testTimerHandle) {
skipDuration := th.mockTimeToFire.Sub(env.mockClock.Now())
env.logger.Debug("Auto fire timer",
zap.Int(tagTimerID, th.timerID),
zap.Duration("TimerDuration", th.duration),
zap.Duration("TimeSkipped", skipDuration))
// Move mockClock forward, this will fire the timer, and the timer callback will remove timer from timers.
env.mockClock.Add(skipDuration)
}
// fire timer if there is no running activity
if env.runningCount == 0 {
if nextTimer.wallTimer != nil {
nextTimer.wallTimer.Stop()
nextTimer.wallTimer = nil
}
fireTimer(nextTimer)
return true
}
durationToFire := nextTimer.mockTimeToFire.Sub(env.mockClock.Now())
wallTimeToFire := env.wallClock.Now().Add(durationToFire)
if nextTimer.wallTimer != nil && nextTimer.wallTimeToFire.Before(wallTimeToFire) {
// nextTimer already set, meaning we already have a wall clock timer for the nextTimer setup earlier. And the
// previously scheduled wall time to fire is before the wallTimeToFire calculated this time. This could happen
// if workflow was blocked while there was activity running, and when that activity completed, there are some
// other activities still running while the nextTimer is still that same nextTimer. In that case, we should not
// reset the wall time to fire for the nextTimer.
return false
}
if nextTimer.wallTimer != nil {
// wallTimer was scheduled, but the wall time to fire should be earlier based on current calculation.
nextTimer.wallTimer.Stop()
}
// there is running activities, we would fire next timer only if wall time passed by nextTimer duration.
nextTimer.wallTimeToFire, nextTimer.wallTimer = wallTimeToFire, env.wallClock.AfterFunc(durationToFire, func() {
// make sure it is running in the main loop
nextTimer.env.postCallback(func() {
if timerHandle, ok := env.timers[getStringID(nextTimer.timerID)]; ok {
fireTimer(timerHandle)
}
}, true)
})
return false
}
func (env *testWorkflowEnvironmentImpl) postCallback(cb func(), startDecisionTask bool) {
env.callbackChannel <- testCallbackHandle{callback: cb, startDecisionTask: startDecisionTask, env: env}
}
func (env *testWorkflowEnvironmentImpl) RequestCancelActivity(activityID string) {
handle, ok := env.activities[activityID]
if !ok {
env.logger.Debug("RequestCancelActivity failed, Activity not exists or already completed.", zap.String(tagActivityID, activityID))
return
}
activityInfo := env.getActivityInfo(activityID, handle.activityType)
env.logger.Debug("RequestCancelActivity", zap.String(tagActivityID, activityID))
delete(env.activities, activityID)
env.postCallback(func() {
handle.callback(nil, NewCanceledError())
if env.onActivityCanceledListener != nil {
env.onActivityCanceledListener(activityInfo)
}
}, true)
}
// RequestCancelTimer request to cancel timer on this testWorkflowEnvironmentImpl.
func (env *testWorkflowEnvironmentImpl) RequestCancelTimer(timerID string) {
env.logger.Debug("RequestCancelTimer", zap.String(tagTimerID, timerID))
timerHandle, ok := env.timers[timerID]
if !ok {
env.logger.Debug("RequestCancelTimer failed, TimerID not exists.", zap.String(tagTimerID, timerID))
return
}
delete(env.timers, timerID)
timerHandle.timer.Stop()
timerHandle.env.postCallback(func() {
timerHandle.callback(nil, NewCanceledError())
if timerHandle.env.onTimerCancelledListener != nil {
timerHandle.env.onTimerCancelledListener(timerID)
}
}, true)
}
func (env *testWorkflowEnvironmentImpl) Complete(result []byte, err error) {
if env.isTestCompleted {
env.logger.Debug("Workflow already completed.")
return
}
if _, ok := err.(*CanceledError); ok && env.workflowCancelHandler != nil {
env.workflowCancelHandler()
}
env.isTestCompleted = true
env.testResult = EncodedValue(result)
if err != nil {
switch err := err.(type) {
case *CanceledError, *ContinueAsNewError, *TimeoutError:
env.testError = err
default:
env.testError = constructError(getErrorDetails(err))
}
}
close(env.doneChannel)
if env.isChildWorkflow() {
// this is completion of child workflow
childWorkflowID := env.workflowInfo.WorkflowExecution.ID
if childWorkflowHandle, ok := env.runningWorkflows[childWorkflowID]; ok && !childWorkflowHandle.handled {
// It is possible that child workflow could complete after cancellation. In that case, childWorkflowHandle
// would have already been removed from the runningWorkflows map by RequestCancelWorkflow().
childWorkflowHandle.handled = true
env.parentEnv.postCallback(func() {
// deliver result
childWorkflowHandle.err = env.testError
childWorkflowHandle.callback(env.testResult, env.testError)
if env.onChildWorkflowCompletedListener != nil {
env.onChildWorkflowCompletedListener(env.workflowInfo, env.testResult, env.testError)
}
}, true /* true to trigger parent workflow to resume to handle child workflow's result */)
}
}
}
func (env *testWorkflowEnvironmentImpl) CompleteActivity(taskToken []byte, result interface{}, err error) error {
if taskToken == nil {
return errors.New("nil task token provided")
}
var data []byte
if result != nil {
var encodeErr error
data, encodeErr = getHostEnvironment().encodeArg(result)
if encodeErr != nil {
return encodeErr
}
}
activityID := string(taskToken)
env.postCallback(func() {
activityHandle, ok := env.activities[activityID]
if !ok {
env.logger.Debug("CompleteActivity: ActivityID not found, could be already completed or cancelled.",
zap.String(tagActivityID, activityID))
return
}
request := convertActivityResultToRespondRequest("test-identity", taskToken, data, err)
env.handleActivityResult(activityID, request, activityHandle.activityType)
}, false /* do not auto schedule decision task, because activity might be still pending */)
return nil
}
func (env *testWorkflowEnvironmentImpl) GetLogger() *zap.Logger {
return env.logger
}
func (env *testWorkflowEnvironmentImpl) GetMetricsScope() tally.Scope {
return env.workerOptions.MetricsScope
}
func (env *testWorkflowEnvironmentImpl) ExecuteActivity(parameters executeActivityParameters, callback resultHandler) *activityInfo {
var activityID string
if parameters.ActivityID == nil || *parameters.ActivityID == "" {
activityID = getStringID(env.nextID())
} else {
activityID = *parameters.ActivityID
}
activityInfo := &activityInfo{activityID: activityID}
task := newTestActivityTask(
defaultTestWorkflowID,
defaultTestRunID,
activityInfo.activityID,
parameters,
)
taskHandler := env.newTestActivityTaskHandler(parameters.TaskListName)
activityHandle := &testActivityHandle{callback: callback, activityType: parameters.ActivityType.Name}
env.activities[activityInfo.activityID] = activityHandle
env.runningCount++
// activity runs in separate goroutinue outside of workflow dispatcher
go func() {
result, err := taskHandler.Execute(parameters.TaskListName, task)
if err != nil {
panic(err)
}
// post activity result to workflow dispatcher
env.postCallback(func() {
env.handleActivityResult(activityInfo.activityID, result, parameters.ActivityType.Name)
env.runningCount--
}, false /* do not auto schedule decision task, because activity might be still pending */)
}()
return activityInfo
}
func (env *testWorkflowEnvironmentImpl) ExecuteLocalActivity(params executeLocalActivityParams, callback resultHandler) *localActivityInfo {
activityID := getStringID(env.nextID())
wOptions := fillWorkerOptionsDefaults(env.workerOptions)
ae := &activityExecutor{name: getFunctionName(params.ActivityFn), fn: params.ActivityFn}
if at, _, _ := getValidatedActivityFunction(params.ActivityFn, params.InputArgs); at != nil {
// local activity could be registered, if so use the registered name. This name is only used to find a mock.
ae.name = at.Name
}
aew := &activityExecutorWrapper{activityExecutor: ae, env: env}
// substitute the local activity function so we could replace with mock if it is supplied.
params.ActivityFn = func(ctx context.Context, inputArgs ...interface{}) ([]byte, error) {
return aew.ExecuteWithActualArgs(ctx, params.InputArgs)
}
task := &localActivityTask{
activityID: activityID,
params: ¶ms,
callback: callback,
}
taskHandler := localActivityTaskHandler{
userContext: wOptions.BackgroundActivityContext,
metricsScope: wOptions.MetricsScope,
logger: wOptions.Logger,
}
env.localActivities[activityID] = task
env.runningCount++
go func() {
result := taskHandler.executeLocalActivityTask(task)
env.postCallback(func() {
env.handleLocalActivityResult(result)
env.runningCount--
}, false)
}()
return &localActivityInfo{activityID: activityID}
}
func (env *testWorkflowEnvironmentImpl) RequestCancelLocalActivity(activityID string) {
task, ok := env.localActivities[activityID]
if !ok {
env.logger.Debug("RequestCancelLocalActivity failed, LocalActivity not exists or already completed.", zap.String(tagActivityID, activityID))
return
}
activityInfo := env.getActivityInfo(activityID, getFunctionName(task.params.ActivityFn))
env.logger.Debug("RequestCancelLocalActivity", zap.String(tagActivityID, activityID))
delete(env.localActivities, activityID)
env.postCallback(func() {
task.callback(nil, NewCanceledError())
if env.onLocalActivityCanceledListener != nil {
env.onLocalActivityCanceledListener(activityInfo)
}
}, true)
}
func (env *testWorkflowEnvironmentImpl) handleActivityResult(activityID string, result interface{}, activityType string) {
env.logger.Debug(fmt.Sprintf("handleActivityResult: %T.", result),
zap.String(tagActivityID, activityID), zap.String(tagActivityType, activityType))
activityInfo := env.getActivityInfo(activityID, activityType)
if result == ErrActivityResultPending {
// In case activity returns ErrActivityResultPending, the respond will be nil, and we don't need to do anything.
// Activity will need to complete asynchronously using CompleteActivity().
if env.onActivityCompletedListener != nil {
env.onActivityCompletedListener(activityInfo, nil, ErrActivityResultPending)
}
return
}
// this is running in dispatcher
activityHandle, ok := env.activities[activityID]
if !ok {
env.logger.Debug("handleActivityResult: ActivityID not exists, could be already completed or cancelled.",
zap.String(tagActivityID, activityID))
return
}
delete(env.activities, activityID)
var blob []byte
var err error
switch request := result.(type) {
case *shared.RespondActivityTaskCanceledRequest:
err = NewCanceledError(request.Details)
activityHandle.callback(nil, err)
case *shared.RespondActivityTaskFailedRequest:
err = constructError(*request.Reason, request.Details)
activityHandle.callback(nil, err)
case *shared.RespondActivityTaskCompletedRequest:
blob = request.Result
activityHandle.callback(blob, nil)
default:
panic(fmt.Sprintf("unsupported respond type %T", result))
}
if env.onActivityCompletedListener != nil {
env.onActivityCompletedListener(activityInfo, EncodedValue(blob), err)
}
env.startDecisionTask()
}
func (env *testWorkflowEnvironmentImpl) handleLocalActivityResult(result *localActivityResult) {
activityID := result.task.activityID
activityType := getFunctionName(result.task.params.ActivityFn)
env.logger.Debug(fmt.Sprintf("handleLocalActivityResult: Err: %v, Result: %v.", result.err, string(result.result)),
zap.String(tagActivityID, activityID), zap.String(tagActivityType, activityType))
activityInfo := env.getActivityInfo(activityID, activityType)
task, ok := env.localActivities[activityID]
if !ok {
env.logger.Debug("handleLocalActivityResult: ActivityID not exists, could be already completed or cancelled.",
zap.String(tagActivityID, activityID))
return
}
delete(env.localActivities, activityID)
task.callback(result.result, result.err)
if env.onLocalActivityCompletedListener != nil {
env.onLocalActivityCompletedListener(activityInfo, EncodedValue(result.result), result.err)
}
env.startDecisionTask()
}
// runBeforeMockCallReturns is registered as mock call's RunFn by *mock.Call.Run(fn). It will be called by testify's
// mock.MethodCalled() before it returns.
func (env *testWorkflowEnvironmentImpl) runBeforeMockCallReturns(call *MockCallWrapper, args mock.Arguments) {
if call.waitDuration > 0 {
// we want this mock call to block until the wait duration is elapsed (on workflow clock).
waitCh := make(chan time.Time)
env.registerDelayedCallback(func() {
env.runningCount++ // increase runningCount as the mock call is ready to resume.
waitCh <- env.Now() // this will unblock mock call
}, call.waitDuration)
// make sure decrease runningCount after delayed callback is posted
env.postCallback(func() {
env.runningCount-- // reduce runningCount, since this mock call is about to be blocked.
}, false)
<-waitCh // this will block until mock clock move forward by waitDuration
}
// run the actual runFn if it was setup
if call.runFn != nil {
call.runFn(args)
}
}
// Execute executes the activity code.
func (a *activityExecutorWrapper) Execute(ctx context.Context, input []byte) ([]byte, error) {
activityInfo := GetActivityInfo(ctx)
if a.env.onActivityStartedListener != nil {
a.env.postCallback(func() {
a.env.onActivityStartedListener(&activityInfo, ctx, EncodedValues(input))
}, false)
}
m := &mockWrapper{env: a.env, name: a.name, fn: a.fn, isWorkflow: false}
if mockRet := m.getMockReturn(ctx, input); mockRet != nil {
return m.executeMock(ctx, input, mockRet)
}
return a.activityExecutor.Execute(ctx, input)
}
// Execute executes the activity code.
func (a *activityExecutorWrapper) ExecuteWithActualArgs(ctx context.Context, inputArgs []interface{}) ([]byte, error) {
activityInfo := GetActivityInfo(ctx)
if a.env.onLocalActivityStartedListener != nil {
a.env.postCallback(func() {
a.env.onLocalActivityStartedListener(&activityInfo, ctx, inputArgs)
}, false)
}
m := &mockWrapper{env: a.env, name: a.name, fn: a.fn, isWorkflow: false}
if mockRet := m.getMockReturnWithActualArgs(ctx, inputArgs); mockRet != nil {
return m.executeMockWithActualArgs(ctx, inputArgs, mockRet)
}
return a.activityExecutor.ExecuteWithActualArgs(ctx, inputArgs)
}
// Execute executes the workflow code.
func (w *workflowExecutorWrapper) Execute(ctx Context, input []byte) (result []byte, err error) {
env := w.env
if env.isChildWorkflow() && env.onChildWorkflowStartedListener != nil {
env.postCallback(func() {
env.onChildWorkflowStartedListener(GetWorkflowInfo(ctx), ctx, EncodedValues(input))
}, false)
}
if !env.isChildWorkflow() {
// This is to prevent auto-forwarding mock clock before main workflow starts. For child workflow, we increase
// the counter in env.ExecuteChildWorkflow(). We cannot do it here for child workflow, because we need to make
// sure the counter is increased before returning from ExecuteChildWorkflow().
env.runningCount++
}
m := &mockWrapper{env: env, name: w.name, fn: w.fn, isWorkflow: true}
// This method is called by workflow's dispatcher. In this test suite, it is run in the main loop. We cannot block
// the main loop, but the mock could block if it is configured to wait. So we need to use a separate goroutinue to
// run the mock, and resume after mock call returns.
mockReadyChannel := NewChannel(ctx)
// make a copy of the context for getMockReturn() call to avoid race condition
ctxCopy := newWorkflowContext(w.env)
go func() {
// getMockReturn could block if mock is configured to wait. The returned mockRet is what has been configured
// for the mock by using MockCallWrapper.Return(). The mockRet could be mock values or mock function. We process
// the returned mockRet by calling executeMock() later in the main thread after it is send over via mockReadyChannel.
mockRet := m.getMockReturn(ctxCopy, input)
env.postCallback(func() {
mockReadyChannel.SendAsync(mockRet)
}, true /* true to trigger the dispatcher for this workflow so it resume from mockReadyChannel block*/)
}()
var mockRet mock.Arguments
// This will block workflow dispatcher (on cadence channel), which the dispatcher understand and will return from
// ExecuteUntilAllBlocked() so the main loop is not blocked. The dispatcher will unblock when getMockReturn() returns.
mockReadyChannel.Receive(ctx, &mockRet)
// reduce runningCount to allow auto-forwarding mock clock after current workflow dispatcher run is blocked (aka
// ExecuteUntilAllBlocked() returns).
env.runningCount--
if mockRet != nil {
return m.executeMock(ctx, input, mockRet)
}
// no mock, so call the actual workflow
return w.workflowExecutor.Execute(ctx, input)
}
func (m *mockWrapper) getCtxArg(ctx interface{}) []interface{} {
fnType := reflect.TypeOf(m.fn)
if fnType.NumIn() > 0 {
if (!m.isWorkflow && isActivityContext(fnType.In(0))) ||
(m.isWorkflow && isWorkflowContext(fnType.In(0))) {
return []interface{}{ctx}
}
}
return nil
}
func (m *mockWrapper) getMockReturn(ctx interface{}, input []byte) (retArgs mock.Arguments) {
if _, ok := m.env.expectedMockCalls[m.name]; !ok {
// no mock
return nil
}
fnType := reflect.TypeOf(m.fn)
reflectArgs, err := getHostEnvironment().decodeArgs(fnType, input)
if err != nil {
panic(err)
}