forked from cadence-workflow/cadence
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_integration_test.go
516 lines (459 loc) · 16.3 KB
/
client_integration_test.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
// Copyright (c) 2021 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 host
import (
"bytes"
"context"
"encoding/gob"
"errors"
"flag"
"fmt"
"reflect"
"strconv"
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
apiv1 "github.com/uber/cadence-idl/go/proto/api/v1"
"go.uber.org/cadence/.gen/go/cadence/workflowserviceclient"
"go.uber.org/cadence/.gen/go/shared"
"go.uber.org/cadence/activity"
"go.uber.org/cadence/client"
"go.uber.org/cadence/compatibility"
"go.uber.org/cadence/encoded"
"go.uber.org/cadence/worker"
"go.uber.org/cadence/workflow"
"go.uber.org/yarpc"
"go.uber.org/yarpc/transport/grpc"
"go.uber.org/zap"
"github.com/uber/cadence/common/log/tag"
"github.com/uber/cadence/common/service"
)
func init() {
workflow.Register(testDataConverterWorkflow)
activity.Register(testActivity)
workflow.Register(testParentWorkflow)
workflow.Register(testChildWorkflow)
}
func TestClientIntegrationSuite(t *testing.T) {
flag.Parse()
clusterConfig, err := GetTestClusterConfig("testdata/clientintegrationtestcluster.yaml")
if err != nil {
panic(err)
}
testCluster := NewPersistenceTestCluster(t, clusterConfig)
s := new(ClientIntegrationSuite)
params := IntegrationBaseParams{
DefaultTestCluster: testCluster,
VisibilityTestCluster: testCluster,
TestClusterConfig: clusterConfig,
}
s.IntegrationBase = NewIntegrationBase(params)
suite.Run(t, s)
}
func (s *ClientIntegrationSuite) SetupSuite() {
s.setupSuite()
var err error
s.wfService, err = s.buildServiceClient()
if err != nil {
s.Logger.Fatal("Error when build service client", tag.Error(err))
}
s.wfClient = client.NewClient(s.wfService, s.domainName, nil)
s.taskList = "client-integration-test-tasklist"
s.worker = worker.New(s.wfService, s.domainName, s.taskList, worker.Options{})
if err := s.worker.Start(); err != nil {
s.Logger.Fatal("Error when start worker", tag.Error(err))
} else {
s.Logger.Info("Worker started")
}
}
func (s *ClientIntegrationSuite) TearDownSuite() {
s.tearDownSuite()
}
func (s *ClientIntegrationSuite) buildServiceClient() (workflowserviceclient.Interface, error) {
cadenceClientName := "cadence-client"
hostPort := "127.0.0.1:7114" // use grpc port
if TestFlags.FrontendAddr != "" {
hostPort = TestFlags.FrontendAddr
}
ch := grpc.NewTransport(
grpc.ServerMaxRecvMsgSize(32*1024*1024),
grpc.ClientMaxRecvMsgSize(32*1024*1024),
)
dispatcher := yarpc.NewDispatcher(yarpc.Config{
Name: cadenceClientName,
Outbounds: yarpc.Outbounds{
service.Frontend: {Unary: ch.NewSingleOutbound(hostPort)},
},
})
if dispatcher == nil {
s.Logger.Fatal("No RPC dispatcher provided to create a connection to Cadence Service")
}
if err := dispatcher.Start(); err != nil {
s.Logger.Fatal("Failed to create outbound transport channel", tag.Error(err))
}
cc := dispatcher.ClientConfig(service.Frontend)
return compatibility.NewThrift2ProtoAdapter(
apiv1.NewDomainAPIYARPCClient(cc),
apiv1.NewWorkflowAPIYARPCClient(cc),
apiv1.NewWorkerAPIYARPCClient(cc),
apiv1.NewVisibilityAPIYARPCClient(cc),
), nil
}
func (s *ClientIntegrationSuite) SetupTest() {
// Have to define our overridden assertions in the test setup. If we did it earlier, s.T() will return nil
s.Assertions = require.New(s.T())
}
// testDataConverter implements encoded.DataConverter using gob
type testDataConverter struct {
NumOfCallToData int // for testing to know testDataConverter is called as expected
NumOfCallFromData int
}
func (tdc *testDataConverter) ToData(value ...interface{}) ([]byte, error) {
tdc.NumOfCallToData++
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
for i, obj := range value {
if err := enc.Encode(obj); err != nil {
return nil, fmt.Errorf(
"unable to encode argument: %d, %v, with gob error: %v", i, reflect.TypeOf(obj), err)
}
}
return buf.Bytes(), nil
}
func (tdc *testDataConverter) FromData(input []byte, valuePtr ...interface{}) error {
tdc.NumOfCallFromData++
dec := gob.NewDecoder(bytes.NewBuffer(input))
for i, obj := range valuePtr {
if err := dec.Decode(obj); err != nil {
return fmt.Errorf(
"unable to decode argument: %d, %v, with gob error: %v", i, reflect.TypeOf(obj), err)
}
}
return nil
}
func newTestDataConverter() encoded.DataConverter {
return &testDataConverter{}
}
func testActivity(ctx context.Context, msg string) (string, error) {
return "hello_" + msg, nil
}
func testDataConverterWorkflow(ctx workflow.Context, tl string) (string, error) {
ao := workflow.ActivityOptions{
ScheduleToStartTimeout: 20 * time.Second,
StartToCloseTimeout: 40 * time.Second,
}
ctx = workflow.WithActivityOptions(ctx, ao)
var result string
err := workflow.ExecuteActivity(ctx, testActivity, "world").Get(ctx, &result)
if err != nil {
return "", err
}
// use another converter to run activity,
// with new taskList so that worker with same data converter can properly process tasks.
var result1 string
ctx1 := workflow.WithDataConverter(ctx, newTestDataConverter())
ctx1 = workflow.WithTaskList(ctx1, tl)
err1 := workflow.ExecuteActivity(ctx1, testActivity, "world1").Get(ctx1, &result1)
if err1 != nil {
return "", err1
}
return result + "," + result1, nil
}
func (s *ClientIntegrationSuite) startWorkerWithDataConverter(tl string, dataConverter encoded.DataConverter) worker.Worker {
opts := worker.Options{}
if dataConverter != nil {
opts.DataConverter = dataConverter
}
worker := worker.New(s.wfService, s.domainName, tl, opts)
if err := worker.Start(); err != nil {
s.Logger.Fatal("Error when start worker with data converter", tag.Error(err))
}
return worker
}
func (s *ClientIntegrationSuite) TestClientDataConverter() {
tl := "client-integration-data-converter-activity-tasklist"
dc := newTestDataConverter()
worker := s.startWorkerWithDataConverter(tl, dc)
defer worker.Stop()
id := "client-integration-data-converter-workflow"
workflowOptions := client.StartWorkflowOptions{
ID: id,
TaskList: s.taskList,
ExecutionStartToCloseTimeout: 60 * time.Second,
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
we, err := s.wfClient.ExecuteWorkflow(ctx, workflowOptions, testDataConverterWorkflow, tl)
if err != nil {
s.Logger.Fatal("Start workflow with err", tag.Error(err))
}
s.NotNil(we)
s.True(we.GetRunID() != "")
var res string
err = we.Get(ctx, &res)
s.NoError(err)
s.Equal("hello_world,hello_world1", res)
// to ensure custom data converter is used, this number might be different if client changed.
d := dc.(*testDataConverter)
s.Equal(1, d.NumOfCallToData)
s.Equal(1, d.NumOfCallFromData)
}
func (s *ClientIntegrationSuite) TestClientDataConverter_Failed() {
tl := "client-integration-data-converter-activity-failed-tasklist"
worker := s.startWorkerWithDataConverter(tl, nil) // mismatch of data converter
defer worker.Stop()
id := "client-integration-data-converter-failed-workflow"
workflowOptions := client.StartWorkflowOptions{
ID: id,
TaskList: s.taskList,
ExecutionStartToCloseTimeout: 60 * time.Second,
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
we, err := s.wfClient.ExecuteWorkflow(ctx, workflowOptions, testDataConverterWorkflow, tl)
if err != nil {
s.Logger.Fatal("Start workflow with err", tag.Error(err))
}
s.NotNil(we)
s.True(we.GetRunID() != "")
var res string
err = we.Get(ctx, &res)
s.Error(err)
// Get history to make sure only the 2nd activity is failed because of mismatch of data converter
iter := s.wfClient.GetWorkflowHistory(ctx, id, we.GetRunID(), false, 0)
completedAct := 0
failedAct := 0
for iter.HasNext() {
event, err := iter.Next()
s.Nil(err)
if event.GetEventType() == shared.EventTypeActivityTaskCompleted {
completedAct++
}
if event.GetEventType() == shared.EventTypeActivityTaskFailed {
failedAct++
attr := event.ActivityTaskFailedEventAttributes
s.True(strings.HasPrefix(string(attr.Details), "unable to decode the activity function input bytes with error"))
}
}
s.Equal(1, completedAct)
s.Equal(1, failedAct)
}
var childTaskList = "client-integration-data-converter-child-tasklist"
func testParentWorkflow(ctx workflow.Context) (string, error) {
logger := workflow.GetLogger(ctx)
execution := workflow.GetInfo(ctx).WorkflowExecution
childID := fmt.Sprintf("child_workflow:%v", execution.RunID)
cwo := workflow.ChildWorkflowOptions{
WorkflowID: childID,
ExecutionStartToCloseTimeout: time.Minute,
}
ctx = workflow.WithChildOptions(ctx, cwo)
var result string
err := workflow.ExecuteChildWorkflow(ctx, testChildWorkflow, 0, 3).Get(ctx, &result)
if err != nil {
logger.Error("Parent execution received child execution failure.", zap.Error(err))
return "", err
}
childID1 := fmt.Sprintf("child_workflow1:%v", execution.RunID)
cwo1 := workflow.ChildWorkflowOptions{
WorkflowID: childID1,
ExecutionStartToCloseTimeout: time.Minute,
TaskList: childTaskList,
}
ctx1 := workflow.WithChildOptions(ctx, cwo1)
ctx1 = workflow.WithDataConverter(ctx1, newTestDataConverter())
var result1 string
err1 := workflow.ExecuteChildWorkflow(ctx1, testChildWorkflow, 0, 2).Get(ctx1, &result1)
if err1 != nil {
logger.Error("Parent execution received child execution 1 failure.", zap.Error(err1))
return "", err1
}
res := fmt.Sprintf("Complete child1 %s times, complete child2 %s times", result, result1)
logger.Info("Parent execution completed.", zap.String("Result", res))
return res, nil
}
func testChildWorkflow(ctx workflow.Context, totalCount, runCount int) (string, error) {
logger := workflow.GetLogger(ctx)
logger.Info("Child workflow execution started.")
if runCount <= 0 {
logger.Error("Invalid valid for run count.", zap.Int("RunCount", runCount))
return "", errors.New("invalid run count")
}
totalCount++
runCount--
if runCount == 0 {
result := fmt.Sprintf("Child workflow execution completed after %v runs", totalCount)
logger.Info("Child workflow completed.", zap.String("Result", result))
return strconv.Itoa(totalCount), nil
}
logger.Info("Child workflow starting new run.", zap.Int("RunCount", runCount), zap.Int("TotalCount",
totalCount))
return "", workflow.NewContinueAsNewError(ctx, testChildWorkflow, totalCount, runCount)
}
func (s *ClientIntegrationSuite) TestClientDataConverter_WithChild() {
dc := newTestDataConverter()
worker := s.startWorkerWithDataConverter(childTaskList, dc)
defer worker.Stop()
id := "client-integration-data-converter-with-child-workflow"
workflowOptions := client.StartWorkflowOptions{
ID: id,
TaskList: s.taskList,
ExecutionStartToCloseTimeout: 60 * time.Second,
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
we, err := s.wfClient.ExecuteWorkflow(ctx, workflowOptions, testParentWorkflow)
if err != nil {
s.Logger.Fatal("Start workflow with err", tag.Error(err))
}
s.NotNil(we)
s.True(we.GetRunID() != "")
var res string
err = we.Get(ctx, &res)
s.NoError(err)
s.Equal("Complete child1 3 times, complete child2 2 times", res)
// to ensure custom data converter is used, this number might be different if client changed.
d := dc.(*testDataConverter)
s.Equal(3, d.NumOfCallToData)
s.Equal(2, d.NumOfCallFromData)
}
func (s *ClientIntegrationSuite) Test_StickyWorkerRestartDecisionTask() {
testCases := []struct {
name string
waitTime time.Duration
doQuery bool
doSignal bool
delayCheck func(duration time.Duration) bool
}{
{
name: "new_query_after_10s_no_delay",
waitTime: 10 * time.Second,
doQuery: true,
delayCheck: func(duration time.Duration) bool {
return duration < 5*time.Second
},
},
{
name: "new_query_immediately_expect_5s_delay",
waitTime: 0,
doQuery: true,
delayCheck: func(duration time.Duration) bool {
return duration > 5*time.Second
},
},
{
name: "new_workflow_task_after_10s_no_delay",
waitTime: 10 * time.Second,
doSignal: true,
delayCheck: func(duration time.Duration) bool {
return duration < 5*time.Second
},
},
{
name: "new_workflow_task_immediately_expect_5s_delay",
waitTime: 0,
doSignal: true,
delayCheck: func(duration time.Duration) bool {
return duration > 5*time.Second
},
},
}
for _, tt := range testCases {
s.Run(tt.name, func() {
workflowFn := func(ctx workflow.Context) (string, error) {
workflow.SetQueryHandler(ctx, "test", func() (string, error) {
return "query works", nil
})
signalCh := workflow.GetSignalChannel(ctx, "test")
var msg string
signalCh.Receive(ctx, &msg)
return msg, nil
}
taskList := "task-list-" + tt.name
oldWorker := worker.New(s.wfService, s.domainName, taskList, worker.Options{})
oldWorker.RegisterWorkflow(workflowFn)
if err := oldWorker.Start(); err != nil {
s.Logger.Fatal("Error when start worker", tag.Error(err))
}
id := "test-sticky-delay" + tt.name
workflowOptions := client.StartWorkflowOptions{
ID: id,
TaskList: taskList,
ExecutionStartToCloseTimeout: 20 * time.Second,
}
ctx, cancel := context.WithTimeout(context.Background(), 1000*time.Second)
defer cancel()
workflowRun, err := s.wfClient.ExecuteWorkflow(ctx, workflowOptions, workflowFn)
if err != nil {
s.Logger.Fatal("Start workflow failed with err", tag.Error(err))
}
s.NotNil(workflowRun)
s.True(workflowRun.GetRunID() != "")
findFirstWorkflowTaskCompleted := false
WaitForFirstWorkflowTaskComplete:
for i := 0; i < 10; i++ {
// wait until first workflow task completed (so we know sticky is set on workflow)
iter := s.wfClient.GetWorkflowHistory(ctx, id, "", false, 0)
for iter.HasNext() {
evt, err := iter.Next()
s.NoError(err)
if evt.GetEventType() == shared.EventTypeDecisionTaskCompleted {
findFirstWorkflowTaskCompleted = true
break WaitForFirstWorkflowTaskComplete
}
}
time.Sleep(time.Second)
}
s.True(findFirstWorkflowTaskCompleted)
// stop old worker
oldWorker.Stop()
// maybe wait for 10s, which will make matching aware the old sticky worker is unavailable
time.Sleep(tt.waitTime)
// start a new worker
newWorker := worker.New(s.wfService, s.domainName, taskList, worker.Options{})
newWorker.RegisterWorkflow(workflowFn)
if err := newWorker.Start(); err != nil {
s.Logger.Fatal("Error when start worker", tag.Error(err))
}
defer newWorker.Stop()
startTime := time.Now()
// send a signal, and workflow should complete immediately, there should not be 5s delay
if tt.doSignal {
err = s.wfClient.SignalWorkflow(ctx, id, "", "test", "test")
s.NoError(err)
err = workflowRun.Get(ctx, nil)
s.NoError(err)
} else if tt.doQuery {
// send a signal, and workflow should complete immediately, there should not be 5s delay
queryResult, err := s.wfClient.QueryWorkflow(ctx, id, "", "test", "test")
s.NoError(err)
var queryResultStr string
err = queryResult.Get(&queryResultStr)
s.NoError(err)
s.Equal("query works", queryResultStr)
}
endTime := time.Now()
duration := endTime.Sub(startTime)
s.True(tt.delayCheck(duration), "delay check failed: %s", duration)
})
}
}