From f0330563ea832cd94d98a2ca63d4ff6ebbdb9521 Mon Sep 17 00:00:00 2001 From: Vytautas Karpavicius Date: Thu, 17 Jun 2021 10:57:53 +0300 Subject: [PATCH] Switch all internals to protobuf --- .gen/go/cadence/cadence.go | 4 +- .../cadence/workflowserviceclient/client.go | 4 +- .gen/go/cadence/workflowservicefx/client.go | 2 +- .gen/go/cadence/workflowservicefx/server.go | 2 +- .../cadence/workflowserviceserver/server.go | 4 +- .gen/go/cadence/workflowservicetest/client.go | 4 +- .gen/go/shadower/shadower.go | 4 +- .gen/go/shared/shared.go | 2 +- Makefile | 2 +- activity/activity.go | 2 +- activity/doc.go | 2 +- cadence.go | 8 +- client/client.go | 42 +- docker/buildkite/docker-compose-local.yml | 5 +- docker/buildkite/docker-compose.yml | 3 +- encoded/encoded.go | 2 +- error.go | 22 +- evictiontest/workflow_cache_eviction_test.go | 68 +- go.mod | 2 +- interceptors/workflow_interceptor.go | 2 +- internal/activity.go | 42 +- internal/activity_test.go | 49 +- internal/api/error.go | 2 +- internal/api/error_test.go | 2 +- internal/api/helpers.go | 82 ++ internal/api/interface.go | 4 +- internal/api/interface_mock.go | 2 +- internal/api/thrift/mapper.go | 1164 +++++++++++++++++ internal/client.go | 62 +- internal/cmd/dummy/dummy.go | 14 +- internal/common/convert.go | 32 - internal/common/metrics/service_wrapper.go | 155 ++- .../common/metrics/service_wrapper_test.go | 81 +- .../common/serializer/history_serializer.go | 108 +- internal/common/util/stringer.go | 124 +- internal/common/util/stringer_test.go | 24 + internal/context.go | 4 +- internal/encoded.go | 4 +- internal/encoding.go | 2 +- internal/error.go | 10 +- internal/error_test.go | 37 +- internal/headers.go | 16 +- internal/headers_test.go | 58 +- internal/internal_activity.go | 30 +- internal/internal_coroutines_test.go | 2 +- internal/internal_decision_state_machine.go | 216 +-- .../internal_decision_state_machine_test.go | 136 +- internal/internal_event_handlers.go | 349 +++-- internal/internal_event_handlers_test.go | 42 +- internal/internal_pressure_points.go | 4 +- internal/internal_public.go | 8 +- internal/internal_retry.go | 22 +- internal/internal_task_handlers.go | 588 +++++---- .../internal_task_handlers_interfaces_test.go | 73 +- internal/internal_task_handlers_test.go | 808 ++++++------ internal/internal_task_pollers.go | 326 ++--- internal/internal_utils.go | 47 +- internal/internal_utils_test.go | 16 +- internal/internal_worker.go | 37 +- internal/internal_worker_base.go | 15 +- internal/internal_worker_interfaces_test.go | 26 +- internal/internal_worker_test.go | 143 +- internal/internal_workers_test.go | 509 +++---- internal/internal_workflow.go | 23 +- internal/internal_workflow_client.go | 425 +++--- internal/internal_workflow_client_test.go | 536 ++++---- internal/internal_workflow_test.go | 10 +- internal/internal_workflow_testsuite.go | 164 +-- internal/internal_workflow_testsuite_test.go | 64 +- internal/query_builder.go | 16 +- internal/registry_test.go | 16 +- internal/session.go | 19 +- internal/testdata/localActivities.json | 2 +- internal/testdata/parentWF.json | 4 +- internal/testdata/sampleHistory.json | 4 +- internal/tracer_test.go | 22 +- internal/worker.go | 12 +- internal/workflow.go | 37 +- internal/workflow_replayer.go | 115 +- internal/workflow_replayer_test.go | 229 ++-- internal/workflow_shadower.go | 12 +- internal/workflow_shadower_activities.go | 42 +- internal/workflow_shadower_activities_test.go | 35 +- internal/workflow_shadower_test.go | 69 +- internal/workflow_shadower_worker.go | 39 +- internal/workflow_shadower_worker_test.go | 60 +- internal/workflow_testsuite.go | 8 +- mocks/Client.go | 111 +- mocks/DomainClient.go | 18 +- mocks/HistoryEventIterator.go | 10 +- mocks/mock_test.go | 10 +- mocks/verify.go | 2 +- test/activity_test.go | 6 +- test/fixtures/activity.cancel.sm.repro.json | 2 +- test/integration_test.go | 43 +- test/replaytests/basic.json | 2 +- test/replaytests/basic_new.json | 2 +- test/replaytests/reply_test.go | 2 +- test/replaytests/version.json | 2 +- test/replaytests/version_new.json | 2 +- test/replaytests/workflows.go | 4 +- test/test_utils.go | 34 +- test/workflow_test.go | 28 +- testsuite/testsuite.go | 2 +- version.go | 2 +- worker/worker.go | 25 +- workflow/activity_options.go | 2 +- workflow/context.go | 2 +- workflow/context_propagator.go | 2 +- workflow/deterministic_wrappers.go | 2 +- workflow/doc.go | 4 +- workflow/error.go | 6 +- workflow/session.go | 2 +- workflow/workflow.go | 4 +- workflow/workflow_options.go | 4 +- 115 files changed, 4655 insertions(+), 3304 deletions(-) create mode 100644 internal/api/helpers.go create mode 100644 internal/api/thrift/mapper.go diff --git a/.gen/go/cadence/cadence.go b/.gen/go/cadence/cadence.go index 9e539eb12..1dd4b3929 100644 --- a/.gen/go/cadence/cadence.go +++ b/.gen/go/cadence/cadence.go @@ -26,7 +26,7 @@ package cadence import ( errors "errors" fmt "fmt" - shared "go.uber.org/cadence/v1/.gen/go/shared" + shared "go.uber.org/cadence/v2/.gen/go/shared" multierr "go.uber.org/multierr" thriftreflect "go.uber.org/thriftrw/thriftreflect" wire "go.uber.org/thriftrw/wire" @@ -37,7 +37,7 @@ import ( // ThriftModule represents the IDL file used to generate this package. var ThriftModule = &thriftreflect.ThriftModule{ Name: "cadence", - Package: "go.uber.org/cadence/v1/.gen/go/cadence", + Package: "go.uber.org/cadence/v2/.gen/go/cadence", FilePath: "cadence.thrift", SHA1: "9bc839885f29c2460af53bf639994d20e53521a0", Includes: []*thriftreflect.ThriftModule{ diff --git a/.gen/go/cadence/workflowserviceclient/client.go b/.gen/go/cadence/workflowserviceclient/client.go index f8ca1af2a..6199eb187 100644 --- a/.gen/go/cadence/workflowserviceclient/client.go +++ b/.gen/go/cadence/workflowserviceclient/client.go @@ -25,8 +25,8 @@ package workflowserviceclient import ( context "context" - cadence "go.uber.org/cadence/v1/.gen/go/cadence" - shared "go.uber.org/cadence/v1/.gen/go/shared" + cadence "go.uber.org/cadence/v2/.gen/go/cadence" + shared "go.uber.org/cadence/v2/.gen/go/shared" wire "go.uber.org/thriftrw/wire" yarpc "go.uber.org/yarpc" transport "go.uber.org/yarpc/api/transport" diff --git a/.gen/go/cadence/workflowservicefx/client.go b/.gen/go/cadence/workflowservicefx/client.go index a39850e16..d17f76896 100644 --- a/.gen/go/cadence/workflowservicefx/client.go +++ b/.gen/go/cadence/workflowservicefx/client.go @@ -24,7 +24,7 @@ package workflowservicefx import ( - workflowserviceclient "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" + workflowserviceclient "go.uber.org/cadence/v2/.gen/go/cadence/workflowserviceclient" fx "go.uber.org/fx" yarpc "go.uber.org/yarpc" transport "go.uber.org/yarpc/api/transport" diff --git a/.gen/go/cadence/workflowservicefx/server.go b/.gen/go/cadence/workflowservicefx/server.go index 543f0dc77..eac8f6ad4 100644 --- a/.gen/go/cadence/workflowservicefx/server.go +++ b/.gen/go/cadence/workflowservicefx/server.go @@ -24,7 +24,7 @@ package workflowservicefx import ( - workflowserviceserver "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceserver" + workflowserviceserver "go.uber.org/cadence/v2/.gen/go/cadence/workflowserviceserver" fx "go.uber.org/fx" transport "go.uber.org/yarpc/api/transport" thrift "go.uber.org/yarpc/encoding/thrift" diff --git a/.gen/go/cadence/workflowserviceserver/server.go b/.gen/go/cadence/workflowserviceserver/server.go index 9c0c9cd2e..8c878d684 100644 --- a/.gen/go/cadence/workflowserviceserver/server.go +++ b/.gen/go/cadence/workflowserviceserver/server.go @@ -25,8 +25,8 @@ package workflowserviceserver import ( context "context" - cadence "go.uber.org/cadence/v1/.gen/go/cadence" - shared "go.uber.org/cadence/v1/.gen/go/shared" + cadence "go.uber.org/cadence/v2/.gen/go/cadence" + shared "go.uber.org/cadence/v2/.gen/go/shared" wire "go.uber.org/thriftrw/wire" transport "go.uber.org/yarpc/api/transport" thrift "go.uber.org/yarpc/encoding/thrift" diff --git a/.gen/go/cadence/workflowservicetest/client.go b/.gen/go/cadence/workflowservicetest/client.go index 4a3ecbff5..023128edf 100644 --- a/.gen/go/cadence/workflowservicetest/client.go +++ b/.gen/go/cadence/workflowservicetest/client.go @@ -26,8 +26,8 @@ package workflowservicetest import ( context "context" gomock "github.com/golang/mock/gomock" - workflowserviceclient "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" - shared "go.uber.org/cadence/v1/.gen/go/shared" + workflowserviceclient "go.uber.org/cadence/v2/.gen/go/cadence/workflowserviceclient" + shared "go.uber.org/cadence/v2/.gen/go/shared" yarpc "go.uber.org/yarpc" ) diff --git a/.gen/go/shadower/shadower.go b/.gen/go/shadower/shadower.go index 76918f226..289087420 100644 --- a/.gen/go/shadower/shadower.go +++ b/.gen/go/shadower/shadower.go @@ -28,7 +28,7 @@ import ( base64 "encoding/base64" json "encoding/json" fmt "fmt" - shared "go.uber.org/cadence/v1/.gen/go/shared" + shared "go.uber.org/cadence/v2/.gen/go/shared" multierr "go.uber.org/multierr" thriftreflect "go.uber.org/thriftrw/thriftreflect" wire "go.uber.org/thriftrw/wire" @@ -2157,7 +2157,7 @@ func (v *WorkflowResult) IsSetFailed() bool { // ThriftModule represents the IDL file used to generate this package. var ThriftModule = &thriftreflect.ThriftModule{ Name: "shadower", - Package: "go.uber.org/cadence/v1/.gen/go/shadower", + Package: "go.uber.org/cadence/v2/.gen/go/shadower", FilePath: "shadower.thrift", SHA1: "f29a425548641e51e02ec1978279c1e37b9df792", Includes: []*thriftreflect.ThriftModule{ diff --git a/.gen/go/shared/shared.go b/.gen/go/shared/shared.go index 5f4d9d2d5..fcdf5a302 100644 --- a/.gen/go/shared/shared.go +++ b/.gen/go/shared/shared.go @@ -62159,7 +62159,7 @@ func (v *WorkflowTypeFilter) IsSetName() bool { // ThriftModule represents the IDL file used to generate this package. var ThriftModule = &thriftreflect.ThriftModule{ Name: "shared", - Package: "go.uber.org/cadence/v1/.gen/go/shared", + Package: "go.uber.org/cadence/v2/.gen/go/shared", FilePath: "shared.thrift", SHA1: "b3a2d4a23233e8f33177d38c1935f0b593db4d31", Raw: rawIDL, diff --git a/Makefile b/Makefile index 5ff4f9255..4fa9aeb09 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ default: test OS = $(shell uname -s) ARCH = $(shell uname -m) -IMPORT_ROOT := go.uber.org/cadence/v1 +IMPORT_ROOT := go.uber.org/cadence/v2 THRIFT_GENDIR := .gen/go THRIFTRW_SRC := idls/thrift/cadence.thrift idls/thrift/shadower.thrift # one or more thriftrw-generated file(s), to create / depend on generated code diff --git a/activity/activity.go b/activity/activity.go index a3c4307a0..b630bc71e 100644 --- a/activity/activity.go +++ b/activity/activity.go @@ -24,7 +24,7 @@ import ( "context" "github.com/uber-go/tally" - "go.uber.org/cadence/v1/internal" + "go.uber.org/cadence/v2/internal" "go.uber.org/zap" ) diff --git a/activity/doc.go b/activity/doc.go index 5d110fdd1..f78f31bae 100644 --- a/activity/doc.go +++ b/activity/doc.go @@ -35,7 +35,7 @@ string parameter, appends a word to it and then returns the result. import ( "context" - "go.uber.org/cadence/v1/activity" + "go.uber.org/cadence/v2/activity" "go.uber.org/zap" ) diff --git a/cadence.go b/cadence.go index b5709c7c2..991566797 100644 --- a/cadence.go +++ b/cadence.go @@ -121,7 +121,13 @@ API to allow you to capture a stack trace from any failed workflow execution his */ package cadence -import "go.uber.org/cadence/v1/internal" +import ( + "go.uber.org/cadence/v2/internal" + "go.uber.org/cadence/v2/internal/api" +) // RetryPolicy defines the retry policy for activity/workflow. type RetryPolicy = internal.RetryPolicy + +// Interface is an API interface to the Cadence server. +type Interface = api.Interface \ No newline at end of file diff --git a/client/client.go b/client/client.go index f9c535855..7bfb4a18f 100644 --- a/client/client.go +++ b/client/client.go @@ -26,11 +26,11 @@ package client import ( "context" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" - s "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/encoded" - "go.uber.org/cadence/v1/internal" - "go.uber.org/cadence/v1/workflow" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/encoded" + "go.uber.org/cadence/v2/internal" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/workflow" ) const ( @@ -187,7 +187,7 @@ type ( // } // events = append(events, event) // } - GetWorkflowHistory(ctx context.Context, workflowID string, runID string, isLongPoll bool, filterType s.HistoryEventFilterType) HistoryEventIterator + GetWorkflowHistory(ctx context.Context, workflowID string, runID string, isLongPoll bool, filterType apiv1.EventFilterType) HistoryEventIterator // CompleteActivity reports activity completed. // activity Execute method can return activity.ErrResultPending to @@ -243,7 +243,7 @@ type ( // - BadRequestError // - InternalServiceError // - EntityNotExistError - ListClosedWorkflow(ctx context.Context, request *s.ListClosedWorkflowExecutionsRequest) (*s.ListClosedWorkflowExecutionsResponse, error) + ListClosedWorkflow(ctx context.Context, request *apiv1.ListClosedWorkflowExecutionsRequest) (*apiv1.ListClosedWorkflowExecutionsResponse, error) // ListOpenWorkflow gets open workflow executions based on request filters. // Retrieved workflow executions are sorted by start time in descending order. @@ -252,7 +252,7 @@ type ( // - BadRequestError // - InternalServiceError // - EntityNotExistError - ListOpenWorkflow(ctx context.Context, request *s.ListOpenWorkflowExecutionsRequest) (*s.ListOpenWorkflowExecutionsResponse, error) + ListOpenWorkflow(ctx context.Context, request *apiv1.ListOpenWorkflowExecutionsRequest) (*apiv1.ListOpenWorkflowExecutionsResponse, error) // ListWorkflow gets workflow executions based on query. This API only works with ElasticSearch, // and will return BadRequestError when using Cassandra or MySQL. The query is basically the SQL WHERE clause, @@ -265,7 +265,7 @@ type ( // The errors it can return: // - BadRequestError // - InternalServiceError - ListWorkflow(ctx context.Context, request *s.ListWorkflowExecutionsRequest) (*s.ListWorkflowExecutionsResponse, error) + ListWorkflow(ctx context.Context, request *apiv1.ListWorkflowExecutionsRequest) (*apiv1.ListWorkflowExecutionsResponse, error) // ListArchivedWorkflow gets archived workflow executions based on query. This API will return BadRequest if Cadence // cluster or target domain is not configured for visibility archival or read is not enabled. The query is basically the SQL WHERE clause. @@ -274,7 +274,7 @@ type ( // The errors it can return: // - BadRequestError // - InternalServiceError - ListArchivedWorkflow(ctx context.Context, request *s.ListArchivedWorkflowExecutionsRequest) (*s.ListArchivedWorkflowExecutionsResponse, error) + ListArchivedWorkflow(ctx context.Context, request *apiv1.ListArchivedWorkflowExecutionsRequest) (*apiv1.ListArchivedWorkflowExecutionsResponse, error) // ScanWorkflow gets workflow executions based on query. This API only works with ElasticSearch, // and will return BadRequestError when using Cassandra or MySQL. The query is basically the SQL WHERE clause @@ -285,7 +285,7 @@ type ( // The errors it can return: // - BadRequestError // - InternalServiceError - ScanWorkflow(ctx context.Context, request *s.ListWorkflowExecutionsRequest) (*s.ListWorkflowExecutionsResponse, error) + ScanWorkflow(ctx context.Context, request *apiv1.ScanWorkflowExecutionsRequest) (*apiv1.ScanWorkflowExecutionsResponse, error) // CountWorkflow gets number of workflow executions based on query. This API only works with ElasticSearch, // and will return BadRequestError when using Cassandra or MySQL. The query is basically the SQL WHERE clause @@ -293,12 +293,12 @@ type ( // The errors it can return: // - BadRequestError // - InternalServiceError - CountWorkflow(ctx context.Context, request *s.CountWorkflowExecutionsRequest) (*s.CountWorkflowExecutionsResponse, error) + CountWorkflow(ctx context.Context, request *apiv1.CountWorkflowExecutionsRequest) (*apiv1.CountWorkflowExecutionsResponse, error) // GetSearchAttributes returns valid search attributes keys and value types. // The search attributes can be used in query of List/Scan/Count APIs. Adding new search attributes requires cadence server // to update dynamic config ValidSearchAttributes. - GetSearchAttributes(ctx context.Context) (*s.GetSearchAttributesResponse, error) + GetSearchAttributes(ctx context.Context) (*apiv1.GetSearchAttributesResponse, error) // QueryWorkflow queries a given workflow's last execution and returns the query result synchronously. Parameter workflowID // and queryType are required, other parameters are optional. The workflowID and runID (optional) identify the @@ -335,7 +335,7 @@ type ( // - BadRequestError // - InternalServiceError // - EntityNotExistError - ResetWorkflow(ctx context.Context, request *s.ResetWorkflowExecutionRequest) (*s.ResetWorkflowExecutionResponse, error) + ResetWorkflow(ctx context.Context, request *apiv1.ResetWorkflowExecutionRequest) (*apiv1.ResetWorkflowExecutionResponse, error) // DescribeWorkflowExecution returns information about the specified workflow execution. // - runID can be default(empty string). if empty string then it will pick the last running execution of that workflow ID. @@ -344,7 +344,7 @@ type ( // - BadRequestError // - InternalServiceError // - EntityNotExistError - DescribeWorkflowExecution(ctx context.Context, workflowID, runID string) (*s.DescribeWorkflowExecutionResponse, error) + DescribeWorkflowExecution(ctx context.Context, workflowID, runID string) (*apiv1.DescribeWorkflowExecutionResponse, error) // DescribeTaskList returns information about the target tasklist, right now this API returns the // pollers which polled this tasklist in last few minutes. @@ -352,7 +352,7 @@ type ( // - BadRequestError // - InternalServiceError // - EntityNotExistError - DescribeTaskList(ctx context.Context, tasklist string, tasklistType s.TaskListType) (*s.DescribeTaskListResponse, error) + DescribeTaskList(ctx context.Context, tasklist string, tasklistType apiv1.TaskListType) (*apiv1.DescribeTaskListResponse, error) } // DomainClient is the client for managing operations on the domain. @@ -363,7 +363,7 @@ type ( // - DomainAlreadyExistsError // - BadRequestError // - InternalServiceError - Register(ctx context.Context, request *s.RegisterDomainRequest) error + Register(ctx context.Context, request *apiv1.RegisterDomainRequest) error // Describe a domain. The domain has 3 part of information // DomainInfo - Which has Name, Status, Description, Owner Email @@ -373,14 +373,14 @@ type ( // - EntityNotExistsError // - BadRequestError // - InternalServiceError - Describe(ctx context.Context, name string) (*s.DescribeDomainResponse, error) + Describe(ctx context.Context, name string) (*apiv1.DescribeDomainResponse, error) // Update a domain. // The errors it can throw: // - EntityNotExistsError // - BadRequestError // - InternalServiceError - Update(ctx context.Context, request *s.UpdateDomainRequest) error + Update(ctx context.Context, request *apiv1.UpdateDomainRequest) error } ) @@ -412,12 +412,12 @@ const ( ) // NewClient creates an instance of a workflow client -func NewClient(service workflowserviceclient.Interface, domain string, options *Options) Client { +func NewClient(service api.Interface, domain string, options *Options) Client { return internal.NewClient(service, domain, options) } // NewDomainClient creates an instance of a domain client, to manage lifecycle of domains. -func NewDomainClient(service workflowserviceclient.Interface, options *Options) DomainClient { +func NewDomainClient(service api.Interface, options *Options) DomainClient { return internal.NewDomainClient(service, options) } diff --git a/docker/buildkite/docker-compose-local.yml b/docker/buildkite/docker-compose-local.yml index 7120699cc..db138c189 100644 --- a/docker/buildkite/docker-compose-local.yml +++ b/docker/buildkite/docker-compose-local.yml @@ -25,6 +25,7 @@ services: cadence: image: ubercadence/server:master-auto-setup ports: + - "7833:7833" - "7933:7933" - "7934:7934" - "7935:7935" @@ -52,7 +53,7 @@ services: - | make integ_test_sticky_off environment: - - "SERVICE_ADDR=cadence:7933" + - "SERVICE_ADDR=cadence:7833" - "GO111MODULE=on" depends_on: - cadence @@ -74,7 +75,7 @@ services: - | make integ_test_sticky_on environment: - - "SERVICE_ADDR=cadence:7933" + - "SERVICE_ADDR=cadence:7833" - "GO111MODULE=on" depends_on: - cadence diff --git a/docker/buildkite/docker-compose.yml b/docker/buildkite/docker-compose.yml index 2b25ed2a0..2b9a5786b 100644 --- a/docker/buildkite/docker-compose.yml +++ b/docker/buildkite/docker-compose.yml @@ -25,6 +25,7 @@ services: cadence: image: ubercadence/server:master-auto-setup ports: + - "7833:7833" - "7933:7933" - "7934:7934" - "7935:7935" @@ -46,7 +47,7 @@ services: context: ../../ dockerfile: ./docker/buildkite/Dockerfile environment: - - "SERVICE_ADDR=cadence:7933" + - "SERVICE_ADDR=cadence:7833" - "GO111MODULE=on" depends_on: - cadence diff --git a/encoded/encoded.go b/encoded/encoded.go index b2e1588fe..2b65f7c22 100644 --- a/encoded/encoded.go +++ b/encoded/encoded.go @@ -21,7 +21,7 @@ // Package encoded contains wrappers that are used for binary payloads deserialization. package encoded -import "go.uber.org/cadence/v1/internal" +import "go.uber.org/cadence/v2/internal" type ( diff --git a/error.go b/error.go index 15f392abc..0dad20eaf 100644 --- a/error.go +++ b/error.go @@ -21,9 +21,10 @@ package cadence import ( - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal" - "go.uber.org/cadence/v1/workflow" + "go.uber.org/cadence/v2/.gen/go/shared" + "go.uber.org/cadence/v2/internal" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/workflow" ) type ( @@ -32,6 +33,21 @@ type ( // CanceledError returned when operation was canceled. CanceledError = internal.CanceledError + + AccessDeniedError = api.AccessDeniedError + BadRequestError = api.BadRequestError + CancellationAlreadyRequestedError = api.CancellationAlreadyRequestedError + ClientVersionNotSupportedError = api.ClientVersionNotSupportedError + DomainAlreadyExistsError = api.DomainAlreadyExistsError + DomainNotActiveError = api.DomainNotActiveError + EntityNotExistsError = api.EntityNotExistsError + WorkflowExecutionAlreadyCompletedError = api.WorkflowExecutionAlreadyCompletedError + InternalServiceError = api.InternalServiceError + LimitExceededError = api.LimitExceededError + QueryFailedError = api.QueryFailedError + ServiceBusyError = api.ServiceBusyError + WorkflowExecutionAlreadyStartedError = api.WorkflowExecutionAlreadyStartedError + EventAlreadyStartedError = api.EventAlreadyStartedError ) // ErrNoData is returned when trying to extract strong typed data while there is no data available. diff --git a/evictiontest/workflow_cache_eviction_test.go b/evictiontest/workflow_cache_eviction_test.go index 88a3c9c2e..c06e19aa9 100644 --- a/evictiontest/workflow_cache_eviction_test.go +++ b/evictiontest/workflow_cache_eviction_test.go @@ -34,15 +34,15 @@ import ( "testing" "time" + "github.com/gogo/protobuf/types" "github.com/golang/mock/gomock" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/suite" "go.uber.org/atomic" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowservicetest" - m "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal" - "go.uber.org/cadence/v1/internal/common" - "go.uber.org/cadence/v1/worker" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/worker" "go.uber.org/yarpc" "golang.org/x/net/context" ) @@ -64,14 +64,14 @@ type ( CacheEvictionSuite struct { suite.Suite mockCtrl *gomock.Controller - service *workflowservicetest.MockClient + service *api.MockInterface } ) // Test suite. func (s *CacheEvictionSuite) SetupTest() { s.mockCtrl = gomock.NewController(s.T()) - s.service = workflowservicetest.NewMockClient(s.mockCtrl) + s.service = api.NewMockInterface(s.mockCtrl) } func (s *CacheEvictionSuite) TearDownTest() { @@ -89,61 +89,59 @@ func TestWorkersTestSuite(t *testing.T) { // this is the mock for yarpcCallOptions, make sure length are the same var callOptions = []interface{}{gomock.Any(), gomock.Any(), gomock.Any()} -func createTestEventWorkflowExecutionStarted(eventID int64, attr *m.WorkflowExecutionStartedEventAttributes) *m.HistoryEvent { - return &m.HistoryEvent{ - EventId: common.Int64Ptr(eventID), - EventType: common.EventTypePtr(m.EventTypeWorkflowExecutionStarted), - WorkflowExecutionStartedEventAttributes: attr, +func createTestEventWorkflowExecutionStarted(eventID int64, attr *apiv1.WorkflowExecutionStartedEventAttributes) *apiv1.HistoryEvent { + return &apiv1.HistoryEvent{ + EventId: eventID, + Attributes: &apiv1.HistoryEvent_WorkflowExecutionStartedEventAttributes{WorkflowExecutionStartedEventAttributes: attr}, } } -func createTestEventDecisionTaskScheduled(eventID int64, attr *m.DecisionTaskScheduledEventAttributes) *m.HistoryEvent { - return &m.HistoryEvent{ - EventId: common.Int64Ptr(eventID), - EventType: common.EventTypePtr(m.EventTypeDecisionTaskScheduled), - DecisionTaskScheduledEventAttributes: attr, +func createTestEventDecisionTaskScheduled(eventID int64, attr *apiv1.DecisionTaskScheduledEventAttributes) *apiv1.HistoryEvent { + return &apiv1.HistoryEvent{ + EventId: eventID, + Attributes: &apiv1.HistoryEvent_DecisionTaskScheduledEventAttributes{DecisionTaskScheduledEventAttributes: attr}, } } func (s *CacheEvictionSuite) TestResetStickyOnEviction() { - testEvents := []*m.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &m.WorkflowExecutionStartedEventAttributes{ - TaskList: &m.TaskList{Name: common.StringPtr("tasklist")}, + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{ + TaskList: &apiv1.TaskList{Name: "tasklist"}, }), - createTestEventDecisionTaskScheduled(2, &m.DecisionTaskScheduledEventAttributes{}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{}), } var taskCounter atomic.Int32 // lambda variable to keep count // mock that manufactures unique decision tasks mockPollForDecisionTask := func( ctx context.Context, - _PollRequest *m.PollForDecisionTaskRequest, + _PollRequest *apiv1.PollForDecisionTaskRequest, opts ...yarpc.CallOption, - ) (success *m.PollForDecisionTaskResponse, err error) { + ) (success *apiv1.PollForDecisionTaskResponse, err error) { taskID := taskCounter.Inc() - workflowID := common.StringPtr("testID" + strconv.Itoa(int(taskID))) - runID := common.StringPtr("runID" + strconv.Itoa(int(taskID))) + workflowID := "testID" + strconv.Itoa(int(taskID)) + runID := "runID" + strconv.Itoa(int(taskID)) // how we initialize the response here is the result of a series of trial and error // the goal is we want to fabricate a response that looks real enough to our worker // that it will actually go along with processing it instead of just tossing it out // after polling it or giving an error - ret := &m.PollForDecisionTaskResponse{ + ret := &apiv1.PollForDecisionTaskResponse{ TaskToken: make([]byte, 5), - WorkflowExecution: &m.WorkflowExecution{WorkflowId: workflowID, RunId: runID}, - WorkflowType: &m.WorkflowType{Name: common.StringPtr("go.uber.org/cadence/v1/evictiontest.testReplayWorkflow")}, - History: &m.History{Events: testEvents}, - PreviousStartedEventId: common.Int64Ptr(5)} + WorkflowExecution: &apiv1.WorkflowExecution{WorkflowId: workflowID, RunId: runID}, + WorkflowType: &apiv1.WorkflowType{Name: "go.uber.org/cadence/v2/evictiontest.testReplayWorkflow"}, + History: &apiv1.History{Events: testEvents}, + PreviousStartedEventId: &types.Int64Value{Value: 5}} return ret, nil } resetStickyAPICalled := make(chan struct{}) mockResetStickyTaskList := func( ctx context.Context, - _ResetRequest *m.ResetStickyTaskListRequest, + _ResetRequest *apiv1.ResetStickyTaskListRequest, opts ...yarpc.CallOption, - ) (success *m.ResetStickyTaskListResponse, err error) { + ) (success *apiv1.ResetStickyTaskListResponse, err error) { resetStickyAPICalled <- struct{}{} - return &m.ResetStickyTaskListResponse{}, nil + return &apiv1.ResetStickyTaskListResponse{}, nil } // pick 5 as cache size because it's not too big and not too small. cacheSize := 5 @@ -159,9 +157,9 @@ func (s *CacheEvictionSuite) TestResetStickyOnEviction() { // these will get tossed away immediately after polled, but we still need them so gomock doesn't compain about unexpected calls. // this is because our worker's poller doesn't stop, it keeps polling on the service client as long // as Stop() is not called on the worker - s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(&m.PollForDecisionTaskResponse{}, nil).AnyTimes() + s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.PollForDecisionTaskResponse{}, nil).AnyTimes() // this gets called after polled decision tasks are processed, any number of times doesn't matter - s.service.EXPECT().RespondDecisionTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).Return(&m.RespondDecisionTaskCompletedResponse{}, nil).AnyTimes() + s.service.EXPECT().RespondDecisionTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.RespondDecisionTaskCompletedResponse{}, nil).AnyTimes() // this is the critical point of the test. // ResetSticky should be called exactly once because our workflow cache evicts when full // so if our worker puts *cacheSize* entries in the cache, it should evict exactly one diff --git a/go.mod b/go.mod index 132d8a85d..9896686de 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module go.uber.org/cadence/v1 +module go.uber.org/cadence/v2 go 1.13 diff --git a/interceptors/workflow_interceptor.go b/interceptors/workflow_interceptor.go index fd112cfc6..edc2b995a 100644 --- a/interceptors/workflow_interceptor.go +++ b/interceptors/workflow_interceptor.go @@ -22,7 +22,7 @@ package interceptors import ( - "go.uber.org/cadence/v1/internal" + "go.uber.org/cadence/v2/internal" ) type ( diff --git a/internal/activity.go b/internal/activity.go index 766c17ee2..f9dd51683 100644 --- a/internal/activity.go +++ b/internal/activity.go @@ -28,7 +28,8 @@ import ( "github.com/opentracing/opentracing-go" "github.com/uber-go/tally" - "go.uber.org/cadence/v1/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) @@ -294,14 +295,15 @@ type ServiceInvoker interface { // without detail. BackgroundHeartbeat() error Close(flushBufferedHeartbeat bool) - GetClient(domain string, options *ClientOptions) Client + + SignalWorkflow(ctx context.Context, domain, workflowID, runID, signalName string, signalInput []byte) error } // WithActivityTask adds activity specific information into context. // Use this method to unit test activity implementations that use context extractor methodshared. func WithActivityTask( ctx context.Context, - task *shared.PollForActivityTaskResponse, + task *apiv1.PollForActivityTaskResponse, taskList string, invoker ServiceInvoker, logger *zap.Logger, @@ -312,11 +314,11 @@ func WithActivityTask( tracer opentracing.Tracer, ) context.Context { var deadline time.Time - scheduled := time.Unix(0, task.GetScheduledTimestampOfThisAttempt()) - started := time.Unix(0, task.GetStartedTimestamp()) - scheduleToCloseTimeout := time.Duration(task.GetScheduleToCloseTimeoutSeconds()) * time.Second - startToCloseTimeout := time.Duration(task.GetStartToCloseTimeoutSeconds()) * time.Second - heartbeatTimeout := time.Duration(task.GetHeartbeatTimeoutSeconds()) * time.Second + scheduled := api.TimeFromProto(task.ScheduledTimeOfThisAttempt) + started := api.TimeFromProto(task.StartedTime) + scheduleToCloseTimeout := api.DurationFromProto(task.ScheduleToCloseTimeout) + startToCloseTimeout := api.DurationFromProto(task.StartToCloseTimeout) + heartbeatTimeout := api.DurationFromProto(task.HeartbeatTimeout) scheduleToCloseDeadline := scheduled.Add(scheduleToCloseTimeout) startToCloseDeadline := started.Add(startToCloseTimeout) // Minimum of the two deadlines. @@ -327,21 +329,21 @@ func WithActivityTask( } logger = logger.With( - zapcore.Field{Key: tagActivityID, Type: zapcore.StringType, String: *task.ActivityId}, - zapcore.Field{Key: tagActivityType, Type: zapcore.StringType, String: *task.ActivityType.Name}, - zapcore.Field{Key: tagWorkflowType, Type: zapcore.StringType, String: *task.WorkflowType.Name}, - zapcore.Field{Key: tagWorkflowID, Type: zapcore.StringType, String: *task.WorkflowExecution.WorkflowId}, - zapcore.Field{Key: tagRunID, Type: zapcore.StringType, String: *task.WorkflowExecution.RunId}, + zapcore.Field{Key: tagActivityID, Type: zapcore.StringType, String: task.ActivityId}, + zapcore.Field{Key: tagActivityType, Type: zapcore.StringType, String: task.ActivityType.Name}, + zapcore.Field{Key: tagWorkflowType, Type: zapcore.StringType, String: task.WorkflowType.Name}, + zapcore.Field{Key: tagWorkflowID, Type: zapcore.StringType, String: task.WorkflowExecution.WorkflowId}, + zapcore.Field{Key: tagRunID, Type: zapcore.StringType, String: task.WorkflowExecution.RunId}, ) return context.WithValue(ctx, activityEnvContextKey, &activityEnvironment{ taskToken: task.TaskToken, serviceInvoker: invoker, - activityType: ActivityType{Name: *task.ActivityType.Name}, - activityID: *task.ActivityId, + activityType: ActivityType{Name: task.ActivityType.Name}, + activityID: task.ActivityId, workflowExecution: WorkflowExecution{ - RunID: *task.WorkflowExecution.RunId, - ID: *task.WorkflowExecution.WorkflowId}, + RunID: task.WorkflowExecution.RunId, + ID: task.WorkflowExecution.WorkflowId}, logger: logger, metricsScope: scope, deadline: deadline, @@ -351,11 +353,11 @@ func WithActivityTask( taskList: taskList, dataConverter: dataConverter, attempt: task.GetAttempt(), - heartbeatDetails: task.HeartbeatDetails, + heartbeatDetails: task.HeartbeatDetails.GetData(), workflowType: &WorkflowType{ - Name: *task.WorkflowType.Name, + Name: task.WorkflowType.Name, }, - workflowDomain: *task.WorkflowDomain, + workflowDomain: task.WorkflowDomain, workerStopChannel: workerStopChannel, contextPropagators: contextPropagators, tracer: tracer, diff --git a/internal/activity_test.go b/internal/activity_test.go index 72d91bcca..b34971903 100644 --- a/internal/activity_test.go +++ b/internal/activity_test.go @@ -28,16 +28,15 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowservicetest" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" "go.uber.org/yarpc" ) type activityTestSuite struct { suite.Suite mockCtrl *gomock.Controller - service *workflowservicetest.MockClient + service *api.MockInterface } func TestActivityTestSuite(t *testing.T) { @@ -47,7 +46,7 @@ func TestActivityTestSuite(t *testing.T) { func (s *activityTestSuite) SetupTest() { s.mockCtrl = gomock.NewController(s.T()) - s.service = workflowservicetest.NewMockClient(s.mockCtrl) + s.service = api.NewMockInterface(s.mockCtrl) } func (s *activityTestSuite) TearDownTest() { @@ -63,7 +62,7 @@ func (s *activityTestSuite) TestActivityHeartbeat() { ctx = context.WithValue(ctx, activityEnvContextKey, &activityEnvironment{serviceInvoker: invoker}) s.service.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), gomock.Any(), callOptions...). - Return(&shared.RecordActivityTaskHeartbeatResponse{}, nil).Times(1) + Return(&apiv1.RecordActivityTaskHeartbeatResponse{}, nil).Times(1) RecordActivityHeartbeat(ctx, "testDetails") } @@ -76,8 +75,8 @@ func (s *activityTestSuite) TestActivityHeartbeat_InternalError() { logger: getTestLogger(s.T())}) s.service.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), gomock.Any(), callOptions...). - Return(nil, &shared.InternalServiceError{}). - Do(func(ctx context.Context, request *shared.RecordActivityTaskHeartbeatRequest, opts ...yarpc.CallOption) { + Return(nil, &api.InternalServiceError{}). + Do(func(ctx context.Context, request *apiv1.RecordActivityTaskHeartbeatRequest, opts ...yarpc.CallOption) { fmt.Println("MOCK RecordActivityTaskHeartbeat executed") }).AnyTimes() @@ -92,7 +91,7 @@ func (s *activityTestSuite) TestActivityHeartbeat_CancelRequested() { logger: getTestLogger(s.T())}) s.service.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), gomock.Any(), callOptions...). - Return(&shared.RecordActivityTaskHeartbeatResponse{CancelRequested: common.BoolPtr(true)}, nil).Times(1) + Return(&apiv1.RecordActivityTaskHeartbeatResponse{CancelRequested: true}, nil).Times(1) RecordActivityHeartbeat(ctx, "testDetails") <-ctx.Done() @@ -107,7 +106,7 @@ func (s *activityTestSuite) TestActivityHeartbeat_EntityNotExist() { logger: getTestLogger(s.T())}) s.service.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), gomock.Any(), callOptions...). - Return(&shared.RecordActivityTaskHeartbeatResponse{}, &shared.EntityNotExistsError{}).Times(1) + Return(&apiv1.RecordActivityTaskHeartbeatResponse{}, &api.EntityNotExistsError{}).Times(1) RecordActivityHeartbeat(ctx, "testDetails") <-ctx.Done() @@ -123,38 +122,38 @@ func (s *activityTestSuite) TestActivityHeartbeat_SuppressContinousInvokes() { // Multiple calls but only one call is made. s.service.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), gomock.Any(), callOptions...). - Return(&shared.RecordActivityTaskHeartbeatResponse{}, nil).Times(1) + Return(&apiv1.RecordActivityTaskHeartbeatResponse{}, nil).Times(1) RecordActivityHeartbeat(ctx, "testDetails") RecordActivityHeartbeat(ctx, "testDetails") RecordActivityHeartbeat(ctx, "testDetails") invoker.Close(false) // No HB timeout configured. - service2 := workflowservicetest.NewMockClient(s.mockCtrl) + service2 := api.NewMockInterface(s.mockCtrl) invoker2 := newServiceInvoker([]byte("task-token"), "identity", service2, cancel, 0, make(chan struct{})) ctx = context.WithValue(ctx, activityEnvContextKey, &activityEnvironment{ serviceInvoker: invoker2, logger: getTestLogger(s.T())}) service2.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), gomock.Any(), callOptions...). - Return(&shared.RecordActivityTaskHeartbeatResponse{}, nil).Times(1) + Return(&apiv1.RecordActivityTaskHeartbeatResponse{}, nil).Times(1) RecordActivityHeartbeat(ctx, "testDetails") RecordActivityHeartbeat(ctx, "testDetails") invoker2.Close(false) // simulate batch picks before expiry. waitCh := make(chan struct{}) - service3 := workflowservicetest.NewMockClient(s.mockCtrl) + service3 := api.NewMockInterface(s.mockCtrl) invoker3 := newServiceInvoker([]byte("task-token"), "identity", service3, cancel, 2, make(chan struct{})) ctx = context.WithValue(ctx, activityEnvContextKey, &activityEnvironment{ serviceInvoker: invoker3, logger: getTestLogger(s.T())}) service3.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), gomock.Any(), callOptions...). - Return(&shared.RecordActivityTaskHeartbeatResponse{}, nil).Times(1) + Return(&apiv1.RecordActivityTaskHeartbeatResponse{}, nil).Times(1) service3.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), gomock.Any(), callOptions...). - Return(&shared.RecordActivityTaskHeartbeatResponse{}, nil). - Do(func(ctx context.Context, request *shared.RecordActivityTaskHeartbeatRequest, opts ...yarpc.CallOption) { - ev := newEncodedValues(request.Details, nil) + Return(&apiv1.RecordActivityTaskHeartbeatResponse{}, nil). + Do(func(ctx context.Context, request *apiv1.RecordActivityTaskHeartbeatRequest, opts ...yarpc.CallOption) { + ev := newEncodedValues(request.Details.GetData(), nil) var progress string err := ev.Get(&progress) if err != nil { @@ -173,17 +172,17 @@ func (s *activityTestSuite) TestActivityHeartbeat_SuppressContinousInvokes() { // simulate batch picks before expiry, with out any progress specified. waitCh2 := make(chan struct{}) - service4 := workflowservicetest.NewMockClient(s.mockCtrl) + service4 := api.NewMockInterface(s.mockCtrl) invoker4 := newServiceInvoker([]byte("task-token"), "identity", service4, cancel, 2, make(chan struct{})) ctx = context.WithValue(ctx, activityEnvContextKey, &activityEnvironment{ serviceInvoker: invoker4, logger: getTestLogger(s.T())}) service4.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), gomock.Any(), callOptions...). - Return(&shared.RecordActivityTaskHeartbeatResponse{}, nil).Times(1) + Return(&apiv1.RecordActivityTaskHeartbeatResponse{}, nil).Times(1) service4.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), gomock.Any(), callOptions...). - Return(&shared.RecordActivityTaskHeartbeatResponse{}, nil). - Do(func(ctx context.Context, request *shared.RecordActivityTaskHeartbeatRequest, opts ...yarpc.CallOption) { - require.Nil(s.T(), request.Details) + Return(&apiv1.RecordActivityTaskHeartbeatResponse{}, nil). + Do(func(ctx context.Context, request *apiv1.RecordActivityTaskHeartbeatRequest, opts ...yarpc.CallOption) { + require.Nil(s.T(), request.Details.GetData()) waitCh2 <- struct{}{} }).Times(1) @@ -206,8 +205,8 @@ func (s *activityTestSuite) TestActivityHeartbeat_WorkerStop() { waitCh <- struct{}{} waitC2 := make(chan struct{}, 1) s.service.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), gomock.Any(), callOptions...). - Return(&shared.RecordActivityTaskHeartbeatResponse{}, nil). - Do(func(ctx context.Context, request *shared.RecordActivityTaskHeartbeatRequest, opts ...yarpc.CallOption) { + Return(&apiv1.RecordActivityTaskHeartbeatResponse{}, nil). + Do(func(ctx context.Context, request *apiv1.RecordActivityTaskHeartbeatRequest, opts ...yarpc.CallOption) { if _, ok := <-waitCh; ok { close(waitCh) return diff --git a/internal/api/error.go b/internal/api/error.go index fe6fc6b64..de5da11e5 100644 --- a/internal/api/error.go +++ b/internal/api/error.go @@ -24,7 +24,7 @@ import ( "fmt" "strings" - apiv1 "go.uber.org/cadence/v1/.gen/proto/api/v1" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" "go.uber.org/yarpc/encoding/protobuf" "go.uber.org/yarpc/yarpcerrors" ) diff --git a/internal/api/error_test.go b/internal/api/error_test.go index 96f980218..ec643e189 100644 --- a/internal/api/error_test.go +++ b/internal/api/error_test.go @@ -25,7 +25,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - apiv1 "go.uber.org/cadence/v1/.gen/proto/api/v1" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" "go.uber.org/yarpc/encoding/protobuf" "go.uber.org/yarpc/yarpcerrors" ) diff --git a/internal/api/helpers.go b/internal/api/helpers.go new file mode 100644 index 000000000..01b64eb0b --- /dev/null +++ b/internal/api/helpers.go @@ -0,0 +1,82 @@ +// Copyright (c) 2017-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 api + +import ( + "github.com/gogo/protobuf/types" + "time" +) + +func DurationToProto(d time.Duration) *types.Duration { + return types.DurationProto(d) +} + +func DurationFromProto(d *types.Duration) time.Duration { + if d == nil { + return time.Duration(0) + } + duration, err := types.DurationFromProto(d) + if err != nil { + panic(err) + } + return duration +} + +func SecondsFromProto(d *types.Duration) int32 { + if d == nil { + return 0 + } + duration, err := types.DurationFromProto(d) + if err != nil { + panic(err) + } + return int32(duration / time.Second) +} + +func SecondsToProto(s int32) *types.Duration { + return DurationToProto(time.Duration(s) * time.Second) +} + +func SecondsPtrToProto(s *int32) *types.Duration { + if s == nil { + return nil + } + return DurationToProto(time.Duration(*s) * time.Second) +} + +func TimeFromProto(t *types.Timestamp) time.Time { + if t == nil { + return time.Time{} + } + timestamp, err := types.TimestampFromProto(t) + if err != nil { + panic(err) + } + return timestamp +} + +func TimeToProto(t time.Time) *types.Timestamp { + timestamp, err := types.TimestampProto(t) + if err != nil { + panic(err) + } + return timestamp +} diff --git a/internal/api/interface.go b/internal/api/interface.go index 187c3bb67..2264fb1b3 100644 --- a/internal/api/interface.go +++ b/internal/api/interface.go @@ -20,9 +20,9 @@ package api -import apiv1 "go.uber.org/cadence/v1/.gen/proto/api/v1" +import apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" -//go:generate mockgen -package $GOPACKAGE -source $GOFILE -destination interface_mock.go -self_package go.uber.org/cadence/v1/internal/api +//go:generate mockgen -package $GOPACKAGE -source $GOFILE -destination interface_mock.go -self_package go.uber.org/cadence/v2/internal/api type Interface interface { apiv1.DomainAPIYARPCClient diff --git a/internal/api/interface_mock.go b/internal/api/interface_mock.go index fd9df6e01..df7718d22 100644 --- a/internal/api/interface_mock.go +++ b/internal/api/interface_mock.go @@ -29,7 +29,7 @@ import ( reflect "reflect" gomock "github.com/golang/mock/gomock" - apiv1 "go.uber.org/cadence/v1/.gen/proto/api/v1" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" yarpc "go.uber.org/yarpc" ) diff --git a/internal/api/thrift/mapper.go b/internal/api/thrift/mapper.go new file mode 100644 index 000000000..c6cc77caf --- /dev/null +++ b/internal/api/thrift/mapper.go @@ -0,0 +1,1164 @@ +// Copyright (c) 2017-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 thrift + +import ( + "go.uber.org/cadence/v2/internal/common" + "time" + + "github.com/gogo/protobuf/types" + "go.uber.org/cadence/v2/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" +) + +func ToHistoryEvents(t []*shared.HistoryEvent) []*apiv1.HistoryEvent { + if t == nil { + return nil + } + v := make([]*apiv1.HistoryEvent, len(t)) + for i := range t { + v[i] = toHistoryEvent(t[i]) + } + return v +} + +func toHistoryEvent(e *shared.HistoryEvent) *apiv1.HistoryEvent { + if e == nil { + return nil + } + event := apiv1.HistoryEvent{ + EventId: e.GetEventId(), + EventTime: unixNanoToTime(e.Timestamp), + Version: e.GetVersion(), + TaskId: e.GetTaskId(), + } + switch *e.EventType { + case shared.EventTypeWorkflowExecutionStarted: + event.Attributes = &apiv1.HistoryEvent_WorkflowExecutionStartedEventAttributes{ + WorkflowExecutionStartedEventAttributes: toWorkflowExecutionStartedEventAttributes(e.WorkflowExecutionStartedEventAttributes), + } + case shared.EventTypeWorkflowExecutionCompleted: + event.Attributes = &apiv1.HistoryEvent_WorkflowExecutionCompletedEventAttributes{ + WorkflowExecutionCompletedEventAttributes: toWorkflowExecutionCompletedEventAttributes(e.WorkflowExecutionCompletedEventAttributes), + } + case shared.EventTypeWorkflowExecutionFailed: + event.Attributes = &apiv1.HistoryEvent_WorkflowExecutionFailedEventAttributes{ + WorkflowExecutionFailedEventAttributes: toWorkflowExecutionFailedEventAttributes(e.WorkflowExecutionFailedEventAttributes), + } + case shared.EventTypeWorkflowExecutionTimedOut: + event.Attributes = &apiv1.HistoryEvent_WorkflowExecutionTimedOutEventAttributes{ + WorkflowExecutionTimedOutEventAttributes: toWorkflowExecutionTimedOutEventAttributes(e.WorkflowExecutionTimedOutEventAttributes), + } + case shared.EventTypeDecisionTaskScheduled: + event.Attributes = &apiv1.HistoryEvent_DecisionTaskScheduledEventAttributes{ + DecisionTaskScheduledEventAttributes: toDecisionTaskScheduledEventAttributes(e.DecisionTaskScheduledEventAttributes), + } + case shared.EventTypeDecisionTaskStarted: + event.Attributes = &apiv1.HistoryEvent_DecisionTaskStartedEventAttributes{ + DecisionTaskStartedEventAttributes: toDecisionTaskStartedEventAttributes(e.DecisionTaskStartedEventAttributes), + } + case shared.EventTypeDecisionTaskCompleted: + event.Attributes = &apiv1.HistoryEvent_DecisionTaskCompletedEventAttributes{ + DecisionTaskCompletedEventAttributes: toDecisionTaskCompletedEventAttributes(e.DecisionTaskCompletedEventAttributes), + } + case shared.EventTypeDecisionTaskTimedOut: + event.Attributes = &apiv1.HistoryEvent_DecisionTaskTimedOutEventAttributes{ + DecisionTaskTimedOutEventAttributes: toDecisionTaskTimedOutEventAttributes(e.DecisionTaskTimedOutEventAttributes), + } + case shared.EventTypeDecisionTaskFailed: + event.Attributes = &apiv1.HistoryEvent_DecisionTaskFailedEventAttributes{ + DecisionTaskFailedEventAttributes: toDecisionTaskFailedEventAttributes(e.DecisionTaskFailedEventAttributes), + } + case shared.EventTypeActivityTaskScheduled: + event.Attributes = &apiv1.HistoryEvent_ActivityTaskScheduledEventAttributes{ + ActivityTaskScheduledEventAttributes: toActivityTaskScheduledEventAttributes(e.ActivityTaskScheduledEventAttributes), + } + case shared.EventTypeActivityTaskStarted: + event.Attributes = &apiv1.HistoryEvent_ActivityTaskStartedEventAttributes{ + ActivityTaskStartedEventAttributes: toActivityTaskStartedEventAttributes(e.ActivityTaskStartedEventAttributes), + } + case shared.EventTypeActivityTaskCompleted: + event.Attributes = &apiv1.HistoryEvent_ActivityTaskCompletedEventAttributes{ + ActivityTaskCompletedEventAttributes: toActivityTaskCompletedEventAttributes(e.ActivityTaskCompletedEventAttributes), + } + case shared.EventTypeActivityTaskFailed: + event.Attributes = &apiv1.HistoryEvent_ActivityTaskFailedEventAttributes{ + ActivityTaskFailedEventAttributes: toActivityTaskFailedEventAttributes(e.ActivityTaskFailedEventAttributes), + } + case shared.EventTypeActivityTaskTimedOut: + event.Attributes = &apiv1.HistoryEvent_ActivityTaskTimedOutEventAttributes{ + ActivityTaskTimedOutEventAttributes: toActivityTaskTimedOutEventAttributes(e.ActivityTaskTimedOutEventAttributes), + } + case shared.EventTypeActivityTaskCancelRequested: + event.Attributes = &apiv1.HistoryEvent_ActivityTaskCancelRequestedEventAttributes{ + ActivityTaskCancelRequestedEventAttributes: toActivityTaskCancelRequestedEventAttributes(e.ActivityTaskCancelRequestedEventAttributes), + } + case shared.EventTypeRequestCancelActivityTaskFailed: + event.Attributes = &apiv1.HistoryEvent_RequestCancelActivityTaskFailedEventAttributes{ + RequestCancelActivityTaskFailedEventAttributes: toRequestCancelActivityTaskFailedEventAttributes(e.RequestCancelActivityTaskFailedEventAttributes), + } + case shared.EventTypeActivityTaskCanceled: + event.Attributes = &apiv1.HistoryEvent_ActivityTaskCanceledEventAttributes{ + ActivityTaskCanceledEventAttributes: toActivityTaskCanceledEventAttributes(e.ActivityTaskCanceledEventAttributes), + } + case shared.EventTypeTimerStarted: + event.Attributes = &apiv1.HistoryEvent_TimerStartedEventAttributes{ + TimerStartedEventAttributes: toTimerStartedEventAttributes(e.TimerStartedEventAttributes), + } + case shared.EventTypeTimerFired: + event.Attributes = &apiv1.HistoryEvent_TimerFiredEventAttributes{ + TimerFiredEventAttributes: toTimerFiredEventAttributes(e.TimerFiredEventAttributes), + } + case shared.EventTypeTimerCanceled: + event.Attributes = &apiv1.HistoryEvent_TimerCanceledEventAttributes{ + TimerCanceledEventAttributes: toTimerCanceledEventAttributes(e.TimerCanceledEventAttributes), + } + case shared.EventTypeCancelTimerFailed: + event.Attributes = &apiv1.HistoryEvent_CancelTimerFailedEventAttributes{ + CancelTimerFailedEventAttributes: toCancelTimerFailedEventAttributes(e.CancelTimerFailedEventAttributes), + } + case shared.EventTypeWorkflowExecutionCancelRequested: + event.Attributes = &apiv1.HistoryEvent_WorkflowExecutionCancelRequestedEventAttributes{ + WorkflowExecutionCancelRequestedEventAttributes: toWorkflowExecutionCancelRequestedEventAttributes(e.WorkflowExecutionCancelRequestedEventAttributes), + } + case shared.EventTypeWorkflowExecutionCanceled: + event.Attributes = &apiv1.HistoryEvent_WorkflowExecutionCanceledEventAttributes{ + WorkflowExecutionCanceledEventAttributes: toWorkflowExecutionCanceledEventAttributes(e.WorkflowExecutionCanceledEventAttributes), + } + case shared.EventTypeRequestCancelExternalWorkflowExecutionInitiated: + event.Attributes = &apiv1.HistoryEvent_RequestCancelExternalWorkflowExecutionInitiatedEventAttributes{ + RequestCancelExternalWorkflowExecutionInitiatedEventAttributes: toRequestCancelExternalWorkflowExecutionInitiatedEventAttributes(e.RequestCancelExternalWorkflowExecutionInitiatedEventAttributes), + } + case shared.EventTypeRequestCancelExternalWorkflowExecutionFailed: + event.Attributes = &apiv1.HistoryEvent_RequestCancelExternalWorkflowExecutionFailedEventAttributes{ + RequestCancelExternalWorkflowExecutionFailedEventAttributes: toRequestCancelExternalWorkflowExecutionFailedEventAttributes(e.RequestCancelExternalWorkflowExecutionFailedEventAttributes), + } + case shared.EventTypeExternalWorkflowExecutionCancelRequested: + event.Attributes = &apiv1.HistoryEvent_ExternalWorkflowExecutionCancelRequestedEventAttributes{ + ExternalWorkflowExecutionCancelRequestedEventAttributes: toExternalWorkflowExecutionCancelRequestedEventAttributes(e.ExternalWorkflowExecutionCancelRequestedEventAttributes), + } + case shared.EventTypeMarkerRecorded: + event.Attributes = &apiv1.HistoryEvent_MarkerRecordedEventAttributes{ + MarkerRecordedEventAttributes: toMarkerRecordedEventAttributes(e.MarkerRecordedEventAttributes), + } + case shared.EventTypeWorkflowExecutionSignaled: + event.Attributes = &apiv1.HistoryEvent_WorkflowExecutionSignaledEventAttributes{ + WorkflowExecutionSignaledEventAttributes: toWorkflowExecutionSignaledEventAttributes(e.WorkflowExecutionSignaledEventAttributes), + } + case shared.EventTypeWorkflowExecutionTerminated: + event.Attributes = &apiv1.HistoryEvent_WorkflowExecutionTerminatedEventAttributes{ + WorkflowExecutionTerminatedEventAttributes: toWorkflowExecutionTerminatedEventAttributes(e.WorkflowExecutionTerminatedEventAttributes), + } + case shared.EventTypeWorkflowExecutionContinuedAsNew: + event.Attributes = &apiv1.HistoryEvent_WorkflowExecutionContinuedAsNewEventAttributes{ + WorkflowExecutionContinuedAsNewEventAttributes: toWorkflowExecutionContinuedAsNewEventAttributes(e.WorkflowExecutionContinuedAsNewEventAttributes), + } + case shared.EventTypeStartChildWorkflowExecutionInitiated: + event.Attributes = &apiv1.HistoryEvent_StartChildWorkflowExecutionInitiatedEventAttributes{ + StartChildWorkflowExecutionInitiatedEventAttributes: toStartChildWorkflowExecutionInitiatedEventAttributes(e.StartChildWorkflowExecutionInitiatedEventAttributes), + } + case shared.EventTypeStartChildWorkflowExecutionFailed: + event.Attributes = &apiv1.HistoryEvent_StartChildWorkflowExecutionFailedEventAttributes{ + StartChildWorkflowExecutionFailedEventAttributes: toStartChildWorkflowExecutionFailedEventAttributes(e.StartChildWorkflowExecutionFailedEventAttributes), + } + case shared.EventTypeChildWorkflowExecutionStarted: + event.Attributes = &apiv1.HistoryEvent_ChildWorkflowExecutionStartedEventAttributes{ + ChildWorkflowExecutionStartedEventAttributes: toChildWorkflowExecutionStartedEventAttributes(e.ChildWorkflowExecutionStartedEventAttributes), + } + case shared.EventTypeChildWorkflowExecutionCompleted: + event.Attributes = &apiv1.HistoryEvent_ChildWorkflowExecutionCompletedEventAttributes{ + ChildWorkflowExecutionCompletedEventAttributes: toChildWorkflowExecutionCompletedEventAttributes(e.ChildWorkflowExecutionCompletedEventAttributes), + } + case shared.EventTypeChildWorkflowExecutionFailed: + event.Attributes = &apiv1.HistoryEvent_ChildWorkflowExecutionFailedEventAttributes{ + ChildWorkflowExecutionFailedEventAttributes: toChildWorkflowExecutionFailedEventAttributes(e.ChildWorkflowExecutionFailedEventAttributes), + } + case shared.EventTypeChildWorkflowExecutionCanceled: + event.Attributes = &apiv1.HistoryEvent_ChildWorkflowExecutionCanceledEventAttributes{ + ChildWorkflowExecutionCanceledEventAttributes: toChildWorkflowExecutionCanceledEventAttributes(e.ChildWorkflowExecutionCanceledEventAttributes), + } + case shared.EventTypeChildWorkflowExecutionTimedOut: + event.Attributes = &apiv1.HistoryEvent_ChildWorkflowExecutionTimedOutEventAttributes{ + ChildWorkflowExecutionTimedOutEventAttributes: toChildWorkflowExecutionTimedOutEventAttributes(e.ChildWorkflowExecutionTimedOutEventAttributes), + } + case shared.EventTypeChildWorkflowExecutionTerminated: + event.Attributes = &apiv1.HistoryEvent_ChildWorkflowExecutionTerminatedEventAttributes{ + ChildWorkflowExecutionTerminatedEventAttributes: toChildWorkflowExecutionTerminatedEventAttributes(e.ChildWorkflowExecutionTerminatedEventAttributes), + } + case shared.EventTypeSignalExternalWorkflowExecutionInitiated: + event.Attributes = &apiv1.HistoryEvent_SignalExternalWorkflowExecutionInitiatedEventAttributes{ + SignalExternalWorkflowExecutionInitiatedEventAttributes: toSignalExternalWorkflowExecutionInitiatedEventAttributes(e.SignalExternalWorkflowExecutionInitiatedEventAttributes), + } + case shared.EventTypeSignalExternalWorkflowExecutionFailed: + event.Attributes = &apiv1.HistoryEvent_SignalExternalWorkflowExecutionFailedEventAttributes{ + SignalExternalWorkflowExecutionFailedEventAttributes: toSignalExternalWorkflowExecutionFailedEventAttributes(e.SignalExternalWorkflowExecutionFailedEventAttributes), + } + case shared.EventTypeExternalWorkflowExecutionSignaled: + event.Attributes = &apiv1.HistoryEvent_ExternalWorkflowExecutionSignaledEventAttributes{ + ExternalWorkflowExecutionSignaledEventAttributes: toExternalWorkflowExecutionSignaledEventAttributes(e.ExternalWorkflowExecutionSignaledEventAttributes), + } + case shared.EventTypeUpsertWorkflowSearchAttributes: + event.Attributes = &apiv1.HistoryEvent_UpsertWorkflowSearchAttributesEventAttributes{ + UpsertWorkflowSearchAttributesEventAttributes: toUpsertWorkflowSearchAttributesEventAttributes(e.UpsertWorkflowSearchAttributesEventAttributes), + } + } + return &event +} + +func toActivityTaskCancelRequestedEventAttributes(t *shared.ActivityTaskCancelRequestedEventAttributes) *apiv1.ActivityTaskCancelRequestedEventAttributes { + if t == nil { + return nil + } + return &apiv1.ActivityTaskCancelRequestedEventAttributes{ + ActivityId: t.GetActivityId(), + DecisionTaskCompletedEventId: t.GetDecisionTaskCompletedEventId(), + } +} + +func toActivityTaskCanceledEventAttributes(t *shared.ActivityTaskCanceledEventAttributes) *apiv1.ActivityTaskCanceledEventAttributes { + if t == nil { + return nil + } + return &apiv1.ActivityTaskCanceledEventAttributes{ + Details: toPayload(t.Details), + LatestCancelRequestedEventId: t.GetLatestCancelRequestedEventId(), + ScheduledEventId: t.GetScheduledEventId(), + StartedEventId: t.GetStartedEventId(), + Identity: t.GetIdentity(), + } +} + +func toActivityTaskCompletedEventAttributes(t *shared.ActivityTaskCompletedEventAttributes) *apiv1.ActivityTaskCompletedEventAttributes { + if t == nil { + return nil + } + return &apiv1.ActivityTaskCompletedEventAttributes{ + Result: toPayload(t.Result), + ScheduledEventId: t.GetScheduledEventId(), + StartedEventId: t.GetStartedEventId(), + Identity: t.GetIdentity(), + } +} + +func toActivityTaskFailedEventAttributes(t *shared.ActivityTaskFailedEventAttributes) *apiv1.ActivityTaskFailedEventAttributes { + if t == nil { + return nil + } + return &apiv1.ActivityTaskFailedEventAttributes{ + Failure: toFailure(t.Reason, t.Details), + ScheduledEventId: t.GetScheduledEventId(), + StartedEventId: t.GetStartedEventId(), + Identity: t.GetIdentity(), + } +} + +func toActivityTaskScheduledEventAttributes(t *shared.ActivityTaskScheduledEventAttributes) *apiv1.ActivityTaskScheduledEventAttributes { + if t == nil { + return nil + } + return &apiv1.ActivityTaskScheduledEventAttributes{ + ActivityId: t.GetActivityId(), + ActivityType: toActivityType(t.ActivityType), + Domain: t.GetDomain(), + TaskList: toTaskList(t.TaskList), + Input: toPayload(t.Input), + ScheduleToCloseTimeout: secondsToDuration(t.ScheduleToCloseTimeoutSeconds), + ScheduleToStartTimeout: secondsToDuration(t.ScheduleToStartTimeoutSeconds), + StartToCloseTimeout: secondsToDuration(t.StartToCloseTimeoutSeconds), + HeartbeatTimeout: secondsToDuration(t.HeartbeatTimeoutSeconds), + DecisionTaskCompletedEventId: t.GetDecisionTaskCompletedEventId(), + RetryPolicy: toRetryPolicy(t.RetryPolicy), + Header: toHeader(t.Header), + } +} + +func toActivityTaskStartedEventAttributes(t *shared.ActivityTaskStartedEventAttributes) *apiv1.ActivityTaskStartedEventAttributes { + if t == nil { + return nil + } + return &apiv1.ActivityTaskStartedEventAttributes{ + ScheduledEventId: t.GetScheduledEventId(), + Identity: t.GetIdentity(), + RequestId: t.GetRequestId(), + Attempt: t.GetAttempt(), + LastFailure: toFailure(t.LastFailureReason, t.LastFailureDetails), + } +} + +func toActivityTaskTimedOutEventAttributes(t *shared.ActivityTaskTimedOutEventAttributes) *apiv1.ActivityTaskTimedOutEventAttributes { + if t == nil { + return nil + } + return &apiv1.ActivityTaskTimedOutEventAttributes{ + Details: toPayload(t.Details), + ScheduledEventId: t.GetScheduledEventId(), + StartedEventId: t.GetStartedEventId(), + TimeoutType: toTimeoutType(t.TimeoutType), + LastFailure: toFailure(t.LastFailureReason, t.LastFailureDetails), + } +} + +func toCancelTimerFailedEventAttributes(t *shared.CancelTimerFailedEventAttributes) *apiv1.CancelTimerFailedEventAttributes { + if t == nil { + return nil + } + return &apiv1.CancelTimerFailedEventAttributes{ + TimerId: t.GetTimerId(), + Cause: t.GetCause(), + DecisionTaskCompletedEventId: t.GetDecisionTaskCompletedEventId(), + Identity: t.GetIdentity(), + } +} + +func toChildWorkflowExecutionCanceledEventAttributes(t *shared.ChildWorkflowExecutionCanceledEventAttributes) *apiv1.ChildWorkflowExecutionCanceledEventAttributes { + if t == nil { + return nil + } + return &apiv1.ChildWorkflowExecutionCanceledEventAttributes{ + Domain: t.GetDomain(), + WorkflowExecution: toWorkflowExecution(t.WorkflowExecution), + WorkflowType: toWorkflowType(t.WorkflowType), + InitiatedEventId: t.GetInitiatedEventId(), + StartedEventId: t.GetStartedEventId(), + Details: toPayload(t.Details), + } +} + +func toChildWorkflowExecutionCompletedEventAttributes(t *shared.ChildWorkflowExecutionCompletedEventAttributes) *apiv1.ChildWorkflowExecutionCompletedEventAttributes { + if t == nil { + return nil + } + return &apiv1.ChildWorkflowExecutionCompletedEventAttributes{ + Domain: t.GetDomain(), + WorkflowExecution: toWorkflowExecution(t.WorkflowExecution), + WorkflowType: toWorkflowType(t.WorkflowType), + InitiatedEventId: t.GetInitiatedEventId(), + StartedEventId: t.GetStartedEventId(), + Result: toPayload(t.Result), + } +} + +func toWorkflowExecutionStartedEventAttributes(t *shared.WorkflowExecutionStartedEventAttributes) *apiv1.WorkflowExecutionStartedEventAttributes { + if t == nil { + return nil + } + return &apiv1.WorkflowExecutionStartedEventAttributes{ + WorkflowType: toWorkflowType(t.WorkflowType), + ParentExecutionInfo: toParentExecutionInfoFields(t.ParentWorkflowDomain, t.ParentWorkflowExecution, t.ParentInitiatedEventId), + TaskList: toTaskList(t.TaskList), + Input: toPayload(t.Input), + ExecutionStartToCloseTimeout: secondsToDuration(t.ExecutionStartToCloseTimeoutSeconds), + TaskStartToCloseTimeout: secondsToDuration(t.TaskStartToCloseTimeoutSeconds), + ContinuedExecutionRunId: t.GetContinuedExecutionRunId(), + Initiator: toContinueAsNewInitiator(t.Initiator), + ContinuedFailure: toFailure(t.ContinuedFailureReason, t.ContinuedFailureDetails), + LastCompletionResult: toPayload(t.LastCompletionResult), + OriginalExecutionRunId: t.GetOriginalExecutionRunId(), + Identity: t.GetIdentity(), + FirstExecutionRunId: t.GetFirstExecutionRunId(), + RetryPolicy: toRetryPolicy(t.RetryPolicy), + Attempt: t.GetAttempt(), + ExpirationTime: unixNanoToTime(t.ExpirationTimestamp), + CronSchedule: t.GetCronSchedule(), + FirstDecisionTaskBackoff: secondsToDuration(t.FirstDecisionTaskBackoffSeconds), + Memo: toMemo(t.Memo), + SearchAttributes: toSearchAttributes(t.SearchAttributes), + PrevAutoResetPoints: toResetPoints(t.PrevAutoResetPoints), + Header: toHeader(t.Header), + } +} + +func toWorkflowExecutionTerminatedEventAttributes(t *shared.WorkflowExecutionTerminatedEventAttributes) *apiv1.WorkflowExecutionTerminatedEventAttributes { + if t == nil { + return nil + } + return &apiv1.WorkflowExecutionTerminatedEventAttributes{ + Reason: t.GetReason(), + Details: toPayload(t.Details), + Identity: t.GetIdentity(), + } +} + +func toWorkflowExecutionTimedOutEventAttributes(t *shared.WorkflowExecutionTimedOutEventAttributes) *apiv1.WorkflowExecutionTimedOutEventAttributes { + if t == nil { + return nil + } + return &apiv1.WorkflowExecutionTimedOutEventAttributes{ + TimeoutType: toTimeoutType(t.TimeoutType), + } +} + +func toWorkflowExecutionCompletedEventAttributes(t *shared.WorkflowExecutionCompletedEventAttributes) *apiv1.WorkflowExecutionCompletedEventAttributes { + if t == nil { + return nil + } + return &apiv1.WorkflowExecutionCompletedEventAttributes{ + Result: toPayload(t.Result), + DecisionTaskCompletedEventId: t.GetDecisionTaskCompletedEventId(), + } +} + +func toWorkflowExecutionFailedEventAttributes(t *shared.WorkflowExecutionFailedEventAttributes) *apiv1.WorkflowExecutionFailedEventAttributes { + if t == nil { + return nil + } + return &apiv1.WorkflowExecutionFailedEventAttributes{ + Failure: toFailure(t.Reason, t.Details), + DecisionTaskCompletedEventId: t.GetDecisionTaskCompletedEventId(), + } +} + +func toDecisionTaskFailedEventAttributes(t *shared.DecisionTaskFailedEventAttributes) *apiv1.DecisionTaskFailedEventAttributes { + if t == nil { + return nil + } + return &apiv1.DecisionTaskFailedEventAttributes{ + ScheduledEventId: t.GetScheduledEventId(), + StartedEventId: t.GetStartedEventId(), + Cause: toDecisionTaskFailedCause(t.Cause), + Failure: toFailure(t.Reason, t.Details), + Identity: t.GetIdentity(), + BaseRunId: t.GetBaseRunId(), + NewRunId: t.GetNewRunId(), + ForkEventVersion: t.GetForkEventVersion(), + BinaryChecksum: t.GetBinaryChecksum(), + } +} + +func toDecisionTaskScheduledEventAttributes(t *shared.DecisionTaskScheduledEventAttributes) *apiv1.DecisionTaskScheduledEventAttributes { + if t == nil { + return nil + } + return &apiv1.DecisionTaskScheduledEventAttributes{ + TaskList: toTaskList(t.TaskList), + StartToCloseTimeout: secondsToDuration(t.StartToCloseTimeoutSeconds), + Attempt: int32(t.GetAttempt()), + } +} + +func toDecisionTaskStartedEventAttributes(t *shared.DecisionTaskStartedEventAttributes) *apiv1.DecisionTaskStartedEventAttributes { + if t == nil { + return nil + } + return &apiv1.DecisionTaskStartedEventAttributes{ + ScheduledEventId: t.GetScheduledEventId(), + Identity: t.GetIdentity(), + RequestId: t.GetRequestId(), + } +} + +func toDecisionTaskTimedOutEventAttributes(t *shared.DecisionTaskTimedOutEventAttributes) *apiv1.DecisionTaskTimedOutEventAttributes { + if t == nil { + return nil + } + return &apiv1.DecisionTaskTimedOutEventAttributes{ + ScheduledEventId: t.GetScheduledEventId(), + StartedEventId: t.GetStartedEventId(), + TimeoutType: toTimeoutType(t.TimeoutType), + BaseRunId: t.GetBaseRunId(), + NewRunId: t.GetNewRunId(), + ForkEventVersion: t.GetForkEventVersion(), + Reason: t.GetReason(), + Cause: toDecisionTaskTimedOutCause(t.Cause), + } +} + +func toRequestCancelActivityTaskFailedEventAttributes(t *shared.RequestCancelActivityTaskFailedEventAttributes) *apiv1.RequestCancelActivityTaskFailedEventAttributes { + if t == nil { + return nil + } + return &apiv1.RequestCancelActivityTaskFailedEventAttributes{ + ActivityId: t.GetActivityId(), + Cause: t.GetCause(), + DecisionTaskCompletedEventId: t.GetDecisionTaskCompletedEventId(), + } +} + +func toTimerCanceledEventAttributes(t *shared.TimerCanceledEventAttributes) *apiv1.TimerCanceledEventAttributes { + if t == nil { + return nil + } + return &apiv1.TimerCanceledEventAttributes{ + TimerId: t.GetTimerId(), + StartedEventId: t.GetStartedEventId(), + DecisionTaskCompletedEventId: t.GetDecisionTaskCompletedEventId(), + Identity: t.GetIdentity(), + } +} + +func toTimerFiredEventAttributes(t *shared.TimerFiredEventAttributes) *apiv1.TimerFiredEventAttributes { + if t == nil { + return nil + } + return &apiv1.TimerFiredEventAttributes{ + TimerId: t.GetTimerId(), + StartedEventId: t.GetStartedEventId(), + } +} + +func toTimerStartedEventAttributes(t *shared.TimerStartedEventAttributes) *apiv1.TimerStartedEventAttributes { + if t == nil { + return nil + } + return &apiv1.TimerStartedEventAttributes{ + TimerId: t.GetTimerId(), + StartToFireTimeout: secondsToDuration(int64To32(t.StartToFireTimeoutSeconds)), + DecisionTaskCompletedEventId: t.GetDecisionTaskCompletedEventId(), + } +} + +func toWorkflowExecutionCancelRequestedEventAttributes(t *shared.WorkflowExecutionCancelRequestedEventAttributes) *apiv1.WorkflowExecutionCancelRequestedEventAttributes { + if t == nil { + return nil + } + return &apiv1.WorkflowExecutionCancelRequestedEventAttributes{ + Cause: t.GetCause(), + ExternalExecutionInfo: toExternalExecutionInfoFields(t.ExternalWorkflowExecution, t.ExternalInitiatedEventId), + Identity: t.GetIdentity(), + } +} + +func toWorkflowExecutionCanceledEventAttributes(t *shared.WorkflowExecutionCanceledEventAttributes) *apiv1.WorkflowExecutionCanceledEventAttributes { + if t == nil { + return nil + } + return &apiv1.WorkflowExecutionCanceledEventAttributes{ + DecisionTaskCompletedEventId: t.GetDecisionTaskCompletedEventId(), + Details: toPayload(t.Details), + } +} + +func toRequestCancelExternalWorkflowExecutionFailedEventAttributes(t *shared.RequestCancelExternalWorkflowExecutionFailedEventAttributes) *apiv1.RequestCancelExternalWorkflowExecutionFailedEventAttributes { + if t == nil { + return nil + } + return &apiv1.RequestCancelExternalWorkflowExecutionFailedEventAttributes{ + Cause: toCancelExternalWorkflowExecutionFailedCause(t.Cause), + DecisionTaskCompletedEventId: t.GetDecisionTaskCompletedEventId(), + Domain: t.GetDomain(), + WorkflowExecution: toWorkflowExecution(t.WorkflowExecution), + InitiatedEventId: t.GetInitiatedEventId(), + Control: t.Control, + } +} + +func toRequestCancelExternalWorkflowExecutionInitiatedEventAttributes(t *shared.RequestCancelExternalWorkflowExecutionInitiatedEventAttributes) *apiv1.RequestCancelExternalWorkflowExecutionInitiatedEventAttributes { + if t == nil { + return nil + } + return &apiv1.RequestCancelExternalWorkflowExecutionInitiatedEventAttributes{ + DecisionTaskCompletedEventId: t.GetDecisionTaskCompletedEventId(), + Domain: t.GetDomain(), + WorkflowExecution: toWorkflowExecution(t.WorkflowExecution), + Control: t.Control, + ChildWorkflowOnly: t.GetChildWorkflowOnly(), + } +} + + +func toDecisionTaskCompletedEventAttributes(t *shared.DecisionTaskCompletedEventAttributes) *apiv1.DecisionTaskCompletedEventAttributes { + if t == nil { + return nil + } + return &apiv1.DecisionTaskCompletedEventAttributes{ + ScheduledEventId: t.GetScheduledEventId(), + StartedEventId: t.GetStartedEventId(), + Identity: t.GetIdentity(), + BinaryChecksum: t.GetBinaryChecksum(), + ExecutionContext: t.ExecutionContext, + } +} + +func toExternalWorkflowExecutionCancelRequestedEventAttributes(t *shared.ExternalWorkflowExecutionCancelRequestedEventAttributes) *apiv1.ExternalWorkflowExecutionCancelRequestedEventAttributes { + if t == nil { + return nil + } + return &apiv1.ExternalWorkflowExecutionCancelRequestedEventAttributes{ + InitiatedEventId: t.GetInitiatedEventId(), + Domain: t.GetDomain(), + WorkflowExecution: toWorkflowExecution(t.WorkflowExecution), + } +} + +func toMarkerRecordedEventAttributes(t *shared.MarkerRecordedEventAttributes) *apiv1.MarkerRecordedEventAttributes { + if t == nil { + return nil + } + return &apiv1.MarkerRecordedEventAttributes{ + MarkerName: t.GetMarkerName(), + Details: toPayload(t.Details), + DecisionTaskCompletedEventId: t.GetDecisionTaskCompletedEventId(), + Header: toHeader(t.Header), + } +} + +func toWorkflowExecutionSignaledEventAttributes(t *shared.WorkflowExecutionSignaledEventAttributes) *apiv1.WorkflowExecutionSignaledEventAttributes { + if t == nil { + return nil + } + return &apiv1.WorkflowExecutionSignaledEventAttributes{ + SignalName: t.GetSignalName(), + Input: toPayload(t.Input), + Identity: t.GetIdentity(), + } +} + +func toWorkflowExecutionContinuedAsNewEventAttributes(t *shared.WorkflowExecutionContinuedAsNewEventAttributes) *apiv1.WorkflowExecutionContinuedAsNewEventAttributes { + if t == nil { + return nil + } + return &apiv1.WorkflowExecutionContinuedAsNewEventAttributes{ + NewExecutionRunId: t.GetNewExecutionRunId(), + WorkflowType: toWorkflowType(t.WorkflowType), + TaskList: toTaskList(t.TaskList), + Input: toPayload(t.Input), + ExecutionStartToCloseTimeout: secondsToDuration(t.ExecutionStartToCloseTimeoutSeconds), + TaskStartToCloseTimeout: secondsToDuration(t.TaskStartToCloseTimeoutSeconds), + DecisionTaskCompletedEventId: t.GetDecisionTaskCompletedEventId(), + BackoffStartInterval: secondsToDuration(t.BackoffStartIntervalInSeconds), + Initiator: toContinueAsNewInitiator(t.Initiator), + Failure: toFailure(t.FailureReason, t.FailureDetails), + LastCompletionResult: toPayload(t.LastCompletionResult), + Header: toHeader(t.Header), + Memo: toMemo(t.Memo), + SearchAttributes: toSearchAttributes(t.SearchAttributes), + } +} + +func toStartChildWorkflowExecutionInitiatedEventAttributes(t *shared.StartChildWorkflowExecutionInitiatedEventAttributes) *apiv1.StartChildWorkflowExecutionInitiatedEventAttributes { + if t == nil { + return nil + } + return &apiv1.StartChildWorkflowExecutionInitiatedEventAttributes{ + Domain: t.GetDomain(), + WorkflowId: t.GetWorkflowId(), + WorkflowType: toWorkflowType(t.WorkflowType), + TaskList: toTaskList(t.TaskList), + Input: toPayload(t.Input), + ExecutionStartToCloseTimeout: secondsToDuration(t.ExecutionStartToCloseTimeoutSeconds), + TaskStartToCloseTimeout: secondsToDuration(t.TaskStartToCloseTimeoutSeconds), + ParentClosePolicy: toParentClosePolicy(t.ParentClosePolicy), + Control: t.Control, + DecisionTaskCompletedEventId: t.GetDecisionTaskCompletedEventId(), + WorkflowIdReusePolicy: toWorkflowIDReusePolicy(t.WorkflowIdReusePolicy), + RetryPolicy: toRetryPolicy(t.RetryPolicy), + CronSchedule: t.GetCronSchedule(), + Header: toHeader(t.Header), + Memo: toMemo(t.Memo), + SearchAttributes: toSearchAttributes(t.SearchAttributes), + DelayStart: secondsToDuration(t.DelayStartSeconds), + } +} + +func toStartChildWorkflowExecutionFailedEventAttributes(t *shared.StartChildWorkflowExecutionFailedEventAttributes) *apiv1.StartChildWorkflowExecutionFailedEventAttributes { + if t == nil { + return nil + } + return &apiv1.StartChildWorkflowExecutionFailedEventAttributes{ + Domain: t.GetDomain(), + WorkflowId: t.GetWorkflowId(), + WorkflowType: toWorkflowType(t.WorkflowType), + Cause: toChildWorkflowExecutionFailedCause(t.Cause), + Control: t.Control, + InitiatedEventId: t.GetInitiatedEventId(), + DecisionTaskCompletedEventId: t.GetDecisionTaskCompletedEventId(), + } +} + +func toChildWorkflowExecutionStartedEventAttributes(t *shared.ChildWorkflowExecutionStartedEventAttributes) *apiv1.ChildWorkflowExecutionStartedEventAttributes { + if t == nil { + return nil + } + return &apiv1.ChildWorkflowExecutionStartedEventAttributes{ + Domain: t.GetDomain(), + WorkflowExecution: toWorkflowExecution(t.WorkflowExecution), + WorkflowType: toWorkflowType(t.WorkflowType), + InitiatedEventId: t.GetInitiatedEventId(), + Header: toHeader(t.Header), + } +} + +func toChildWorkflowExecutionFailedEventAttributes(t *shared.ChildWorkflowExecutionFailedEventAttributes) *apiv1.ChildWorkflowExecutionFailedEventAttributes { + if t == nil { + return nil + } + return &apiv1.ChildWorkflowExecutionFailedEventAttributes{ + Domain: t.GetDomain(), + WorkflowExecution: toWorkflowExecution(t.WorkflowExecution), + WorkflowType: toWorkflowType(t.WorkflowType), + InitiatedEventId: t.GetInitiatedEventId(), + StartedEventId: t.GetStartedEventId(), + Failure: toFailure(t.Reason, t.Details), + } +} + +func toChildWorkflowExecutionTimedOutEventAttributes(t *shared.ChildWorkflowExecutionTimedOutEventAttributes) *apiv1.ChildWorkflowExecutionTimedOutEventAttributes { + if t == nil { + return nil + } + return &apiv1.ChildWorkflowExecutionTimedOutEventAttributes{ + Domain: t.GetDomain(), + WorkflowExecution: toWorkflowExecution(t.WorkflowExecution), + WorkflowType: toWorkflowType(t.WorkflowType), + InitiatedEventId: t.GetInitiatedEventId(), + StartedEventId: t.GetStartedEventId(), + TimeoutType: toTimeoutType(t.TimeoutType), + } +} + + +func toChildWorkflowExecutionTerminatedEventAttributes(t *shared.ChildWorkflowExecutionTerminatedEventAttributes) *apiv1.ChildWorkflowExecutionTerminatedEventAttributes { + if t == nil { + return nil + } + return &apiv1.ChildWorkflowExecutionTerminatedEventAttributes{ + Domain: t.GetDomain(), + WorkflowExecution: toWorkflowExecution(t.WorkflowExecution), + WorkflowType: toWorkflowType(t.WorkflowType), + InitiatedEventId: t.GetInitiatedEventId(), + StartedEventId: t.GetStartedEventId(), + } +} + +func toSignalExternalWorkflowExecutionInitiatedEventAttributes(t *shared.SignalExternalWorkflowExecutionInitiatedEventAttributes) *apiv1.SignalExternalWorkflowExecutionInitiatedEventAttributes { + if t == nil { + return nil + } + return &apiv1.SignalExternalWorkflowExecutionInitiatedEventAttributes{ + DecisionTaskCompletedEventId: t.GetDecisionTaskCompletedEventId(), + Domain: t.GetDomain(), + WorkflowExecution: toWorkflowExecution(t.WorkflowExecution), + SignalName: t.GetSignalName(), + Input: toPayload(t.Input), + Control: t.Control, + ChildWorkflowOnly: t.GetChildWorkflowOnly(), + } +} + +func toSignalExternalWorkflowExecutionFailedEventAttributes(t *shared.SignalExternalWorkflowExecutionFailedEventAttributes) *apiv1.SignalExternalWorkflowExecutionFailedEventAttributes { + if t == nil { + return nil + } + return &apiv1.SignalExternalWorkflowExecutionFailedEventAttributes{ + Cause: toSignalExternalWorkflowExecutionFailedCause(t.Cause), + DecisionTaskCompletedEventId: t.GetDecisionTaskCompletedEventId(), + Domain: t.GetDomain(), + WorkflowExecution: toWorkflowExecution(t.WorkflowExecution), + InitiatedEventId: t.GetInitiatedEventId(), + Control: t.Control, + } +} + +func toExternalWorkflowExecutionSignaledEventAttributes(t *shared.ExternalWorkflowExecutionSignaledEventAttributes) *apiv1.ExternalWorkflowExecutionSignaledEventAttributes { + if t == nil { + return nil + } + return &apiv1.ExternalWorkflowExecutionSignaledEventAttributes{ + InitiatedEventId: t.GetInitiatedEventId(), + Domain: t.GetDomain(), + WorkflowExecution: toWorkflowExecution(t.WorkflowExecution), + Control: t.Control, + } +} + +func toUpsertWorkflowSearchAttributesEventAttributes(t *shared.UpsertWorkflowSearchAttributesEventAttributes) *apiv1.UpsertWorkflowSearchAttributesEventAttributes { + if t == nil { + return nil + } + return &apiv1.UpsertWorkflowSearchAttributesEventAttributes{ + DecisionTaskCompletedEventId: t.GetDecisionTaskCompletedEventId(), + SearchAttributes: toSearchAttributes(t.SearchAttributes), + } +} + +func toPayload(data []byte) *apiv1.Payload { + if data == nil { + return nil + } + return &apiv1.Payload{ + Data: data, + } +} + +func toFailure(reason *string, details []byte) *apiv1.Failure { + if reason == nil { + return nil + } + return &apiv1.Failure{ + Reason: *reason, + Details: details, + } +} + +func toWorkflowExecution(t *shared.WorkflowExecution) *apiv1.WorkflowExecution { + if t == nil { + return nil + } + return &apiv1.WorkflowExecution{ + WorkflowId: t.GetWorkflowId(), + RunId: t.GetRunId(), + } +} + +func toExternalExecutionInfoFields(we *shared.WorkflowExecution, initiatedID *int64) *apiv1.ExternalExecutionInfo { + if we == nil && initiatedID == nil { + return nil + } + if we == nil || initiatedID == nil { + panic("either all or none external execution info fields must be set") + } + return &apiv1.ExternalExecutionInfo{ + WorkflowExecution: toWorkflowExecution(we), + InitiatedId: *initiatedID, + } +} + +func toActivityType(t *shared.ActivityType) *apiv1.ActivityType { + if t == nil { + return nil + } + return &apiv1.ActivityType{ + Name: t.GetName(), + } +} + +func toWorkflowType(t *shared.WorkflowType) *apiv1.WorkflowType { + if t == nil { + return nil + } + return &apiv1.WorkflowType{ + Name: t.GetName(), + } +} + +func toTaskList(t *shared.TaskList) *apiv1.TaskList { + if t == nil { + return nil + } + return &apiv1.TaskList{ + Name: t.GetName(), + Kind: toTaskListKind(t.Kind), + } +} + +func toTaskListKind(t *shared.TaskListKind) apiv1.TaskListKind { + if t == nil { + return apiv1.TaskListKind_TASK_LIST_KIND_INVALID + } + switch *t { + case shared.TaskListKindNormal: + return apiv1.TaskListKind_TASK_LIST_KIND_NORMAL + case shared.TaskListKindSticky: + return apiv1.TaskListKind_TASK_LIST_KIND_STICKY + } + panic("unexpected enum value") +} + +func toHeader(t *shared.Header) *apiv1.Header { + if t == nil { + return nil + } + return &apiv1.Header{ + Fields: toPayloadMap(t.Fields), + } +} + +func toMemo(t *shared.Memo) *apiv1.Memo { + if t == nil { + return nil + } + return &apiv1.Memo{ + Fields: toPayloadMap(t.Fields), + } +} + +func toSearchAttributes(t *shared.SearchAttributes) *apiv1.SearchAttributes { + if t == nil { + return nil + } + return &apiv1.SearchAttributes{ + IndexedFields: toPayloadMap(t.IndexedFields), + } +} + +func toPayloadMap(t map[string][]byte) map[string]*apiv1.Payload { + if t == nil { + return nil + } + v := make(map[string]*apiv1.Payload, len(t)) + for key := range t { + v[key] = toPayload(t[key]) + } + return v +} + +func toRetryPolicy(t *shared.RetryPolicy) *apiv1.RetryPolicy { + if t == nil { + return nil + } + return &apiv1.RetryPolicy{ + InitialInterval: secondsToDuration(t.InitialIntervalInSeconds), + BackoffCoefficient: t.GetBackoffCoefficient(), + MaximumInterval: secondsToDuration(t.MaximumIntervalInSeconds), + MaximumAttempts: t.GetMaximumAttempts(), + NonRetryableErrorReasons: t.NonRetriableErrorReasons, + ExpirationInterval: secondsToDuration(t.ExpirationIntervalInSeconds), + } +} + +func toResetPoints(t *shared.ResetPoints) *apiv1.ResetPoints { + if t == nil { + return nil + } + return &apiv1.ResetPoints{ + Points: toResetPointInfoArray(t.Points), + } +} + +func toResetPointInfoArray(t []*shared.ResetPointInfo) []*apiv1.ResetPointInfo { + if t == nil { + return nil + } + v := make([]*apiv1.ResetPointInfo, len(t)) + for i := range t { + v[i] = toResetPointInfo(t[i]) + } + return v +} + +func toResetPointInfo(t *shared.ResetPointInfo) *apiv1.ResetPointInfo { + if t == nil { + return nil + } + return &apiv1.ResetPointInfo{ + BinaryChecksum: t.GetBinaryChecksum(), + RunId: t.GetRunId(), + FirstDecisionCompletedId: t.GetFirstDecisionCompletedId(), + CreatedTime: unixNanoToTime(t.CreatedTimeNano), + ExpiringTime: unixNanoToTime(t.ExpiringTimeNano), + Resettable: t.GetResettable(), + } +} + +func toParentExecutionInfoFields(domainName *string, we *shared.WorkflowExecution, initiatedID *int64) *apiv1.ParentExecutionInfo { + if domainName == nil && we == nil && initiatedID == nil { + return nil + } + if domainName == nil || we == nil || initiatedID == nil { + panic("either all or none parent execution info must be set") + } + + return &apiv1.ParentExecutionInfo{ + DomainName: *domainName, + WorkflowExecution: toWorkflowExecution(we), + InitiatedId: *initiatedID, + } +} + +func secondsToDuration(d *int32) *types.Duration { + if d == nil { + return nil + } + return types.DurationProto(time.Duration(*d) * time.Second) +} + +func unixNanoToTime(t *int64) *types.Timestamp { + if t == nil { + return nil + } + time, err := types.TimestampProto(time.Unix(0, *t)) + if err != nil { + panic(err) + } + return time +} + +func int64To32(v *int64) *int32 { + if v == nil { + return nil + } + return common.Int32Ptr(int32(*v)) +} + +func toTimeoutType(t *shared.TimeoutType) apiv1.TimeoutType { + if t == nil { + return apiv1.TimeoutType_TIMEOUT_TYPE_INVALID + } + switch *t { + case shared.TimeoutTypeStartToClose: + return apiv1.TimeoutType_TIMEOUT_TYPE_START_TO_CLOSE + case shared.TimeoutTypeScheduleToStart: + return apiv1.TimeoutType_TIMEOUT_TYPE_SCHEDULE_TO_START + case shared.TimeoutTypeScheduleToClose: + return apiv1.TimeoutType_TIMEOUT_TYPE_SCHEDULE_TO_CLOSE + case shared.TimeoutTypeHeartbeat: + return apiv1.TimeoutType_TIMEOUT_TYPE_HEARTBEAT + } + panic("unexpected enum value") +} + +func toContinueAsNewInitiator(t *shared.ContinueAsNewInitiator) apiv1.ContinueAsNewInitiator { + if t == nil { + return apiv1.ContinueAsNewInitiator_CONTINUE_AS_NEW_INITIATOR_INVALID + } + switch *t { + case shared.ContinueAsNewInitiatorDecider: + return apiv1.ContinueAsNewInitiator_CONTINUE_AS_NEW_INITIATOR_DECIDER + case shared.ContinueAsNewInitiatorRetryPolicy: + return apiv1.ContinueAsNewInitiator_CONTINUE_AS_NEW_INITIATOR_RETRY_POLICY + case shared.ContinueAsNewInitiatorCronSchedule: + return apiv1.ContinueAsNewInitiator_CONTINUE_AS_NEW_INITIATOR_CRON_SCHEDULE + } + panic("unexpected enum value") +} + +func toDecisionTaskFailedCause(t *shared.DecisionTaskFailedCause) apiv1.DecisionTaskFailedCause { + if t == nil { + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_INVALID + } + switch *t { + case shared.DecisionTaskFailedCauseUnhandledDecision: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_UNHANDLED_DECISION + case shared.DecisionTaskFailedCauseBadScheduleActivityAttributes: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_BAD_SCHEDULE_ACTIVITY_ATTRIBUTES + case shared.DecisionTaskFailedCauseBadRequestCancelActivityAttributes: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_BAD_REQUEST_CANCEL_ACTIVITY_ATTRIBUTES + case shared.DecisionTaskFailedCauseBadStartTimerAttributes: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_BAD_START_TIMER_ATTRIBUTES + case shared.DecisionTaskFailedCauseBadCancelTimerAttributes: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_BAD_CANCEL_TIMER_ATTRIBUTES + case shared.DecisionTaskFailedCauseBadRecordMarkerAttributes: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_BAD_RECORD_MARKER_ATTRIBUTES + case shared.DecisionTaskFailedCauseBadCompleteWorkflowExecutionAttributes: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_BAD_COMPLETE_WORKFLOW_EXECUTION_ATTRIBUTES + case shared.DecisionTaskFailedCauseBadFailWorkflowExecutionAttributes: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_BAD_FAIL_WORKFLOW_EXECUTION_ATTRIBUTES + case shared.DecisionTaskFailedCauseBadCancelWorkflowExecutionAttributes: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_BAD_CANCEL_WORKFLOW_EXECUTION_ATTRIBUTES + case shared.DecisionTaskFailedCauseBadRequestCancelExternalWorkflowExecutionAttributes: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_BAD_REQUEST_CANCEL_EXTERNAL_WORKFLOW_EXECUTION_ATTRIBUTES + case shared.DecisionTaskFailedCauseBadContinueAsNewAttributes: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_BAD_CONTINUE_AS_NEW_ATTRIBUTES + case shared.DecisionTaskFailedCauseStartTimerDuplicateID: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_START_TIMER_DUPLICATE_ID + case shared.DecisionTaskFailedCauseResetStickyTasklist: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_RESET_STICKY_TASK_LIST + case shared.DecisionTaskFailedCauseWorkflowWorkerUnhandledFailure: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_WORKFLOW_WORKER_UNHANDLED_FAILURE + case shared.DecisionTaskFailedCauseBadSignalWorkflowExecutionAttributes: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_BAD_SIGNAL_WORKFLOW_EXECUTION_ATTRIBUTES + case shared.DecisionTaskFailedCauseBadStartChildExecutionAttributes: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_BAD_START_CHILD_EXECUTION_ATTRIBUTES + case shared.DecisionTaskFailedCauseForceCloseDecision: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_FORCE_CLOSE_DECISION + case shared.DecisionTaskFailedCauseFailoverCloseDecision: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_FAILOVER_CLOSE_DECISION + case shared.DecisionTaskFailedCauseBadSignalInputSize: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_BAD_SIGNAL_INPUT_SIZE + case shared.DecisionTaskFailedCauseResetWorkflow: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_RESET_WORKFLOW + case shared.DecisionTaskFailedCauseBadBinary: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_BAD_BINARY + case shared.DecisionTaskFailedCauseScheduleActivityDuplicateID: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_SCHEDULE_ACTIVITY_DUPLICATE_ID + case shared.DecisionTaskFailedCauseBadSearchAttributes: + return apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_BAD_SEARCH_ATTRIBUTES + } + panic("unexpected enum value") +} + +func toDecisionTaskTimedOutCause(t *shared.DecisionTaskTimedOutCause) apiv1.DecisionTaskTimedOutCause { + if t == nil { + return apiv1.DecisionTaskTimedOutCause_DECISION_TASK_TIMED_OUT_CAUSE_INVALID + } + switch *t { + case shared.DecisionTaskTimedOutCauseTimeout: + return apiv1.DecisionTaskTimedOutCause_DECISION_TASK_TIMED_OUT_CAUSE_TIMEOUT + case shared.DecisionTaskTimedOutCauseReset: + return apiv1.DecisionTaskTimedOutCause_DECISION_TASK_TIMED_OUT_CAUSE_RESET + } + panic("unexpected enum value") +} + +func toCancelExternalWorkflowExecutionFailedCause(t *shared.CancelExternalWorkflowExecutionFailedCause) apiv1.CancelExternalWorkflowExecutionFailedCause { + if t == nil { + return apiv1.CancelExternalWorkflowExecutionFailedCause_CANCEL_EXTERNAL_WORKFLOW_EXECUTION_FAILED_CAUSE_INVALID + } + switch *t { + case shared.CancelExternalWorkflowExecutionFailedCauseUnknownExternalWorkflowExecution: + return apiv1.CancelExternalWorkflowExecutionFailedCause_CANCEL_EXTERNAL_WORKFLOW_EXECUTION_FAILED_CAUSE_UNKNOWN_EXTERNAL_WORKFLOW_EXECUTION + } + panic("unexpected enum value") +} + +func toParentClosePolicy(t *shared.ParentClosePolicy) apiv1.ParentClosePolicy { + if t == nil { + return apiv1.ParentClosePolicy_PARENT_CLOSE_POLICY_INVALID + } + switch *t { + case shared.ParentClosePolicyAbandon: + return apiv1.ParentClosePolicy_PARENT_CLOSE_POLICY_ABANDON + case shared.ParentClosePolicyRequestCancel: + return apiv1.ParentClosePolicy_PARENT_CLOSE_POLICY_REQUEST_CANCEL + case shared.ParentClosePolicyTerminate: + return apiv1.ParentClosePolicy_PARENT_CLOSE_POLICY_TERMINATE + } + panic("unexpected enum value") +} + +func toWorkflowIDReusePolicy(t *shared.WorkflowIdReusePolicy) apiv1.WorkflowIdReusePolicy { + if t == nil { + return apiv1.WorkflowIdReusePolicy_WORKFLOW_ID_REUSE_POLICY_INVALID + } + switch *t { + case shared.WorkflowIdReusePolicyAllowDuplicateFailedOnly: + return apiv1.WorkflowIdReusePolicy_WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE_FAILED_ONLY + case shared.WorkflowIdReusePolicyAllowDuplicate: + return apiv1.WorkflowIdReusePolicy_WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE + case shared.WorkflowIdReusePolicyRejectDuplicate: + return apiv1.WorkflowIdReusePolicy_WORKFLOW_ID_REUSE_POLICY_REJECT_DUPLICATE + case shared.WorkflowIdReusePolicyTerminateIfRunning: + return apiv1.WorkflowIdReusePolicy_WORKFLOW_ID_REUSE_POLICY_TERMINATE_IF_RUNNING + } + panic("unexpected enum value") +} + +func toChildWorkflowExecutionFailedCause(t *shared.ChildWorkflowExecutionFailedCause) apiv1.ChildWorkflowExecutionFailedCause { + if t == nil { + return apiv1.ChildWorkflowExecutionFailedCause_CHILD_WORKFLOW_EXECUTION_FAILED_CAUSE_INVALID + } + switch *t { + case shared.ChildWorkflowExecutionFailedCauseWorkflowAlreadyRunning: + return apiv1.ChildWorkflowExecutionFailedCause_CHILD_WORKFLOW_EXECUTION_FAILED_CAUSE_WORKFLOW_ALREADY_RUNNING + } + panic("unexpected enum value") +} + +func toSignalExternalWorkflowExecutionFailedCause(t *shared.SignalExternalWorkflowExecutionFailedCause) apiv1.SignalExternalWorkflowExecutionFailedCause { + if t == nil { + return apiv1.SignalExternalWorkflowExecutionFailedCause_SIGNAL_EXTERNAL_WORKFLOW_EXECUTION_FAILED_CAUSE_INVALID + } + switch *t { + case shared.SignalExternalWorkflowExecutionFailedCauseUnknownExternalWorkflowExecution: + return apiv1.SignalExternalWorkflowExecutionFailedCause_SIGNAL_EXTERNAL_WORKFLOW_EXECUTION_FAILED_CAUSE_UNKNOWN_EXTERNAL_WORKFLOW_EXECUTION + } + panic("unexpected enum value") +} \ No newline at end of file diff --git a/internal/client.go b/internal/client.go index 6c490f13d..b238f5dcf 100644 --- a/internal/client.go +++ b/internal/client.go @@ -28,9 +28,9 @@ import ( "github.com/opentracing/opentracing-go" "github.com/uber-go/tally" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" - s "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common/metrics" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/internal/common/metrics" "go.uber.org/zap" ) @@ -161,7 +161,7 @@ type ( // Example:- // To iterate all events, // iter := GetWorkflowHistory(ctx, workflowID, runID, isLongPoll, filterType) - // events := []*shared.HistoryEvent{} + // events := []*apiv1.HistoryEvent{} // for iter.HasNext() { // event, err := iter.Next() // if err != nil { @@ -169,7 +169,7 @@ type ( // } // events = append(events, event) // } - GetWorkflowHistory(ctx context.Context, workflowID string, runID string, isLongPoll bool, filterType s.HistoryEventFilterType) HistoryEventIterator + GetWorkflowHistory(ctx context.Context, workflowID string, runID string, isLongPoll bool, filterType apiv1.EventFilterType) HistoryEventIterator // CompleteActivity reports activity completed. // activity Execute method can return acitivity.activity.ErrResultPending to @@ -220,14 +220,14 @@ type ( // - BadRequestError // - InternalServiceError // - EntityNotExistError - ListClosedWorkflow(ctx context.Context, request *s.ListClosedWorkflowExecutionsRequest) (*s.ListClosedWorkflowExecutionsResponse, error) + ListClosedWorkflow(ctx context.Context, request *apiv1.ListClosedWorkflowExecutionsRequest) (*apiv1.ListClosedWorkflowExecutionsResponse, error) // ListClosedWorkflow gets open workflow executions based on request filters // The errors it can return: // - BadRequestError // - InternalServiceError // - EntityNotExistError - ListOpenWorkflow(ctx context.Context, request *s.ListOpenWorkflowExecutionsRequest) (*s.ListOpenWorkflowExecutionsResponse, error) + ListOpenWorkflow(ctx context.Context, request *apiv1.ListOpenWorkflowExecutionsRequest) (*apiv1.ListOpenWorkflowExecutionsResponse, error) // ListWorkflow gets workflow executions based on query. This API only works with ElasticSearch, // and will return BadRequestError when using Cassandra or MySQL. The query is basically the SQL WHERE clause, @@ -240,7 +240,7 @@ type ( // The errors it can return: // - BadRequestError // - InternalServiceError - ListWorkflow(ctx context.Context, request *s.ListWorkflowExecutionsRequest) (*s.ListWorkflowExecutionsResponse, error) + ListWorkflow(ctx context.Context, request *apiv1.ListWorkflowExecutionsRequest) (*apiv1.ListWorkflowExecutionsResponse, error) // ListArchivedWorkflow gets archived workflow executions based on query. This API will return BadRequest if Cadence // cluster or target domain is not configured for visibility archival or read is not enabled. The query is basically the SQL WHERE clause. @@ -249,7 +249,7 @@ type ( // The errors it can return: // - BadRequestError // - InternalServiceError - ListArchivedWorkflow(ctx context.Context, request *s.ListArchivedWorkflowExecutionsRequest) (*s.ListArchivedWorkflowExecutionsResponse, error) + ListArchivedWorkflow(ctx context.Context, request *apiv1.ListArchivedWorkflowExecutionsRequest) (*apiv1.ListArchivedWorkflowExecutionsResponse, error) // ScanWorkflow gets workflow executions based on query. This API only works with ElasticSearch, // and will return BadRequestError when using Cassandra or MySQL. The query is basically the SQL WHERE clause @@ -260,7 +260,7 @@ type ( // The errors it can return: // - BadRequestError // - InternalServiceError - ScanWorkflow(ctx context.Context, request *s.ListWorkflowExecutionsRequest) (*s.ListWorkflowExecutionsResponse, error) + ScanWorkflow(ctx context.Context, request *apiv1.ScanWorkflowExecutionsRequest) (*apiv1.ScanWorkflowExecutionsResponse, error) // CountWorkflow gets number of workflow executions based on query. This API only works with ElasticSearch, // and will return BadRequestError when using Cassandra or MySQL. The query is basically the SQL WHERE clause @@ -268,12 +268,12 @@ type ( // The errors it can return: // - BadRequestError // - InternalServiceError - CountWorkflow(ctx context.Context, request *s.CountWorkflowExecutionsRequest) (*s.CountWorkflowExecutionsResponse, error) + CountWorkflow(ctx context.Context, request *apiv1.CountWorkflowExecutionsRequest) (*apiv1.CountWorkflowExecutionsResponse, error) // GetSearchAttributes returns valid search attributes keys and value types. // The search attributes can be used in query of List/Scan/Count APIs. Adding new search attributes requires cadence server // to update dynamic config ValidSearchAttributes. - GetSearchAttributes(ctx context.Context) (*s.GetSearchAttributesResponse, error) + GetSearchAttributes(ctx context.Context) (*apiv1.GetSearchAttributesResponse, error) // QueryWorkflow queries a given workflow execution and returns the query result synchronously. Parameter workflowID // and queryType are required, other parameters are optional. The workflowID and runID (optional) identify the @@ -310,14 +310,14 @@ type ( // - BadRequestError // - InternalServiceError // - EntityNotExistError - ResetWorkflow(ctx context.Context, request *s.ResetWorkflowExecutionRequest) (*s.ResetWorkflowExecutionResponse, error) + ResetWorkflow(ctx context.Context, request *apiv1.ResetWorkflowExecutionRequest) (*apiv1.ResetWorkflowExecutionResponse, error) // DescribeWorkflowExecution returns information about the specified workflow execution. // The errors it can return: // - BadRequestError // - InternalServiceError // - EntityNotExistError - DescribeWorkflowExecution(ctx context.Context, workflowID, runID string) (*s.DescribeWorkflowExecutionResponse, error) + DescribeWorkflowExecution(ctx context.Context, workflowID, runID string) (*apiv1.DescribeWorkflowExecutionResponse, error) // DescribeTaskList returns information about the target tasklist, right now this API returns the // pollers which polled this tasklist in last few minutes. @@ -325,7 +325,7 @@ type ( // - BadRequestError // - InternalServiceError // - EntityNotExistError - DescribeTaskList(ctx context.Context, tasklist string, tasklistType s.TaskListType) (*s.DescribeTaskListResponse, error) + DescribeTaskList(ctx context.Context, tasklist string, tasklistType apiv1.TaskListType) (*apiv1.DescribeTaskListResponse, error) } // ClientOptions are optional parameters for Client creation. @@ -448,7 +448,7 @@ type ( // - DomainAlreadyExistsError // - BadRequestError // - InternalServiceError - Register(ctx context.Context, request *s.RegisterDomainRequest) error + Register(ctx context.Context, request *apiv1.RegisterDomainRequest) error // Describe a domain. The domain has 3 part of information // DomainInfo - Which has Name, Status, Description, Owner Email @@ -458,14 +458,14 @@ type ( // - EntityNotExistsError // - BadRequestError // - InternalServiceError - Describe(ctx context.Context, name string) (*s.DescribeDomainResponse, error) + Describe(ctx context.Context, name string) (*apiv1.DescribeDomainResponse, error) // Update a domain. // The errors it can throw: // - EntityNotExistsError // - BadRequestError // - InternalServiceError - Update(ctx context.Context, request *s.UpdateDomainRequest) error + Update(ctx context.Context, request *apiv1.UpdateDomainRequest) error } // WorkflowIDReusePolicy defines workflow ID reuse behavior. @@ -503,7 +503,7 @@ const ( ) // NewClient creates an instance of a workflow client -func NewClient(service workflowserviceclient.Interface, domain string, options *ClientOptions) Client { +func NewClient(service api.Interface, domain string, options *ClientOptions) Client { var identity string if options == nil || options.Identity == "" { identity = getWorkerIdentity("") @@ -545,7 +545,7 @@ func NewClient(service workflowserviceclient.Interface, domain string, options * } // NewDomainClient creates an instance of a domain client, to manager lifecycle of domains. -func NewDomainClient(service workflowserviceclient.Interface, options *ClientOptions) DomainClient { +func NewDomainClient(service api.Interface, options *ClientOptions) DomainClient { var identity string if options == nil || options.Identity == "" { identity = getWorkerIdentity("") @@ -564,36 +564,32 @@ func NewDomainClient(service workflowserviceclient.Interface, options *ClientOpt } } -func (p WorkflowIDReusePolicy) toThriftPtr() *s.WorkflowIdReusePolicy { - var policy s.WorkflowIdReusePolicy +func (p WorkflowIDReusePolicy) toProto() apiv1.WorkflowIdReusePolicy { switch p { case WorkflowIDReusePolicyAllowDuplicate: - policy = s.WorkflowIdReusePolicyAllowDuplicate + return apiv1.WorkflowIdReusePolicy_WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE case WorkflowIDReusePolicyAllowDuplicateFailedOnly: - policy = s.WorkflowIdReusePolicyAllowDuplicateFailedOnly + return apiv1.WorkflowIdReusePolicy_WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE_FAILED_ONLY case WorkflowIDReusePolicyRejectDuplicate: - policy = s.WorkflowIdReusePolicyRejectDuplicate + return apiv1.WorkflowIdReusePolicy_WORKFLOW_ID_REUSE_POLICY_REJECT_DUPLICATE case WorkflowIDReusePolicyTerminateIfRunning: - policy = s.WorkflowIdReusePolicyTerminateIfRunning + return apiv1.WorkflowIdReusePolicy_WORKFLOW_ID_REUSE_POLICY_TERMINATE_IF_RUNNING default: panic(fmt.Sprintf("unknown workflow reuse policy %v", p)) } - return &policy } -func (p ParentClosePolicy) toThriftPtr() *s.ParentClosePolicy { - var policy s.ParentClosePolicy +func (p ParentClosePolicy) toProto() apiv1.ParentClosePolicy { switch p { case ParentClosePolicyAbandon: - policy = s.ParentClosePolicyAbandon + return apiv1.ParentClosePolicy_PARENT_CLOSE_POLICY_ABANDON case ParentClosePolicyRequestCancel: - policy = s.ParentClosePolicyRequestCancel + return apiv1.ParentClosePolicy_PARENT_CLOSE_POLICY_REQUEST_CANCEL case ParentClosePolicyTerminate: - policy = s.ParentClosePolicyTerminate + return apiv1.ParentClosePolicy_PARENT_CLOSE_POLICY_TERMINATE default: panic(fmt.Sprintf("unknown workflow parent close policy %v", p)) } - return &policy } // NewValue creates a new encoded.Value which can be used to decode binary data returned by Cadence. For example: diff --git a/internal/cmd/dummy/dummy.go b/internal/cmd/dummy/dummy.go index cb70a7d22..78434a3b6 100644 --- a/internal/cmd/dummy/dummy.go +++ b/internal/cmd/dummy/dummy.go @@ -22,13 +22,13 @@ package main import ( - _ "go.uber.org/cadence/v1" - _ "go.uber.org/cadence/v1/activity" - _ "go.uber.org/cadence/v1/client" - _ "go.uber.org/cadence/v1/encoded" - _ "go.uber.org/cadence/v1/testsuite" - _ "go.uber.org/cadence/v1/worker" - _ "go.uber.org/cadence/v1/workflow" + _ "go.uber.org/cadence/v2" + _ "go.uber.org/cadence/v2/activity" + _ "go.uber.org/cadence/v2/client" + _ "go.uber.org/cadence/v2/encoded" + _ "go.uber.org/cadence/v2/testsuite" + _ "go.uber.org/cadence/v2/worker" + _ "go.uber.org/cadence/v2/workflow" ) func main() { diff --git a/internal/common/convert.go b/internal/common/convert.go index 021c8e703..567d7cc01 100644 --- a/internal/common/convert.go +++ b/internal/common/convert.go @@ -22,8 +22,6 @@ package common import ( "math" - - s "go.uber.org/cadence/v1/.gen/go/shared" ) // Int32Ceil return the int32 ceil of a float64 @@ -60,33 +58,3 @@ func StringPtr(v string) *string { func BoolPtr(v bool) *bool { return &v } - -// TaskListPtr makes a copy and returns the pointer to a TaskList. -func TaskListPtr(v s.TaskList) *s.TaskList { - return &v -} - -// DecisionTypePtr makes a copy and returns the pointer to a DecisionType. -func DecisionTypePtr(t s.DecisionType) *s.DecisionType { - return &t -} - -// EventTypePtr makes a copy and returns the pointer to a EventType. -func EventTypePtr(t s.EventType) *s.EventType { - return &t -} - -// QueryTaskCompletedTypePtr makes a copy and returns the pointer to a QueryTaskCompletedType. -func QueryTaskCompletedTypePtr(t s.QueryTaskCompletedType) *s.QueryTaskCompletedType { - return &t -} - -// TaskListKindPtr makes a copy and returns the pointer to a TaskListKind. -func TaskListKindPtr(t s.TaskListKind) *s.TaskListKind { - return &t -} - -// QueryResultTypePtr makes a copy and returns the pointer to a QueryResultType. -func QueryResultTypePtr(t s.QueryResultType) *s.QueryResultType { - return &t -} diff --git a/internal/common/metrics/service_wrapper.go b/internal/common/metrics/service_wrapper.go index 63b401595..f00122a66 100644 --- a/internal/common/metrics/service_wrapper.go +++ b/internal/common/metrics/service_wrapper.go @@ -26,14 +26,14 @@ import ( "time" "github.com/uber-go/tally" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" - "go.uber.org/cadence/v1/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" "go.uber.org/yarpc" ) type ( workflowServiceMetricsWrapper struct { - service workflowserviceclient.Interface + service api.Interface scope tally.Scope childScopes map[string]tally.Scope mutex sync.Mutex @@ -89,7 +89,7 @@ const ( ) // NewWorkflowServiceWrapper creates a new wrapper to WorkflowService that will emit metrics for each service call. -func NewWorkflowServiceWrapper(service workflowserviceclient.Interface, scope tally.Scope) workflowserviceclient.Interface { +func NewWorkflowServiceWrapper(service api.Interface, scope tally.Scope) api.Interface { return &workflowServiceMetricsWrapper{service: service, scope: scope, childScopes: make(map[string]tally.Scope)} } @@ -116,282 +116,281 @@ func (w *workflowServiceMetricsWrapper) getOperationScope(scopeName string) *ope func (s *operationScope) handleError(err error) { s.scope.Timer(CadenceLatency).Record(time.Now().Sub(s.startTime)) if err != nil { - switch err.(type) { - case *shared.EntityNotExistsError, - *shared.BadRequestError, - *shared.DomainAlreadyExistsError, - *shared.WorkflowExecutionAlreadyStartedError, - *shared.WorkflowExecutionAlreadyCompletedError, - *shared.QueryFailedError: + switch api.ConvertError(err).(type) { + case *api.EntityNotExistsError, + *api.BadRequestError, + *api.DomainAlreadyExistsError, + *api.WorkflowExecutionAlreadyStartedError, + *api.WorkflowExecutionAlreadyCompletedError, + *api.QueryFailedError: s.scope.Counter(CadenceInvalidRequest).Inc(1) default: s.scope.Counter(CadenceError).Inc(1) } } } - -func (w *workflowServiceMetricsWrapper) DeprecateDomain(ctx context.Context, request *shared.DeprecateDomainRequest, opts ...yarpc.CallOption) error { +func (w *workflowServiceMetricsWrapper) DeprecateDomain(ctx context.Context, request *apiv1.DeprecateDomainRequest, opts ...yarpc.CallOption) (*apiv1.DeprecateDomainResponse, error) { scope := w.getOperationScope(scopeNameDeprecateDomain) - err := w.service.DeprecateDomain(ctx, request, opts...) + result, err := w.service.DeprecateDomain(ctx, request, opts...) scope.handleError(err) - return err + return result, err } -func (w *workflowServiceMetricsWrapper) ListDomains(ctx context.Context, request *shared.ListDomainsRequest, opts ...yarpc.CallOption) (*shared.ListDomainsResponse, error) { +func (w *workflowServiceMetricsWrapper) ListDomains(ctx context.Context, request *apiv1.ListDomainsRequest, opts ...yarpc.CallOption) (*apiv1.ListDomainsResponse, error) { scope := w.getOperationScope(scopeNameListDomains) result, err := w.service.ListDomains(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) DescribeDomain(ctx context.Context, request *shared.DescribeDomainRequest, opts ...yarpc.CallOption) (*shared.DescribeDomainResponse, error) { +func (w *workflowServiceMetricsWrapper) DescribeDomain(ctx context.Context, request *apiv1.DescribeDomainRequest, opts ...yarpc.CallOption) (*apiv1.DescribeDomainResponse, error) { scope := w.getOperationScope(scopeNameDescribeDomain) result, err := w.service.DescribeDomain(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) DescribeWorkflowExecution(ctx context.Context, request *shared.DescribeWorkflowExecutionRequest, opts ...yarpc.CallOption) (*shared.DescribeWorkflowExecutionResponse, error) { +func (w *workflowServiceMetricsWrapper) DescribeWorkflowExecution(ctx context.Context, request *apiv1.DescribeWorkflowExecutionRequest, opts ...yarpc.CallOption) (*apiv1.DescribeWorkflowExecutionResponse, error) { scope := w.getOperationScope(scopeNameDescribeWorkflowExecution) result, err := w.service.DescribeWorkflowExecution(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) GetWorkflowExecutionHistory(ctx context.Context, request *shared.GetWorkflowExecutionHistoryRequest, opts ...yarpc.CallOption) (*shared.GetWorkflowExecutionHistoryResponse, error) { +func (w *workflowServiceMetricsWrapper) GetWorkflowExecutionHistory(ctx context.Context, request *apiv1.GetWorkflowExecutionHistoryRequest, opts ...yarpc.CallOption) (*apiv1.GetWorkflowExecutionHistoryResponse, error) { scope := w.getOperationScope(scopeNameGetWorkflowExecutionHistory) result, err := w.service.GetWorkflowExecutionHistory(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) ListClosedWorkflowExecutions(ctx context.Context, request *shared.ListClosedWorkflowExecutionsRequest, opts ...yarpc.CallOption) (*shared.ListClosedWorkflowExecutionsResponse, error) { +func (w *workflowServiceMetricsWrapper) ListClosedWorkflowExecutions(ctx context.Context, request *apiv1.ListClosedWorkflowExecutionsRequest, opts ...yarpc.CallOption) (*apiv1.ListClosedWorkflowExecutionsResponse, error) { scope := w.getOperationScope(scopeNameListClosedWorkflowExecutions) result, err := w.service.ListClosedWorkflowExecutions(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) ListOpenWorkflowExecutions(ctx context.Context, request *shared.ListOpenWorkflowExecutionsRequest, opts ...yarpc.CallOption) (*shared.ListOpenWorkflowExecutionsResponse, error) { +func (w *workflowServiceMetricsWrapper) ListOpenWorkflowExecutions(ctx context.Context, request *apiv1.ListOpenWorkflowExecutionsRequest, opts ...yarpc.CallOption) (*apiv1.ListOpenWorkflowExecutionsResponse, error) { scope := w.getOperationScope(scopeNameListOpenWorkflowExecutions) result, err := w.service.ListOpenWorkflowExecutions(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) ListWorkflowExecutions(ctx context.Context, request *shared.ListWorkflowExecutionsRequest, opts ...yarpc.CallOption) (*shared.ListWorkflowExecutionsResponse, error) { +func (w *workflowServiceMetricsWrapper) ListWorkflowExecutions(ctx context.Context, request *apiv1.ListWorkflowExecutionsRequest, opts ...yarpc.CallOption) (*apiv1.ListWorkflowExecutionsResponse, error) { scope := w.getOperationScope(scopeNameListWorkflowExecutions) result, err := w.service.ListWorkflowExecutions(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) ListArchivedWorkflowExecutions(ctx context.Context, request *shared.ListArchivedWorkflowExecutionsRequest, opts ...yarpc.CallOption) (*shared.ListArchivedWorkflowExecutionsResponse, error) { +func (w *workflowServiceMetricsWrapper) ListArchivedWorkflowExecutions(ctx context.Context, request *apiv1.ListArchivedWorkflowExecutionsRequest, opts ...yarpc.CallOption) (*apiv1.ListArchivedWorkflowExecutionsResponse, error) { scope := w.getOperationScope(scopeNameListArchivedWorkflowExecutions) result, err := w.service.ListArchivedWorkflowExecutions(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) ScanWorkflowExecutions(ctx context.Context, request *shared.ListWorkflowExecutionsRequest, opts ...yarpc.CallOption) (*shared.ListWorkflowExecutionsResponse, error) { +func (w *workflowServiceMetricsWrapper) ScanWorkflowExecutions(ctx context.Context, request *apiv1.ScanWorkflowExecutionsRequest, opts ...yarpc.CallOption) (*apiv1.ScanWorkflowExecutionsResponse, error) { scope := w.getOperationScope(scopeNameScanWorkflowExecutions) result, err := w.service.ScanWorkflowExecutions(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) CountWorkflowExecutions(ctx context.Context, request *shared.CountWorkflowExecutionsRequest, opts ...yarpc.CallOption) (*shared.CountWorkflowExecutionsResponse, error) { +func (w *workflowServiceMetricsWrapper) CountWorkflowExecutions(ctx context.Context, request *apiv1.CountWorkflowExecutionsRequest, opts ...yarpc.CallOption) (*apiv1.CountWorkflowExecutionsResponse, error) { scope := w.getOperationScope(scopeNameCountWorkflowExecutions) result, err := w.service.CountWorkflowExecutions(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) PollForActivityTask(ctx context.Context, request *shared.PollForActivityTaskRequest, opts ...yarpc.CallOption) (*shared.PollForActivityTaskResponse, error) { +func (w *workflowServiceMetricsWrapper) PollForActivityTask(ctx context.Context, request *apiv1.PollForActivityTaskRequest, opts ...yarpc.CallOption) (*apiv1.PollForActivityTaskResponse, error) { scope := w.getOperationScope(scopeNamePollForActivityTask) result, err := w.service.PollForActivityTask(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) PollForDecisionTask(ctx context.Context, request *shared.PollForDecisionTaskRequest, opts ...yarpc.CallOption) (*shared.PollForDecisionTaskResponse, error) { +func (w *workflowServiceMetricsWrapper) PollForDecisionTask(ctx context.Context, request *apiv1.PollForDecisionTaskRequest, opts ...yarpc.CallOption) (*apiv1.PollForDecisionTaskResponse, error) { scope := w.getOperationScope(scopeNamePollForDecisionTask) result, err := w.service.PollForDecisionTask(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) RecordActivityTaskHeartbeat(ctx context.Context, request *shared.RecordActivityTaskHeartbeatRequest, opts ...yarpc.CallOption) (*shared.RecordActivityTaskHeartbeatResponse, error) { +func (w *workflowServiceMetricsWrapper) RecordActivityTaskHeartbeat(ctx context.Context, request *apiv1.RecordActivityTaskHeartbeatRequest, opts ...yarpc.CallOption) (*apiv1.RecordActivityTaskHeartbeatResponse, error) { scope := w.getOperationScope(scopeNameRecordActivityTaskHeartbeat) result, err := w.service.RecordActivityTaskHeartbeat(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) RecordActivityTaskHeartbeatByID(ctx context.Context, request *shared.RecordActivityTaskHeartbeatByIDRequest, opts ...yarpc.CallOption) (*shared.RecordActivityTaskHeartbeatResponse, error) { +func (w *workflowServiceMetricsWrapper) RecordActivityTaskHeartbeatByID(ctx context.Context, request *apiv1.RecordActivityTaskHeartbeatByIDRequest, opts ...yarpc.CallOption) (*apiv1.RecordActivityTaskHeartbeatByIDResponse, error) { scope := w.getOperationScope(scopeNameRecordActivityTaskHeartbeatByID) result, err := w.service.RecordActivityTaskHeartbeatByID(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) RegisterDomain(ctx context.Context, request *shared.RegisterDomainRequest, opts ...yarpc.CallOption) error { +func (w *workflowServiceMetricsWrapper) RegisterDomain(ctx context.Context, request *apiv1.RegisterDomainRequest, opts ...yarpc.CallOption) (*apiv1.RegisterDomainResponse, error) { scope := w.getOperationScope(scopeNameRegisterDomain) - err := w.service.RegisterDomain(ctx, request, opts...) + result, err := w.service.RegisterDomain(ctx, request, opts...) scope.handleError(err) - return err + return result, err } -func (w *workflowServiceMetricsWrapper) RequestCancelWorkflowExecution(ctx context.Context, request *shared.RequestCancelWorkflowExecutionRequest, opts ...yarpc.CallOption) error { +func (w *workflowServiceMetricsWrapper) RequestCancelWorkflowExecution(ctx context.Context, request *apiv1.RequestCancelWorkflowExecutionRequest, opts ...yarpc.CallOption) (*apiv1.RequestCancelWorkflowExecutionResponse, error) { scope := w.getOperationScope(scopeNameRequestCancelWorkflowExecution) - err := w.service.RequestCancelWorkflowExecution(ctx, request, opts...) + result, err := w.service.RequestCancelWorkflowExecution(ctx, request, opts...) scope.handleError(err) - return err + return result, err } -func (w *workflowServiceMetricsWrapper) RespondActivityTaskCanceled(ctx context.Context, request *shared.RespondActivityTaskCanceledRequest, opts ...yarpc.CallOption) error { +func (w *workflowServiceMetricsWrapper) RespondActivityTaskCanceled(ctx context.Context, request *apiv1.RespondActivityTaskCanceledRequest, opts ...yarpc.CallOption) (*apiv1.RespondActivityTaskCanceledResponse, error) { scope := w.getOperationScope(scopeNameRespondActivityTaskCanceled) - err := w.service.RespondActivityTaskCanceled(ctx, request, opts...) + result, err := w.service.RespondActivityTaskCanceled(ctx, request, opts...) scope.handleError(err) - return err + return result, err } -func (w *workflowServiceMetricsWrapper) RespondActivityTaskCompleted(ctx context.Context, request *shared.RespondActivityTaskCompletedRequest, opts ...yarpc.CallOption) error { +func (w *workflowServiceMetricsWrapper) RespondActivityTaskCompleted(ctx context.Context, request *apiv1.RespondActivityTaskCompletedRequest, opts ...yarpc.CallOption) (*apiv1.RespondActivityTaskCompletedResponse, error) { scope := w.getOperationScope(scopeNameRespondActivityTaskCompleted) - err := w.service.RespondActivityTaskCompleted(ctx, request, opts...) + result, err := w.service.RespondActivityTaskCompleted(ctx, request, opts...) scope.handleError(err) - return err + return result, err } -func (w *workflowServiceMetricsWrapper) RespondActivityTaskFailed(ctx context.Context, request *shared.RespondActivityTaskFailedRequest, opts ...yarpc.CallOption) error { +func (w *workflowServiceMetricsWrapper) RespondActivityTaskFailed(ctx context.Context, request *apiv1.RespondActivityTaskFailedRequest, opts ...yarpc.CallOption) (*apiv1.RespondActivityTaskFailedResponse, error) { scope := w.getOperationScope(scopeNameRespondActivityTaskFailed) - err := w.service.RespondActivityTaskFailed(ctx, request, opts...) + result, err := w.service.RespondActivityTaskFailed(ctx, request, opts...) scope.handleError(err) - return err + return result, err } -func (w *workflowServiceMetricsWrapper) RespondActivityTaskCanceledByID(ctx context.Context, request *shared.RespondActivityTaskCanceledByIDRequest, opts ...yarpc.CallOption) error { +func (w *workflowServiceMetricsWrapper) RespondActivityTaskCanceledByID(ctx context.Context, request *apiv1.RespondActivityTaskCanceledByIDRequest, opts ...yarpc.CallOption) (*apiv1.RespondActivityTaskCanceledByIDResponse, error) { scope := w.getOperationScope(scopeNameRespondActivityTaskCanceledByID) - err := w.service.RespondActivityTaskCanceledByID(ctx, request, opts...) + result, err := w.service.RespondActivityTaskCanceledByID(ctx, request, opts...) scope.handleError(err) - return err + return result, err } -func (w *workflowServiceMetricsWrapper) RespondActivityTaskCompletedByID(ctx context.Context, request *shared.RespondActivityTaskCompletedByIDRequest, opts ...yarpc.CallOption) error { +func (w *workflowServiceMetricsWrapper) RespondActivityTaskCompletedByID(ctx context.Context, request *apiv1.RespondActivityTaskCompletedByIDRequest, opts ...yarpc.CallOption) (*apiv1.RespondActivityTaskCompletedByIDResponse, error) { scope := w.getOperationScope(scopeNameRespondActivityTaskCompletedByID) - err := w.service.RespondActivityTaskCompletedByID(ctx, request, opts...) + result, err := w.service.RespondActivityTaskCompletedByID(ctx, request, opts...) scope.handleError(err) - return err + return result, err } -func (w *workflowServiceMetricsWrapper) RespondActivityTaskFailedByID(ctx context.Context, request *shared.RespondActivityTaskFailedByIDRequest, opts ...yarpc.CallOption) error { +func (w *workflowServiceMetricsWrapper) RespondActivityTaskFailedByID(ctx context.Context, request *apiv1.RespondActivityTaskFailedByIDRequest, opts ...yarpc.CallOption) (*apiv1.RespondActivityTaskFailedByIDResponse, error) { scope := w.getOperationScope(scopeNameRespondActivityTaskFailedByID) - err := w.service.RespondActivityTaskFailedByID(ctx, request, opts...) + result, err := w.service.RespondActivityTaskFailedByID(ctx, request, opts...) scope.handleError(err) - return err + return result, err } -func (w *workflowServiceMetricsWrapper) RespondDecisionTaskCompleted(ctx context.Context, request *shared.RespondDecisionTaskCompletedRequest, opts ...yarpc.CallOption) (*shared.RespondDecisionTaskCompletedResponse, error) { +func (w *workflowServiceMetricsWrapper) RespondDecisionTaskCompleted(ctx context.Context, request *apiv1.RespondDecisionTaskCompletedRequest, opts ...yarpc.CallOption) (*apiv1.RespondDecisionTaskCompletedResponse, error) { scope := w.getOperationScope(scopeNameRespondDecisionTaskCompleted) response, err := w.service.RespondDecisionTaskCompleted(ctx, request, opts...) scope.handleError(err) return response, err } -func (w *workflowServiceMetricsWrapper) RespondDecisionTaskFailed(ctx context.Context, request *shared.RespondDecisionTaskFailedRequest, opts ...yarpc.CallOption) error { +func (w *workflowServiceMetricsWrapper) RespondDecisionTaskFailed(ctx context.Context, request *apiv1.RespondDecisionTaskFailedRequest, opts ...yarpc.CallOption) (*apiv1.RespondDecisionTaskFailedResponse, error) { scope := w.getOperationScope(scopeNameRespondDecisionTaskFailed) - err := w.service.RespondDecisionTaskFailed(ctx, request, opts...) + result, err := w.service.RespondDecisionTaskFailed(ctx, request, opts...) scope.handleError(err) - return err + return result, err } -func (w *workflowServiceMetricsWrapper) SignalWorkflowExecution(ctx context.Context, request *shared.SignalWorkflowExecutionRequest, opts ...yarpc.CallOption) error { +func (w *workflowServiceMetricsWrapper) SignalWorkflowExecution(ctx context.Context, request *apiv1.SignalWorkflowExecutionRequest, opts ...yarpc.CallOption) (*apiv1.SignalWorkflowExecutionResponse, error) { scope := w.getOperationScope(scopeNameSignalWorkflowExecution) - err := w.service.SignalWorkflowExecution(ctx, request, opts...) + result, err := w.service.SignalWorkflowExecution(ctx, request, opts...) scope.handleError(err) - return err + return result, err } -func (w *workflowServiceMetricsWrapper) SignalWithStartWorkflowExecution(ctx context.Context, request *shared.SignalWithStartWorkflowExecutionRequest, opts ...yarpc.CallOption) (*shared.StartWorkflowExecutionResponse, error) { +func (w *workflowServiceMetricsWrapper) SignalWithStartWorkflowExecution(ctx context.Context, request *apiv1.SignalWithStartWorkflowExecutionRequest, opts ...yarpc.CallOption) (*apiv1.SignalWithStartWorkflowExecutionResponse, error) { scope := w.getOperationScope(scopeNameSignalWithStartWorkflowExecution) result, err := w.service.SignalWithStartWorkflowExecution(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) StartWorkflowExecution(ctx context.Context, request *shared.StartWorkflowExecutionRequest, opts ...yarpc.CallOption) (*shared.StartWorkflowExecutionResponse, error) { +func (w *workflowServiceMetricsWrapper) StartWorkflowExecution(ctx context.Context, request *apiv1.StartWorkflowExecutionRequest, opts ...yarpc.CallOption) (*apiv1.StartWorkflowExecutionResponse, error) { scope := w.getOperationScope(scopeNameStartWorkflowExecution) result, err := w.service.StartWorkflowExecution(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) TerminateWorkflowExecution(ctx context.Context, request *shared.TerminateWorkflowExecutionRequest, opts ...yarpc.CallOption) error { +func (w *workflowServiceMetricsWrapper) TerminateWorkflowExecution(ctx context.Context, request *apiv1.TerminateWorkflowExecutionRequest, opts ...yarpc.CallOption) (*apiv1.TerminateWorkflowExecutionResponse, error) { scope := w.getOperationScope(scopeNameTerminateWorkflowExecution) - err := w.service.TerminateWorkflowExecution(ctx, request, opts...) + result, err := w.service.TerminateWorkflowExecution(ctx, request, opts...) scope.handleError(err) - return err + return result, err } -func (w *workflowServiceMetricsWrapper) ResetWorkflowExecution(ctx context.Context, request *shared.ResetWorkflowExecutionRequest, opts ...yarpc.CallOption) (*shared.ResetWorkflowExecutionResponse, error) { +func (w *workflowServiceMetricsWrapper) ResetWorkflowExecution(ctx context.Context, request *apiv1.ResetWorkflowExecutionRequest, opts ...yarpc.CallOption) (*apiv1.ResetWorkflowExecutionResponse, error) { scope := w.getOperationScope(scopeNameResetWorkflowExecution) result, err := w.service.ResetWorkflowExecution(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) UpdateDomain(ctx context.Context, request *shared.UpdateDomainRequest, opts ...yarpc.CallOption) (*shared.UpdateDomainResponse, error) { +func (w *workflowServiceMetricsWrapper) UpdateDomain(ctx context.Context, request *apiv1.UpdateDomainRequest, opts ...yarpc.CallOption) (*apiv1.UpdateDomainResponse, error) { scope := w.getOperationScope(scopeNameUpdateDomain) result, err := w.service.UpdateDomain(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) QueryWorkflow(ctx context.Context, request *shared.QueryWorkflowRequest, opts ...yarpc.CallOption) (*shared.QueryWorkflowResponse, error) { +func (w *workflowServiceMetricsWrapper) QueryWorkflow(ctx context.Context, request *apiv1.QueryWorkflowRequest, opts ...yarpc.CallOption) (*apiv1.QueryWorkflowResponse, error) { scope := w.getOperationScope(scopeNameQueryWorkflow) result, err := w.service.QueryWorkflow(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) ResetStickyTaskList(ctx context.Context, request *shared.ResetStickyTaskListRequest, opts ...yarpc.CallOption) (*shared.ResetStickyTaskListResponse, error) { +func (w *workflowServiceMetricsWrapper) ResetStickyTaskList(ctx context.Context, request *apiv1.ResetStickyTaskListRequest, opts ...yarpc.CallOption) (*apiv1.ResetStickyTaskListResponse, error) { scope := w.getOperationScope(scopeNameResetStickyTaskList) result, err := w.service.ResetStickyTaskList(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) DescribeTaskList(ctx context.Context, request *shared.DescribeTaskListRequest, opts ...yarpc.CallOption) (*shared.DescribeTaskListResponse, error) { +func (w *workflowServiceMetricsWrapper) DescribeTaskList(ctx context.Context, request *apiv1.DescribeTaskListRequest, opts ...yarpc.CallOption) (*apiv1.DescribeTaskListResponse, error) { scope := w.getOperationScope(scopeNameDescribeTaskList) result, err := w.service.DescribeTaskList(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) RespondQueryTaskCompleted(ctx context.Context, request *shared.RespondQueryTaskCompletedRequest, opts ...yarpc.CallOption) error { +func (w *workflowServiceMetricsWrapper) RespondQueryTaskCompleted(ctx context.Context, request *apiv1.RespondQueryTaskCompletedRequest, opts ...yarpc.CallOption) (*apiv1.RespondQueryTaskCompletedResponse, error) { scope := w.getOperationScope(scopeNameRespondQueryTaskCompleted) - err := w.service.RespondQueryTaskCompleted(ctx, request, opts...) + result, err := w.service.RespondQueryTaskCompleted(ctx, request, opts...) scope.handleError(err) - return err + return result, err } -func (w *workflowServiceMetricsWrapper) GetSearchAttributes(ctx context.Context, opts ...yarpc.CallOption) (*shared.GetSearchAttributesResponse, error) { +func (w *workflowServiceMetricsWrapper) GetSearchAttributes(ctx context.Context, request *apiv1.GetSearchAttributesRequest, opts ...yarpc.CallOption) (*apiv1.GetSearchAttributesResponse, error) { scope := w.getOperationScope(scopeNameGetSearchAttributes) - result, err := w.service.GetSearchAttributes(ctx, opts...) + result, err := w.service.GetSearchAttributes(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) ListTaskListPartitions(ctx context.Context, request *shared.ListTaskListPartitionsRequest, opts ...yarpc.CallOption) (*shared.ListTaskListPartitionsResponse, error) { +func (w *workflowServiceMetricsWrapper) ListTaskListPartitions(ctx context.Context, request *apiv1.ListTaskListPartitionsRequest, opts ...yarpc.CallOption) (*apiv1.ListTaskListPartitionsResponse, error) { scope := w.getOperationScope(scopeNameListTaskListPartitions) result, err := w.service.ListTaskListPartitions(ctx, request, opts...) scope.handleError(err) return result, err } -func (w *workflowServiceMetricsWrapper) GetClusterInfo(ctx context.Context, opts ...yarpc.CallOption) (*shared.ClusterInfo, error) { +func (w *workflowServiceMetricsWrapper) GetClusterInfo(ctx context.Context, request *apiv1.GetClusterInfoRequest, opts ...yarpc.CallOption) (*apiv1.GetClusterInfoResponse, error) { scope := w.getOperationScope(scopeNameGetClusterInfo) - result, err := w.service.GetClusterInfo(ctx, opts...) + result, err := w.service.GetClusterInfo(ctx, request, opts...) scope.handleError(err) return result, err } diff --git a/internal/common/metrics/service_wrapper_test.go b/internal/common/metrics/service_wrapper_test.go index 0bc9bd9ac..a265e3a91 100644 --- a/internal/common/metrics/service_wrapper_test.go +++ b/internal/common/metrics/service_wrapper_test.go @@ -21,6 +21,7 @@ package metrics import ( + "context" "fmt" "io" "reflect" @@ -31,10 +32,8 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" "github.com/uber-go/tally" - "github.com/uber/tchannel-go/thrift" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowservicetest" - s "go.uber.org/cadence/v1/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" "go.uber.org/yarpc" ) @@ -66,50 +65,50 @@ type testCase struct { } func Test_Wrapper(t *testing.T) { - ctx, _ := thrift.NewContext(time.Minute) + ctx, _ := context.WithTimeout(context.Background(), time.Minute) tests := []testCase{ // one case for each service call - {"DeprecateDomain", []interface{}{ctx, &s.DeprecateDomainRequest{}}, []interface{}{nil}, []string{CadenceRequest}}, - {"DescribeDomain", []interface{}{ctx, &s.DescribeDomainRequest{}}, []interface{}{&s.DescribeDomainResponse{}, nil}, []string{CadenceRequest}}, - {"GetWorkflowExecutionHistory", []interface{}{ctx, &s.GetWorkflowExecutionHistoryRequest{}}, []interface{}{&s.GetWorkflowExecutionHistoryResponse{}, nil}, []string{CadenceRequest}}, - {"ListClosedWorkflowExecutions", []interface{}{ctx, &s.ListClosedWorkflowExecutionsRequest{}}, []interface{}{&s.ListClosedWorkflowExecutionsResponse{}, nil}, []string{CadenceRequest}}, - {"ListOpenWorkflowExecutions", []interface{}{ctx, &s.ListOpenWorkflowExecutionsRequest{}}, []interface{}{&s.ListOpenWorkflowExecutionsResponse{}, nil}, []string{CadenceRequest}}, - {"PollForActivityTask", []interface{}{ctx, &s.PollForActivityTaskRequest{}}, []interface{}{&s.PollForActivityTaskResponse{}, nil}, []string{CadenceRequest}}, - {"PollForDecisionTask", []interface{}{ctx, &s.PollForDecisionTaskRequest{}}, []interface{}{&s.PollForDecisionTaskResponse{}, nil}, []string{CadenceRequest}}, - {"RecordActivityTaskHeartbeat", []interface{}{ctx, &s.RecordActivityTaskHeartbeatRequest{}}, []interface{}{&s.RecordActivityTaskHeartbeatResponse{}, nil}, []string{CadenceRequest}}, - {"RegisterDomain", []interface{}{ctx, &s.RegisterDomainRequest{}}, []interface{}{nil}, []string{CadenceRequest}}, - {"RequestCancelWorkflowExecution", []interface{}{ctx, &s.RequestCancelWorkflowExecutionRequest{}}, []interface{}{nil}, []string{CadenceRequest}}, - {"RespondActivityTaskCanceled", []interface{}{ctx, &s.RespondActivityTaskCanceledRequest{}}, []interface{}{nil}, []string{CadenceRequest}}, - {"RespondActivityTaskCompleted", []interface{}{ctx, &s.RespondActivityTaskCompletedRequest{}}, []interface{}{nil}, []string{CadenceRequest}}, - {"RespondActivityTaskFailed", []interface{}{ctx, &s.RespondActivityTaskFailedRequest{}}, []interface{}{nil}, []string{CadenceRequest}}, - {"RespondActivityTaskCanceledByID", []interface{}{ctx, &s.RespondActivityTaskCanceledByIDRequest{}}, []interface{}{nil}, []string{CadenceRequest}}, - {"RespondActivityTaskCompletedByID", []interface{}{ctx, &s.RespondActivityTaskCompletedByIDRequest{}}, []interface{}{nil}, []string{CadenceRequest}}, - {"RespondActivityTaskFailedByID", []interface{}{ctx, &s.RespondActivityTaskFailedByIDRequest{}}, []interface{}{nil}, []string{CadenceRequest}}, - {"RespondDecisionTaskCompleted", []interface{}{ctx, &s.RespondDecisionTaskCompletedRequest{}}, []interface{}{nil, nil}, []string{CadenceRequest}}, - {"SignalWorkflowExecution", []interface{}{ctx, &s.SignalWorkflowExecutionRequest{}}, []interface{}{nil}, []string{CadenceRequest}}, - {"StartWorkflowExecution", []interface{}{ctx, &s.StartWorkflowExecutionRequest{}}, []interface{}{&s.StartWorkflowExecutionResponse{}, nil}, []string{CadenceRequest}}, - {"TerminateWorkflowExecution", []interface{}{ctx, &s.TerminateWorkflowExecutionRequest{}}, []interface{}{nil}, []string{CadenceRequest}}, - {"ResetWorkflowExecution", []interface{}{ctx, &s.ResetWorkflowExecutionRequest{}}, []interface{}{&s.ResetWorkflowExecutionResponse{}, nil}, []string{CadenceRequest}}, - {"UpdateDomain", []interface{}{ctx, &s.UpdateDomainRequest{}}, []interface{}{&s.UpdateDomainResponse{}, nil}, []string{CadenceRequest}}, + {"DeprecateDomain", []interface{}{ctx, &apiv1.DeprecateDomainRequest{}}, []interface{}{&apiv1.DeprecateDomainResponse{}, nil}, []string{CadenceRequest}}, + {"DescribeDomain", []interface{}{ctx, &apiv1.DescribeDomainRequest{}}, []interface{}{&apiv1.DescribeDomainResponse{}, nil}, []string{CadenceRequest}}, + {"GetWorkflowExecutionHistory", []interface{}{ctx, &apiv1.GetWorkflowExecutionHistoryRequest{}}, []interface{}{&apiv1.GetWorkflowExecutionHistoryResponse{}, nil}, []string{CadenceRequest}}, + {"ListClosedWorkflowExecutions", []interface{}{ctx, &apiv1.ListClosedWorkflowExecutionsRequest{}}, []interface{}{&apiv1.ListClosedWorkflowExecutionsResponse{}, nil}, []string{CadenceRequest}}, + {"ListOpenWorkflowExecutions", []interface{}{ctx, &apiv1.ListOpenWorkflowExecutionsRequest{}}, []interface{}{&apiv1.ListOpenWorkflowExecutionsResponse{}, nil}, []string{CadenceRequest}}, + {"PollForActivityTask", []interface{}{ctx, &apiv1.PollForActivityTaskRequest{}}, []interface{}{&apiv1.PollForActivityTaskResponse{}, nil}, []string{CadenceRequest}}, + {"PollForDecisionTask", []interface{}{ctx, &apiv1.PollForDecisionTaskRequest{}}, []interface{}{&apiv1.PollForDecisionTaskResponse{}, nil}, []string{CadenceRequest}}, + {"RecordActivityTaskHeartbeat", []interface{}{ctx, &apiv1.RecordActivityTaskHeartbeatRequest{}}, []interface{}{&apiv1.RecordActivityTaskHeartbeatResponse{}, nil}, []string{CadenceRequest}}, + {"RegisterDomain", []interface{}{ctx, &apiv1.RegisterDomainRequest{}}, []interface{}{&apiv1.RegisterDomainResponse{}, nil}, []string{CadenceRequest}}, + {"RequestCancelWorkflowExecution", []interface{}{ctx, &apiv1.RequestCancelWorkflowExecutionRequest{}}, []interface{}{&apiv1.RequestCancelWorkflowExecutionResponse{}, nil}, []string{CadenceRequest}}, + {"RespondActivityTaskCanceled", []interface{}{ctx, &apiv1.RespondActivityTaskCanceledRequest{}}, []interface{}{&apiv1.RespondActivityTaskCanceledResponse{}, nil}, []string{CadenceRequest}}, + {"RespondActivityTaskCompleted", []interface{}{ctx, &apiv1.RespondActivityTaskCompletedRequest{}}, []interface{}{&apiv1.RespondActivityTaskCompletedResponse{}, nil}, []string{CadenceRequest}}, + {"RespondActivityTaskFailed", []interface{}{ctx, &apiv1.RespondActivityTaskFailedRequest{}}, []interface{}{&apiv1.RespondActivityTaskFailedResponse{}, nil}, []string{CadenceRequest}}, + {"RespondActivityTaskCanceledByID", []interface{}{ctx, &apiv1.RespondActivityTaskCanceledByIDRequest{}}, []interface{}{&apiv1.RespondActivityTaskCanceledByIDResponse{}, nil}, []string{CadenceRequest}}, + {"RespondActivityTaskCompletedByID", []interface{}{ctx, &apiv1.RespondActivityTaskCompletedByIDRequest{}}, []interface{}{&apiv1.RespondActivityTaskCompletedByIDResponse{}, nil}, []string{CadenceRequest}}, + {"RespondActivityTaskFailedByID", []interface{}{ctx, &apiv1.RespondActivityTaskFailedByIDRequest{}}, []interface{}{&apiv1.RespondActivityTaskFailedByIDResponse{}, nil}, []string{CadenceRequest}}, + {"RespondDecisionTaskCompleted", []interface{}{ctx, &apiv1.RespondDecisionTaskCompletedRequest{}}, []interface{}{nil, nil}, []string{CadenceRequest}}, + {"SignalWorkflowExecution", []interface{}{ctx, &apiv1.SignalWorkflowExecutionRequest{}}, []interface{}{&apiv1.SignalWorkflowExecutionResponse{}, nil}, []string{CadenceRequest}}, + {"StartWorkflowExecution", []interface{}{ctx, &apiv1.StartWorkflowExecutionRequest{}}, []interface{}{&apiv1.StartWorkflowExecutionResponse{}, nil}, []string{CadenceRequest}}, + {"TerminateWorkflowExecution", []interface{}{ctx, &apiv1.TerminateWorkflowExecutionRequest{}}, []interface{}{&apiv1.TerminateWorkflowExecutionResponse{}, nil}, []string{CadenceRequest}}, + {"ResetWorkflowExecution", []interface{}{ctx, &apiv1.ResetWorkflowExecutionRequest{}}, []interface{}{&apiv1.ResetWorkflowExecutionResponse{}, nil}, []string{CadenceRequest}}, + {"UpdateDomain", []interface{}{ctx, &apiv1.UpdateDomainRequest{}}, []interface{}{&apiv1.UpdateDomainResponse{}, nil}, []string{CadenceRequest}}, // one case of invalid request - {"PollForActivityTask", []interface{}{ctx, &s.PollForActivityTaskRequest{}}, []interface{}{nil, &s.EntityNotExistsError{}}, []string{CadenceRequest, CadenceInvalidRequest}}, + {"PollForActivityTask", []interface{}{ctx, &apiv1.PollForActivityTaskRequest{}}, []interface{}{nil, &api.EntityNotExistsError{}}, []string{CadenceRequest, CadenceInvalidRequest}}, // one case of server error - {"PollForActivityTask", []interface{}{ctx, &s.PollForActivityTaskRequest{}}, []interface{}{nil, &s.InternalServiceError{}}, []string{CadenceRequest, CadenceError}}, - {"QueryWorkflow", []interface{}{ctx, &s.QueryWorkflowRequest{}}, []interface{}{nil, &s.InternalServiceError{}}, []string{CadenceRequest, CadenceError}}, - {"RespondQueryTaskCompleted", []interface{}{ctx, &s.RespondQueryTaskCompletedRequest{}}, []interface{}{&s.InternalServiceError{}}, []string{CadenceRequest, CadenceError}}, + {"PollForActivityTask", []interface{}{ctx, &apiv1.PollForActivityTaskRequest{}}, []interface{}{nil, &api.InternalServiceError{}}, []string{CadenceRequest, CadenceError}}, + {"QueryWorkflow", []interface{}{ctx, &apiv1.QueryWorkflowRequest{}}, []interface{}{nil, &api.InternalServiceError{}}, []string{CadenceRequest, CadenceError}}, + {"RespondQueryTaskCompleted", []interface{}{ctx, &apiv1.RespondQueryTaskCompletedRequest{}}, []interface{}{&apiv1.RespondQueryTaskCompletedResponse{}, &api.InternalServiceError{}}, []string{CadenceRequest, CadenceError}}, } // run each test twice - once with the regular scope, once with a sanitized metrics scope for _, test := range tests { - runTest(t, test, newService, assertMetrics, fmt.Sprintf("%v_normal", test.serviceMethod)) - runTest(t, test, newPromService, assertPromMetrics, fmt.Sprintf("%v_prom_sanitized", test.serviceMethod)) + runWrapperTest(t, test, newService, assertMetrics, fmt.Sprintf("%v_normal", test.serviceMethod)) + runWrapperTest(t, test, newPromService, assertPromMetrics, fmt.Sprintf("%v_prom_sanitized", test.serviceMethod)) } } -func runTest( +func runWrapperTest( t *testing.T, test testCase, - serviceFunc func(*testing.T) (*workflowservicetest.MockClient, workflowserviceclient.Interface, io.Closer, *CapturingStatsReporter), + serviceFunc func(*testing.T) (*api.MockInterface, api.Interface, io.Closer, *CapturingStatsReporter), validationFunc func(*testing.T, *CapturingStatsReporter, string, []string), name string, ) { @@ -232,13 +231,13 @@ func makePromCompatible(name string) string { } func newService(t *testing.T) ( - mockService *workflowservicetest.MockClient, - wrapperService workflowserviceclient.Interface, + mockService *api.MockInterface, + wrapperService api.Interface, closer io.Closer, reporter *CapturingStatsReporter, ) { mockCtrl := gomock.NewController(t) - mockService = workflowservicetest.NewMockClient(mockCtrl) + mockService = api.NewMockInterface(mockCtrl) isReplay := false scope, closer, reporter := NewMetricsScope(&isReplay) wrapperService = NewWorkflowServiceWrapper(mockService, scope) @@ -246,13 +245,13 @@ func newService(t *testing.T) ( } func newPromService(t *testing.T) ( - mockService *workflowservicetest.MockClient, - wrapperService workflowserviceclient.Interface, + mockService *api.MockInterface, + wrapperService api.Interface, closer io.Closer, reporter *CapturingStatsReporter, ) { mockCtrl := gomock.NewController(t) - mockService = workflowservicetest.NewMockClient(mockCtrl) + mockService = api.NewMockInterface(mockCtrl) isReplay := false scope, closer, reporter := newPromScope(&isReplay) wrapperService = NewWorkflowServiceWrapper(mockService, scope) diff --git a/internal/common/serializer/history_serializer.go b/internal/common/serializer/history_serializer.go index 214df0718..d727e7d50 100644 --- a/internal/common/serializer/history_serializer.go +++ b/internal/common/serializer/history_serializer.go @@ -25,7 +25,11 @@ import ( "encoding/json" "errors" "fmt" - "go.uber.org/cadence/v1/.gen/go/shared" + "github.com/gogo/protobuf/proto" + "go.uber.org/cadence/v2/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/internal/api/thrift" "go.uber.org/thriftrw/protocol" "go.uber.org/thriftrw/wire" ) @@ -45,11 +49,11 @@ const ( var ( // MissingBinaryEncodingVersion indicate that the encoding version is missing - MissingBinaryEncodingVersion = &shared.BadRequestError{Message: "Missing binary encoding version."} + MissingBinaryEncodingVersion = &api.BadRequestError{Message: "Missing binary encoding version."} // InvalidBinaryEncodingVersion indicate that the encoding version is incorrect - InvalidBinaryEncodingVersion = &shared.BadRequestError{Message: "Invalid binary encoding version."} + InvalidBinaryEncodingVersion = &api.BadRequestError{Message: "Invalid binary encoding version."} // MsgPayloadNotThriftEncoded indicate message is not thrift encoded - MsgPayloadNotThriftEncoded = &shared.BadRequestError{Message: "Message payload is not thrift encoded."} + MsgPayloadNotThriftEncoded = &api.BadRequestError{Message: "Message payload is not thrift encoded."} ) // Decode decode the object @@ -95,25 +99,28 @@ func Encode(obj ThriftObject) ([]byte, error) { } // SerializeBatchEvents will serialize history event data to blob data -func SerializeBatchEvents(events []*shared.HistoryEvent, encodingType shared.EncodingType) (*shared.DataBlob, error) { +func SerializeBatchEvents(events []*apiv1.HistoryEvent, encodingType apiv1.EncodingType) (*apiv1.DataBlob, error) { return serialize(events, encodingType) } // DeserializeBatchEvents will deserialize blob data to history event data -func DeserializeBatchEvents(data *shared.DataBlob) ([]*shared.HistoryEvent, error) { +func DeserializeBatchEvents(data *apiv1.DataBlob) ([]*apiv1.HistoryEvent, error) { if data == nil { return nil, nil } - var events []*shared.HistoryEvent + var events []*apiv1.HistoryEvent if data != nil && len(data.Data) == 0 { return events, nil } - err := deserialize(data, &events) + events, err := deserialize(data) + if err != nil { + return nil, fmt.Errorf("DeserializeBatchEvents encoding: \"%v\", error: %v", data.EncodingType, err.Error()) + } return events, err } -func serialize(input interface{}, encodingType shared.EncodingType) (*shared.DataBlob, error) { - if input == nil { +func serialize(events []*apiv1.HistoryEvent, encodingType apiv1.EncodingType) (*apiv1.DataBlob, error) { + if events == nil { return nil, nil } @@ -121,11 +128,13 @@ func serialize(input interface{}, encodingType shared.EncodingType) (*shared.Dat var err error switch encodingType { - case shared.EncodingTypeThriftRW: - data, err = thriftrwEncode(input) - case shared.EncodingTypeJSON: // For backward-compatibility - encodingType = shared.EncodingTypeJSON - data, err = json.Marshal(input) + case apiv1.EncodingType_ENCODING_TYPE_THRIFTRW: + data, err = thriftrwEncode(events) + case apiv1.EncodingType_ENCODING_TYPE_JSON: // For backward-compatibility + encodingType = apiv1.EncodingType_ENCODING_TYPE_JSON + data, err = json.Marshal(events) + case apiv1.EncodingType_ENCODING_TYPE_PROTO3: + data, err = proto.Marshal(&apiv1.History{Events: events}) default: return nil, fmt.Errorf("unknown or unsupported encoding type %v", encodingType) } @@ -155,27 +164,48 @@ func thriftrwEncode(input interface{}) ([]byte, error) { } } -func deserialize(data *shared.DataBlob, target interface{}) error { - if data == nil { - return nil +func deserializeThrift(blob []byte) ([]*apiv1.HistoryEvent, error) { + var target []*shared.HistoryEvent + if err := thriftrwDecode(blob, target); err != nil { + return nil, err } - if len(data.Data) == 0 { - return errors.New("DeserializeEvent empty data") + return thrift.ToHistoryEvents(target), nil +} + +func deserializeThriftBasedJson(blob []byte) ([]*apiv1.HistoryEvent, error) { + var target []*shared.HistoryEvent + if err := json.Unmarshal(blob, target); err != nil { + return nil, err } - var err error + return thrift.ToHistoryEvents(target), nil +} - switch *(data.EncodingType) { - case shared.EncodingTypeThriftRW: - err = thriftrwDecode(data.Data, target) - case shared.EncodingTypeJSON: // For backward-compatibility - err = json.Unmarshal(data.Data, target) +func deserializeProto(blob []byte) ([]*apiv1.HistoryEvent, error) { + var target apiv1.History + if err := proto.Unmarshal(blob, &target); err != nil { + return nil, err + } + return target.Events, nil +} +func deserialize(data *apiv1.DataBlob) ([]*apiv1.HistoryEvent, error) { + if data == nil { + return nil, nil + } + if len(data.Data) == 0 { + return nil, errors.New("DeserializeEvent empty data") } - if err != nil { - return fmt.Errorf("DeserializeBatchEvents encoding: \"%v\", error: %v", data.EncodingType, err.Error()) + switch data.EncodingType { + case apiv1.EncodingType_ENCODING_TYPE_THRIFTRW: + return deserializeThrift(data.Data) + case apiv1.EncodingType_ENCODING_TYPE_JSON: // For backward-compatibility + return deserializeThriftBasedJson(data.Data) + case apiv1.EncodingType_ENCODING_TYPE_PROTO3: + return deserializeProto(data.Data) } - return nil + + return nil, nil } func thriftrwDecode(data []byte, target interface{}) error { @@ -203,23 +233,23 @@ func thriftrwDecode(data []byte, target interface{}) error { } // NewDataBlob creates new blob data -func NewDataBlob(data []byte, encodingType shared.EncodingType) *shared.DataBlob { +func NewDataBlob(data []byte, encodingType apiv1.EncodingType) *apiv1.DataBlob { if data == nil || len(data) == 0 { return nil } - return &shared.DataBlob{ + return &apiv1.DataBlob{ Data: data, - EncodingType: &encodingType, + EncodingType: encodingType, } } // DeserializeBlobDataToHistoryEvents deserialize the blob data to history event data func DeserializeBlobDataToHistoryEvents( - dataBlobs []*shared.DataBlob, filterType shared.HistoryEventFilterType, -) (*shared.History, error) { + dataBlobs []*apiv1.DataBlob, filterType apiv1.EventFilterType, +) (*apiv1.History, error) { - var historyEvents []*shared.HistoryEvent + var historyEvents []*apiv1.HistoryEvent for _, batch := range dataBlobs { events, err := DeserializeBatchEvents(batch) @@ -227,7 +257,7 @@ func DeserializeBlobDataToHistoryEvents( return nil, err } if len(events) == 0 { - return nil, &shared.InternalServiceError{ + return nil, &api.InternalServiceError{ Message: fmt.Sprintf("corrupted history event batch, empty events"), } } @@ -235,8 +265,8 @@ func DeserializeBlobDataToHistoryEvents( historyEvents = append(historyEvents, events...) } - if filterType == shared.HistoryEventFilterTypeCloseEvent { - historyEvents = []*shared.HistoryEvent{historyEvents[len(historyEvents)-1]} + if filterType == apiv1.EventFilterType_EVENT_FILTER_TYPE_CLOSE_EVENT { + historyEvents = []*apiv1.HistoryEvent{historyEvents[len(historyEvents)-1]} } - return &shared.History{Events: historyEvents}, nil + return &apiv1.History{Events: historyEvents}, nil } diff --git a/internal/common/util/stringer.go b/internal/common/util/stringer.go index ff6582e41..65e56ab6b 100644 --- a/internal/common/util/stringer.go +++ b/internal/common/util/stringer.go @@ -24,8 +24,9 @@ import ( "bytes" "fmt" "reflect" + "strings" - s "go.uber.org/cadence/v1/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" ) func anyToString(d interface{}) string { @@ -46,6 +47,10 @@ func anyToString(d interface{}) string { if len(fieldValue) == 0 { continue } + if strings.HasPrefix(t.Field(i).Name, "XXX_") { + // Skip generated gogo proto XXX_ fields + continue + } if buf.Len() > 1 { buf.WriteString(", ") } @@ -77,110 +82,25 @@ func valueToString(v reflect.Value) string { } // HistoryEventToString convert HistoryEvent to string -func HistoryEventToString(e *s.HistoryEvent) string { - var data interface{} - switch e.GetEventType() { - case s.EventTypeWorkflowExecutionStarted: - data = e.WorkflowExecutionStartedEventAttributes - - case s.EventTypeWorkflowExecutionCompleted: - data = e.WorkflowExecutionCompletedEventAttributes - - case s.EventTypeWorkflowExecutionFailed: - data = e.WorkflowExecutionFailedEventAttributes - - case s.EventTypeWorkflowExecutionTimedOut: - data = e.WorkflowExecutionTimedOutEventAttributes - - case s.EventTypeDecisionTaskScheduled: - data = e.DecisionTaskScheduledEventAttributes - - case s.EventTypeDecisionTaskStarted: - data = e.DecisionTaskStartedEventAttributes - - case s.EventTypeDecisionTaskCompleted: - data = e.DecisionTaskCompletedEventAttributes - - case s.EventTypeDecisionTaskTimedOut: - data = e.DecisionTaskTimedOutEventAttributes - - case s.EventTypeActivityTaskScheduled: - data = e.ActivityTaskScheduledEventAttributes - - case s.EventTypeActivityTaskStarted: - data = e.ActivityTaskStartedEventAttributes - - case s.EventTypeActivityTaskCompleted: - data = e.ActivityTaskCompletedEventAttributes - - case s.EventTypeActivityTaskFailed: - data = e.ActivityTaskFailedEventAttributes - - case s.EventTypeActivityTaskTimedOut: - data = e.ActivityTaskTimedOutEventAttributes - - case s.EventTypeActivityTaskCancelRequested: - data = e.ActivityTaskCancelRequestedEventAttributes - - case s.EventTypeRequestCancelActivityTaskFailed: - data = e.RequestCancelActivityTaskFailedEventAttributes - - case s.EventTypeActivityTaskCanceled: - data = e.ActivityTaskCanceledEventAttributes - - case s.EventTypeTimerStarted: - data = e.TimerStartedEventAttributes - - case s.EventTypeTimerFired: - data = e.TimerFiredEventAttributes - - case s.EventTypeCancelTimerFailed: - data = e.CancelTimerFailedEventAttributes - - case s.EventTypeTimerCanceled: - data = e.TimerCanceledEventAttributes - - case s.EventTypeMarkerRecorded: - data = e.MarkerRecordedEventAttributes - - case s.EventTypeWorkflowExecutionTerminated: - data = e.WorkflowExecutionTerminatedEventAttributes - - default: - data = e - } - - return e.GetEventType().String() + ": " + anyToString(data) +func HistoryEventToString(e *apiv1.HistoryEvent) string { + return GetHistoryEventType(e) + ": " + anyToString(e.Attributes) } // DecisionToString convert Decision to string -func DecisionToString(d *s.Decision) string { - var data interface{} - switch d.GetDecisionType() { - case s.DecisionTypeScheduleActivityTask: - data = d.ScheduleActivityTaskDecisionAttributes - - case s.DecisionTypeRequestCancelActivityTask: - data = d.RequestCancelActivityTaskDecisionAttributes - - case s.DecisionTypeStartTimer: - data = d.StartTimerDecisionAttributes - - case s.DecisionTypeCancelTimer: - data = d.CancelTimerDecisionAttributes - - case s.DecisionTypeCompleteWorkflowExecution: - data = d.CompleteWorkflowExecutionDecisionAttributes - - case s.DecisionTypeFailWorkflowExecution: - data = d.FailWorkflowExecutionDecisionAttributes - - case s.DecisionTypeRecordMarker: - data = d.RecordMarkerDecisionAttributes +func DecisionToString(d *apiv1.Decision) string { + return GetDecisionType(d) + ": " + anyToString(d.GetAttributes()) +} - default: - data = d - } +func GetHistoryEventType(d *apiv1.HistoryEvent) string { + eventType := reflect.TypeOf(d.Attributes).Elem().Name() + eventType = strings.TrimPrefix(eventType, "HistoryEvent_") + eventType = strings.TrimSuffix(eventType, "EventAttributes") + return eventType +} - return d.GetDecisionType().String() + ": " + anyToString(data) +func GetDecisionType(d *apiv1.Decision) string { + decisionType := reflect.TypeOf(d.Attributes).Elem().Name() + decisionType = strings.TrimPrefix(decisionType, "Decision_") + decisionType = strings.TrimSuffix(decisionType, "DecisionAttributes") + return decisionType } diff --git a/internal/common/util/stringer_test.go b/internal/common/util/stringer_test.go index 34000d485..aa265427a 100644 --- a/internal/common/util/stringer_test.go +++ b/internal/common/util/stringer_test.go @@ -25,6 +25,7 @@ import ( "testing" "github.com/stretchr/testify/require" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" ) func Test_byteSliceToString(t *testing.T) { @@ -40,3 +41,26 @@ func Test_byteSliceToString(t *testing.T) { require.Equal(t, "[len=3]", strVal2) } + +func Test_GetHistoryEventType(t *testing.T) { + event := apiv1.HistoryEvent{Attributes: &apiv1.HistoryEvent_WorkflowExecutionCompletedEventAttributes{}} + eventType := GetHistoryEventType(&event) + require.Equal(t, "WorkflowExecutionCompleted", eventType) +} + +func Test_GetDecisionType(t *testing.T) { + decision := apiv1.Decision{Attributes: &apiv1.Decision_StartChildWorkflowExecutionDecisionAttributes{}} + eventType := GetDecisionType(&decision) + require.Equal(t, "StartChildWorkflowExecution", eventType) +} + +func Test_HistoryEventToString(t *testing.T) { + event := apiv1.HistoryEvent{Attributes: &apiv1.HistoryEvent_WorkflowExecutionCompletedEventAttributes{ + WorkflowExecutionCompletedEventAttributes: &apiv1.WorkflowExecutionCompletedEventAttributes { + Result: &apiv1.Payload{Data: []byte{'a','b','c'}}, + DecisionTaskCompletedEventId: 123, + }, + }} + str := HistoryEventToString(&event) + require.Equal(t, "WorkflowExecutionCompleted: (WorkflowExecutionCompletedEventAttributes:(Result:(Data:[abc]), DecisionTaskCompletedEventId:123))", str) +} \ No newline at end of file diff --git a/internal/context.go b/internal/context.go index ddd1c1f84..9faefedec 100644 --- a/internal/context.go +++ b/internal/context.go @@ -25,7 +25,7 @@ import ( "time" "github.com/opentracing/opentracing-go" - "go.uber.org/cadence/v1/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" ) const activeSpanContextKey contextKey = "activeSpanContextKey" @@ -175,7 +175,7 @@ var ErrCanceled = NewCanceledError() // ErrDeadlineExceeded is the error returned by Context.Err when the context's // deadline passes. -var ErrDeadlineExceeded = NewTimeoutError(shared.TimeoutTypeScheduleToClose) +var ErrDeadlineExceeded = NewTimeoutError(apiv1.TimeoutType_TIMEOUT_TYPE_SCHEDULE_TO_CLOSE) // A CancelFunc tells an operation to abandon its work. // A CancelFunc does not wait for the work to stop. diff --git a/internal/encoded.go b/internal/encoded.go index e1bcbc5a7..36360641e 100644 --- a/internal/encoded.go +++ b/internal/encoded.go @@ -23,8 +23,8 @@ package internal import ( "reflect" - "go.uber.org/cadence/v1/internal/common" - "go.uber.org/cadence/v1/internal/common/util" + "go.uber.org/cadence/v2/internal/common" + "go.uber.org/cadence/v2/internal/common/util" ) type ( diff --git a/internal/encoding.go b/internal/encoding.go index 763f891ae..7ee7f9490 100644 --- a/internal/encoding.go +++ b/internal/encoding.go @@ -28,7 +28,7 @@ import ( "reflect" "github.com/apache/thrift/lib/go/thrift" - "go.uber.org/cadence/v1/internal/common" + "go.uber.org/cadence/v2/internal/common" ) // encoding is capable of encoding and decoding objects diff --git a/internal/error.go b/internal/error.go index 118f438a4..5983f6284 100644 --- a/internal/error.go +++ b/internal/error.go @@ -27,7 +27,7 @@ import ( "reflect" "strings" - "go.uber.org/cadence/v1/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" ) /* @@ -99,7 +99,7 @@ type ( // TimeoutError returned when activity or child workflow timed out. TimeoutError struct { - timeoutType shared.TimeoutType + timeoutType apiv1.TimeoutType details Values } @@ -176,7 +176,7 @@ func NewCustomError(reason string, details ...interface{}) *CustomError { // NewTimeoutError creates TimeoutError instance. // Use NewHeartbeatTimeoutError to create heartbeat TimeoutError -func NewTimeoutError(timeoutType shared.TimeoutType, details ...interface{}) *TimeoutError { +func NewTimeoutError(timeoutType apiv1.TimeoutType, details ...interface{}) *TimeoutError { if len(details) == 1 { if d, ok := details[0].(*EncodedValues); ok { return &TimeoutError{timeoutType: timeoutType, details: d} @@ -187,7 +187,7 @@ func NewTimeoutError(timeoutType shared.TimeoutType, details ...interface{}) *Ti // NewHeartbeatTimeoutError creates TimeoutError instance func NewHeartbeatTimeoutError(details ...interface{}) *TimeoutError { - return NewTimeoutError(shared.TimeoutTypeHeartbeat, details...) + return NewTimeoutError(apiv1.TimeoutType_TIMEOUT_TYPE_HEARTBEAT, details...) } // NewCanceledError creates CanceledError instance @@ -282,7 +282,7 @@ func (e *TimeoutError) Error() string { } // TimeoutType return timeout type of this error -func (e *TimeoutError) TimeoutType() shared.TimeoutType { +func (e *TimeoutError) TimeoutType() apiv1.TimeoutType { return e.timeoutType } diff --git a/internal/error_test.go b/internal/error_test.go index 52f3fcaeb..fd59548e8 100644 --- a/internal/error_test.go +++ b/internal/error_test.go @@ -26,8 +26,7 @@ import ( "testing" "github.com/stretchr/testify/require" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" "go.uber.org/zap" ) @@ -99,7 +98,7 @@ func Test_ActivityNotRegistered(t *testing.T) { } func Test_TimeoutError(t *testing.T) { - timeoutErr := NewTimeoutError(shared.TimeoutTypeScheduleToStart) + timeoutErr := NewTimeoutError(apiv1.TimeoutType_TIMEOUT_TYPE_SCHEDULE_TO_START) require.False(t, timeoutErr.HasDetails()) var data string require.Equal(t, ErrNoData, timeoutErr.Details(&data)) @@ -111,12 +110,12 @@ func Test_TimeoutError(t *testing.T) { } func Test_TimeoutError_WithDetails(t *testing.T) { - testTimeoutErrorDetails(t, shared.TimeoutTypeHeartbeat) - testTimeoutErrorDetails(t, shared.TimeoutTypeScheduleToClose) - testTimeoutErrorDetails(t, shared.TimeoutTypeStartToClose) + testTimeoutErrorDetails(t, apiv1.TimeoutType_TIMEOUT_TYPE_HEARTBEAT) + testTimeoutErrorDetails(t, apiv1.TimeoutType_TIMEOUT_TYPE_SCHEDULE_TO_CLOSE) + testTimeoutErrorDetails(t, apiv1.TimeoutType_TIMEOUT_TYPE_START_TO_CLOSE) } -func testTimeoutErrorDetails(t *testing.T, timeoutType shared.TimeoutType) { +func testTimeoutErrorDetails(t *testing.T, timeoutType apiv1.TimeoutType) { context := &workflowEnvironmentImpl{ decisionsHelper: newDecisionsHelper(), dataConverter: getDefaultDataConverter(), @@ -126,7 +125,7 @@ func testTimeoutErrorDetails(t *testing.T, timeoutType shared.TimeoutType) { activityID := "activityID" context.decisionsHelper.scheduledEventIDToActivityID[5] = activityID di := h.newActivityDecisionStateMachine( - &shared.ScheduleActivityTaskDecisionAttributes{ActivityId: common.StringPtr(activityID)}) + &apiv1.ScheduleActivityTaskDecisionAttributes{ActivityId: activityID}) di.state = decisionStateInitiated di.setData(&scheduledActivity{ callback: func(r []byte, e error) { @@ -135,11 +134,11 @@ func testTimeoutErrorDetails(t *testing.T, timeoutType shared.TimeoutType) { }) context.decisionsHelper.addDecision(di) encodedDetails1, _ := context.dataConverter.ToData(testErrorDetails1) - event := createTestEventActivityTaskTimedOut(7, &shared.ActivityTaskTimedOutEventAttributes{ - Details: encodedDetails1, - ScheduledEventId: common.Int64Ptr(5), - StartedEventId: common.Int64Ptr(6), - TimeoutType: &timeoutType, + event := createTestEventActivityTaskTimedOut(7, &apiv1.ActivityTaskTimedOutEventAttributes{ + Details: &apiv1.Payload{Data: encodedDetails1}, + ScheduledEventId: 5, + StartedEventId: 6, + TimeoutType: timeoutType, }) weh := &workflowExecutionEventHandlerImpl{context, nil} weh.handleActivityTaskTimedOut(event) @@ -438,7 +437,7 @@ func Test_SignalExternalWorkflowExecutionFailedError(t *testing.T) { signalID := "signalID" context.decisionsHelper.scheduledEventIDToSignalID[initiatedEventID] = signalID di := h.newSignalExternalWorkflowStateMachine( - &shared.SignalExternalWorkflowExecutionDecisionAttributes{}, + &apiv1.SignalExternalWorkflowExecutionDecisionAttributes{}, signalID, ) di.state = decisionStateInitiated @@ -449,9 +448,9 @@ func Test_SignalExternalWorkflowExecutionFailedError(t *testing.T) { }) context.decisionsHelper.addDecision(di) weh := &workflowExecutionEventHandlerImpl{context, nil} - event := createTestEventSignalExternalWorkflowExecutionFailed(1, &shared.SignalExternalWorkflowExecutionFailedEventAttributes{ - InitiatedEventId: common.Int64Ptr(initiatedEventID), - Cause: shared.SignalExternalWorkflowExecutionFailedCauseUnknownExternalWorkflowExecution.Ptr(), + event := createTestEventSignalExternalWorkflowExecutionFailed(1, &apiv1.SignalExternalWorkflowExecutionFailedEventAttributes{ + InitiatedEventId: initiatedEventID, + Cause: apiv1.SignalExternalWorkflowExecutionFailedCause_SIGNAL_EXTERNAL_WORKFLOW_EXECUTION_FAILED_CAUSE_UNKNOWN_EXTERNAL_WORKFLOW_EXECUTION, }) require.NoError(t, weh.handleSignalExternalWorkflowExecutionFailed(event)) _, ok := actualErr.(*UnknownExternalWorkflowExecutionError) @@ -467,8 +466,8 @@ func Test_ContinueAsNewError(t *testing.T) { return NewContinueAsNewError(ctx, continueAsNewWfName, a1, a2) } - header := &shared.Header{ - Fields: map[string][]byte{"test": []byte("test-data")}, + header := &apiv1.Header{ + Fields: map[string]*apiv1.Payload{"test": {Data: []byte("test-data")}}, } s := &WorkflowTestSuite{ diff --git a/internal/headers.go b/internal/headers.go index 8bb22abde..8904c4f42 100644 --- a/internal/headers.go +++ b/internal/headers.go @@ -23,7 +23,7 @@ package internal import ( "context" - "go.uber.org/cadence/v1/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" ) // HeaderWriter is an interface to write information to cadence headers @@ -55,7 +55,7 @@ type ContextPropagator interface { } type headerReader struct { - header *shared.Header + header *apiv1.Header } func (hr *headerReader) ForEachKey(handler func(string, []byte) error) error { @@ -63,7 +63,7 @@ func (hr *headerReader) ForEachKey(handler func(string, []byte) error) error { return nil } for key, value := range hr.header.Fields { - if err := handler(key, value); err != nil { + if err := handler(key, value.GetData()); err != nil { return err } } @@ -71,25 +71,25 @@ func (hr *headerReader) ForEachKey(handler func(string, []byte) error) error { } // NewHeaderReader returns a header reader interface -func NewHeaderReader(header *shared.Header) HeaderReader { +func NewHeaderReader(header *apiv1.Header) HeaderReader { return &headerReader{header} } type headerWriter struct { - header *shared.Header + header *apiv1.Header } func (hw *headerWriter) Set(key string, value []byte) { if hw.header == nil { return } - hw.header.Fields[key] = value + hw.header.Fields[key] = &apiv1.Payload{Data: value} } // NewHeaderWriter returns a header writer interface -func NewHeaderWriter(header *shared.Header) HeaderWriter { +func NewHeaderWriter(header *apiv1.Header) HeaderWriter { if header != nil && header.Fields == nil { - header.Fields = make(map[string][]byte) + header.Fields = make(map[string]*apiv1.Payload) } return &headerWriter{header} } diff --git a/internal/headers_test.go b/internal/headers_test.go index 9ea4fffaf..3fa0a31c5 100644 --- a/internal/headers_test.go +++ b/internal/headers_test.go @@ -24,36 +24,36 @@ import ( "testing" "github.com/stretchr/testify/assert" - "go.uber.org/cadence/v1/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" ) func TestHeaderWriter(t *testing.T) { t.Parallel() tests := []struct { name string - initial *shared.Header - expected *shared.Header + initial *apiv1.Header + expected *apiv1.Header vals map[string][]byte }{ { "no values", - &shared.Header{ - Fields: map[string][]byte{}, + &apiv1.Header{ + Fields: map[string]*apiv1.Payload{}, }, - &shared.Header{ - Fields: map[string][]byte{}, + &apiv1.Header{ + Fields: map[string]*apiv1.Payload{}, }, map[string][]byte{}, }, { "add values", - &shared.Header{ - Fields: map[string][]byte{}, + &apiv1.Header{ + Fields: map[string]*apiv1.Payload{}, }, - &shared.Header{ - Fields: map[string][]byte{ - "key1": []byte("val1"), - "key2": []byte("val2"), + &apiv1.Header{ + Fields: map[string]*apiv1.Payload{ + "key1": {Data: []byte("val1")}, + "key2": {Data: []byte("val2")}, }, }, map[string][]byte{ @@ -63,15 +63,15 @@ func TestHeaderWriter(t *testing.T) { }, { "overwrite values", - &shared.Header{ - Fields: map[string][]byte{ - "key1": []byte("unexpected"), + &apiv1.Header{ + Fields: map[string]*apiv1.Payload{ + "key1": {Data: []byte("unexpected")}, }, }, - &shared.Header{ - Fields: map[string][]byte{ - "key1": []byte("val1"), - "key2": []byte("val2"), + &apiv1.Header{ + Fields: map[string]*apiv1.Payload{ + "key1": {Data: []byte("val1")}, + "key2": {Data: []byte("val2")}, }, }, map[string][]byte{ @@ -98,16 +98,16 @@ func TestHeaderReader(t *testing.T) { t.Parallel() tests := []struct { name string - header *shared.Header + header *apiv1.Header keys map[string]struct{} isError bool }{ { "valid values", - &shared.Header{ - Fields: map[string][]byte{ - "key1": []byte("val1"), - "key2": []byte("val2"), + &apiv1.Header{ + Fields: map[string]*apiv1.Payload{ + "key1": {Data: []byte("val1")}, + "key2": {Data: []byte("val2")}, }, }, map[string]struct{}{"key1": struct{}{}, "key2": struct{}{}}, @@ -115,10 +115,10 @@ func TestHeaderReader(t *testing.T) { }, { "invalid values", - &shared.Header{ - Fields: map[string][]byte{ - "key1": []byte("val1"), - "key2": []byte("val2"), + &apiv1.Header{ + Fields: map[string]*apiv1.Payload{ + "key1": {Data: []byte("val1")}, + "key2": {Data: []byte("val2")}, }, }, map[string]struct{}{"key2": struct{}{}}, diff --git a/internal/internal_activity.go b/internal/internal_activity.go index 9c9e39637..447961ed2 100644 --- a/internal/internal_activity.go +++ b/internal/internal_activity.go @@ -32,8 +32,8 @@ import ( "github.com/opentracing/opentracing-go" "github.com/uber-go/tally" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" "go.uber.org/zap" ) @@ -64,7 +64,7 @@ type ( HeartbeatTimeoutSeconds int32 WaitForCancellation bool OriginalTaskListName string - RetryPolicy *shared.RetryPolicy + RetryPolicy *apiv1.RetryPolicy } localActivityOptions struct { @@ -77,7 +77,7 @@ type ( ActivityType ActivityType Input []byte DataConverter DataConverter - Header *shared.Header + Header *apiv1.Header } executeLocalActivityParams struct { @@ -89,7 +89,7 @@ type ( DataConverter DataConverter Attempt int32 ScheduledTime time.Time - Header *shared.Header + Header *apiv1.Header } // asyncActivityClient for requesting activity execution @@ -215,31 +215,31 @@ func getValidatedLocalActivityOptions(ctx Context) (*localActivityOptions, error return p, nil } -func validateRetryPolicy(p *shared.RetryPolicy) error { +func validateRetryPolicy(p *apiv1.RetryPolicy) error { if p == nil { return nil } - if p.GetInitialIntervalInSeconds() <= 0 { - return errors.New("missing or negative InitialIntervalInSeconds on retry policy") + if api.DurationFromProto(p.InitialInterval) <= 0 { + return errors.New("missing or negative InitialInterval on retry policy") } - if p.GetMaximumIntervalInSeconds() < 0 { - return errors.New("negative MaximumIntervalInSeconds on retry policy is invalid") + if api.DurationFromProto(p.MaximumInterval) < 0 { + return errors.New("negative MaximumInterval on retry policy is invalid") } - if p.GetMaximumIntervalInSeconds() == 0 { + if api.DurationFromProto(p.MaximumInterval) == 0 { // if not set, default to 100x of initial interval - p.MaximumIntervalInSeconds = common.Int32Ptr(100 * p.GetInitialIntervalInSeconds()) + p.MaximumInterval = api.DurationToProto(100 * api.DurationFromProto(p.InitialInterval)) } if p.GetMaximumAttempts() < 0 { return errors.New("negative MaximumAttempts on retry policy is invalid") } - if p.GetExpirationIntervalInSeconds() < 0 { + if api.DurationFromProto(p.ExpirationInterval) < 0 { return errors.New("ExpirationIntervalInSeconds cannot be less than 0 on retry policy") } if p.GetBackoffCoefficient() < 1 { return errors.New("BackoffCoefficient on retry policy cannot be less than 1.0") } - if p.GetMaximumAttempts() == 0 && p.GetExpirationIntervalInSeconds() == 0 { + if p.GetMaximumAttempts() == 0 && api.DurationFromProto(p.ExpirationInterval) == 0 { return errors.New("both MaximumAttempts and ExpirationIntervalInSeconds on retry policy are not set, at least one of them must be set") } @@ -440,7 +440,7 @@ func setActivityParametersIfNotExist(ctx Context) Context { if params != nil { newParams = *params if params.RetryPolicy != nil { - var newRetryPolicy shared.RetryPolicy + var newRetryPolicy apiv1.RetryPolicy newRetryPolicy = *newParams.RetryPolicy newParams.RetryPolicy = &newRetryPolicy } diff --git a/internal/internal_coroutines_test.go b/internal/internal_coroutines_test.go index 7fb0af135..fbec72106 100644 --- a/internal/internal_coroutines_test.go +++ b/internal/internal_coroutines_test.go @@ -688,7 +688,7 @@ func TestPanic(t *testing.T) { require.EqualValues(t, "simulated failure", err.Error()) panicError, ok := err.(*workflowPanicError) require.True(t, ok) - require.Contains(t, panicError.StackTrace(), "cadence/v1/internal.TestPanic") + require.Contains(t, panicError.StackTrace(), "cadence/v2/internal.TestPanic") } func TestAwait(t *testing.T) { diff --git a/internal/internal_decision_state_machine.go b/internal/internal_decision_state_machine.go index 2ac9d5754..bebfc1940 100644 --- a/internal/internal_decision_state_machine.go +++ b/internal/internal_decision_state_machine.go @@ -23,9 +23,9 @@ package internal import ( "container/list" "fmt" - s "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" - "go.uber.org/cadence/v1/internal/common/util" + + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/common/util" ) type ( @@ -41,7 +41,7 @@ type ( getState() decisionState getID() decisionID isDone() bool - getDecision() *s.Decision // return nil if there is no decision in current state + getDecision() *apiv1.Decision // return nil if there is no decision in current state cancel() handleStartedEvent() @@ -68,23 +68,23 @@ type ( activityDecisionStateMachine struct { *decisionStateMachineBase - attributes *s.ScheduleActivityTaskDecisionAttributes + attributes *apiv1.ScheduleActivityTaskDecisionAttributes } timerDecisionStateMachine struct { *decisionStateMachineBase - attributes *s.StartTimerDecisionAttributes + attributes *apiv1.StartTimerDecisionAttributes canceled bool } childWorkflowDecisionStateMachine struct { *decisionStateMachineBase - attributes *s.StartChildWorkflowExecutionDecisionAttributes + attributes *apiv1.StartChildWorkflowExecutionDecisionAttributes } naiveDecisionStateMachine struct { *decisionStateMachineBase - decision *s.Decision + decision *apiv1.Decision } // only possible state transition is: CREATED->SENT->INITIATED->COMPLETED @@ -225,7 +225,7 @@ func (h *decisionsHelper) newDecisionStateMachineBase(decisionType decisionType, } } -func (h *decisionsHelper) newActivityDecisionStateMachine(attributes *s.ScheduleActivityTaskDecisionAttributes) *activityDecisionStateMachine { +func (h *decisionsHelper) newActivityDecisionStateMachine(attributes *apiv1.ScheduleActivityTaskDecisionAttributes) *activityDecisionStateMachine { base := h.newDecisionStateMachineBase(decisionTypeActivity, attributes.GetActivityId()) return &activityDecisionStateMachine{ decisionStateMachineBase: base, @@ -233,7 +233,7 @@ func (h *decisionsHelper) newActivityDecisionStateMachine(attributes *s.Schedule } } -func (h *decisionsHelper) newTimerDecisionStateMachine(attributes *s.StartTimerDecisionAttributes) *timerDecisionStateMachine { +func (h *decisionsHelper) newTimerDecisionStateMachine(attributes *apiv1.StartTimerDecisionAttributes) *timerDecisionStateMachine { base := h.newDecisionStateMachineBase(decisionTypeTimer, attributes.GetTimerId()) return &timerDecisionStateMachine{ decisionStateMachineBase: base, @@ -241,7 +241,7 @@ func (h *decisionsHelper) newTimerDecisionStateMachine(attributes *s.StartTimerD } } -func (h *decisionsHelper) newChildWorkflowDecisionStateMachine(attributes *s.StartChildWorkflowExecutionDecisionAttributes) *childWorkflowDecisionStateMachine { +func (h *decisionsHelper) newChildWorkflowDecisionStateMachine(attributes *apiv1.StartChildWorkflowExecutionDecisionAttributes) *childWorkflowDecisionStateMachine { base := h.newDecisionStateMachineBase(decisionTypeChildWorkflow, attributes.GetWorkflowId()) return &childWorkflowDecisionStateMachine{ decisionStateMachineBase: base, @@ -249,7 +249,7 @@ func (h *decisionsHelper) newChildWorkflowDecisionStateMachine(attributes *s.Sta } } -func (h *decisionsHelper) newNaiveDecisionStateMachine(decisionType decisionType, id string, decision *s.Decision) *naiveDecisionStateMachine { +func (h *decisionsHelper) newNaiveDecisionStateMachine(decisionType decisionType, id string, decision *apiv1.Decision) *naiveDecisionStateMachine { base := h.newDecisionStateMachineBase(decisionType, id) return &naiveDecisionStateMachine{ decisionStateMachineBase: base, @@ -257,33 +257,45 @@ func (h *decisionsHelper) newNaiveDecisionStateMachine(decisionType decisionType } } -func (h *decisionsHelper) newMarkerDecisionStateMachine(id string, attributes *s.RecordMarkerDecisionAttributes) *markerDecisionStateMachine { - d := createNewDecision(s.DecisionTypeRecordMarker) - d.RecordMarkerDecisionAttributes = attributes +func (h *decisionsHelper) newMarkerDecisionStateMachine(id string, attributes *apiv1.RecordMarkerDecisionAttributes) *markerDecisionStateMachine { + d := &apiv1.Decision{ + Attributes: &apiv1.Decision_RecordMarkerDecisionAttributes{ + RecordMarkerDecisionAttributes: attributes, + }, + } return &markerDecisionStateMachine{ naiveDecisionStateMachine: h.newNaiveDecisionStateMachine(decisionTypeMarker, id, d), } } -func (h *decisionsHelper) newCancelExternalWorkflowStateMachine(attributes *s.RequestCancelExternalWorkflowExecutionDecisionAttributes, cancellationID string) *cancelExternalWorkflowDecisionStateMachine { - d := createNewDecision(s.DecisionTypeRequestCancelExternalWorkflowExecution) - d.RequestCancelExternalWorkflowExecutionDecisionAttributes = attributes +func (h *decisionsHelper) newCancelExternalWorkflowStateMachine(attributes *apiv1.RequestCancelExternalWorkflowExecutionDecisionAttributes, cancellationID string) *cancelExternalWorkflowDecisionStateMachine { + d := &apiv1.Decision{ + Attributes: &apiv1.Decision_RequestCancelExternalWorkflowExecutionDecisionAttributes{ + RequestCancelExternalWorkflowExecutionDecisionAttributes: attributes, + }, + } return &cancelExternalWorkflowDecisionStateMachine{ naiveDecisionStateMachine: h.newNaiveDecisionStateMachine(decisionTypeCancellation, cancellationID, d), } } -func (h *decisionsHelper) newSignalExternalWorkflowStateMachine(attributes *s.SignalExternalWorkflowExecutionDecisionAttributes, signalID string) *signalExternalWorkflowDecisionStateMachine { - d := createNewDecision(s.DecisionTypeSignalExternalWorkflowExecution) - d.SignalExternalWorkflowExecutionDecisionAttributes = attributes +func (h *decisionsHelper) newSignalExternalWorkflowStateMachine(attributes *apiv1.SignalExternalWorkflowExecutionDecisionAttributes, signalID string) *signalExternalWorkflowDecisionStateMachine { + d := &apiv1.Decision{ + Attributes: &apiv1.Decision_SignalExternalWorkflowExecutionDecisionAttributes{ + SignalExternalWorkflowExecutionDecisionAttributes: attributes, + }, + } return &signalExternalWorkflowDecisionStateMachine{ naiveDecisionStateMachine: h.newNaiveDecisionStateMachine(decisionTypeSignal, signalID, d), } } -func (h *decisionsHelper) newUpsertSearchAttributesStateMachine(attributes *s.UpsertWorkflowSearchAttributesDecisionAttributes, upsertID string) *upsertSearchAttributesDecisionStateMachine { - d := createNewDecision(s.DecisionTypeUpsertWorkflowSearchAttributes) - d.UpsertWorkflowSearchAttributesDecisionAttributes = attributes +func (h *decisionsHelper) newUpsertSearchAttributesStateMachine(attributes *apiv1.UpsertWorkflowSearchAttributesDecisionAttributes, upsertID string) *upsertSearchAttributesDecisionStateMachine { + d := &apiv1.Decision{ + Attributes: &apiv1.Decision_UpsertWorkflowSearchAttributesDecisionAttributes{ + UpsertWorkflowSearchAttributesDecisionAttributes: attributes, + }, + } return &upsertSearchAttributesDecisionStateMachine{ naiveDecisionStateMachine: h.newNaiveDecisionStateMachine(decisionTypeUpsertSearchAttributes, upsertID, d), } @@ -425,18 +437,22 @@ func (d *decisionStateMachineBase) String() string { d.id, d.state, d.isDone(), d.history) } -func (d *activityDecisionStateMachine) getDecision() *s.Decision { +func (d *activityDecisionStateMachine) getDecision() *apiv1.Decision { switch d.state { case decisionStateCreated: - decision := createNewDecision(s.DecisionTypeScheduleActivityTask) - decision.ScheduleActivityTaskDecisionAttributes = d.attributes - return decision + return &apiv1.Decision{ + Attributes: &apiv1.Decision_ScheduleActivityTaskDecisionAttributes{ + ScheduleActivityTaskDecisionAttributes: d.attributes, + }, + } case decisionStateCanceledAfterInitiated: - decision := createNewDecision(s.DecisionTypeRequestCancelActivityTask) - decision.RequestCancelActivityTaskDecisionAttributes = &s.RequestCancelActivityTaskDecisionAttributes{ - ActivityId: d.attributes.ActivityId, + return &apiv1.Decision{ + Attributes: &apiv1.Decision_RequestCancelActivityTaskDecisionAttributes{ + RequestCancelActivityTaskDecisionAttributes: &apiv1.RequestCancelActivityTaskDecisionAttributes{ + ActivityId: d.attributes.ActivityId, + }, + }, } - return decision default: return nil } @@ -487,37 +503,47 @@ func (d *timerDecisionStateMachine) handleCancelFailedEvent() { } } -func (d *timerDecisionStateMachine) getDecision() *s.Decision { +func (d *timerDecisionStateMachine) getDecision() *apiv1.Decision { switch d.state { case decisionStateCreated: - decision := createNewDecision(s.DecisionTypeStartTimer) - decision.StartTimerDecisionAttributes = d.attributes - return decision + return &apiv1.Decision{ + Attributes: &apiv1.Decision_StartTimerDecisionAttributes{ + StartTimerDecisionAttributes: d.attributes, + }, + } case decisionStateCanceledAfterInitiated: - decision := createNewDecision(s.DecisionTypeCancelTimer) - decision.CancelTimerDecisionAttributes = &s.CancelTimerDecisionAttributes{ - TimerId: d.attributes.TimerId, + return &apiv1.Decision{ + Attributes: &apiv1.Decision_CancelTimerDecisionAttributes{ + CancelTimerDecisionAttributes: &apiv1.CancelTimerDecisionAttributes{ + TimerId: d.attributes.TimerId, + }, + }, } - return decision default: return nil } } -func (d *childWorkflowDecisionStateMachine) getDecision() *s.Decision { +func (d *childWorkflowDecisionStateMachine) getDecision() *apiv1.Decision { switch d.state { case decisionStateCreated: - decision := createNewDecision(s.DecisionTypeStartChildWorkflowExecution) - decision.StartChildWorkflowExecutionDecisionAttributes = d.attributes - return decision + return &apiv1.Decision{ + Attributes: &apiv1.Decision_StartChildWorkflowExecutionDecisionAttributes{ + StartChildWorkflowExecutionDecisionAttributes: d.attributes, + }, + } case decisionStateCanceledAfterStarted: - decision := createNewDecision(s.DecisionTypeRequestCancelExternalWorkflowExecution) - decision.RequestCancelExternalWorkflowExecutionDecisionAttributes = &s.RequestCancelExternalWorkflowExecutionDecisionAttributes{ - Domain: d.attributes.Domain, - WorkflowId: d.attributes.WorkflowId, - ChildWorkflowOnly: common.BoolPtr(true), + return &apiv1.Decision{ + Attributes: &apiv1.Decision_RequestCancelExternalWorkflowExecutionDecisionAttributes{ + RequestCancelExternalWorkflowExecutionDecisionAttributes: &apiv1.RequestCancelExternalWorkflowExecutionDecisionAttributes{ + Domain: d.attributes.Domain, + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: d.attributes.WorkflowId, + }, + ChildWorkflowOnly: true, + }, + }, } - return decision default: return nil } @@ -579,7 +605,7 @@ func (d *childWorkflowDecisionStateMachine) handleCompletionEvent() { } } -func (d *naiveDecisionStateMachine) getDecision() *s.Decision { +func (d *naiveDecisionStateMachine) getDecision() *apiv1.Decision { switch d.state { case decisionStateCreated: return d.decision @@ -709,7 +735,7 @@ func (h *decisionsHelper) addDecision(decision decisionStateMachine) { h.decisions[decision.getID()] = element } -func (h *decisionsHelper) scheduleActivityTask(attributes *s.ScheduleActivityTaskDecisionAttributes) decisionStateMachine { +func (h *decisionsHelper) scheduleActivityTask(attributes *apiv1.ScheduleActivityTaskDecisionAttributes) decisionStateMachine { decision := h.newActivityDecisionStateMachine(attributes) h.addDecision(decision) return decision @@ -750,19 +776,19 @@ func (h *decisionsHelper) handleRequestCancelActivityTaskFailed(activityID strin decision.handleCancelFailedEvent() } -func (h *decisionsHelper) getActivityID(event *s.HistoryEvent) string { +func (h *decisionsHelper) getActivityID(event *apiv1.HistoryEvent) string { var scheduledEventID int64 = -1 - switch event.GetEventType() { - case s.EventTypeActivityTaskCanceled: - scheduledEventID = event.ActivityTaskCanceledEventAttributes.GetScheduledEventId() - case s.EventTypeActivityTaskCompleted: - scheduledEventID = event.ActivityTaskCompletedEventAttributes.GetScheduledEventId() - case s.EventTypeActivityTaskFailed: - scheduledEventID = event.ActivityTaskFailedEventAttributes.GetScheduledEventId() - case s.EventTypeActivityTaskTimedOut: - scheduledEventID = event.ActivityTaskTimedOutEventAttributes.GetScheduledEventId() + switch attr := event.Attributes.(type) { + case *apiv1.HistoryEvent_ActivityTaskCanceledEventAttributes: + scheduledEventID = attr.ActivityTaskCanceledEventAttributes.GetScheduledEventId() + case *apiv1.HistoryEvent_ActivityTaskCompletedEventAttributes: + scheduledEventID = attr.ActivityTaskCompletedEventAttributes.GetScheduledEventId() + case *apiv1.HistoryEvent_ActivityTaskFailedEventAttributes: + scheduledEventID = attr.ActivityTaskFailedEventAttributes.GetScheduledEventId() + case *apiv1.HistoryEvent_ActivityTaskTimedOutEventAttributes: + scheduledEventID = attr.ActivityTaskTimedOutEventAttributes.GetScheduledEventId() default: - panicIllegalState(fmt.Sprintf("unexpected event type %v", event.GetEventType())) + panicIllegalState(fmt.Sprintf("unexpected event type %v", util.GetHistoryEventType(event))) } activityID, ok := h.scheduledEventIDToActivityID[scheduledEventID] @@ -779,9 +805,9 @@ func (h *decisionsHelper) recordVersionMarker(changeID string, version Version, panic(err) } - recordMarker := &s.RecordMarkerDecisionAttributes{ - MarkerName: common.StringPtr(versionMarkerName), - Details: details, // Keep + recordMarker := &apiv1.RecordMarkerDecisionAttributes{ + MarkerName: versionMarkerName, + Details: &apiv1.Payload{Data: details}, // Keep } decision := h.newMarkerDecisionStateMachine(markerID, recordMarker) @@ -791,9 +817,9 @@ func (h *decisionsHelper) recordVersionMarker(changeID string, version Version, func (h *decisionsHelper) recordSideEffectMarker(sideEffectID int32, data []byte) decisionStateMachine { markerID := fmt.Sprintf("%v_%v", sideEffectMarkerName, sideEffectID) - attributes := &s.RecordMarkerDecisionAttributes{ - MarkerName: common.StringPtr(sideEffectMarkerName), - Details: data, + attributes := &apiv1.RecordMarkerDecisionAttributes{ + MarkerName: sideEffectMarkerName, + Details: &apiv1.Payload{Data: data}, } decision := h.newMarkerDecisionStateMachine(markerID, attributes) h.addDecision(decision) @@ -802,9 +828,9 @@ func (h *decisionsHelper) recordSideEffectMarker(sideEffectID int32, data []byte func (h *decisionsHelper) recordLocalActivityMarker(activityID string, result []byte) decisionStateMachine { markerID := fmt.Sprintf("%v_%v", localActivityMarkerName, activityID) - attributes := &s.RecordMarkerDecisionAttributes{ - MarkerName: common.StringPtr(localActivityMarkerName), - Details: result, + attributes := &apiv1.RecordMarkerDecisionAttributes{ + MarkerName: localActivityMarkerName, + Details: &apiv1.Payload{Data: result}, } decision := h.newMarkerDecisionStateMachine(markerID, attributes) h.addDecision(decision) @@ -813,16 +839,16 @@ func (h *decisionsHelper) recordLocalActivityMarker(activityID string, result [] func (h *decisionsHelper) recordMutableSideEffectMarker(mutableSideEffectID string, data []byte) decisionStateMachine { markerID := fmt.Sprintf("%v_%v", mutableSideEffectMarkerName, mutableSideEffectID) - attributes := &s.RecordMarkerDecisionAttributes{ - MarkerName: common.StringPtr(mutableSideEffectMarkerName), - Details: data, + attributes := &apiv1.RecordMarkerDecisionAttributes{ + MarkerName: mutableSideEffectMarkerName, + Details: &apiv1.Payload{Data: data}, } decision := h.newMarkerDecisionStateMachine(markerID, attributes) h.addDecision(decision) return decision } -func (h *decisionsHelper) startChildWorkflowExecution(attributes *s.StartChildWorkflowExecutionDecisionAttributes) decisionStateMachine { +func (h *decisionsHelper) startChildWorkflowExecution(attributes *apiv1.StartChildWorkflowExecutionDecisionAttributes) decisionStateMachine { decision := h.newChildWorkflowDecisionStateMachine(attributes) h.addDecision(decision) return decision @@ -871,12 +897,14 @@ func (h *decisionsHelper) requestCancelExternalWorkflowExecution(domain, workflo if len(cancellationID) == 0 { panic("cancellation on external workflow should use cancellation ID") } - attributes := &s.RequestCancelExternalWorkflowExecutionDecisionAttributes{ - Domain: common.StringPtr(domain), - WorkflowId: common.StringPtr(workflowID), - RunId: common.StringPtr(runID), + attributes := &apiv1.RequestCancelExternalWorkflowExecutionDecisionAttributes{ + Domain: domain, + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: workflowID, + RunId: runID, + }, Control: []byte(cancellationID), - ChildWorkflowOnly: common.BoolPtr(false), + ChildWorkflowOnly: false, } decision := h.newCancelExternalWorkflowStateMachine(attributes, cancellationID) h.addDecision(decision) @@ -927,24 +955,24 @@ func (h *decisionsHelper) handleRequestCancelExternalWorkflowExecutionFailed(ini } func (h *decisionsHelper) signalExternalWorkflowExecution(domain, workflowID, runID, signalName string, input []byte, signalID string, childWorkflowOnly bool) decisionStateMachine { - attributes := &s.SignalExternalWorkflowExecutionDecisionAttributes{ - Domain: common.StringPtr(domain), - Execution: &s.WorkflowExecution{ - WorkflowId: common.StringPtr(workflowID), - RunId: common.StringPtr(runID), + attributes := &apiv1.SignalExternalWorkflowExecutionDecisionAttributes{ + Domain: domain, + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: workflowID, + RunId: runID, }, - SignalName: common.StringPtr(signalName), - Input: input, + SignalName: signalName, + Input: &apiv1.Payload{Data: input}, Control: []byte(signalID), - ChildWorkflowOnly: common.BoolPtr(childWorkflowOnly), + ChildWorkflowOnly: childWorkflowOnly, } decision := h.newSignalExternalWorkflowStateMachine(attributes, signalID) h.addDecision(decision) return decision } -func (h *decisionsHelper) upsertSearchAttributes(upsertID string, searchAttr *s.SearchAttributes) decisionStateMachine { - attributes := &s.UpsertWorkflowSearchAttributesDecisionAttributes{ +func (h *decisionsHelper) upsertSearchAttributes(upsertID string, searchAttr *apiv1.SearchAttributes) decisionStateMachine { + attributes := &apiv1.UpsertWorkflowSearchAttributesDecisionAttributes{ SearchAttributes: searchAttr, } decision := h.newUpsertSearchAttributesStateMachine(attributes, upsertID) @@ -978,7 +1006,7 @@ func (h *decisionsHelper) getSignalID(initiatedEventID int64) string { return signalID } -func (h *decisionsHelper) startTimer(attributes *s.StartTimerDecisionAttributes) decisionStateMachine { +func (h *decisionsHelper) startTimer(attributes *apiv1.StartTimerDecisionAttributes) decisionStateMachine { decision := h.newTimerDecisionStateMachine(attributes) h.addDecision(decision) return decision @@ -1029,8 +1057,8 @@ func (h *decisionsHelper) handleChildWorkflowExecutionCanceled(workflowID string return decision } -func (h *decisionsHelper) getDecisions(markAsSent bool) []*s.Decision { - var result []*s.Decision +func (h *decisionsHelper) getDecisions(markAsSent bool) []*apiv1.Decision { + var result []*apiv1.Decision for curr := h.orderedDecisions.Front(); curr != nil; { next := curr.Next() // get next item here as we might need to remove curr in the loop d := curr.Value.(decisionStateMachine) diff --git a/internal/internal_decision_state_machine_test.go b/internal/internal_decision_state_machine_test.go index 767bac0eb..efe5954d7 100644 --- a/internal/internal_decision_state_machine_test.go +++ b/internal/internal_decision_state_machine_test.go @@ -24,15 +24,14 @@ import ( "testing" "github.com/stretchr/testify/require" - s "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" ) func Test_TimerStateMachine_CancelBeforeSent(t *testing.T) { t.Parallel() timerID := "test-timer-1" - attributes := &s.StartTimerDecisionAttributes{ - TimerId: common.StringPtr(timerID), + attributes := &apiv1.StartTimerDecisionAttributes{ + TimerId: timerID, } h := newDecisionsHelper() d := h.startTimer(attributes) @@ -46,8 +45,8 @@ func Test_TimerStateMachine_CancelBeforeSent(t *testing.T) { func Test_TimerStateMachine_CancelAfterInitiated(t *testing.T) { t.Parallel() timerID := "test-timer-1" - attributes := &s.StartTimerDecisionAttributes{ - TimerId: common.StringPtr(timerID), + attributes := &apiv1.StartTimerDecisionAttributes{ + TimerId: timerID, } h := newDecisionsHelper() d := h.startTimer(attributes) @@ -55,15 +54,14 @@ func Test_TimerStateMachine_CancelAfterInitiated(t *testing.T) { decisions := h.getDecisions(true) require.Equal(t, decisionStateDecisionSent, d.getState()) require.Equal(t, 1, len(decisions)) - require.Equal(t, s.DecisionTypeStartTimer, decisions[0].GetDecisionType()) - require.Equal(t, attributes, decisions[0].StartTimerDecisionAttributes) + require.Equal(t, attributes, decisions[0].GetStartTimerDecisionAttributes()) h.handleTimerStarted(timerID) require.Equal(t, decisionStateInitiated, d.getState()) h.cancelTimer(timerID) require.Equal(t, decisionStateCanceledAfterInitiated, d.getState()) decisions = h.getDecisions(true) require.Equal(t, 1, len(decisions)) - require.Equal(t, s.DecisionTypeCancelTimer, decisions[0].GetDecisionType()) + require.NotNil(t, decisions[0].GetCancelTimerDecisionAttributes()) require.Equal(t, decisionStateCancellationDecisionSent, d.getState()) h.handleTimerCanceled(timerID) require.Equal(t, decisionStateCompleted, d.getState()) @@ -72,8 +70,8 @@ func Test_TimerStateMachine_CancelAfterInitiated(t *testing.T) { func Test_TimerStateMachine_CompletedAfterCancel(t *testing.T) { t.Parallel() timerID := "test-timer-1" - attributes := &s.StartTimerDecisionAttributes{ - TimerId: common.StringPtr(timerID), + attributes := &apiv1.StartTimerDecisionAttributes{ + TimerId: timerID, } h := newDecisionsHelper() d := h.startTimer(attributes) @@ -81,7 +79,7 @@ func Test_TimerStateMachine_CompletedAfterCancel(t *testing.T) { decisions := h.getDecisions(true) require.Equal(t, decisionStateDecisionSent, d.getState()) require.Equal(t, 1, len(decisions)) - require.Equal(t, s.DecisionTypeStartTimer, decisions[0].GetDecisionType()) + require.NotNil(t, decisions[0].GetStartTimerDecisionAttributes()) h.cancelTimer(timerID) require.Equal(t, decisionStateCanceledBeforeInitiated, d.getState()) require.Equal(t, 0, len(h.getDecisions(true))) @@ -89,7 +87,7 @@ func Test_TimerStateMachine_CompletedAfterCancel(t *testing.T) { require.Equal(t, decisionStateCanceledAfterInitiated, d.getState()) decisions = h.getDecisions(true) require.Equal(t, 1, len(decisions)) - require.Equal(t, s.DecisionTypeCancelTimer, decisions[0].GetDecisionType()) + require.NotNil(t, decisions[0].GetCancelTimerDecisionAttributes()) require.Equal(t, decisionStateCancellationDecisionSent, d.getState()) h.handleTimerClosed(timerID) require.Equal(t, decisionStateCompletedAfterCancellationDecisionSent, d.getState()) @@ -98,8 +96,8 @@ func Test_TimerStateMachine_CompletedAfterCancel(t *testing.T) { func Test_TimerStateMachine_CompleteWithoutCancel(t *testing.T) { t.Parallel() timerID := "test-timer-1" - attributes := &s.StartTimerDecisionAttributes{ - TimerId: common.StringPtr(timerID), + attributes := &apiv1.StartTimerDecisionAttributes{ + TimerId: timerID, } h := newDecisionsHelper() d := h.startTimer(attributes) @@ -107,7 +105,7 @@ func Test_TimerStateMachine_CompleteWithoutCancel(t *testing.T) { decisions := h.getDecisions(true) require.Equal(t, decisionStateDecisionSent, d.getState()) require.Equal(t, 1, len(decisions)) - require.Equal(t, s.DecisionTypeStartTimer, decisions[0].GetDecisionType()) + require.NotNil(t, decisions[0].GetStartTimerDecisionAttributes()) h.handleTimerStarted(timerID) require.Equal(t, decisionStateInitiated, d.getState()) require.Equal(t, 0, len(h.getDecisions(false))) @@ -118,8 +116,8 @@ func Test_TimerStateMachine_CompleteWithoutCancel(t *testing.T) { func Test_TimerStateMachine_PanicInvalidStateTransition(t *testing.T) { t.Parallel() timerID := "test-timer-1" - attributes := &s.StartTimerDecisionAttributes{ - TimerId: common.StringPtr(timerID), + attributes := &apiv1.StartTimerDecisionAttributes{ + TimerId: timerID, } h := newDecisionsHelper() h.startTimer(attributes) @@ -138,8 +136,8 @@ func Test_TimerCancelEventOrdering(t *testing.T) { t.Parallel() timerID := "test-timer-1" localActivityID := "test-activity-1" - attributes := &s.StartTimerDecisionAttributes{ - TimerId: common.StringPtr(timerID), + attributes := &apiv1.StartTimerDecisionAttributes{ + TimerId: timerID, } h := newDecisionsHelper() d := h.startTimer(attributes) @@ -147,8 +145,8 @@ func Test_TimerCancelEventOrdering(t *testing.T) { decisions := h.getDecisions(true) require.Equal(t, decisionStateDecisionSent, d.getState()) require.Equal(t, 1, len(decisions)) - require.Equal(t, s.DecisionTypeStartTimer, decisions[0].GetDecisionType()) - require.Equal(t, attributes, decisions[0].StartTimerDecisionAttributes) + require.NotNil(t, decisions[0].GetStartTimerDecisionAttributes()) + require.Equal(t, attributes, decisions[0].GetStartTimerDecisionAttributes()) h.handleTimerStarted(timerID) require.Equal(t, decisionStateInitiated, d.getState()) m := h.recordLocalActivityMarker(localActivityID, []byte{}) @@ -157,15 +155,15 @@ func Test_TimerCancelEventOrdering(t *testing.T) { require.Equal(t, decisionStateCanceledAfterInitiated, d.getState()) decisions = h.getDecisions(true) require.Equal(t, 2, len(decisions)) - require.Equal(t, s.DecisionTypeRecordMarker, decisions[0].GetDecisionType()) - require.Equal(t, s.DecisionTypeCancelTimer, decisions[1].GetDecisionType()) + require.NotNil(t, decisions[0].GetRecordMarkerDecisionAttributes()) + require.NotNil(t, decisions[1].GetCancelTimerDecisionAttributes()) } func Test_ActivityStateMachine_CompleteWithoutCancel(t *testing.T) { t.Parallel() activityID := "test-activity-1" - attributes := &s.ScheduleActivityTaskDecisionAttributes{ - ActivityId: common.StringPtr(activityID), + attributes := &apiv1.ScheduleActivityTaskDecisionAttributes{ + ActivityId: activityID, } h := newDecisionsHelper() @@ -175,7 +173,7 @@ func Test_ActivityStateMachine_CompleteWithoutCancel(t *testing.T) { decisions := h.getDecisions(true) require.Equal(t, decisionStateDecisionSent, d.getState()) require.Equal(t, 1, len(decisions)) - require.Equal(t, s.DecisionTypeScheduleActivityTask, decisions[0].GetDecisionType()) + require.NotNil(t, decisions[0].GetScheduleActivityTaskDecisionAttributes()) // activity scheduled h.handleActivityTaskScheduled(1, activityID) @@ -189,8 +187,8 @@ func Test_ActivityStateMachine_CompleteWithoutCancel(t *testing.T) { func Test_ActivityStateMachine_CancelBeforeSent(t *testing.T) { t.Parallel() activityID := "test-activity-1" - attributes := &s.ScheduleActivityTaskDecisionAttributes{ - ActivityId: common.StringPtr(activityID), + attributes := &apiv1.ScheduleActivityTaskDecisionAttributes{ + ActivityId: activityID, } h := newDecisionsHelper() @@ -210,8 +208,8 @@ func Test_ActivityStateMachine_CancelBeforeSent(t *testing.T) { func Test_ActivityStateMachine_CancelAfterSent(t *testing.T) { t.Parallel() activityID := "test-activity-1" - attributes := &s.ScheduleActivityTaskDecisionAttributes{ - ActivityId: common.StringPtr(activityID), + attributes := &apiv1.ScheduleActivityTaskDecisionAttributes{ + ActivityId: activityID, } h := newDecisionsHelper() @@ -220,7 +218,7 @@ func Test_ActivityStateMachine_CancelAfterSent(t *testing.T) { require.Equal(t, decisionStateCreated, d.getState()) decisions := h.getDecisions(true) require.Equal(t, 1, len(decisions)) - require.Equal(t, s.DecisionTypeScheduleActivityTask, decisions[0].GetDecisionType()) + require.NotNil(t, decisions[0].GetScheduleActivityTaskDecisionAttributes()) // cancel activity h.requestCancelActivityTask(activityID) @@ -232,7 +230,7 @@ func Test_ActivityStateMachine_CancelAfterSent(t *testing.T) { require.Equal(t, decisionStateCanceledAfterInitiated, d.getState()) decisions = h.getDecisions(true) require.Equal(t, 1, len(decisions)) - require.Equal(t, s.DecisionTypeRequestCancelActivityTask, decisions[0].GetDecisionType()) + require.NotNil(t, decisions[0].GetRequestCancelActivityTaskDecisionAttributes()) // activity canceled h.handleActivityTaskCanceled(activityID) @@ -243,8 +241,8 @@ func Test_ActivityStateMachine_CancelAfterSent(t *testing.T) { func Test_ActivityStateMachine_CompletedAfterCancel(t *testing.T) { t.Parallel() activityID := "test-activity-1" - attributes := &s.ScheduleActivityTaskDecisionAttributes{ - ActivityId: common.StringPtr(activityID), + attributes := &apiv1.ScheduleActivityTaskDecisionAttributes{ + ActivityId: activityID, } h := newDecisionsHelper() @@ -253,7 +251,7 @@ func Test_ActivityStateMachine_CompletedAfterCancel(t *testing.T) { require.Equal(t, decisionStateCreated, d.getState()) decisions := h.getDecisions(true) require.Equal(t, 1, len(decisions)) - require.Equal(t, s.DecisionTypeScheduleActivityTask, decisions[0].GetDecisionType()) + require.NotNil(t, decisions[0].GetScheduleActivityTaskDecisionAttributes()) // cancel activity h.requestCancelActivityTask(activityID) @@ -265,7 +263,7 @@ func Test_ActivityStateMachine_CompletedAfterCancel(t *testing.T) { require.Equal(t, decisionStateCanceledAfterInitiated, d.getState()) decisions = h.getDecisions(true) require.Equal(t, 1, len(decisions)) - require.Equal(t, s.DecisionTypeRequestCancelActivityTask, decisions[0].GetDecisionType()) + require.NotNil(t, decisions[0].GetRequestCancelActivityTaskDecisionAttributes()) // activity completed after cancel h.handleActivityTaskClosed(activityID) @@ -276,8 +274,8 @@ func Test_ActivityStateMachine_CompletedAfterCancel(t *testing.T) { func Test_ActivityStateMachine_PanicInvalidStateTransition(t *testing.T) { t.Parallel() activityID := "test-activity-1" - attributes := &s.ScheduleActivityTaskDecisionAttributes{ - ActivityId: common.StringPtr(activityID), + attributes := &apiv1.ScheduleActivityTaskDecisionAttributes{ + ActivityId: activityID, } h := newDecisionsHelper() @@ -305,8 +303,8 @@ func Test_ActivityStateMachine_PanicInvalidStateTransition(t *testing.T) { func Test_ChildWorkflowStateMachine_Basic(t *testing.T) { t.Parallel() workflowID := "test-child-workflow-1" - attributes := &s.StartChildWorkflowExecutionDecisionAttributes{ - WorkflowId: common.StringPtr(workflowID), + attributes := &apiv1.StartChildWorkflowExecutionDecisionAttributes{ + WorkflowId: workflowID, } h := newDecisionsHelper() @@ -318,7 +316,7 @@ func Test_ChildWorkflowStateMachine_Basic(t *testing.T) { decisions := h.getDecisions(true) require.Equal(t, decisionStateDecisionSent, d.getState()) require.Equal(t, 1, len(decisions)) - require.Equal(t, s.DecisionTypeStartChildWorkflowExecution, decisions[0].GetDecisionType()) + require.NotNil(t, decisions[0].GetStartChildWorkflowExecutionDecisionAttributes()) // child workflow initiated h.handleStartChildWorkflowExecutionInitiated(workflowID) @@ -344,8 +342,8 @@ func Test_ChildWorkflowStateMachine_CancelSucceed(t *testing.T) { cancellationID := "" initiatedEventID := int64(28) isChildWorkflowOnly := true - attributes := &s.StartChildWorkflowExecutionDecisionAttributes{ - WorkflowId: common.StringPtr(workflowID), + attributes := &apiv1.StartChildWorkflowExecutionDecisionAttributes{ + WorkflowId: workflowID, } h := newDecisionsHelper() @@ -366,7 +364,7 @@ func Test_ChildWorkflowStateMachine_CancelSucceed(t *testing.T) { decisions = h.getDecisions(true) require.Equal(t, decisionStateCancellationDecisionSent, d.getState()) require.Equal(t, 1, len(decisions)) - require.Equal(t, s.DecisionTypeRequestCancelExternalWorkflowExecution, decisions[0].GetDecisionType()) + require.NotNil(t, decisions[0].GetRequestCancelExternalWorkflowExecutionDecisionAttributes()) // cancel request initiated h.handleRequestCancelExternalWorkflowExecutionInitiated(initiatedEventID, workflowID, cancellationID) @@ -386,8 +384,8 @@ func Test_ChildWorkflowStateMachine_InvalidStates(t *testing.T) { domain := "test-domain" workflowID := "test-workflow-id" runID := "" - attributes := &s.StartChildWorkflowExecutionDecisionAttributes{ - WorkflowId: common.StringPtr(workflowID), + attributes := &apiv1.StartChildWorkflowExecutionDecisionAttributes{ + WorkflowId: workflowID, } cancellationID := "" initiatedEventID := int64(28) @@ -435,7 +433,7 @@ func Test_ChildWorkflowStateMachine_InvalidStates(t *testing.T) { decisions = h.getDecisions(true) require.Equal(t, decisionStateCancellationDecisionSent, d.getState()) require.Equal(t, 1, len(decisions)) - require.Equal(t, s.DecisionTypeRequestCancelExternalWorkflowExecution, decisions[0].GetDecisionType()) + require.NotNil(t, decisions[0].GetRequestCancelExternalWorkflowExecutionDecisionAttributes()) // invalid: start child workflow failed after it was already started err = runAndCatchPanic(func() { @@ -469,8 +467,8 @@ func Test_ChildWorkflowStateMachine_CancelFailed(t *testing.T) { domain := "test-domain" workflowID := "test-workflow-id" runID := "" - attributes := &s.StartChildWorkflowExecutionDecisionAttributes{ - WorkflowId: common.StringPtr(workflowID), + attributes := &apiv1.StartChildWorkflowExecutionDecisionAttributes{ + WorkflowId: workflowID, } cancellationID := "" initiatedEventID := int64(28) @@ -513,21 +511,21 @@ func Test_MarkerStateMachine(t *testing.T) { decisions := h.getDecisions(true) require.Equal(t, decisionStateCompleted, d.getState()) require.Equal(t, 1, len(decisions)) - require.Equal(t, s.DecisionTypeRecordMarker, decisions[0].GetDecisionType()) + require.NotNil(t, decisions[0].GetRecordMarkerDecisionAttributes()) } func Test_UpsertSearchAttributesDecisionStateMachine(t *testing.T) { t.Parallel() h := newDecisionsHelper() - attr := &s.SearchAttributes{} + attr := &apiv1.SearchAttributes{} d := h.upsertSearchAttributes("1", attr) require.Equal(t, decisionStateCreated, d.getState()) decisions := h.getDecisions(true) require.Equal(t, decisionStateCompleted, d.getState()) require.Equal(t, 1, len(decisions)) - require.Equal(t, s.DecisionTypeUpsertWorkflowSearchAttributes, decisions[0].GetDecisionType()) + require.NotNil(t, decisions[0].GetUpsertWorkflowSearchAttributesDecisionAttributes()) } func Test_CancelExternalWorkflowStateMachine_Succeed(t *testing.T) { @@ -549,17 +547,19 @@ func Test_CancelExternalWorkflowStateMachine_Succeed(t *testing.T) { // send decisions decisions := h.getDecisions(true) require.Equal(t, 1, len(decisions)) - require.Equal(t, s.DecisionTypeRequestCancelExternalWorkflowExecution, decisions[0].GetDecisionType()) + require.NotNil(t, decisions[0].GetRequestCancelExternalWorkflowExecutionDecisionAttributes()) require.Equal( t, - &s.RequestCancelExternalWorkflowExecutionDecisionAttributes{ - Domain: common.StringPtr(domain), - WorkflowId: common.StringPtr(workflowID), - RunId: common.StringPtr(runID), + &apiv1.RequestCancelExternalWorkflowExecutionDecisionAttributes{ + Domain: domain, + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: workflowID, + RunId: runID, + }, Control: []byte(cancellationID), - ChildWorkflowOnly: common.BoolPtr(childWorkflowOnly), + ChildWorkflowOnly: childWorkflowOnly, }, - decisions[0].RequestCancelExternalWorkflowExecutionDecisionAttributes, + decisions[0].GetRequestCancelExternalWorkflowExecutionDecisionAttributes(), ) // cancel request initiated @@ -596,17 +596,19 @@ func Test_CancelExternalWorkflowStateMachine_Failed(t *testing.T) { // send decisions decisions := h.getDecisions(true) require.Equal(t, 1, len(decisions)) - require.Equal(t, s.DecisionTypeRequestCancelExternalWorkflowExecution, decisions[0].GetDecisionType()) + require.NotNil(t, decisions[0].GetRequestCancelExternalWorkflowExecutionDecisionAttributes()) require.Equal( t, - &s.RequestCancelExternalWorkflowExecutionDecisionAttributes{ - Domain: common.StringPtr(domain), - WorkflowId: common.StringPtr(workflowID), - RunId: common.StringPtr(runID), + &apiv1.RequestCancelExternalWorkflowExecutionDecisionAttributes{ + Domain: domain, + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: workflowID, + RunId: runID, + }, Control: []byte(cancellationID), - ChildWorkflowOnly: common.BoolPtr(childWorkflowOnly), + ChildWorkflowOnly: childWorkflowOnly, }, - decisions[0].RequestCancelExternalWorkflowExecutionDecisionAttributes, + decisions[0].GetRequestCancelExternalWorkflowExecutionDecisionAttributes(), ) // cancel request initiated diff --git a/internal/internal_event_handlers.go b/internal/internal_event_handlers.go index 1f3970636..5a00526ec 100644 --- a/internal/internal_event_handlers.go +++ b/internal/internal_event_handlers.go @@ -31,12 +31,13 @@ import ( "sync" "time" + "github.com/gogo/protobuf/types" "github.com/opentracing/opentracing-go" "github.com/uber-go/tally" - "go.uber.org/cadence/v1/.gen/go/shared" - m "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" - "go.uber.org/cadence/v1/internal/common/metrics" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/internal/common/metrics" + "go.uber.org/cadence/v2/internal/common/util" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) @@ -132,26 +133,26 @@ type ( attempt int32 // attempt starting from 0 retryPolicy *RetryPolicy expireTime time.Time - header *shared.Header + header *apiv1.Header } locallyDispatchedActivityTask struct { // used to notify the poller the response from server is completed and the task is ready - readyCh chan bool - TaskToken []byte - WorkflowExecution *shared.WorkflowExecution - ActivityId *string - ActivityType *shared.ActivityType - Input []byte - ScheduledTimestamp *int64 - ScheduleToCloseTimeoutSeconds *int32 - StartedTimestamp *int64 - StartToCloseTimeoutSeconds *int32 - HeartbeatTimeoutSeconds *int32 - ScheduledTimestampOfThisAttempt *int64 - WorkflowType *shared.WorkflowType - WorkflowDomain *string - Header *shared.Header + readyCh chan bool + TaskToken []byte + WorkflowExecution *apiv1.WorkflowExecution + ActivityId string + ActivityType *apiv1.ActivityType + Input *apiv1.Payload + ScheduledTime *types.Timestamp + ScheduleToCloseTimeout *types.Duration + StartedTime *types.Timestamp + StartToCloseTimeout *types.Duration + HeartbeatTimeout *types.Duration + ScheduledTimeOfThisAttempt *types.Timestamp + WorkflowType *apiv1.WorkflowType + WorkflowDomain string + Header *apiv1.Header } localActivityMarkerData struct { @@ -335,17 +336,17 @@ func (wc *workflowEnvironmentImpl) UpsertSearchAttributes(attributes map[string] return nil } -func (wc *workflowEnvironmentImpl) updateWorkflowInfoWithSearchAttributes(attributes *shared.SearchAttributes) { +func (wc *workflowEnvironmentImpl) updateWorkflowInfoWithSearchAttributes(attributes *apiv1.SearchAttributes) { wc.workflowInfo.SearchAttributes = mergeSearchAttributes(wc.workflowInfo.SearchAttributes, attributes) } -func mergeSearchAttributes(current, upsert *shared.SearchAttributes) *shared.SearchAttributes { +func mergeSearchAttributes(current, upsert *apiv1.SearchAttributes) *apiv1.SearchAttributes { if current == nil || len(current.IndexedFields) == 0 { if upsert == nil || len(upsert.IndexedFields) == 0 { return nil } - current = &shared.SearchAttributes{ - IndexedFields: make(map[string][]byte), + current = &apiv1.SearchAttributes{ + IndexedFields: make(map[string]*apiv1.Payload), } } @@ -356,7 +357,7 @@ func mergeSearchAttributes(current, upsert *shared.SearchAttributes) *shared.Sea return current } -func validateAndSerializeSearchAttributes(attributes map[string]interface{}) (*shared.SearchAttributes, error) { +func validateAndSerializeSearchAttributes(attributes map[string]interface{}) (*apiv1.SearchAttributes, error) { if len(attributes) == 0 { return nil, errSearchAttributesNotSet } @@ -385,23 +386,21 @@ func (wc *workflowEnvironmentImpl) ExecuteChildWorkflow( return err } - attributes := &m.StartChildWorkflowExecutionDecisionAttributes{} - - attributes.Domain = params.domain - attributes.TaskList = &m.TaskList{Name: params.taskListName} - attributes.WorkflowId = common.StringPtr(params.workflowID) - attributes.ExecutionStartToCloseTimeoutSeconds = params.executionStartToCloseTimeoutSeconds - attributes.TaskStartToCloseTimeoutSeconds = params.taskStartToCloseTimeoutSeconds - attributes.Input = params.input - attributes.WorkflowType = workflowTypePtr(*params.workflowType) - attributes.WorkflowIdReusePolicy = params.workflowIDReusePolicy.toThriftPtr() - attributes.ParentClosePolicy = params.parentClosePolicy.toThriftPtr() - attributes.RetryPolicy = params.retryPolicy - attributes.Header = params.header - attributes.Memo = memo - attributes.SearchAttributes = searchAttr - if len(params.cronSchedule) > 0 { - attributes.CronSchedule = common.StringPtr(params.cronSchedule) + attributes := &apiv1.StartChildWorkflowExecutionDecisionAttributes{ + Domain: *params.domain, + TaskList: &apiv1.TaskList{Name: *params.taskListName}, + WorkflowId: params.workflowID, + ExecutionStartToCloseTimeout: api.SecondsToProto(*params.executionStartToCloseTimeoutSeconds), + TaskStartToCloseTimeout: api.SecondsToProto(*params.taskStartToCloseTimeoutSeconds), + Input: &apiv1.Payload{Data: params.input}, + WorkflowType: &apiv1.WorkflowType{Name: params.workflowType.Name}, + WorkflowIdReusePolicy: params.workflowIDReusePolicy.toProto(), + ParentClosePolicy: params.parentClosePolicy.toProto(), + RetryPolicy: params.retryPolicy, + Header: params.header, + Memo: memo, + SearchAttributes: searchAttr, + CronSchedule: params.cronSchedule, } decision := wc.decisionsHelper.startChildWorkflowExecution(attributes) @@ -456,27 +455,21 @@ func (wc *workflowEnvironmentImpl) GenerateSequence() int32 { return result } -func (wc *workflowEnvironmentImpl) CreateNewDecision(decisionType m.DecisionType) *m.Decision { - return &m.Decision{ - DecisionType: common.DecisionTypePtr(decisionType), - } -} - func (wc *workflowEnvironmentImpl) ExecuteActivity(parameters executeActivityParams, callback resultHandler) *activityInfo { - scheduleTaskAttr := &m.ScheduleActivityTaskDecisionAttributes{} + scheduleTaskAttr := &apiv1.ScheduleActivityTaskDecisionAttributes{} if parameters.ActivityID == nil || *parameters.ActivityID == "" { - scheduleTaskAttr.ActivityId = common.StringPtr(wc.GenerateSequenceID()) + scheduleTaskAttr.ActivityId = wc.GenerateSequenceID() } else { - scheduleTaskAttr.ActivityId = parameters.ActivityID + scheduleTaskAttr.ActivityId = *parameters.ActivityID } activityID := scheduleTaskAttr.GetActivityId() - scheduleTaskAttr.ActivityType = activityTypePtr(parameters.ActivityType) - scheduleTaskAttr.TaskList = common.TaskListPtr(m.TaskList{Name: common.StringPtr(parameters.TaskListName)}) - scheduleTaskAttr.Input = parameters.Input - scheduleTaskAttr.ScheduleToCloseTimeoutSeconds = common.Int32Ptr(parameters.ScheduleToCloseTimeoutSeconds) - scheduleTaskAttr.StartToCloseTimeoutSeconds = common.Int32Ptr(parameters.StartToCloseTimeoutSeconds) - scheduleTaskAttr.ScheduleToStartTimeoutSeconds = common.Int32Ptr(parameters.ScheduleToStartTimeoutSeconds) - scheduleTaskAttr.HeartbeatTimeoutSeconds = common.Int32Ptr(parameters.HeartbeatTimeoutSeconds) + scheduleTaskAttr.ActivityType = &apiv1.ActivityType{Name: parameters.ActivityType.Name} + scheduleTaskAttr.TaskList = &apiv1.TaskList{Name: parameters.TaskListName} + scheduleTaskAttr.Input = &apiv1.Payload{Data: parameters.Input} + scheduleTaskAttr.ScheduleToCloseTimeout = api.SecondsToProto(parameters.ScheduleToCloseTimeoutSeconds) + scheduleTaskAttr.StartToCloseTimeout = api.SecondsToProto(parameters.StartToCloseTimeoutSeconds) + scheduleTaskAttr.ScheduleToStartTimeout = api.SecondsToProto(parameters.ScheduleToStartTimeoutSeconds) + scheduleTaskAttr.HeartbeatTimeout = api.SecondsToProto(parameters.HeartbeatTimeoutSeconds) scheduleTaskAttr.RetryPolicy = parameters.RetryPolicy scheduleTaskAttr.Header = parameters.Header @@ -561,9 +554,10 @@ func (wc *workflowEnvironmentImpl) NewTimer(d time.Duration, callback resultHand } timerID := wc.GenerateSequenceID() - startTimerAttr := &m.StartTimerDecisionAttributes{} - startTimerAttr.TimerId = common.StringPtr(timerID) - startTimerAttr.StartToFireTimeoutSeconds = common.Int64Ptr(common.Int64Ceil(d.Seconds())) + startTimerAttr := &apiv1.StartTimerDecisionAttributes{ + TimerId: timerID, + StartToFireTimeout: api.DurationToProto(d), + } decision := wc.decisionsHelper.startTimer(startTimerAttr) decision.setData(&scheduledTimer{callback: callback}) @@ -768,7 +762,7 @@ func (wc *workflowEnvironmentImpl) GetWorkflowInterceptors() []WorkflowIntercept } func (weh *workflowExecutionEventHandlerImpl) ProcessEvent( - event *m.HistoryEvent, + event *apiv1.HistoryEvent, isReplay bool, isLast bool, ) (err error) { @@ -792,137 +786,137 @@ func (weh *workflowExecutionEventHandlerImpl) ProcessEvent( traceLog(func() { weh.logger.Debug("ProcessEvent", zap.Int64(tagEventID, event.GetEventId()), - zap.String(tagEventType, event.GetEventType().String())) + zap.String(tagEventType, util.GetHistoryEventType(event))) }) - switch event.GetEventType() { - case m.EventTypeWorkflowExecutionStarted: - err = weh.handleWorkflowExecutionStarted(event.WorkflowExecutionStartedEventAttributes) + switch attr := event.Attributes.(type) { + case *apiv1.HistoryEvent_WorkflowExecutionStartedEventAttributes: + err = weh.handleWorkflowExecutionStarted(attr.WorkflowExecutionStartedEventAttributes) - case m.EventTypeWorkflowExecutionCompleted: + case *apiv1.HistoryEvent_WorkflowExecutionCompletedEventAttributes: // No Operation - case m.EventTypeWorkflowExecutionFailed: + case *apiv1.HistoryEvent_WorkflowExecutionFailedEventAttributes: // No Operation - case m.EventTypeWorkflowExecutionTimedOut: + case *apiv1.HistoryEvent_WorkflowExecutionTimedOutEventAttributes: // No Operation - case m.EventTypeDecisionTaskScheduled: + case *apiv1.HistoryEvent_DecisionTaskScheduledEventAttributes: // No Operation - case m.EventTypeDecisionTaskStarted: + case *apiv1.HistoryEvent_DecisionTaskStartedEventAttributes: // Set replay clock. - weh.SetCurrentReplayTime(time.Unix(0, event.GetTimestamp())) + weh.SetCurrentReplayTime(api.TimeFromProto(event.GetEventTime())) weh.workflowDefinition.OnDecisionTaskStarted() - case m.EventTypeDecisionTaskTimedOut: + case *apiv1.HistoryEvent_DecisionTaskTimedOutEventAttributes: // No Operation - case m.EventTypeDecisionTaskFailed: + case *apiv1.HistoryEvent_DecisionTaskFailedEventAttributes: // No Operation - case m.EventTypeDecisionTaskCompleted: + case *apiv1.HistoryEvent_DecisionTaskCompletedEventAttributes: // No Operation - case m.EventTypeActivityTaskScheduled: + case *apiv1.HistoryEvent_ActivityTaskScheduledEventAttributes: weh.decisionsHelper.handleActivityTaskScheduled( - event.GetEventId(), event.ActivityTaskScheduledEventAttributes.GetActivityId()) + event.GetEventId(), attr.ActivityTaskScheduledEventAttributes.GetActivityId()) - case m.EventTypeActivityTaskStarted: + case *apiv1.HistoryEvent_ActivityTaskStartedEventAttributes: // No Operation - case m.EventTypeActivityTaskCompleted: + case *apiv1.HistoryEvent_ActivityTaskCompletedEventAttributes: err = weh.handleActivityTaskCompleted(event) - case m.EventTypeActivityTaskFailed: + case *apiv1.HistoryEvent_ActivityTaskFailedEventAttributes: err = weh.handleActivityTaskFailed(event) - case m.EventTypeActivityTaskTimedOut: + case *apiv1.HistoryEvent_ActivityTaskTimedOutEventAttributes: err = weh.handleActivityTaskTimedOut(event) - case m.EventTypeActivityTaskCancelRequested: + case *apiv1.HistoryEvent_ActivityTaskCancelRequestedEventAttributes: weh.decisionsHelper.handleActivityTaskCancelRequested( - event.ActivityTaskCancelRequestedEventAttributes.GetActivityId()) + attr.ActivityTaskCancelRequestedEventAttributes.GetActivityId()) - case m.EventTypeRequestCancelActivityTaskFailed: + case *apiv1.HistoryEvent_RequestCancelActivityTaskFailedEventAttributes: weh.decisionsHelper.handleRequestCancelActivityTaskFailed( - event.RequestCancelActivityTaskFailedEventAttributes.GetActivityId()) + attr.RequestCancelActivityTaskFailedEventAttributes.GetActivityId()) - case m.EventTypeActivityTaskCanceled: + case *apiv1.HistoryEvent_ActivityTaskCanceledEventAttributes: err = weh.handleActivityTaskCanceled(event) - case m.EventTypeTimerStarted: - weh.decisionsHelper.handleTimerStarted(event.TimerStartedEventAttributes.GetTimerId()) + case *apiv1.HistoryEvent_TimerStartedEventAttributes: + weh.decisionsHelper.handleTimerStarted(attr.TimerStartedEventAttributes.GetTimerId()) - case m.EventTypeTimerFired: + case *apiv1.HistoryEvent_TimerFiredEventAttributes: weh.handleTimerFired(event) - case m.EventTypeTimerCanceled: - weh.decisionsHelper.handleTimerCanceled(event.TimerCanceledEventAttributes.GetTimerId()) + case *apiv1.HistoryEvent_TimerCanceledEventAttributes: + weh.decisionsHelper.handleTimerCanceled(attr.TimerCanceledEventAttributes.GetTimerId()) - case m.EventTypeCancelTimerFailed: - weh.decisionsHelper.handleCancelTimerFailed(event.CancelTimerFailedEventAttributes.GetTimerId()) + case *apiv1.HistoryEvent_CancelTimerFailedEventAttributes: + weh.decisionsHelper.handleCancelTimerFailed(attr.CancelTimerFailedEventAttributes.GetTimerId()) - case m.EventTypeWorkflowExecutionCancelRequested: + case *apiv1.HistoryEvent_WorkflowExecutionCancelRequestedEventAttributes: weh.handleWorkflowExecutionCancelRequested() - case m.EventTypeWorkflowExecutionCanceled: + case *apiv1.HistoryEvent_WorkflowExecutionCanceledEventAttributes: // No Operation. - case m.EventTypeRequestCancelExternalWorkflowExecutionInitiated: + case *apiv1.HistoryEvent_RequestCancelExternalWorkflowExecutionInitiatedEventAttributes: weh.handleRequestCancelExternalWorkflowExecutionInitiated(event) - case m.EventTypeRequestCancelExternalWorkflowExecutionFailed: + case *apiv1.HistoryEvent_RequestCancelExternalWorkflowExecutionFailedEventAttributes: weh.handleRequestCancelExternalWorkflowExecutionFailed(event) - case m.EventTypeExternalWorkflowExecutionCancelRequested: + case *apiv1.HistoryEvent_ExternalWorkflowExecutionCancelRequestedEventAttributes: weh.handleExternalWorkflowExecutionCancelRequested(event) - case m.EventTypeWorkflowExecutionContinuedAsNew: + case *apiv1.HistoryEvent_WorkflowExecutionContinuedAsNewEventAttributes: // No Operation. - case m.EventTypeWorkflowExecutionSignaled: - weh.handleWorkflowExecutionSignaled(event.WorkflowExecutionSignaledEventAttributes) + case *apiv1.HistoryEvent_WorkflowExecutionSignaledEventAttributes: + weh.handleWorkflowExecutionSignaled(attr.WorkflowExecutionSignaledEventAttributes) - case m.EventTypeSignalExternalWorkflowExecutionInitiated: - signalID := string(event.SignalExternalWorkflowExecutionInitiatedEventAttributes.Control) + case *apiv1.HistoryEvent_SignalExternalWorkflowExecutionInitiatedEventAttributes: + signalID := string(attr.SignalExternalWorkflowExecutionInitiatedEventAttributes.Control) weh.decisionsHelper.handleSignalExternalWorkflowExecutionInitiated(event.GetEventId(), signalID) - case m.EventTypeSignalExternalWorkflowExecutionFailed: + case *apiv1.HistoryEvent_SignalExternalWorkflowExecutionFailedEventAttributes: weh.handleSignalExternalWorkflowExecutionFailed(event) - case m.EventTypeExternalWorkflowExecutionSignaled: + case *apiv1.HistoryEvent_ExternalWorkflowExecutionSignaledEventAttributes: weh.handleSignalExternalWorkflowExecutionCompleted(event) - case m.EventTypeMarkerRecorded: - err = weh.handleMarkerRecorded(event.GetEventId(), event.MarkerRecordedEventAttributes) + case *apiv1.HistoryEvent_MarkerRecordedEventAttributes: + err = weh.handleMarkerRecorded(event.GetEventId(), attr.MarkerRecordedEventAttributes) - case m.EventTypeStartChildWorkflowExecutionInitiated: + case *apiv1.HistoryEvent_StartChildWorkflowExecutionInitiatedEventAttributes: weh.decisionsHelper.handleStartChildWorkflowExecutionInitiated( - event.StartChildWorkflowExecutionInitiatedEventAttributes.GetWorkflowId()) + attr.StartChildWorkflowExecutionInitiatedEventAttributes.GetWorkflowId()) - case m.EventTypeStartChildWorkflowExecutionFailed: + case *apiv1.HistoryEvent_StartChildWorkflowExecutionFailedEventAttributes: err = weh.handleStartChildWorkflowExecutionFailed(event) - case m.EventTypeChildWorkflowExecutionStarted: + case *apiv1.HistoryEvent_ChildWorkflowExecutionStartedEventAttributes: err = weh.handleChildWorkflowExecutionStarted(event) - case m.EventTypeChildWorkflowExecutionCompleted: + case *apiv1.HistoryEvent_ChildWorkflowExecutionCompletedEventAttributes: err = weh.handleChildWorkflowExecutionCompleted(event) - case m.EventTypeChildWorkflowExecutionFailed: + case *apiv1.HistoryEvent_ChildWorkflowExecutionFailedEventAttributes: err = weh.handleChildWorkflowExecutionFailed(event) - case m.EventTypeChildWorkflowExecutionCanceled: + case *apiv1.HistoryEvent_ChildWorkflowExecutionCanceledEventAttributes: err = weh.handleChildWorkflowExecutionCanceled(event) - case m.EventTypeChildWorkflowExecutionTimedOut: + case *apiv1.HistoryEvent_ChildWorkflowExecutionTimedOutEventAttributes: err = weh.handleChildWorkflowExecutionTimedOut(event) - case m.EventTypeChildWorkflowExecutionTerminated: + case *apiv1.HistoryEvent_ChildWorkflowExecutionTerminatedEventAttributes: err = weh.handleChildWorkflowExecutionTerminated(event) - case m.EventTypeUpsertWorkflowSearchAttributes: + case *apiv1.HistoryEvent_UpsertWorkflowSearchAttributesEventAttributes: weh.handleUpsertWorkflowSearchAttributes(event) default: weh.logger.Error("unknown event type", zap.Int64(tagEventID, event.GetEventId()), - zap.String(tagEventType, event.GetEventType().String())) + zap.String(tagEventType, util.GetHistoryEventType(event))) // Do not fail to be forward compatible with new events } @@ -933,7 +927,7 @@ func (weh *workflowExecutionEventHandlerImpl) ProcessEvent( // When replaying histories to get stack trace or current state the last event might be not // decision started. So always call OnDecisionTaskStarted on the last event. // Don't call for EventType_DecisionTaskStarted as it was already called when handling it. - if isLast && event.GetEventType() != m.EventTypeDecisionTaskStarted { + if isLast && event.GetDecisionTaskStartedEventAttributes() == nil { weh.workflowDefinition.OnDecisionTaskStarted() } @@ -976,7 +970,7 @@ func (weh *workflowExecutionEventHandlerImpl) Close() { } func (weh *workflowExecutionEventHandlerImpl) handleWorkflowExecutionStarted( - attributes *m.WorkflowExecutionStartedEventAttributes) (err error) { + attributes *apiv1.WorkflowExecutionStartedEventAttributes) (err error) { weh.workflowDefinition, err = weh.registry.getWorkflowDefinition( weh.workflowInfo.WorkflowType, ) @@ -985,23 +979,23 @@ func (weh *workflowExecutionEventHandlerImpl) handleWorkflowExecutionStarted( } // Invoke the workflow. - weh.workflowDefinition.Execute(weh, attributes.Header, attributes.Input) + weh.workflowDefinition.Execute(weh, attributes.Header, attributes.Input.GetData()) return nil } -func (weh *workflowExecutionEventHandlerImpl) handleActivityTaskCompleted(event *m.HistoryEvent) error { +func (weh *workflowExecutionEventHandlerImpl) handleActivityTaskCompleted(event *apiv1.HistoryEvent) error { activityID := weh.decisionsHelper.getActivityID(event) decision := weh.decisionsHelper.handleActivityTaskClosed(activityID) activity := decision.getData().(*scheduledActivity) if activity.handled { return nil } - activity.handle(event.ActivityTaskCompletedEventAttributes.Result, nil) + activity.handle(event.GetActivityTaskCompletedEventAttributes().Result.GetData(), nil) return nil } -func (weh *workflowExecutionEventHandlerImpl) handleActivityTaskFailed(event *m.HistoryEvent) error { +func (weh *workflowExecutionEventHandlerImpl) handleActivityTaskFailed(event *apiv1.HistoryEvent) error { activityID := weh.decisionsHelper.getActivityID(event) decision := weh.decisionsHelper.handleActivityTaskClosed(activityID) activity := decision.getData().(*scheduledActivity) @@ -1009,13 +1003,13 @@ func (weh *workflowExecutionEventHandlerImpl) handleActivityTaskFailed(event *m. return nil } - attributes := event.ActivityTaskFailedEventAttributes - err := constructError(*attributes.Reason, attributes.Details, weh.GetDataConverter()) + attributes := event.GetActivityTaskFailedEventAttributes() + err := constructError(attributes.Failure.GetReason(), attributes.Failure.GetDetails(), weh.GetDataConverter()) activity.handle(nil, err) return nil } -func (weh *workflowExecutionEventHandlerImpl) handleActivityTaskTimedOut(event *m.HistoryEvent) error { +func (weh *workflowExecutionEventHandlerImpl) handleActivityTaskTimedOut(event *apiv1.HistoryEvent) error { activityID := weh.decisionsHelper.getActivityID(event) decision := weh.decisionsHelper.handleActivityTaskClosed(activityID) activity := decision.getData().(*scheduledActivity) @@ -1024,21 +1018,21 @@ func (weh *workflowExecutionEventHandlerImpl) handleActivityTaskTimedOut(event * } var err error - attributes := event.ActivityTaskTimedOutEventAttributes - if len(attributes.GetLastFailureReason()) > 0 && attributes.GetTimeoutType() == shared.TimeoutTypeStartToClose { + attributes := event.GetActivityTaskTimedOutEventAttributes() + if len(attributes.LastFailure.GetReason()) > 0 && attributes.GetTimeoutType() == apiv1.TimeoutType_TIMEOUT_TYPE_START_TO_CLOSE { // When retry activity timeout, it is possible that previous attempts got other customer timeout errors. // To stabilize the error type, we always return the customer error. // See more details of background: https://github.com/uber/cadence/issues/2627 - err = constructError(attributes.GetLastFailureReason(), attributes.LastFailureDetails, weh.GetDataConverter()) + err = constructError(attributes.LastFailure.GetReason(), attributes.LastFailure.GetDetails(), weh.GetDataConverter()) } else { - details := newEncodedValues(attributes.Details, weh.GetDataConverter()) + details := newEncodedValues(attributes.Details.GetData(), weh.GetDataConverter()) err = NewTimeoutError(attributes.GetTimeoutType(), details) } activity.handle(nil, err) return nil } -func (weh *workflowExecutionEventHandlerImpl) handleActivityTaskCanceled(event *m.HistoryEvent) error { +func (weh *workflowExecutionEventHandlerImpl) handleActivityTaskCanceled(event *apiv1.HistoryEvent) error { activityID := weh.decisionsHelper.getActivityID(event) decision := weh.decisionsHelper.handleActivityTaskCanceled(activityID) activity := decision.getData().(*scheduledActivity) @@ -1048,7 +1042,7 @@ func (weh *workflowExecutionEventHandlerImpl) handleActivityTaskCanceled(event * if decision.isDone() || !activity.waitForCancelRequest { // Clear this so we don't have a recursive call that while executing might call the cancel one. - details := newEncodedValues(event.ActivityTaskCanceledEventAttributes.Details, weh.GetDataConverter()) + details := newEncodedValues(event.GetActivityTaskCanceledEventAttributes().Details.GetData(), weh.GetDataConverter()) err := NewCanceledError(details) activity.handle(nil, err) } @@ -1056,8 +1050,8 @@ func (weh *workflowExecutionEventHandlerImpl) handleActivityTaskCanceled(event * return nil } -func (weh *workflowExecutionEventHandlerImpl) handleTimerFired(event *m.HistoryEvent) { - timerID := event.TimerFiredEventAttributes.GetTimerId() +func (weh *workflowExecutionEventHandlerImpl) handleTimerFired(event *apiv1.HistoryEvent) { + timerID := event.GetTimerFiredEventAttributes().GetTimerId() decision := weh.decisionsHelper.handleTimerClosed(timerID) timer := decision.getData().(*scheduledTimer) if timer.handled { @@ -1073,9 +1067,9 @@ func (weh *workflowExecutionEventHandlerImpl) handleWorkflowExecutionCancelReque func (weh *workflowExecutionEventHandlerImpl) handleMarkerRecorded( eventID int64, - attributes *m.MarkerRecordedEventAttributes, + attributes *apiv1.MarkerRecordedEventAttributes, ) error { - encodedValues := newEncodedValues(attributes.Details, weh.dataConverter) + encodedValues := newEncodedValues(attributes.Details.GetData(), weh.dataConverter) switch attributes.GetMarkerName() { case sideEffectMarkerName: var sideEffectID int32 @@ -1090,7 +1084,7 @@ func (weh *workflowExecutionEventHandlerImpl) handleMarkerRecorded( weh.changeVersions[changeID] = version return nil case localActivityMarkerName: - return weh.handleLocalActivityMarker(attributes.Details) + return weh.handleLocalActivityMarker(attributes.Details.GetData()) case mutableSideEffectMarkerName: var fixedID string var result string @@ -1162,11 +1156,12 @@ func (weh *workflowExecutionEventHandlerImpl) ProcessLocalActivityResult(lar *lo } // create marker event for local activity result - markerEvent := &m.HistoryEvent{ - EventType: common.EventTypePtr(m.EventTypeMarkerRecorded), - MarkerRecordedEventAttributes: &m.MarkerRecordedEventAttributes{ - MarkerName: common.StringPtr(localActivityMarkerName), - Details: markerData, + markerEvent := &apiv1.HistoryEvent{ + Attributes: &apiv1.HistoryEvent_MarkerRecordedEventAttributes{ + MarkerRecordedEventAttributes: &apiv1.MarkerRecordedEventAttributes{ + MarkerName: localActivityMarkerName, + Details: &apiv1.Payload{Data: markerData}, + }, }, } @@ -1175,12 +1170,12 @@ func (weh *workflowExecutionEventHandlerImpl) ProcessLocalActivityResult(lar *lo } func (weh *workflowExecutionEventHandlerImpl) handleWorkflowExecutionSignaled( - attributes *m.WorkflowExecutionSignaledEventAttributes) { - weh.signalHandler(attributes.GetSignalName(), attributes.Input) + attributes *apiv1.WorkflowExecutionSignaledEventAttributes) { + weh.signalHandler(attributes.GetSignalName(), attributes.Input.GetData()) } -func (weh *workflowExecutionEventHandlerImpl) handleStartChildWorkflowExecutionFailed(event *m.HistoryEvent) error { - attributes := event.StartChildWorkflowExecutionFailedEventAttributes +func (weh *workflowExecutionEventHandlerImpl) handleStartChildWorkflowExecutionFailed(event *apiv1.HistoryEvent) error { + attributes := event.GetStartChildWorkflowExecutionFailedEventAttributes() childWorkflowID := attributes.GetWorkflowId() decision := weh.decisionsHelper.handleStartChildWorkflowExecutionFailed(childWorkflowID) childWorkflow := decision.getData().(*scheduledChildWorkflow) @@ -1188,8 +1183,8 @@ func (weh *workflowExecutionEventHandlerImpl) handleStartChildWorkflowExecutionF return nil } - err := &m.WorkflowExecutionAlreadyStartedError{ - Message: common.StringPtr("Workflow execution already started"), + err := &api.WorkflowExecutionAlreadyStartedError{ + Message: "Workflow execution already started", } childWorkflow.startedCallback(WorkflowExecution{}, err) childWorkflow.handle(nil, err) @@ -1197,8 +1192,8 @@ func (weh *workflowExecutionEventHandlerImpl) handleStartChildWorkflowExecutionF return nil } -func (weh *workflowExecutionEventHandlerImpl) handleChildWorkflowExecutionStarted(event *m.HistoryEvent) error { - attributes := event.ChildWorkflowExecutionStartedEventAttributes +func (weh *workflowExecutionEventHandlerImpl) handleChildWorkflowExecutionStarted(event *apiv1.HistoryEvent) error { + attributes := event.GetChildWorkflowExecutionStartedEventAttributes() childWorkflowID := attributes.WorkflowExecution.GetWorkflowId() childRunID := attributes.WorkflowExecution.GetRunId() decision := weh.decisionsHelper.handleChildWorkflowExecutionStarted(childWorkflowID) @@ -1216,21 +1211,21 @@ func (weh *workflowExecutionEventHandlerImpl) handleChildWorkflowExecutionStarte return nil } -func (weh *workflowExecutionEventHandlerImpl) handleChildWorkflowExecutionCompleted(event *m.HistoryEvent) error { - attributes := event.ChildWorkflowExecutionCompletedEventAttributes +func (weh *workflowExecutionEventHandlerImpl) handleChildWorkflowExecutionCompleted(event *apiv1.HistoryEvent) error { + attributes := event.GetChildWorkflowExecutionCompletedEventAttributes() childWorkflowID := attributes.WorkflowExecution.GetWorkflowId() decision := weh.decisionsHelper.handleChildWorkflowExecutionClosed(childWorkflowID) childWorkflow := decision.getData().(*scheduledChildWorkflow) if childWorkflow.handled { return nil } - childWorkflow.handle(attributes.Result, nil) + childWorkflow.handle(attributes.Result.GetData(), nil) return nil } -func (weh *workflowExecutionEventHandlerImpl) handleChildWorkflowExecutionFailed(event *m.HistoryEvent) error { - attributes := event.ChildWorkflowExecutionFailedEventAttributes +func (weh *workflowExecutionEventHandlerImpl) handleChildWorkflowExecutionFailed(event *apiv1.HistoryEvent) error { + attributes := event.GetChildWorkflowExecutionFailedEventAttributes() childWorkflowID := attributes.WorkflowExecution.GetWorkflowId() decision := weh.decisionsHelper.handleChildWorkflowExecutionClosed(childWorkflowID) childWorkflow := decision.getData().(*scheduledChildWorkflow) @@ -1238,28 +1233,28 @@ func (weh *workflowExecutionEventHandlerImpl) handleChildWorkflowExecutionFailed return nil } - err := constructError(attributes.GetReason(), attributes.Details, weh.GetDataConverter()) + err := constructError(attributes.Failure.GetReason(), attributes.Failure.GetDetails(), weh.GetDataConverter()) childWorkflow.handle(nil, err) return nil } -func (weh *workflowExecutionEventHandlerImpl) handleChildWorkflowExecutionCanceled(event *m.HistoryEvent) error { - attributes := event.ChildWorkflowExecutionCanceledEventAttributes +func (weh *workflowExecutionEventHandlerImpl) handleChildWorkflowExecutionCanceled(event *apiv1.HistoryEvent) error { + attributes := event.GetChildWorkflowExecutionCanceledEventAttributes() childWorkflowID := attributes.WorkflowExecution.GetWorkflowId() decision := weh.decisionsHelper.handleChildWorkflowExecutionCanceled(childWorkflowID) childWorkflow := decision.getData().(*scheduledChildWorkflow) if childWorkflow.handled { return nil } - details := newEncodedValues(attributes.Details, weh.GetDataConverter()) + details := newEncodedValues(attributes.Details.GetData(), weh.GetDataConverter()) err := NewCanceledError(details) childWorkflow.handle(nil, err) return nil } -func (weh *workflowExecutionEventHandlerImpl) handleChildWorkflowExecutionTimedOut(event *m.HistoryEvent) error { - attributes := event.ChildWorkflowExecutionTimedOutEventAttributes +func (weh *workflowExecutionEventHandlerImpl) handleChildWorkflowExecutionTimedOut(event *apiv1.HistoryEvent) error { + attributes := event.GetChildWorkflowExecutionTimedOutEventAttributes() childWorkflowID := attributes.WorkflowExecution.GetWorkflowId() decision := weh.decisionsHelper.handleChildWorkflowExecutionClosed(childWorkflowID) childWorkflow := decision.getData().(*scheduledChildWorkflow) @@ -1272,8 +1267,8 @@ func (weh *workflowExecutionEventHandlerImpl) handleChildWorkflowExecutionTimedO return nil } -func (weh *workflowExecutionEventHandlerImpl) handleChildWorkflowExecutionTerminated(event *m.HistoryEvent) error { - attributes := event.ChildWorkflowExecutionTerminatedEventAttributes +func (weh *workflowExecutionEventHandlerImpl) handleChildWorkflowExecutionTerminated(event *apiv1.HistoryEvent) error { + attributes := event.GetChildWorkflowExecutionTerminatedEventAttributes() childWorkflowID := attributes.WorkflowExecution.GetWorkflowId() decision := weh.decisionsHelper.handleChildWorkflowExecutionClosed(childWorkflowID) childWorkflow := decision.getData().(*scheduledChildWorkflow) @@ -1286,24 +1281,24 @@ func (weh *workflowExecutionEventHandlerImpl) handleChildWorkflowExecutionTermin return nil } -func (weh *workflowExecutionEventHandlerImpl) handleUpsertWorkflowSearchAttributes(event *m.HistoryEvent) { - weh.updateWorkflowInfoWithSearchAttributes(event.UpsertWorkflowSearchAttributesEventAttributes.SearchAttributes) +func (weh *workflowExecutionEventHandlerImpl) handleUpsertWorkflowSearchAttributes(event *apiv1.HistoryEvent) { + weh.updateWorkflowInfoWithSearchAttributes(event.GetUpsertWorkflowSearchAttributesEventAttributes().SearchAttributes) } -func (weh *workflowExecutionEventHandlerImpl) handleRequestCancelExternalWorkflowExecutionInitiated(event *m.HistoryEvent) error { +func (weh *workflowExecutionEventHandlerImpl) handleRequestCancelExternalWorkflowExecutionInitiated(event *apiv1.HistoryEvent) error { // For cancellation of child workflow only, we do not use cancellation ID // for cancellation of external workflow, we have to use cancellation ID - attribute := event.RequestCancelExternalWorkflowExecutionInitiatedEventAttributes + attribute := event.GetRequestCancelExternalWorkflowExecutionInitiatedEventAttributes() workflowID := attribute.WorkflowExecution.GetWorkflowId() cancellationID := string(attribute.Control) weh.decisionsHelper.handleRequestCancelExternalWorkflowExecutionInitiated(event.GetEventId(), workflowID, cancellationID) return nil } -func (weh *workflowExecutionEventHandlerImpl) handleExternalWorkflowExecutionCancelRequested(event *m.HistoryEvent) error { +func (weh *workflowExecutionEventHandlerImpl) handleExternalWorkflowExecutionCancelRequested(event *apiv1.HistoryEvent) error { // For cancellation of child workflow only, we do not use cancellation ID // for cancellation of external workflow, we have to use cancellation ID - attributes := event.ExternalWorkflowExecutionCancelRequestedEventAttributes + attributes := event.GetExternalWorkflowExecutionCancelRequestedEventAttributes() workflowID := attributes.WorkflowExecution.GetWorkflowId() isExternal, decision := weh.decisionsHelper.handleExternalWorkflowExecutionCancelRequested(attributes.GetInitiatedEventId(), workflowID) if isExternal { @@ -1318,10 +1313,10 @@ func (weh *workflowExecutionEventHandlerImpl) handleExternalWorkflowExecutionCan return nil } -func (weh *workflowExecutionEventHandlerImpl) handleRequestCancelExternalWorkflowExecutionFailed(event *m.HistoryEvent) error { +func (weh *workflowExecutionEventHandlerImpl) handleRequestCancelExternalWorkflowExecutionFailed(event *apiv1.HistoryEvent) error { // For cancellation of child workflow only, we do not use cancellation ID // for cancellation of external workflow, we have to use cancellation ID - attributes := event.RequestCancelExternalWorkflowExecutionFailedEventAttributes + attributes := event.GetRequestCancelExternalWorkflowExecutionFailedEventAttributes() workflowID := attributes.WorkflowExecution.GetWorkflowId() isExternal, decision := weh.decisionsHelper.handleRequestCancelExternalWorkflowExecutionFailed(attributes.GetInitiatedEventId(), workflowID) if isExternal { @@ -1337,8 +1332,8 @@ func (weh *workflowExecutionEventHandlerImpl) handleRequestCancelExternalWorkflo return nil } -func (weh *workflowExecutionEventHandlerImpl) handleSignalExternalWorkflowExecutionCompleted(event *m.HistoryEvent) error { - attributes := event.ExternalWorkflowExecutionSignaledEventAttributes +func (weh *workflowExecutionEventHandlerImpl) handleSignalExternalWorkflowExecutionCompleted(event *apiv1.HistoryEvent) error { + attributes := event.GetExternalWorkflowExecutionSignaledEventAttributes() decision := weh.decisionsHelper.handleSignalExternalWorkflowExecutionCompleted(attributes.GetInitiatedEventId()) signal := decision.getData().(*scheduledSignal) if signal.handled { @@ -1349,8 +1344,8 @@ func (weh *workflowExecutionEventHandlerImpl) handleSignalExternalWorkflowExecut return nil } -func (weh *workflowExecutionEventHandlerImpl) handleSignalExternalWorkflowExecutionFailed(event *m.HistoryEvent) error { - attributes := event.SignalExternalWorkflowExecutionFailedEventAttributes +func (weh *workflowExecutionEventHandlerImpl) handleSignalExternalWorkflowExecutionFailed(event *apiv1.HistoryEvent) error { + attributes := event.GetSignalExternalWorkflowExecutionFailedEventAttributes() decision := weh.decisionsHelper.handleSignalExternalWorkflowExecutionFailed(attributes.GetInitiatedEventId()) signal := decision.getData().(*scheduledSignal) if signal.handled { @@ -1359,7 +1354,7 @@ func (weh *workflowExecutionEventHandlerImpl) handleSignalExternalWorkflowExecut var err error switch attributes.GetCause() { - case shared.SignalExternalWorkflowExecutionFailedCauseUnknownExternalWorkflowExecution: + case apiv1.SignalExternalWorkflowExecutionFailedCause_SIGNAL_EXTERNAL_WORKFLOW_EXECUTION_FAILED_CAUSE_UNKNOWN_EXTERNAL_WORKFLOW_EXECUTION: err = newUnknownExternalWorkflowExecutionError() default: err = fmt.Errorf("signal external workflow failed, %v", attributes.GetCause()) diff --git a/internal/internal_event_handlers_test.go b/internal/internal_event_handlers_test.go index 8a5dd260a..deaeb1028 100644 --- a/internal/internal_event_handlers_test.go +++ b/internal/internal_event_handlers_test.go @@ -26,7 +26,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - s "go.uber.org/cadence/v1/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" "go.uber.org/zap" "go.uber.org/zap/zapcore" "go.uber.org/zap/zaptest/observer" @@ -157,7 +157,7 @@ func Test_ValidateAndSerializeSearchAttributes(t *testing.T) { require.NoError(t, err) require.Equal(t, 1, len(searchAttr.IndexedFields)) var resp int - json.Unmarshal(searchAttr.IndexedFields["key"], &resp) + json.Unmarshal(searchAttr.IndexedFields["key"].GetData(), &resp) require.Equal(t, 1, resp) } @@ -187,41 +187,41 @@ func Test_MergeSearchAttributes(t *testing.T) { t.Parallel() tests := []struct { name string - current *s.SearchAttributes - upsert *s.SearchAttributes - expected *s.SearchAttributes + current *apiv1.SearchAttributes + upsert *apiv1.SearchAttributes + expected *apiv1.SearchAttributes }{ { name: "currentIsNil", current: nil, - upsert: &s.SearchAttributes{}, + upsert: &apiv1.SearchAttributes{}, expected: nil, }, { name: "currentIsEmpty", - current: &s.SearchAttributes{IndexedFields: make(map[string][]byte)}, - upsert: &s.SearchAttributes{}, + current: &apiv1.SearchAttributes{IndexedFields: make(map[string]*apiv1.Payload)}, + upsert: &apiv1.SearchAttributes{}, expected: nil, }, { name: "normalMerge", - current: &s.SearchAttributes{ - IndexedFields: map[string][]byte{ - "CustomIntField": []byte(`1`), - "CustomKeywordField": []byte(`keyword`), + current: &apiv1.SearchAttributes{ + IndexedFields: map[string]*apiv1.Payload{ + "CustomIntField": {Data: []byte(`1`)}, + "CustomKeywordField": {Data: []byte(`keyword`)}, }, }, - upsert: &s.SearchAttributes{ - IndexedFields: map[string][]byte{ - "CustomIntField": []byte(`2`), - "CustomBoolField": []byte(`true`), + upsert: &apiv1.SearchAttributes{ + IndexedFields: map[string]*apiv1.Payload{ + "CustomIntField": {Data: []byte(`2`)}, + "CustomBoolField": {Data: []byte(`true`)}, }, }, - expected: &s.SearchAttributes{ - IndexedFields: map[string][]byte{ - "CustomIntField": []byte(`2`), - "CustomKeywordField": []byte(`keyword`), - "CustomBoolField": []byte(`true`), + expected: &apiv1.SearchAttributes{ + IndexedFields: map[string]*apiv1.Payload{ + "CustomIntField": {Data: []byte(`2`)}, + "CustomKeywordField": {Data: []byte(`keyword`)}, + "CustomBoolField": {Data: []byte(`true`)}, }, }, }, diff --git a/internal/internal_pressure_points.go b/internal/internal_pressure_points.go index ed460ff6c..826470278 100644 --- a/internal/internal_pressure_points.go +++ b/internal/internal_pressure_points.go @@ -27,7 +27,7 @@ import ( "strconv" "time" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" + "go.uber.org/cadence/v2/internal/api" "go.uber.org/zap" ) @@ -58,7 +58,7 @@ type ( // newWorkflowWorkerWithPressurePoints returns an instance of a workflow worker. func newWorkflowWorkerWithPressurePoints( - service workflowserviceclient.Interface, + service api.Interface, domain string, params workerExecutionParameters, pressurePoints map[string]map[string]string, diff --git a/internal/internal_public.go b/internal/internal_public.go index a4e856cbd..a41b17829 100644 --- a/internal/internal_public.go +++ b/internal/internal_public.go @@ -30,7 +30,7 @@ package internal import ( "time" - s "go.uber.org/cadence/v1/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" ) type ( @@ -39,7 +39,7 @@ type ( // HistoryIterator iterator through history events HistoryIterator interface { // GetNextPage returns next page of history events - GetNextPage() (*s.History, error) + GetNextPage() (*apiv1.History, error) // Reset resets the internal state so next GetNextPage() call will return first page of events from beginning. Reset() // HasNextPage returns if there are more page of events @@ -64,7 +64,7 @@ type ( CompleteDecisionTask(workflowTask *workflowTask, waitLocalActivity bool) interface{} // GetDecisionTimeout returns the TaskStartToCloseTimeout GetDecisionTimeout() time.Duration - GetCurrentDecisionTask() *s.PollForDecisionTaskResponse + GetCurrentDecisionTask() *apiv1.PollForDecisionTaskResponse IsDestroyed() bool StackTrace() string } @@ -89,7 +89,7 @@ type ( // - RespondActivityTaskCompletedRequest // - RespondActivityTaskFailedRequest // - RespondActivityTaskCanceledRequest - Execute(taskList string, task *s.PollForActivityTaskResponse) (interface{}, error) + Execute(taskList string, task *apiv1.PollForActivityTaskResponse) (interface{}, error) } ) diff --git a/internal/internal_retry.go b/internal/internal_retry.go index cec631159..4597f9f5c 100644 --- a/internal/internal_retry.go +++ b/internal/internal_retry.go @@ -26,8 +26,8 @@ import ( "context" "time" - s "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common/backoff" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/internal/common/backoff" ) const ( @@ -64,15 +64,15 @@ func createDynamicServiceRetryPolicy(ctx context.Context) backoff.RetryPolicy { func isServiceTransientError(err error) bool { // Retrying by default so it covers all transport errors. switch err.(type) { - case *s.BadRequestError, - *s.EntityNotExistsError, - *s.WorkflowExecutionAlreadyStartedError, - *s.WorkflowExecutionAlreadyCompletedError, - *s.DomainAlreadyExistsError, - *s.QueryFailedError, - *s.DomainNotActiveError, - *s.CancellationAlreadyRequestedError, - *s.ClientVersionNotSupportedError: + case *api.BadRequestError, + *api.EntityNotExistsError, + *api.WorkflowExecutionAlreadyStartedError, + *api.WorkflowExecutionAlreadyCompletedError, + *api.DomainAlreadyExistsError, + *api.QueryFailedError, + *api.DomainNotActiveError, + *api.CancellationAlreadyRequestedError, + *api.ClientVersionNotSupportedError: return false } diff --git a/internal/internal_task_handlers.go b/internal/internal_task_handlers.go index 97150ad73..bf06ebfa9 100644 --- a/internal/internal_task_handlers.go +++ b/internal/internal_task_handlers.go @@ -36,13 +36,13 @@ import ( "time" "github.com/opentracing/opentracing-go" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" - s "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" - "go.uber.org/cadence/v1/internal/common/backoff" - "go.uber.org/cadence/v1/internal/common/cache" - "go.uber.org/cadence/v1/internal/common/metrics" - "go.uber.org/cadence/v1/internal/common/util" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/internal/common" + "go.uber.org/cadence/v2/internal/common/backoff" + "go.uber.org/cadence/v2/internal/common/cache" + "go.uber.org/cadence/v2/internal/common/metrics" + "go.uber.org/cadence/v2/internal/common/util" "go.uber.org/zap" ) @@ -59,7 +59,7 @@ type ( workflowExecutionEventHandler interface { // Process a single event and return the assosciated decisions. // Return List of decisions made, any error. - ProcessEvent(event *s.HistoryEvent, isReplay bool, isLast bool) error + ProcessEvent(event *apiv1.HistoryEvent, isReplay bool, isLast bool) error // ProcessQuery process a query request. ProcessQuery(queryType string, queryArgs []byte) ([]byte, error) StackTrace() string @@ -69,7 +69,7 @@ type ( // workflowTask wraps a decision task. workflowTask struct { - task *s.PollForDecisionTaskResponse + task *apiv1.PollForDecisionTaskResponse historyIterator HistoryIterator doneCh chan struct{} laResultCh chan *localActivityResult @@ -77,13 +77,13 @@ type ( // activityTask wraps a activity task. activityTask struct { - task *s.PollForActivityTaskResponse + task *apiv1.PollForActivityTaskResponse pollStartTime time.Time } // resetStickinessTask wraps a ResetStickyTaskListRequest. resetStickinessTask struct { - task *s.ResetStickyTaskListRequest + task *apiv1.ResetStickyTaskListRequest } // workflowExecutionContextImpl is the cached workflow state for sticky execution @@ -104,8 +104,8 @@ type ( previousStartedEventID int64 - newDecisions []*s.Decision - currentDecisionTask *s.PollForDecisionTaskResponse + newDecisions []*apiv1.Decision + currentDecisionTask *apiv1.PollForDecisionTaskResponse laTunnel *localActivityTunnel decisionStartTime time.Time } @@ -134,7 +134,7 @@ type ( activityTaskHandlerImpl struct { taskListName string identity string - service workflowserviceclient.Interface + service api.Interface metricsScope *metrics.TaggedScope logger *zap.Logger userContext context.Context @@ -150,11 +150,11 @@ type ( history struct { workflowTask *workflowTask eventsHandler *workflowExecutionEventHandlerImpl - loadedEvents []*s.HistoryEvent + loadedEvents []*apiv1.HistoryEvent currentIndex int nextEventID int64 // next expected eventID for sanity lastEventID int64 // last expected eventID, zero indicates read until end of stream - next []*s.HistoryEvent + next []*apiv1.HistoryEvent binaryChecksum *string } @@ -186,16 +186,16 @@ func (e decisionHeartbeatError) Error() string { } // Get workflow start event. -func (eh *history) GetWorkflowStartedEvent() (*s.HistoryEvent, error) { +func (eh *history) GetWorkflowStartedEvent() (*apiv1.HistoryEvent, error) { events := eh.workflowTask.task.History.Events - if len(events) == 0 || events[0].GetEventType() != s.EventTypeWorkflowExecutionStarted { + if len(events) == 0 || events[0].GetWorkflowExecutionStartedEventAttributes() == nil{ return nil, errors.New("unable to find WorkflowExecutionStartedEventAttributes in the history") } return events[0], nil } -func (eh *history) IsReplayEvent(event *s.HistoryEvent) bool { - return event.GetEventId() <= eh.workflowTask.task.GetPreviousStartedEventId() || isDecisionEvent(event.GetEventType()) +func (eh *history) IsReplayEvent(event *apiv1.HistoryEvent) bool { + return event.GetEventId() <= eh.workflowTask.task.GetPreviousStartedEventId().GetValue() || isDecisionEvent(event) } func (eh *history) IsNextDecisionFailed() (isFailed bool, binaryChecksum *string, err error) { @@ -209,13 +209,16 @@ func (eh *history) IsNextDecisionFailed() (isFailed bool, binaryChecksum *string if nextIndex < len(eh.loadedEvents) { nextEvent := eh.loadedEvents[nextIndex] - nextEventType := nextEvent.GetEventType() - isFailed := nextEventType == s.EventTypeDecisionTaskTimedOut || nextEventType == s.EventTypeDecisionTaskFailed - var binaryChecksum *string - if nextEventType == s.EventTypeDecisionTaskCompleted { - binaryChecksum = nextEvent.DecisionTaskCompletedEventAttributes.BinaryChecksum + isFailed := false + var binaryChecksum string + switch attr := nextEvent.Attributes.(type) { + case *apiv1.HistoryEvent_DecisionTaskTimedOutEventAttributes: + case *apiv1.HistoryEvent_DecisionTaskFailedEventAttributes: + isFailed = true + case *apiv1.HistoryEvent_DecisionTaskCompletedEventAttributes: + binaryChecksum = attr.DecisionTaskCompletedEventAttributes.BinaryChecksum } - return isFailed, binaryChecksum, nil + return isFailed, &binaryChecksum, nil } return false, nil, nil } @@ -232,31 +235,35 @@ func (eh *history) loadMoreEvents() error { return nil } -func isDecisionEvent(eventType s.EventType) bool { - switch eventType { - case s.EventTypeWorkflowExecutionCompleted, - s.EventTypeWorkflowExecutionFailed, - s.EventTypeWorkflowExecutionCanceled, - s.EventTypeWorkflowExecutionContinuedAsNew, - s.EventTypeActivityTaskScheduled, - s.EventTypeActivityTaskCancelRequested, - s.EventTypeTimerStarted, - s.EventTypeTimerCanceled, - s.EventTypeCancelTimerFailed, - s.EventTypeMarkerRecorded, - s.EventTypeStartChildWorkflowExecutionInitiated, - s.EventTypeRequestCancelExternalWorkflowExecutionInitiated, - s.EventTypeSignalExternalWorkflowExecutionInitiated, - s.EventTypeUpsertWorkflowSearchAttributes: +func isDecisionEventAttributes(attr interface{}) bool { + switch attr.(type) { + case *apiv1.HistoryEvent_WorkflowExecutionCompletedEventAttributes, + *apiv1.HistoryEvent_WorkflowExecutionFailedEventAttributes, + *apiv1.HistoryEvent_WorkflowExecutionCanceledEventAttributes, + *apiv1.HistoryEvent_WorkflowExecutionContinuedAsNewEventAttributes, + *apiv1.HistoryEvent_ActivityTaskScheduledEventAttributes, + *apiv1.HistoryEvent_ActivityTaskCancelRequestedEventAttributes, + *apiv1.HistoryEvent_TimerStartedEventAttributes, + *apiv1.HistoryEvent_TimerCanceledEventAttributes, + *apiv1.HistoryEvent_CancelTimerFailedEventAttributes, + *apiv1.HistoryEvent_MarkerRecordedEventAttributes, + *apiv1.HistoryEvent_StartChildWorkflowExecutionInitiatedEventAttributes, + *apiv1.HistoryEvent_RequestCancelExternalWorkflowExecutionInitiatedEventAttributes, + *apiv1.HistoryEvent_SignalExternalWorkflowExecutionInitiatedEventAttributes, + *apiv1.HistoryEvent_UpsertWorkflowSearchAttributesEventAttributes: return true default: return false } } +func isDecisionEvent(event *apiv1.HistoryEvent) bool { + return isDecisionEventAttributes(event.Attributes) +} + // NextDecisionEvents returns events that there processed as new by the next decision. // TODO(maxim): Refactor to return a struct instead of multiple parameters -func (eh *history) NextDecisionEvents() (result []*s.HistoryEvent, markers []*s.HistoryEvent, binaryChecksum *string, err error) { +func (eh *history) NextDecisionEvents() (result []*apiv1.HistoryEvent, markers []*apiv1.HistoryEvent, binaryChecksum *string, err error) { if eh.next == nil { eh.next, _, err = eh.nextDecisionEvents() if err != nil { @@ -281,7 +288,7 @@ func (eh *history) hasMoreEvents() bool { return historyIterator != nil && historyIterator.HasNextPage() } -func (eh *history) getMoreEvents() (*s.History, error) { +func (eh *history) getMoreEvents() (*apiv1.History, error) { return eh.workflowTask.historyIterator.GetNextPage() } @@ -301,12 +308,12 @@ func (eh *history) verifyAllEventsProcessed() error { return nil } -func (eh *history) nextDecisionEvents() (nextEvents []*s.HistoryEvent, markers []*s.HistoryEvent, err error) { +func (eh *history) nextDecisionEvents() (nextEvents []*apiv1.HistoryEvent, markers []*apiv1.HistoryEvent, err error) { if eh.currentIndex == len(eh.loadedEvents) && !eh.hasMoreEvents() { if err := eh.verifyAllEventsProcessed(); err != nil { return nil, nil, err } - return []*s.HistoryEvent{}, []*s.HistoryEvent{}, nil + return []*apiv1.HistoryEvent{}, []*apiv1.HistoryEvent{}, nil } // Process events @@ -337,8 +344,8 @@ OrderEvents: eh.nextEventID++ - switch event.GetEventType() { - case s.EventTypeDecisionTaskStarted: + switch event.Attributes.(type) { + case *apiv1.HistoryEvent_DecisionTaskStartedEventAttributes: isFailed, binaryChecksum, err1 := eh.IsNextDecisionFailed() if err1 != nil { err = err1 @@ -350,9 +357,9 @@ OrderEvents: nextEvents = append(nextEvents, event) break OrderEvents } - case s.EventTypeDecisionTaskScheduled, - s.EventTypeDecisionTaskTimedOut, - s.EventTypeDecisionTaskFailed: + case *apiv1.HistoryEvent_DecisionTaskScheduledEventAttributes: + case *apiv1.HistoryEvent_DecisionTaskTimedOutEventAttributes: + case *apiv1.HistoryEvent_DecisionTaskFailedEventAttributes: // Skip default: if isPreloadMarkerEvent(event) { @@ -370,8 +377,8 @@ OrderEvents: return nextEvents, markers, nil } -func isPreloadMarkerEvent(event *s.HistoryEvent) bool { - return event.GetEventType() == s.EventTypeMarkerRecorded +func isPreloadMarkerEvent(event *apiv1.HistoryEvent) bool { + return event.GetMarkerRecordedEventAttributes() != nil } // newWorkflowTaskHandler returns an implementation of workflow task handler. @@ -539,11 +546,11 @@ func (w *workflowExecutionContextImpl) IsDestroyed() bool { func (w *workflowExecutionContextImpl) queueResetStickinessTask() { var task resetStickinessTask - task.task = &s.ResetStickyTaskListRequest{ - Domain: common.StringPtr(w.workflowInfo.Domain), - Execution: &s.WorkflowExecution{ - WorkflowId: common.StringPtr(w.workflowInfo.WorkflowExecution.ID), - RunId: common.StringPtr(w.workflowInfo.WorkflowExecution.RunID), + task.task = &apiv1.ResetStickyTaskListRequest{ + Domain: w.workflowInfo.Domain, + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: w.workflowInfo.WorkflowExecution.ID, + RunId: w.workflowInfo.WorkflowExecution.RunID, }, } // w.laTunnel could be nil for worker.ReplayHistory() because there is no worker started, in that case we don't @@ -587,7 +594,7 @@ func (w *workflowExecutionContextImpl) createEventHandler() { w.eventHandler.Store(eventHandler) } -func resetHistory(task *s.PollForDecisionTaskResponse, historyIterator HistoryIterator) (*s.History, error) { +func resetHistory(task *apiv1.PollForDecisionTaskResponse, historyIterator HistoryIterator) (*apiv1.History, error) { historyIterator.Reset() firstPageHistory, err := historyIterator.GetNextPage() if err != nil { @@ -597,9 +604,9 @@ func resetHistory(task *s.PollForDecisionTaskResponse, historyIterator HistoryIt return firstPageHistory, nil } -func (wth *workflowTaskHandlerImpl) createWorkflowContext(task *s.PollForDecisionTaskResponse) (*workflowExecutionContextImpl, error) { +func (wth *workflowTaskHandlerImpl) createWorkflowContext(task *apiv1.PollForDecisionTaskResponse) (*workflowExecutionContextImpl, error) { h := task.History - attributes := h.Events[0].WorkflowExecutionStartedEventAttributes + attributes := h.Events[0].GetWorkflowExecutionStartedEventAttributes() if attributes == nil { return nil, errors.New("first history event is not WorkflowExecutionStarted") } @@ -613,10 +620,12 @@ func (wth *workflowTaskHandlerImpl) createWorkflowContext(task *s.PollForDecisio // Setup workflow Info var parentWorkflowExecution *WorkflowExecution - if attributes.ParentWorkflowExecution != nil { + var parentDomain *string + if attributes.ParentExecutionInfo != nil { + parentDomain = &attributes.ParentExecutionInfo.DomainName parentWorkflowExecution = &WorkflowExecution{ - ID: attributes.ParentWorkflowExecution.GetWorkflowId(), - RunID: attributes.ParentWorkflowExecution.GetRunId(), + ID: attributes.ParentExecutionInfo.WorkflowExecution.GetWorkflowId(), + RunID: attributes.ParentExecutionInfo.WorkflowExecution.GetRunId(), } } workflowInfo := &WorkflowInfo{ @@ -624,28 +633,28 @@ func (wth *workflowTaskHandlerImpl) createWorkflowContext(task *s.PollForDecisio ID: workflowID, RunID: runID, }, - WorkflowType: flowWorkflowTypeFrom(*task.WorkflowType), + WorkflowType: WorkflowType{Name: task.WorkflowType.Name}, TaskListName: taskList.GetName(), - ExecutionStartToCloseTimeoutSeconds: attributes.GetExecutionStartToCloseTimeoutSeconds(), - TaskStartToCloseTimeoutSeconds: attributes.GetTaskStartToCloseTimeoutSeconds(), + ExecutionStartToCloseTimeoutSeconds: api.SecondsFromProto(attributes.ExecutionStartToCloseTimeout), + TaskStartToCloseTimeoutSeconds: api.SecondsFromProto(attributes.TaskStartToCloseTimeout), Domain: wth.domain, Attempt: attributes.GetAttempt(), - lastCompletionResult: attributes.LastCompletionResult, - CronSchedule: attributes.CronSchedule, - ContinuedExecutionRunID: attributes.ContinuedExecutionRunId, - ParentWorkflowDomain: attributes.ParentWorkflowDomain, + lastCompletionResult: attributes.LastCompletionResult.GetData(), + CronSchedule: &attributes.CronSchedule, + ContinuedExecutionRunID: &attributes.ContinuedExecutionRunId, + ParentWorkflowDomain: parentDomain, ParentWorkflowExecution: parentWorkflowExecution, Memo: attributes.Memo, SearchAttributes: attributes.SearchAttributes, RetryPolicy: attributes.RetryPolicy, } - wfStartTime := time.Unix(0, h.Events[0].GetTimestamp()) + wfStartTime := api.TimeFromProto(h.Events[0].EventTime) return newWorkflowExecutionContext(wfStartTime, workflowInfo, wth), nil } func (wth *workflowTaskHandlerImpl) getOrCreateWorkflowContext( - task *s.PollForDecisionTaskResponse, + task *apiv1.PollForDecisionTaskResponse, historyIterator HistoryIterator, ) (workflowContext *workflowExecutionContextImpl, err error) { metricsScope := wth.metricsScope.GetTaggedScope(tagWorkflowType, task.WorkflowType.GetName()) @@ -706,14 +715,14 @@ func (wth *workflowTaskHandlerImpl) getOrCreateWorkflowContext( return } -func isFullHistory(history *s.History) bool { - if len(history.Events) == 0 || history.Events[0].GetEventType() != s.EventTypeWorkflowExecutionStarted { +func isFullHistory(history *apiv1.History) bool { + if len(history.Events) == 0 || history.Events[0].GetWorkflowExecutionStartedEventAttributes() == nil { return false } return true } -func (w *workflowExecutionContextImpl) resetStateIfDestroyed(task *s.PollForDecisionTaskResponse, historyIterator HistoryIterator) error { +func (w *workflowExecutionContextImpl) resetStateIfDestroyed(task *apiv1.PollForDecisionTaskResponse, historyIterator HistoryIterator) error { // It is possible that 2 threads (one for decision task and one for query task) that both are getting this same // cached workflowContext. If one task finished with err, it would destroy the cached state. In that case, the // second task needs to reset the cache state and start from beginning of the history. @@ -739,8 +748,8 @@ func (wth *workflowTaskHandlerImpl) ProcessWorkflowTask( } task := workflowTask.task if task.History == nil || len(task.History.Events) == 0 { - task.History = &s.History{ - Events: []*s.HistoryEvent{}, + task.History = &apiv1.History{ + Events: []*apiv1.HistoryEvent{}, } } if task.Query == nil && len(task.History.Events) == 0 { @@ -758,7 +767,7 @@ func (wth *workflowTaskHandlerImpl) ProcessWorkflowTask( zap.String(tagWorkflowType, task.WorkflowType.GetName()), zap.String(tagWorkflowID, workflowID), zap.String(tagRunID, runID), - zap.Int64("PreviousStartedEventId", task.GetPreviousStartedEventId())) + zap.Int64("PreviousStartedEventId", task.GetPreviousStartedEventId().GetValue())) }) workflowContext, err := wth.getOrCreateWorkflowContext(task, workflowTask.historyIterator) @@ -822,11 +831,11 @@ func (w *workflowExecutionContextImpl) ProcessWorkflowTask(workflowTask *workflo eventHandler := w.getEventHandler() reorderedHistory := newHistory(workflowTask, eventHandler) - var replayDecisions []*s.Decision - var respondEvents []*s.HistoryEvent + var replayDecisions []*apiv1.Decision + var respondEvents []*apiv1.HistoryEvent skipReplayCheck := w.skipReplayCheck() - isReplayTest := task.GetPreviousStartedEventId() == replayPreviousStartedEventID + isReplayTest := task.GetPreviousStartedEventId().GetValue() == replayPreviousStartedEventID if isReplayTest { w.wth.logger.Info("Processing workflow task in replay test mode", zap.String(tagWorkflowType, task.WorkflowType.GetName()), @@ -852,7 +861,7 @@ ProcessEvents: } // Markers are from the events that are produced from the current decision for _, m := range markers { - if m.MarkerRecordedEventAttributes.GetMarkerName() != localActivityMarkerName { + if m.GetMarkerRecordedEventAttributes().GetMarkerName() != localActivityMarkerName { // local activity marker needs to be applied after decision task started event err := eventHandler.ProcessEvent(m, true, false) if err != nil { @@ -867,7 +876,7 @@ ProcessEvents: for i, event := range reorderedEvents { isInReplay := reorderedHistory.IsReplayEvent(event) isLast := !isInReplay && i == len(reorderedEvents)-1 - if !skipReplayCheck && isDecisionEvent(event.GetEventType()) { + if !skipReplayCheck && isDecisionEvent(event) { respondEvents = append(respondEvents, event) } @@ -893,7 +902,7 @@ ProcessEvents: // now apply local activity markers for _, m := range markers { - if m.MarkerRecordedEventAttributes.GetMarkerName() == localActivityMarkerName { + if m.GetMarkerRecordedEventAttributes().GetMarkerName() == localActivityMarkerName { err := eventHandler.ProcessEvent(m, true, false) if err != nil { return nil, err @@ -1033,7 +1042,7 @@ func getRetryBackoff(lar *localActivityResult, now time.Time) time.Duration { var errReason string if len(p.NonRetriableErrorReasons) > 0 { if lar.err == ErrDeadlineExceeded { - errReason = "timeout:" + s.TimeoutTypeScheduleToClose.String() + errReason = "timeout: " + timeoutTypeString(apiv1.TimeoutType_TIMEOUT_TYPE_SCHEDULE_TO_START) } else { errReason, _ = getErrorDetails(lar.err, nil) } @@ -1139,7 +1148,7 @@ func (w *workflowExecutionContextImpl) skipReplayCheck() bool { return w.currentDecisionTask.Query != nil || !isFullHistory(w.currentDecisionTask.History) } -func (w *workflowExecutionContextImpl) SetCurrentTask(task *s.PollForDecisionTaskResponse) { +func (w *workflowExecutionContextImpl) SetCurrentTask(task *apiv1.PollForDecisionTaskResponse) { w.currentDecisionTask = task // do not update the previousStartedEventID for query task if task.Query == nil { @@ -1148,7 +1157,7 @@ func (w *workflowExecutionContextImpl) SetCurrentTask(task *s.PollForDecisionTas w.decisionStartTime = time.Now() } -func (w *workflowExecutionContextImpl) ResetIfStale(task *s.PollForDecisionTaskResponse, historyIterator HistoryIterator) error { +func (w *workflowExecutionContextImpl) ResetIfStale(task *apiv1.PollForDecisionTaskResponse, historyIterator HistoryIterator) error { if len(task.History.Events) > 0 && task.History.Events[0].GetEventId() != w.previousStartedEventID+1 { w.wth.logger.Debug("Cached state staled, new task has unexpected events", zap.String(tagWorkflowID, task.WorkflowExecution.GetWorkflowId()), @@ -1156,7 +1165,7 @@ func (w *workflowExecutionContextImpl) ResetIfStale(task *s.PollForDecisionTaskR zap.Int64("CachedPreviousStartedEventID", w.previousStartedEventID), zap.Int64("TaskFirstEventID", task.History.Events[0].GetEventId()), zap.Int64("TaskStartedEventID", task.GetStartedEventId()), - zap.Int64("TaskPreviousStartedEventID", task.GetPreviousStartedEventId())) + zap.Int64("TaskPreviousStartedEventID", task.GetPreviousStartedEventId().GetValue())) w.wth.metricsScope. GetTaggedScope(tagWorkflowType, task.WorkflowType.GetName()). @@ -1172,9 +1181,9 @@ func (w *workflowExecutionContextImpl) GetDecisionTimeout() time.Duration { return time.Second * time.Duration(w.workflowInfo.TaskStartToCloseTimeoutSeconds) } -func skipDeterministicCheckForDecision(d *s.Decision) bool { - if d.GetDecisionType() == s.DecisionTypeRecordMarker { - markerName := d.RecordMarkerDecisionAttributes.GetMarkerName() +func skipDeterministicCheckForDecision(d *apiv1.Decision) bool { + if attr := d.GetRecordMarkerDecisionAttributes(); attr != nil { + markerName := attr.GetMarkerName() if markerName == versionMarkerName || markerName == mutableSideEffectMarkerName { return true } @@ -1182,9 +1191,9 @@ func skipDeterministicCheckForDecision(d *s.Decision) bool { return false } -func skipDeterministicCheckForEvent(e *s.HistoryEvent) bool { - if e.GetEventType() == s.EventTypeMarkerRecorded { - markerName := e.MarkerRecordedEventAttributes.GetMarkerName() +func skipDeterministicCheckForEvent(e *apiv1.HistoryEvent) bool { + if attr := e.GetMarkerRecordedEventAttributes(); attr != nil { + markerName := attr.GetMarkerName() if markerName == versionMarkerName || markerName == mutableSideEffectMarkerName { return true } @@ -1193,27 +1202,27 @@ func skipDeterministicCheckForEvent(e *s.HistoryEvent) bool { } // special check for upsert change version event -func skipDeterministicCheckForUpsertChangeVersion(events []*s.HistoryEvent, idx int) bool { +func skipDeterministicCheckForUpsertChangeVersion(events []*apiv1.HistoryEvent, idx int) bool { e := events[idx] - if e.GetEventType() == s.EventTypeMarkerRecorded && - e.MarkerRecordedEventAttributes.GetMarkerName() == versionMarkerName && + if attr := e.GetMarkerRecordedEventAttributes(); attr != nil && + attr.GetMarkerName() == versionMarkerName && idx < len(events)-1 && - events[idx+1].GetEventType() == s.EventTypeUpsertWorkflowSearchAttributes { - if _, ok := events[idx+1].UpsertWorkflowSearchAttributesEventAttributes.SearchAttributes.IndexedFields[CadenceChangeVersion]; ok { + events[idx+1].GetUpsertWorkflowSearchAttributesEventAttributes() != nil { + if _, ok := events[idx+1].GetUpsertWorkflowSearchAttributesEventAttributes().SearchAttributes.IndexedFields[CadenceChangeVersion]; ok { return true } } return false } -func matchReplayWithHistory(replayDecisions []*s.Decision, historyEvents []*s.HistoryEvent) error { +func matchReplayWithHistory(replayDecisions []*apiv1.Decision, historyEvents []*apiv1.HistoryEvent) error { di := 0 hi := 0 hSize := len(historyEvents) dSize := len(replayDecisions) matchLoop: for hi < hSize || di < dSize { - var e *s.HistoryEvent + var e *apiv1.HistoryEvent if hi < hSize { e = historyEvents[hi] if skipDeterministicCheckForUpsertChangeVersion(historyEvents, hi) { @@ -1226,7 +1235,7 @@ matchLoop: } } - var d *s.Decision + var d *apiv1.Decision if di < dSize { d = replayDecisions[di] if skipDeterministicCheckForDecision(d) { @@ -1263,165 +1272,170 @@ func lastPartOfName(name string) string { return name[lastDotIdx+1:] } -func isDecisionMatchEvent(d *s.Decision, e *s.HistoryEvent, strictMode bool) bool { - switch d.GetDecisionType() { - case s.DecisionTypeScheduleActivityTask: - if e.GetEventType() != s.EventTypeActivityTaskScheduled { +func isDecisionMatchEvent(d *apiv1.Decision, e *apiv1.HistoryEvent, strictMode bool) bool { + switch attr := d.Attributes.(type) { + case *apiv1.Decision_ScheduleActivityTaskDecisionAttributes: + eventAttributes := e.GetActivityTaskScheduledEventAttributes() + if eventAttributes == nil { return false } - eventAttributes := e.ActivityTaskScheduledEventAttributes - decisionAttributes := d.ScheduleActivityTaskDecisionAttributes + decisionAttributes := attr.ScheduleActivityTaskDecisionAttributes if eventAttributes.GetActivityId() != decisionAttributes.GetActivityId() || lastPartOfName(eventAttributes.ActivityType.GetName()) != lastPartOfName(decisionAttributes.ActivityType.GetName()) || (strictMode && eventAttributes.TaskList.GetName() != decisionAttributes.TaskList.GetName()) || - (strictMode && bytes.Compare(eventAttributes.Input, decisionAttributes.Input) != 0) { + (strictMode && bytes.Compare(eventAttributes.Input.GetData(), decisionAttributes.Input.GetData()) != 0) { return false } return true - case s.DecisionTypeRequestCancelActivityTask: - if e.GetEventType() != s.EventTypeActivityTaskCancelRequested { + case *apiv1.Decision_RequestCancelActivityTaskDecisionAttributes: + eventAttributes := e.GetActivityTaskCancelRequestedEventAttributes() + if eventAttributes == nil { return false } - decisionAttributes := d.RequestCancelActivityTaskDecisionAttributes - eventAttributes := e.ActivityTaskCancelRequestedEventAttributes + decisionAttributes := attr.RequestCancelActivityTaskDecisionAttributes + if eventAttributes.GetActivityId() != decisionAttributes.GetActivityId() { return false } return true - case s.DecisionTypeStartTimer: - if e.GetEventType() != s.EventTypeTimerStarted { + case *apiv1.Decision_StartTimerDecisionAttributes: + eventAttributes := e.GetTimerStartedEventAttributes() + if eventAttributes == nil { return false } - eventAttributes := e.TimerStartedEventAttributes - decisionAttributes := d.StartTimerDecisionAttributes + decisionAttributes := attr.StartTimerDecisionAttributes if eventAttributes.GetTimerId() != decisionAttributes.GetTimerId() || - (strictMode && eventAttributes.GetStartToFireTimeoutSeconds() != decisionAttributes.GetStartToFireTimeoutSeconds()) { + (strictMode && api.DurationFromProto(eventAttributes.GetStartToFireTimeout()) != api.DurationFromProto(decisionAttributes.GetStartToFireTimeout())) { return false } return true - case s.DecisionTypeCancelTimer: - if e.GetEventType() != s.EventTypeTimerCanceled && e.GetEventType() != s.EventTypeCancelTimerFailed { - return false - } - decisionAttributes := d.CancelTimerDecisionAttributes - if e.GetEventType() == s.EventTypeTimerCanceled { - eventAttributes := e.TimerCanceledEventAttributes + case *apiv1.Decision_CancelTimerDecisionAttributes: + decisionAttributes := attr.CancelTimerDecisionAttributes + switch eAttr := e.Attributes.(type) { + case *apiv1.HistoryEvent_TimerCanceledEventAttributes: + eventAttributes := eAttr.TimerCanceledEventAttributes if eventAttributes.GetTimerId() != decisionAttributes.GetTimerId() { return false } - } else if e.GetEventType() == s.EventTypeCancelTimerFailed { - eventAttributes := e.CancelTimerFailedEventAttributes + return true + case *apiv1.HistoryEvent_CancelTimerFailedEventAttributes: + eventAttributes := eAttr.CancelTimerFailedEventAttributes if eventAttributes.GetTimerId() != decisionAttributes.GetTimerId() { return false } + return true + default: + return false } - return true - - case s.DecisionTypeCompleteWorkflowExecution: - if e.GetEventType() != s.EventTypeWorkflowExecutionCompleted { + case *apiv1.Decision_CompleteWorkflowExecutionDecisionAttributes: + eventAttributes := e.GetWorkflowExecutionCompletedEventAttributes() + if eventAttributes == nil { return false } if strictMode { - eventAttributes := e.WorkflowExecutionCompletedEventAttributes - decisionAttributes := d.CompleteWorkflowExecutionDecisionAttributes + decisionAttributes := attr.CompleteWorkflowExecutionDecisionAttributes - if bytes.Compare(eventAttributes.Result, decisionAttributes.Result) != 0 { + if bytes.Compare(eventAttributes.Result.GetData(), decisionAttributes.Result.GetData()) != 0 { return false } } return true - case s.DecisionTypeFailWorkflowExecution: - if e.GetEventType() != s.EventTypeWorkflowExecutionFailed { + case *apiv1.Decision_FailWorkflowExecutionDecisionAttributes: + eventAttributes := e.GetWorkflowExecutionFailedEventAttributes() + if eventAttributes == nil { return false } if strictMode { - eventAttributes := e.WorkflowExecutionFailedEventAttributes - decisionAttributes := d.FailWorkflowExecutionDecisionAttributes + decisionAttributes := attr.FailWorkflowExecutionDecisionAttributes - if eventAttributes.GetReason() != decisionAttributes.GetReason() || - bytes.Compare(eventAttributes.Details, decisionAttributes.Details) != 0 { + if eventAttributes.Failure.GetReason() != decisionAttributes.Failure.GetReason() || + bytes.Compare(eventAttributes.Failure.GetDetails(), decisionAttributes.Failure.GetDetails()) != 0 { return false } } return true - case s.DecisionTypeRecordMarker: - if e.GetEventType() != s.EventTypeMarkerRecorded { + case *apiv1.Decision_RecordMarkerDecisionAttributes: + eventAttributes := e.GetMarkerRecordedEventAttributes() + if eventAttributes == nil { return false } - eventAttributes := e.MarkerRecordedEventAttributes - decisionAttributes := d.RecordMarkerDecisionAttributes + + decisionAttributes := attr.RecordMarkerDecisionAttributes if eventAttributes.GetMarkerName() != decisionAttributes.GetMarkerName() { return false } return true - case s.DecisionTypeRequestCancelExternalWorkflowExecution: - if e.GetEventType() != s.EventTypeRequestCancelExternalWorkflowExecutionInitiated { + case *apiv1.Decision_RequestCancelExternalWorkflowExecutionDecisionAttributes: + eventAttributes := e.GetRequestCancelExternalWorkflowExecutionInitiatedEventAttributes() + if eventAttributes == nil { return false } - eventAttributes := e.RequestCancelExternalWorkflowExecutionInitiatedEventAttributes - decisionAttributes := d.RequestCancelExternalWorkflowExecutionDecisionAttributes + + decisionAttributes := attr.RequestCancelExternalWorkflowExecutionDecisionAttributes if checkDomainsInDecisionAndEvent(eventAttributes.GetDomain(), decisionAttributes.GetDomain()) || - eventAttributes.WorkflowExecution.GetWorkflowId() != decisionAttributes.GetWorkflowId() { + eventAttributes.WorkflowExecution.GetWorkflowId() != decisionAttributes.WorkflowExecution.GetWorkflowId() { return false } return true - case s.DecisionTypeSignalExternalWorkflowExecution: - if e.GetEventType() != s.EventTypeSignalExternalWorkflowExecutionInitiated { + case *apiv1.Decision_SignalExternalWorkflowExecutionDecisionAttributes: + eventAttributes := e.GetSignalExternalWorkflowExecutionInitiatedEventAttributes() + if eventAttributes == nil { return false } - eventAttributes := e.SignalExternalWorkflowExecutionInitiatedEventAttributes - decisionAttributes := d.SignalExternalWorkflowExecutionDecisionAttributes + + decisionAttributes := attr.SignalExternalWorkflowExecutionDecisionAttributes if checkDomainsInDecisionAndEvent(eventAttributes.GetDomain(), decisionAttributes.GetDomain()) || eventAttributes.GetSignalName() != decisionAttributes.GetSignalName() || - eventAttributes.WorkflowExecution.GetWorkflowId() != decisionAttributes.Execution.GetWorkflowId() { + eventAttributes.WorkflowExecution.GetWorkflowId() != decisionAttributes.WorkflowExecution.GetWorkflowId() { return false } return true - case s.DecisionTypeCancelWorkflowExecution: - if e.GetEventType() != s.EventTypeWorkflowExecutionCanceled { + case *apiv1.Decision_CancelWorkflowExecutionDecisionAttributes: + eventAttributes := e.GetWorkflowExecutionCanceledEventAttributes() + if eventAttributes == nil { return false } if strictMode { - eventAttributes := e.WorkflowExecutionCanceledEventAttributes - decisionAttributes := d.CancelWorkflowExecutionDecisionAttributes - if bytes.Compare(eventAttributes.Details, decisionAttributes.Details) != 0 { + decisionAttributes := attr.CancelWorkflowExecutionDecisionAttributes + if bytes.Compare(eventAttributes.Details.GetData(), decisionAttributes.Details.GetData()) != 0 { return false } } return true - case s.DecisionTypeContinueAsNewWorkflowExecution: - if e.GetEventType() != s.EventTypeWorkflowExecutionContinuedAsNew { + case *apiv1.Decision_ContinueAsNewWorkflowExecutionDecisionAttributes: + if e.GetWorkflowExecutionContinuedAsNewEventAttributes() == nil { return false } return true - case s.DecisionTypeStartChildWorkflowExecution: - if e.GetEventType() != s.EventTypeStartChildWorkflowExecutionInitiated { + case *apiv1.Decision_StartChildWorkflowExecutionDecisionAttributes: + eventAttributes := e.GetStartChildWorkflowExecutionInitiatedEventAttributes() + if eventAttributes == nil { return false } - eventAttributes := e.StartChildWorkflowExecutionInitiatedEventAttributes - decisionAttributes := d.StartChildWorkflowExecutionDecisionAttributes + + decisionAttributes := attr.StartChildWorkflowExecutionDecisionAttributes if lastPartOfName(eventAttributes.WorkflowType.GetName()) != lastPartOfName(decisionAttributes.WorkflowType.GetName()) || (strictMode && checkDomainsInDecisionAndEvent(eventAttributes.GetDomain(), decisionAttributes.GetDomain())) || (strictMode && eventAttributes.TaskList.GetName() != decisionAttributes.TaskList.GetName()) { @@ -1430,12 +1444,12 @@ func isDecisionMatchEvent(d *s.Decision, e *s.HistoryEvent, strictMode bool) boo return true - case s.DecisionTypeUpsertWorkflowSearchAttributes: - if e.GetEventType() != s.EventTypeUpsertWorkflowSearchAttributes { + case *apiv1.Decision_UpsertWorkflowSearchAttributesDecisionAttributes: + eventAttributes := e.GetUpsertWorkflowSearchAttributesEventAttributes() + if eventAttributes == nil { return false } - eventAttributes := e.UpsertWorkflowSearchAttributesEventAttributes - decisionAttributes := d.UpsertWorkflowSearchAttributesDecisionAttributes + decisionAttributes := attr.UpsertWorkflowSearchAttributesDecisionAttributes if strictMode && !isSearchAttributesMatched(eventAttributes.SearchAttributes, decisionAttributes.SearchAttributes) { return false } @@ -1445,7 +1459,7 @@ func isDecisionMatchEvent(d *s.Decision, e *s.HistoryEvent, strictMode bool) boo return false } -func isSearchAttributesMatched(attrFromEvent, attrFromDecision *s.SearchAttributes) bool { +func isSearchAttributesMatched(attrFromEvent, attrFromDecision *apiv1.SearchAttributes) bool { if attrFromEvent != nil && attrFromDecision != nil { return reflect.DeepEqual(attrFromEvent.IndexedFields, attrFromDecision.IndexedFields) } @@ -1465,14 +1479,14 @@ func checkDomainsInDecisionAndEvent(eventDomainName, decisionDomainName string) func (wth *workflowTaskHandlerImpl) completeWorkflow( eventHandler *workflowExecutionEventHandlerImpl, - task *s.PollForDecisionTaskResponse, + task *apiv1.PollForDecisionTaskResponse, workflowContext *workflowExecutionContextImpl, - decisions []*s.Decision, + decisions []*apiv1.Decision, forceNewDecision bool) interface{} { // for query task if task.Query != nil { - queryCompletedRequest := &s.RespondQueryTaskCompletedRequest{TaskToken: task.TaskToken} + queryCompletedRequest := &apiv1.RespondQueryTaskCompletedRequest{TaskToken: task.TaskToken} if panicErr, ok := workflowContext.err.(*PanicError); ok { // NOTE: this code path should never be executed, we should check for workflowPanicError instead of PanicError wth.logger.Warn("Encountered PanicError in workflow query task", @@ -1482,8 +1496,10 @@ func (wth *workflowTaskHandlerImpl) completeWorkflow( zap.String(tagPanicStack, panicErr.StackTrace()), ) - queryCompletedRequest.CompletedType = common.QueryTaskCompletedTypePtr(s.QueryTaskCompletedTypeFailed) - queryCompletedRequest.ErrorMessage = common.StringPtr("Workflow panic: " + panicErr.Error()) + queryCompletedRequest.Result = &apiv1.WorkflowQueryResult{ + ResultType: apiv1.QueryResultType_QUERY_RESULT_TYPE_FAILED, + ErrorMessage: "Workflow panic: " + panicErr.Error(), + } return queryCompletedRequest } @@ -1495,17 +1511,21 @@ func (wth *workflowTaskHandlerImpl) completeWorkflow( zap.String(tagRunID, task.WorkflowExecution.GetRunId()), zap.String(tagPanicError, workflowPanicErr.Error()), zap.String(tagPanicStack, workflowPanicErr.StackTrace()), - zap.Int64("PreviousStartedEventID", task.GetPreviousStartedEventId()), + zap.Int64("PreviousStartedEventID", task.GetPreviousStartedEventId().GetValue()), ) } - result, err := eventHandler.ProcessQuery(task.Query.GetQueryType(), task.Query.QueryArgs) + result, err := eventHandler.ProcessQuery(task.Query.GetQueryType(), task.Query.QueryArgs.GetData()) if err != nil { - queryCompletedRequest.CompletedType = common.QueryTaskCompletedTypePtr(s.QueryTaskCompletedTypeFailed) - queryCompletedRequest.ErrorMessage = common.StringPtr(err.Error()) + queryCompletedRequest.Result = &apiv1.WorkflowQueryResult{ + ResultType: apiv1.QueryResultType_QUERY_RESULT_TYPE_FAILED, + ErrorMessage: err.Error(), + } } else { - queryCompletedRequest.CompletedType = common.QueryTaskCompletedTypePtr(s.QueryTaskCompletedTypeCompleted) - queryCompletedRequest.QueryResult = result + queryCompletedRequest.Result = &apiv1.WorkflowQueryResult{ + ResultType: apiv1.QueryResultType_QUERY_RESULT_TYPE_ANSWERED, + Answer: &apiv1.Payload{Data: result}, + } } return queryCompletedRequest } @@ -1525,45 +1545,59 @@ func (wth *workflowTaskHandlerImpl) completeWorkflow( } // complete decision task - var closeDecision *s.Decision + var closeDecision *apiv1.Decision if canceledErr, ok := workflowContext.err.(*CanceledError); ok { // Workflow cancelled metricsScope.Counter(metrics.WorkflowCanceledCounter).Inc(1) - closeDecision = createNewDecision(s.DecisionTypeCancelWorkflowExecution) _, details := getErrorDetails(canceledErr, wth.dataConverter) - closeDecision.CancelWorkflowExecutionDecisionAttributes = &s.CancelWorkflowExecutionDecisionAttributes{ - Details: details, + closeDecision = &apiv1.Decision{ + Attributes: &apiv1.Decision_CancelWorkflowExecutionDecisionAttributes{ + CancelWorkflowExecutionDecisionAttributes: &apiv1.CancelWorkflowExecutionDecisionAttributes{ + Details: &apiv1.Payload{Data: details}, + }, + }, } } else if contErr, ok := workflowContext.err.(*ContinueAsNewError); ok { // Continue as new error. metricsScope.Counter(metrics.WorkflowContinueAsNewCounter).Inc(1) - closeDecision = createNewDecision(s.DecisionTypeContinueAsNewWorkflowExecution) - closeDecision.ContinueAsNewWorkflowExecutionDecisionAttributes = &s.ContinueAsNewWorkflowExecutionDecisionAttributes{ - WorkflowType: workflowTypePtr(*contErr.params.workflowType), - Input: contErr.params.input, - TaskList: common.TaskListPtr(s.TaskList{Name: contErr.params.taskListName}), - ExecutionStartToCloseTimeoutSeconds: contErr.params.executionStartToCloseTimeoutSeconds, - TaskStartToCloseTimeoutSeconds: contErr.params.taskStartToCloseTimeoutSeconds, - Header: contErr.params.header, - Memo: workflowContext.workflowInfo.Memo, - SearchAttributes: workflowContext.workflowInfo.SearchAttributes, - RetryPolicy: workflowContext.workflowInfo.RetryPolicy, + closeDecision = &apiv1.Decision{ + Attributes: &apiv1.Decision_ContinueAsNewWorkflowExecutionDecisionAttributes{ + ContinueAsNewWorkflowExecutionDecisionAttributes: &apiv1.ContinueAsNewWorkflowExecutionDecisionAttributes{ + WorkflowType: &apiv1.WorkflowType{Name: contErr.params.workflowType.Name}, + Input: &apiv1.Payload{Data: contErr.params.input}, + TaskList: &apiv1.TaskList{Name: *contErr.params.taskListName}, + ExecutionStartToCloseTimeout: api.SecondsPtrToProto(contErr.params.executionStartToCloseTimeoutSeconds), + TaskStartToCloseTimeout: api.SecondsPtrToProto(contErr.params.taskStartToCloseTimeoutSeconds), + Header: contErr.params.header, + Memo: workflowContext.workflowInfo.Memo, + SearchAttributes: workflowContext.workflowInfo.SearchAttributes, + RetryPolicy: workflowContext.workflowInfo.RetryPolicy, + }, + }, } } else if workflowContext.err != nil { // Workflow failures metricsScope.Counter(metrics.WorkflowFailedCounter).Inc(1) - closeDecision = createNewDecision(s.DecisionTypeFailWorkflowExecution) reason, details := getErrorDetails(workflowContext.err, wth.dataConverter) - closeDecision.FailWorkflowExecutionDecisionAttributes = &s.FailWorkflowExecutionDecisionAttributes{ - Reason: common.StringPtr(reason), - Details: details, + closeDecision = &apiv1.Decision{ + Attributes: &apiv1.Decision_FailWorkflowExecutionDecisionAttributes{ + FailWorkflowExecutionDecisionAttributes: &apiv1.FailWorkflowExecutionDecisionAttributes{ + Failure: &apiv1.Failure{ + Reason: reason, + Details: details, + }, + }, + }, } } else if workflowContext.isWorkflowCompleted { // Workflow completion metricsScope.Counter(metrics.WorkflowCompletedCounter).Inc(1) - closeDecision = createNewDecision(s.DecisionTypeCompleteWorkflowExecution) - closeDecision.CompleteWorkflowExecutionDecisionAttributes = &s.CompleteWorkflowExecutionDecisionAttributes{ - Result: workflowContext.result, + closeDecision = &apiv1.Decision{ + Attributes: &apiv1.Decision_CompleteWorkflowExecutionDecisionAttributes{ + CompleteWorkflowExecutionDecisionAttributes: &apiv1.CompleteWorkflowExecutionDecisionAttributes{ + Result: &apiv1.Payload{Data: workflowContext.result}, + }, + }, } } @@ -1574,58 +1608,57 @@ func (wth *workflowTaskHandlerImpl) completeWorkflow( forceNewDecision = false } - var queryResults map[string]*s.WorkflowQueryResult + var queryResults map[string]*apiv1.WorkflowQueryResult if len(task.Queries) != 0 { - queryResults = make(map[string]*s.WorkflowQueryResult) + queryResults = make(map[string]*apiv1.WorkflowQueryResult) for queryID, query := range task.Queries { - result, err := eventHandler.ProcessQuery(query.GetQueryType(), query.QueryArgs) + result, err := eventHandler.ProcessQuery(query.GetQueryType(), query.QueryArgs.GetData()) if err != nil { - queryResults[queryID] = &s.WorkflowQueryResult{ - ResultType: common.QueryResultTypePtr(s.QueryResultTypeFailed), - ErrorMessage: common.StringPtr(err.Error()), + queryResults[queryID] = &apiv1.WorkflowQueryResult{ + ResultType: apiv1.QueryResultType_QUERY_RESULT_TYPE_FAILED, + ErrorMessage: err.Error(), } } else { - queryResults[queryID] = &s.WorkflowQueryResult{ - ResultType: common.QueryResultTypePtr(s.QueryResultTypeAnswered), - Answer: result, + queryResults[queryID] = &apiv1.WorkflowQueryResult{ + ResultType: apiv1.QueryResultType_QUERY_RESULT_TYPE_ANSWERED, + Answer: &apiv1.Payload{Data: result}, } } } } - return &s.RespondDecisionTaskCompletedRequest{ + return &apiv1.RespondDecisionTaskCompletedRequest{ TaskToken: task.TaskToken, Decisions: decisions, - Identity: common.StringPtr(wth.identity), - ReturnNewDecisionTask: common.BoolPtr(true), - ForceCreateNewDecisionTask: common.BoolPtr(forceNewDecision), - BinaryChecksum: common.StringPtr(getBinaryChecksum()), + Identity: wth.identity, + ReturnNewDecisionTask: true, + ForceCreateNewDecisionTask: forceNewDecision, + BinaryChecksum: getBinaryChecksum(), QueryResults: queryResults, } } -func errorToFailDecisionTask(taskToken []byte, err error, identity string) *s.RespondDecisionTaskFailedRequest { - failedCause := s.DecisionTaskFailedCauseWorkflowWorkerUnhandledFailure +func errorToFailDecisionTask(taskToken []byte, err error, identity string) *apiv1.RespondDecisionTaskFailedRequest { _, details := getErrorDetails(err, nil) - return &s.RespondDecisionTaskFailedRequest{ + return &apiv1.RespondDecisionTaskFailedRequest{ TaskToken: taskToken, - Cause: &failedCause, - Details: details, - Identity: common.StringPtr(identity), - BinaryChecksum: common.StringPtr(getBinaryChecksum()), + Cause: apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_WORKFLOW_WORKER_UNHANDLED_FAILURE, + Details: &apiv1.Payload{Data: details}, + Identity: identity, + BinaryChecksum: getBinaryChecksum(), } } -func (wth *workflowTaskHandlerImpl) executeAnyPressurePoints(event *s.HistoryEvent, isInReplay bool) error { +func (wth *workflowTaskHandlerImpl) executeAnyPressurePoints(event *apiv1.HistoryEvent, isInReplay bool) error { if wth.ppMgr != nil && !reflect.ValueOf(wth.ppMgr).IsNil() && !isInReplay { - switch event.GetEventType() { - case s.EventTypeDecisionTaskStarted: + switch event.Attributes.(type) { + case *apiv1.HistoryEvent_DecisionTaskStartedEventAttributes: return wth.ppMgr.Execute(pressurePointTypeDecisionTaskStartTimeout) - case s.EventTypeActivityTaskScheduled: + case *apiv1.HistoryEvent_ActivityTaskScheduledEventAttributes: return wth.ppMgr.Execute(pressurePointTypeActivityTaskScheduleTimeout) - case s.EventTypeActivityTaskStarted: + case *apiv1.HistoryEvent_ActivityTaskStartedEventAttributes: return wth.ppMgr.Execute(pressurePointTypeActivityTaskStartTimeout) - case s.EventTypeDecisionTaskCompleted: + case *apiv1.HistoryEvent_DecisionTaskCompletedEventAttributes: return wth.ppMgr.Execute(pressurePointTypeDecisionTaskCompleted) } } @@ -1633,7 +1666,7 @@ func (wth *workflowTaskHandlerImpl) executeAnyPressurePoints(event *s.HistoryEve } func newActivityTaskHandler( - service workflowserviceclient.Interface, + service api.Interface, params workerExecutionParameters, registry *registry, ) ActivityTaskHandler { @@ -1641,7 +1674,7 @@ func newActivityTaskHandler( } func newActivityTaskHandlerWithCustomProvider( - service workflowserviceclient.Interface, + service api.Interface, params workerExecutionParameters, registry *registry, activityProvider activityProvider, @@ -1665,7 +1698,7 @@ func newActivityTaskHandlerWithCustomProvider( type cadenceInvoker struct { sync.Mutex identity string - service workflowserviceclient.Interface + service api.Interface taskToken []byte cancelHandler func() heartBeatTimeoutInSec int32 // The heart beat interval configured for this activity. @@ -1786,7 +1819,7 @@ func (i *cadenceInvoker) internalHeartBeat(details []byte) (bool, error) { i.cancelHandler() isActivityCancelled = true - case *s.EntityNotExistsError, *s.WorkflowExecutionAlreadyCompletedError, *s.DomainNotActiveError: + case *api.EntityNotExistsError, *api.WorkflowExecutionAlreadyCompletedError, *api.DomainNotActiveError: // We will pass these through as cancellation for now but something we can change // later when we have setter on cancel handler. i.cancelHandler() @@ -1812,14 +1845,14 @@ func (i *cadenceInvoker) Close(flushBufferedHeartbeat bool) { } } -func (i *cadenceInvoker) GetClient(domain string, options *ClientOptions) Client { - return NewClient(i.service, domain, options) +func (i *cadenceInvoker) SignalWorkflow(ctx context.Context, domain, workflowID, runID, signalName string, signalInput []byte) error { + return signalWorkflow(ctx, i.service, i.identity, domain, workflowID, runID, signalName, signalInput) } func newServiceInvoker( taskToken []byte, identity string, - service workflowserviceclient.Interface, + service api.Interface, cancelHandler func(), heartBeatTimeoutInSec int32, workerStopChannel <-chan struct{}, @@ -1836,7 +1869,7 @@ func newServiceInvoker( } // Execute executes an implementation of the activity. -func (ath *activityTaskHandlerImpl) Execute(taskList string, t *s.PollForActivityTaskResponse) (result interface{}, err error) { +func (ath *activityTaskHandlerImpl) Execute(taskList string, t *apiv1.PollForActivityTaskResponse) (result interface{}, err error) { traceLog(func() { ath.logger.Debug("Processing new activity task", zap.String(tagWorkflowID, t.WorkflowExecution.GetWorkflowId()), @@ -1851,9 +1884,9 @@ func (ath *activityTaskHandlerImpl) Execute(taskList string, t *s.PollForActivit canCtx, cancel := context.WithCancel(rootCtx) defer cancel() - invoker := newServiceInvoker(t.TaskToken, ath.identity, ath.service, cancel, t.GetHeartbeatTimeoutSeconds(), ath.workerStopCh) + invoker := newServiceInvoker(t.TaskToken, ath.identity, ath.service, cancel, api.SecondsFromProto(t.HeartbeatTimeout), ath.workerStopCh) defer func() { - _, activityCompleted := result.(*s.RespondActivityTaskCompletedRequest) + _, activityCompleted := result.(*apiv1.RespondActivityTaskCompletedRequest) invoker.Close(!activityCompleted) // flush buffered heartbeat if activity was not successfully completed. }() @@ -1901,9 +1934,10 @@ func (ath *activityTaskHandlerImpl) Execute(taskList string, t *s.PollForActivit ctx, span := createOpenTracingActivitySpan(ctx, ath.tracer, time.Now(), activityType, t.WorkflowExecution.GetWorkflowId(), t.WorkflowExecution.GetRunId()) defer span.Finish() - if activityImplementation.GetOptions().EnableAutoHeartbeat && t.HeartbeatTimeoutSeconds != nil && *t.HeartbeatTimeoutSeconds > 0 { + heartbeatTimeoutSeconds := api.SecondsFromProto(t.HeartbeatTimeout) + if activityImplementation.GetOptions().EnableAutoHeartbeat && heartbeatTimeoutSeconds > 0 { go func() { - autoHbInterval := time.Duration(*t.HeartbeatTimeoutSeconds) * time.Second / 2 + autoHbInterval := time.Duration(heartbeatTimeoutSeconds) * time.Second / 2 ticker := time.NewTicker(autoHbInterval) defer ticker.Stop() for { @@ -1927,7 +1961,7 @@ func (ath *activityTaskHandlerImpl) Execute(taskList string, t *s.PollForActivit }() } - output, err := activityImplementation.Execute(ctx, t.Input) + output, err := activityImplementation.Execute(ctx, t.Input.GetData()) dlCancelFunc() if <-ctx.Done(); ctx.Err() == context.DeadlineExceeded { @@ -1963,24 +1997,48 @@ func (ath *activityTaskHandlerImpl) getRegisteredActivityNames() (activityNames return } -func createNewDecision(decisionType s.DecisionType) *s.Decision { - return &s.Decision{ - DecisionType: common.DecisionTypePtr(decisionType), +func signalWorkflow( + ctx context.Context, + service api.Interface, + identity string, + domain string, + workflowID string, + runID string, + signalName string, + signalInput []byte, +) error { + request := &apiv1.SignalWorkflowExecutionRequest{ + Domain: domain, + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: workflowID, + RunId: runID, + }, + SignalName: signalName, + SignalInput: &apiv1.Payload{Data: signalInput}, + Identity: identity, } + + return backoff.Retry(ctx, + func() error { + tchCtx, cancel, opt := newChannelContext(ctx) + defer cancel() + _, err := service.SignalWorkflowExecution(tchCtx, request, opt...) + return api.ConvertError(err) + }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) } func recordActivityHeartbeat( ctx context.Context, - service workflowserviceclient.Interface, + service api.Interface, identity string, taskToken, details []byte, ) error { - request := &s.RecordActivityTaskHeartbeatRequest{ + request := &apiv1.RecordActivityTaskHeartbeatRequest{ TaskToken: taskToken, - Details: details, - Identity: common.StringPtr(identity)} + Details: &apiv1.Payload{Data: details}, + Identity: identity} - var heartbeatResponse *s.RecordActivityTaskHeartbeatResponse + var heartbeatResponse *apiv1.RecordActivityTaskHeartbeatResponse heartbeatErr := backoff.Retry(ctx, func() error { tchCtx, cancel, opt := newChannelContext(ctx) @@ -1988,7 +2046,7 @@ func recordActivityHeartbeat( var err error heartbeatResponse, err = service.RecordActivityTaskHeartbeat(tchCtx, request, opt...) - return err + return api.ConvertError(err) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) if heartbeatErr == nil && heartbeatResponse != nil && heartbeatResponse.GetCancelRequested() { @@ -2000,20 +2058,22 @@ func recordActivityHeartbeat( func recordActivityHeartbeatByID( ctx context.Context, - service workflowserviceclient.Interface, + service api.Interface, identity string, domain, workflowID, runID, activityID string, details []byte, ) error { - request := &s.RecordActivityTaskHeartbeatByIDRequest{ - Domain: common.StringPtr(domain), - WorkflowID: common.StringPtr(workflowID), - RunID: common.StringPtr(runID), - ActivityID: common.StringPtr(activityID), - Details: details, - Identity: common.StringPtr(identity)} - - var heartbeatResponse *s.RecordActivityTaskHeartbeatResponse + request := &apiv1.RecordActivityTaskHeartbeatByIDRequest{ + Domain: domain, + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: workflowID, + RunId: runID, + }, + ActivityId: activityID, + Details: &apiv1.Payload{Data: details}, + Identity: identity} + + var heartbeatResponse *apiv1.RecordActivityTaskHeartbeatByIDResponse heartbeatErr := backoff.Retry(ctx, func() error { tchCtx, cancel, opt := newChannelContext(ctx) @@ -2021,7 +2081,7 @@ func recordActivityHeartbeatByID( var err error heartbeatResponse, err = service.RecordActivityTaskHeartbeatByID(tchCtx, request, opt...) - return err + return api.ConvertError(err) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) if heartbeatErr == nil && heartbeatResponse != nil && heartbeatResponse.GetCancelRequested() { diff --git a/internal/internal_task_handlers_interfaces_test.go b/internal/internal_task_handlers_interfaces_test.go index c509c1f6c..0495148d8 100644 --- a/internal/internal_task_handlers_interfaces_test.go +++ b/internal/internal_task_handlers_interfaces_test.go @@ -27,9 +27,8 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/suite" "github.com/uber/tchannel-go/thrift" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowservicetest" - m "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" "golang.org/x/net/context" ) @@ -37,7 +36,7 @@ type ( PollLayerInterfacesTestSuite struct { suite.Suite mockCtrl *gomock.Controller - service *workflowservicetest.MockClient + service *api.MockInterface } ) @@ -49,7 +48,7 @@ func (wth sampleWorkflowTaskHandler) ProcessWorkflowTask( workflowTask *workflowTask, d decisionHeartbeatFunc, ) (interface{}, error) { - return &m.RespondDecisionTaskCompletedRequest{ + return &apiv1.RespondDecisionTaskCompletedRequest{ TaskToken: workflowTask.task.TaskToken, }, nil } @@ -66,19 +65,21 @@ func newSampleActivityTaskHandler() *sampleActivityTaskHandler { return &sampleActivityTaskHandler{} } -func (ath sampleActivityTaskHandler) Execute(taskList string, task *m.PollForActivityTaskResponse) (interface{}, error) { +func (ath sampleActivityTaskHandler) Execute(taskList string, task *apiv1.PollForActivityTaskResponse) (interface{}, error) { activityImplementation := &greeterActivity{} - result, err := activityImplementation.Execute(context.Background(), task.Input) + result, err := activityImplementation.Execute(context.Background(), task.Input.GetData()) if err != nil { reason := err.Error() - return &m.RespondActivityTaskFailedRequest{ + return &apiv1.RespondActivityTaskFailedRequest{ TaskToken: task.TaskToken, - Reason: &reason, + Failure: &apiv1.Failure{ + Reason: reason, + }, }, nil } - return &m.RespondActivityTaskCompletedRequest{ + return &apiv1.RespondActivityTaskCompletedRequest{ TaskToken: task.TaskToken, - Result: result, + Result: &apiv1.Payload{Data: result}, }, nil } @@ -89,7 +90,7 @@ func TestPollLayerInterfacesTestSuite(t *testing.T) { func (s *PollLayerInterfacesTestSuite) SetupTest() { s.mockCtrl = gomock.NewController(s.T()) - s.service = workflowservicetest.NewMockClient(s.mockCtrl) + s.service = api.NewMockInterface(s.mockCtrl) } func (s *PollLayerInterfacesTestSuite) TearDownTest() { @@ -101,16 +102,16 @@ func (s *PollLayerInterfacesTestSuite) TestProcessWorkflowTaskInterface() { defer cancel() // mocks - s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any()).Return(&m.PollForDecisionTaskResponse{}, nil) + s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any()).Return(&apiv1.PollForDecisionTaskResponse{}, nil) s.service.EXPECT().RespondDecisionTaskCompleted(gomock.Any(), gomock.Any()).Return(nil, nil) - response, err := s.service.PollForDecisionTask(ctx, &m.PollForDecisionTaskRequest{}) + response, err := s.service.PollForDecisionTask(ctx, &apiv1.PollForDecisionTaskRequest{}) s.NoError(err) // Process task and respond to the service. taskHandler := newSampleWorkflowTaskHandler() request, err := taskHandler.ProcessWorkflowTask(&workflowTask{task: response}, nil) - completionRequest := request.(*m.RespondDecisionTaskCompletedRequest) + completionRequest := request.(*apiv1.RespondDecisionTaskCompletedRequest) s.NoError(err) _, err = s.service.RespondDecisionTaskCompleted(ctx, completionRequest) @@ -122,10 +123,10 @@ func (s *PollLayerInterfacesTestSuite) TestProcessActivityTaskInterface() { defer cancel() // mocks - s.service.EXPECT().PollForActivityTask(gomock.Any(), gomock.Any()).Return(&m.PollForActivityTaskResponse{}, nil) - s.service.EXPECT().RespondActivityTaskCompleted(gomock.Any(), gomock.Any()).Return(nil) + s.service.EXPECT().PollForActivityTask(gomock.Any(), gomock.Any()).Return(&apiv1.PollForActivityTaskResponse{}, nil) + s.service.EXPECT().RespondActivityTaskCompleted(gomock.Any(), gomock.Any()).Return(nil, nil) - response, err := s.service.PollForActivityTask(ctx, &m.PollForActivityTaskRequest{}) + response, err := s.service.PollForActivityTask(ctx, &apiv1.PollForActivityTaskRequest{}) s.NoError(err) // Execute activity task and respond to the service. @@ -133,11 +134,11 @@ func (s *PollLayerInterfacesTestSuite) TestProcessActivityTaskInterface() { request, err := taskHandler.Execute(tasklist, response) s.NoError(err) switch request.(type) { - case *m.RespondActivityTaskCompletedRequest: - err = s.service.RespondActivityTaskCompleted(ctx, request.(*m.RespondActivityTaskCompletedRequest)) + case *apiv1.RespondActivityTaskCompletedRequest: + _, err = s.service.RespondActivityTaskCompleted(ctx, request.(*apiv1.RespondActivityTaskCompletedRequest)) s.NoError(err) - case *m.RespondActivityTaskFailedRequest: // shouldn't happen - err = s.service.RespondActivityTaskFailed(ctx, request.(*m.RespondActivityTaskFailedRequest)) + case *apiv1.RespondActivityTaskFailedRequest: // shouldn't happen + _, err = s.service.RespondActivityTaskFailed(ctx, request.(*apiv1.RespondActivityTaskFailedRequest)) s.NoError(err) } } @@ -145,26 +146,30 @@ func (s *PollLayerInterfacesTestSuite) TestProcessActivityTaskInterface() { func (s *PollLayerInterfacesTestSuite) TestGetNextDecisions() { // Schedule an activity and see if we complete workflow. taskList := "tl1" - testEvents := []*m.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &m.WorkflowExecutionStartedEventAttributes{TaskList: &m.TaskList{Name: &taskList}}), - createTestEventDecisionTaskScheduled(2, &m.DecisionTaskScheduledEventAttributes{TaskList: &m.TaskList{Name: &taskList}}), + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(3), { - EventId: common.Int64Ptr(4), - EventType: common.EventTypePtr(m.EventTypeDecisionTaskFailed), + EventId: 4, + Attributes: &apiv1.HistoryEvent_DecisionTaskFailedEventAttributes{ + DecisionTaskFailedEventAttributes: &apiv1.DecisionTaskFailedEventAttributes{}, + }, }, { - EventId: common.Int64Ptr(5), - EventType: common.EventTypePtr(m.EventTypeWorkflowExecutionSignaled), + EventId: 5, + Attributes: &apiv1.HistoryEvent_WorkflowExecutionSignaledEventAttributes{ + WorkflowExecutionSignaledEventAttributes: &apiv1.WorkflowExecutionSignaledEventAttributes{}, + }, }, - createTestEventDecisionTaskScheduled(6, &m.DecisionTaskScheduledEventAttributes{TaskList: &m.TaskList{Name: &taskList}}), + createTestEventDecisionTaskScheduled(6, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(7), } task := createWorkflowTask(testEvents[0:3], 0, "HelloWorld_Workflow") historyIterator := &historyIteratorImpl{ - iteratorFunc: func(nextToken []byte) (*m.History, []byte, error) { - return &m.History{ + iteratorFunc: func(nextToken []byte) (*apiv1.History, []byte, error) { + return &apiv1.History{ Events: testEvents[3:], }, nil, nil }, @@ -179,7 +184,7 @@ func (s *PollLayerInterfacesTestSuite) TestGetNextDecisions() { s.NoError(err) s.Equal(3, len(events)) - s.Equal(m.EventTypeWorkflowExecutionSignaled, events[1].GetEventType()) - s.Equal(m.EventTypeDecisionTaskStarted, events[2].GetEventType()) + s.NotNil(events[1].GetWorkflowExecutionSignaledEventAttributes()) + s.NotNil(events[2].GetDecisionTaskStartedEventAttributes()) s.Equal(int64(7), events[2].GetEventId()) } diff --git a/internal/internal_task_handlers_test.go b/internal/internal_task_handlers_test.go index fdaa89239..2b2c037a8 100644 --- a/internal/internal_task_handlers_test.go +++ b/internal/internal_task_handlers_test.go @@ -31,15 +31,15 @@ import ( "testing" "time" + "github.com/gogo/protobuf/types" "github.com/opentracing/opentracing-go" "github.com/pborman/uuid" "github.com/stretchr/testify/suite" "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowservicetest" - s "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" "go.uber.org/zap" ) @@ -51,7 +51,7 @@ type ( TaskHandlersTestSuite struct { suite.Suite logger *zap.Logger - service *workflowservicetest.MockClient + service *api.MockInterface registry *registry } ) @@ -128,185 +128,196 @@ func TestTaskHandlersTestSuite(t *testing.T) { }) } -func createTestEventWorkflowExecutionCompleted(eventID int64, attr *s.WorkflowExecutionCompletedEventAttributes) *s.HistoryEvent { - return &s.HistoryEvent{EventId: common.Int64Ptr(eventID), EventType: common.EventTypePtr(s.EventTypeWorkflowExecutionCompleted), WorkflowExecutionCompletedEventAttributes: attr} +func createTestEventWorkflowExecutionCompleted(eventID int64, attr *apiv1.WorkflowExecutionCompletedEventAttributes) *apiv1.HistoryEvent { + return &apiv1.HistoryEvent{ + EventId: eventID, + Attributes: &apiv1.HistoryEvent_WorkflowExecutionCompletedEventAttributes{WorkflowExecutionCompletedEventAttributes: attr}, + } } -func createTestEventWorkflowExecutionContinuedAsNew(eventID int64, attr *s.WorkflowExecutionContinuedAsNewEventAttributes) *s.HistoryEvent { - return &s.HistoryEvent{EventId: common.Int64Ptr(eventID), EventType: common.EventTypePtr(s.EventTypeWorkflowExecutionContinuedAsNew), WorkflowExecutionContinuedAsNewEventAttributes: attr} +func createTestEventWorkflowExecutionContinuedAsNew(eventID int64, attr *apiv1.WorkflowExecutionContinuedAsNewEventAttributes) *apiv1.HistoryEvent { + return &apiv1.HistoryEvent{ + EventId: eventID, + Attributes: &apiv1.HistoryEvent_WorkflowExecutionContinuedAsNewEventAttributes{WorkflowExecutionContinuedAsNewEventAttributes: attr}, + } } -func createTestEventWorkflowExecutionStarted(eventID int64, attr *s.WorkflowExecutionStartedEventAttributes) *s.HistoryEvent { - return &s.HistoryEvent{EventId: common.Int64Ptr(eventID), EventType: common.EventTypePtr(s.EventTypeWorkflowExecutionStarted), WorkflowExecutionStartedEventAttributes: attr} +func createTestEventWorkflowExecutionStarted(eventID int64, attr *apiv1.WorkflowExecutionStartedEventAttributes) *apiv1.HistoryEvent { + return &apiv1.HistoryEvent{ + EventId: eventID, + Attributes: &apiv1.HistoryEvent_WorkflowExecutionStartedEventAttributes{WorkflowExecutionStartedEventAttributes: attr}, + } } -func createTestEventLocalActivity(eventID int64, attr *s.MarkerRecordedEventAttributes) *s.HistoryEvent { - return &s.HistoryEvent{ - EventId: common.Int64Ptr(eventID), - EventType: common.EventTypePtr(s.EventTypeMarkerRecorded), - MarkerRecordedEventAttributes: attr} +func createTestEventLocalActivity(eventID int64, attr *apiv1.MarkerRecordedEventAttributes) *apiv1.HistoryEvent { + return &apiv1.HistoryEvent{ + EventId: eventID, + Attributes: &apiv1.HistoryEvent_MarkerRecordedEventAttributes{MarkerRecordedEventAttributes: attr}, + } } -func createTestEventActivityTaskScheduled(eventID int64, attr *s.ActivityTaskScheduledEventAttributes) *s.HistoryEvent { - return &s.HistoryEvent{ - EventId: common.Int64Ptr(eventID), - EventType: common.EventTypePtr(s.EventTypeActivityTaskScheduled), - ActivityTaskScheduledEventAttributes: attr} +func createTestEventActivityTaskScheduled(eventID int64, attr *apiv1.ActivityTaskScheduledEventAttributes) *apiv1.HistoryEvent { + return &apiv1.HistoryEvent{ + EventId: eventID, + Attributes: &apiv1.HistoryEvent_ActivityTaskScheduledEventAttributes{ActivityTaskScheduledEventAttributes: attr}, + } } -func createTestEventActivityTaskStarted(eventID int64, attr *s.ActivityTaskStartedEventAttributes) *s.HistoryEvent { - return &s.HistoryEvent{ - EventId: common.Int64Ptr(eventID), - EventType: common.EventTypePtr(s.EventTypeActivityTaskStarted), - ActivityTaskStartedEventAttributes: attr} +func createTestEventActivityTaskStarted(eventID int64, attr *apiv1.ActivityTaskStartedEventAttributes) *apiv1.HistoryEvent { + return &apiv1.HistoryEvent{ + EventId: eventID, + Attributes: &apiv1.HistoryEvent_ActivityTaskStartedEventAttributes{ActivityTaskStartedEventAttributes: attr}, + } } -func createTestEventActivityTaskCompleted(eventID int64, attr *s.ActivityTaskCompletedEventAttributes) *s.HistoryEvent { - return &s.HistoryEvent{ - EventId: common.Int64Ptr(eventID), - EventType: common.EventTypePtr(s.EventTypeActivityTaskCompleted), - ActivityTaskCompletedEventAttributes: attr} +func createTestEventActivityTaskCompleted(eventID int64, attr *apiv1.ActivityTaskCompletedEventAttributes) *apiv1.HistoryEvent { + return &apiv1.HistoryEvent{ + EventId: eventID, + Attributes: &apiv1.HistoryEvent_ActivityTaskCompletedEventAttributes{ActivityTaskCompletedEventAttributes: attr}, + } } -func createTestEventActivityTaskTimedOut(eventID int64, attr *s.ActivityTaskTimedOutEventAttributes) *s.HistoryEvent { - return &s.HistoryEvent{ - EventId: common.Int64Ptr(eventID), - EventType: common.EventTypePtr(s.EventTypeActivityTaskTimedOut), - ActivityTaskTimedOutEventAttributes: attr} +func createTestEventActivityTaskTimedOut(eventID int64, attr *apiv1.ActivityTaskTimedOutEventAttributes) *apiv1.HistoryEvent { + return &apiv1.HistoryEvent{ + EventId: eventID, + Attributes: &apiv1.HistoryEvent_ActivityTaskTimedOutEventAttributes{ActivityTaskTimedOutEventAttributes: attr}, + } } -func createTestEventDecisionTaskScheduled(eventID int64, attr *s.DecisionTaskScheduledEventAttributes) *s.HistoryEvent { - return &s.HistoryEvent{ - EventId: common.Int64Ptr(eventID), - EventType: common.EventTypePtr(s.EventTypeDecisionTaskScheduled), - DecisionTaskScheduledEventAttributes: attr} +func createTestEventDecisionTaskScheduled(eventID int64, attr *apiv1.DecisionTaskScheduledEventAttributes) *apiv1.HistoryEvent { + return &apiv1.HistoryEvent{ + EventId: eventID, + Attributes: &apiv1.HistoryEvent_DecisionTaskScheduledEventAttributes{DecisionTaskScheduledEventAttributes: attr}, + } } -func createTestEventDecisionTaskStarted(eventID int64) *s.HistoryEvent { - return &s.HistoryEvent{ - EventId: common.Int64Ptr(eventID), - EventType: common.EventTypePtr(s.EventTypeDecisionTaskStarted)} +func createTestEventDecisionTaskStarted(eventID int64) *apiv1.HistoryEvent { + return &apiv1.HistoryEvent{ + EventId: eventID, + Attributes: &apiv1.HistoryEvent_DecisionTaskStartedEventAttributes{ + DecisionTaskStartedEventAttributes: &apiv1.DecisionTaskStartedEventAttributes{}, + }, + } } -func createTestEventWorkflowExecutionSignaled(eventID int64, signalName string) *s.HistoryEvent { +func createTestEventWorkflowExecutionSignaled(eventID int64, signalName string) *apiv1.HistoryEvent { return createTestEventWorkflowExecutionSignaledWithPayload(eventID, signalName, nil) } -func createTestEventWorkflowExecutionSignaledWithPayload(eventID int64, signalName string, payload []byte) *s.HistoryEvent { - return &s.HistoryEvent{ - EventId: common.Int64Ptr(eventID), - EventType: common.EventTypePtr(s.EventTypeWorkflowExecutionSignaled), - WorkflowExecutionSignaledEventAttributes: &s.WorkflowExecutionSignaledEventAttributes{ - SignalName: common.StringPtr(signalName), - Input: payload, - Identity: common.StringPtr("test-identity"), +func createTestEventWorkflowExecutionSignaledWithPayload(eventID int64, signalName string, payload []byte) *apiv1.HistoryEvent { + return &apiv1.HistoryEvent{ + EventId: eventID, + Attributes: &apiv1.HistoryEvent_WorkflowExecutionSignaledEventAttributes{ + WorkflowExecutionSignaledEventAttributes: &apiv1.WorkflowExecutionSignaledEventAttributes{ + SignalName: signalName, + Input: &apiv1.Payload{Data: payload}, + Identity: "test-identity", + }, }, } } -func createTestEventDecisionTaskCompleted(eventID int64, attr *s.DecisionTaskCompletedEventAttributes) *s.HistoryEvent { - return &s.HistoryEvent{ - EventId: common.Int64Ptr(eventID), - EventType: common.EventTypePtr(s.EventTypeDecisionTaskCompleted), - DecisionTaskCompletedEventAttributes: attr} +func createTestEventDecisionTaskCompleted(eventID int64, attr *apiv1.DecisionTaskCompletedEventAttributes) *apiv1.HistoryEvent { + return &apiv1.HistoryEvent{ + EventId: eventID, + Attributes: &apiv1.HistoryEvent_DecisionTaskCompletedEventAttributes{DecisionTaskCompletedEventAttributes: attr}, + } } -func createTestEventDecisionTaskFailed(eventID int64, attr *s.DecisionTaskFailedEventAttributes) *s.HistoryEvent { - return &s.HistoryEvent{ - EventId: common.Int64Ptr(eventID), - EventType: common.EventTypePtr(s.EventTypeDecisionTaskFailed), - DecisionTaskFailedEventAttributes: attr} +func createTestEventDecisionTaskFailed(eventID int64, attr *apiv1.DecisionTaskFailedEventAttributes) *apiv1.HistoryEvent { + return &apiv1.HistoryEvent{ + EventId: eventID, + Attributes: &apiv1.HistoryEvent_DecisionTaskFailedEventAttributes{DecisionTaskFailedEventAttributes: attr}, + } } -func createTestEventSignalExternalWorkflowExecutionFailed(eventID int64, attr *s.SignalExternalWorkflowExecutionFailedEventAttributes) *s.HistoryEvent { - return &s.HistoryEvent{ - EventId: common.Int64Ptr(eventID), - EventType: common.EventTypePtr(s.EventTypeSignalExternalWorkflowExecutionFailed), - SignalExternalWorkflowExecutionFailedEventAttributes: attr, +func createTestEventSignalExternalWorkflowExecutionFailed(eventID int64, attr *apiv1.SignalExternalWorkflowExecutionFailedEventAttributes) *apiv1.HistoryEvent { + return &apiv1.HistoryEvent{ + EventId: eventID, + Attributes: &apiv1.HistoryEvent_SignalExternalWorkflowExecutionFailedEventAttributes{SignalExternalWorkflowExecutionFailedEventAttributes: attr}, } } func createWorkflowTask( - events []*s.HistoryEvent, + events []*apiv1.HistoryEvent, previousStartEventID int64, workflowName string, -) *s.PollForDecisionTaskResponse { +) *apiv1.PollForDecisionTaskResponse { return createWorkflowTaskWithQueries(events, previousStartEventID, workflowName, nil) } func createWorkflowTaskWithQueries( - events []*s.HistoryEvent, + events []*apiv1.HistoryEvent, previousStartEventID int64, workflowName string, - queries map[string]*s.WorkflowQuery, -) *s.PollForDecisionTaskResponse { - eventsCopy := make([]*s.HistoryEvent, len(events)) + queries map[string]*apiv1.WorkflowQuery, +) *apiv1.PollForDecisionTaskResponse { + eventsCopy := make([]*apiv1.HistoryEvent, len(events)) copy(eventsCopy, events) - return &s.PollForDecisionTaskResponse{ - PreviousStartedEventId: common.Int64Ptr(previousStartEventID), - WorkflowType: workflowTypePtr(WorkflowType{workflowName}), - History: &s.History{Events: eventsCopy}, - WorkflowExecution: &s.WorkflowExecution{ - WorkflowId: common.StringPtr("fake-workflow-id"), - RunId: common.StringPtr(uuid.New()), + return &apiv1.PollForDecisionTaskResponse{ + PreviousStartedEventId: &types.Int64Value{Value: previousStartEventID}, + WorkflowType: &apiv1.WorkflowType{Name: workflowName}, + History: &apiv1.History{Events: eventsCopy}, + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: "fake-workflow-id", + RunId: uuid.New(), }, Queries: queries, } } func createQueryTask( - events []*s.HistoryEvent, + events []*apiv1.HistoryEvent, previousStartEventID int64, workflowName string, queryType string, -) *s.PollForDecisionTaskResponse { +) *apiv1.PollForDecisionTaskResponse { task := createWorkflowTask(events, previousStartEventID, workflowName) - task.Query = &s.WorkflowQuery{ - QueryType: common.StringPtr(queryType), + task.Query = &apiv1.WorkflowQuery{ + QueryType: queryType, } return task } -func createTestEventTimerStarted(eventID int64, id int) *s.HistoryEvent { +func createTestEventTimerStarted(eventID int64, id int) *apiv1.HistoryEvent { timerID := fmt.Sprintf("%v", id) - attr := &s.TimerStartedEventAttributes{ - TimerId: common.StringPtr(timerID), - StartToFireTimeoutSeconds: nil, - DecisionTaskCompletedEventId: nil, + attr := &apiv1.TimerStartedEventAttributes{ + TimerId: timerID, + StartToFireTimeout: nil, + DecisionTaskCompletedEventId: 0, + } + return &apiv1.HistoryEvent{ + EventId: eventID, + Attributes: &apiv1.HistoryEvent_TimerStartedEventAttributes{TimerStartedEventAttributes: attr}, } - return &s.HistoryEvent{ - EventId: common.Int64Ptr(eventID), - EventType: common.EventTypePtr(s.EventTypeTimerStarted), - TimerStartedEventAttributes: attr} } -func createTestEventTimerFired(eventID int64, id int) *s.HistoryEvent { +func createTestEventTimerFired(eventID int64, id int) *apiv1.HistoryEvent { timerID := fmt.Sprintf("%v", id) - attr := &s.TimerFiredEventAttributes{ - TimerId: common.StringPtr(timerID), + attr := &apiv1.TimerFiredEventAttributes{ + TimerId: timerID, } - return &s.HistoryEvent{ - EventId: common.Int64Ptr(eventID), - EventType: common.EventTypePtr(s.EventTypeTimerFired), - TimerFiredEventAttributes: attr} + return &apiv1.HistoryEvent{ + EventId: eventID, + Attributes: &apiv1.HistoryEvent_TimerFiredEventAttributes{TimerFiredEventAttributes: attr}, + } } var testWorkflowTaskTasklist = "tl1" func (t *TaskHandlersTestSuite) testWorkflowTaskWorkflowExecutionStartedHelper(params workerExecutionParameters) { - testEvents := []*s.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &s.WorkflowExecutionStartedEventAttributes{TaskList: &s.TaskList{Name: &testWorkflowTaskTasklist}}), + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{TaskList: &apiv1.TaskList{Name: testWorkflowTaskTasklist}}), } task := createWorkflowTask(testEvents, 0, "HelloWorld_Workflow") taskHandler := newWorkflowTaskHandler(testDomain, params, nil, t.registry) request, err := taskHandler.ProcessWorkflowTask(&workflowTask{task: task}, nil) - response := request.(*s.RespondDecisionTaskCompletedRequest) + response := request.(*apiv1.RespondDecisionTaskCompletedRequest) t.NoError(err) t.NotNil(response) t.Equal(1, len(response.Decisions)) - t.Equal(s.DecisionTypeScheduleActivityTask, response.Decisions[0].GetDecisionType()) - t.NotNil(response.Decisions[0].ScheduleActivityTaskDecisionAttributes) + t.NotNil(response.Decisions[0].GetScheduleActivityTaskDecisionAttributes()) } func (t *TaskHandlersTestSuite) TestWorkflowTask_WorkflowExecutionStarted() { @@ -332,21 +343,21 @@ func (t *TaskHandlersTestSuite) TestWorkflowTask_BinaryChecksum() { taskList := "tl1" checksum1 := "chck1" checksum2 := "chck2" - testEvents := []*s.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &s.WorkflowExecutionStartedEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), - createTestEventDecisionTaskScheduled(2, &s.DecisionTaskScheduledEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskCompleted(4, &s.DecisionTaskCompletedEventAttributes{ - ScheduledEventId: common.Int64Ptr(2), BinaryChecksum: common.StringPtr(checksum1)}), + createTestEventDecisionTaskCompleted(4, &apiv1.DecisionTaskCompletedEventAttributes{ + ScheduledEventId: 2, BinaryChecksum: checksum1}), createTestEventTimerStarted(5, 0), createTestEventTimerFired(6, 0), - createTestEventDecisionTaskScheduled(7, &s.DecisionTaskScheduledEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), + createTestEventDecisionTaskScheduled(7, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(8), - createTestEventDecisionTaskCompleted(9, &s.DecisionTaskCompletedEventAttributes{ - ScheduledEventId: common.Int64Ptr(7), BinaryChecksum: common.StringPtr(checksum2)}), + createTestEventDecisionTaskCompleted(9, &apiv1.DecisionTaskCompletedEventAttributes{ + ScheduledEventId: 7, BinaryChecksum: checksum2}), createTestEventTimerStarted(10, 1), createTestEventTimerFired(11, 1), - createTestEventDecisionTaskScheduled(12, &s.DecisionTaskScheduledEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), + createTestEventDecisionTaskScheduled(12, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(13), } task := createWorkflowTask(testEvents, 8, "BinaryChecksumWorkflow") @@ -357,13 +368,13 @@ func (t *TaskHandlersTestSuite) TestWorkflowTask_BinaryChecksum() { } taskHandler := newWorkflowTaskHandler(testDomain, params, nil, t.registry) request, err := taskHandler.ProcessWorkflowTask(&workflowTask{task: task}, nil) - response := request.(*s.RespondDecisionTaskCompletedRequest) + response := request.(*apiv1.RespondDecisionTaskCompletedRequest) t.NoError(err) t.NotNil(response) t.Equal(1, len(response.Decisions)) - t.Equal(s.DecisionTypeCompleteWorkflowExecution, response.Decisions[0].GetDecisionType()) - checksumsBytes := response.Decisions[0].CompleteWorkflowExecutionDecisionAttributes.Result + t.NotNil(response.Decisions[0].GetCompleteWorkflowExecutionDecisionAttributes()) + checksumsBytes := response.Decisions[0].GetCompleteWorkflowExecutionDecisionAttributes().Result.GetData() var checksums []string json.Unmarshal(checksumsBytes, &checksums) t.Equal(3, len(checksums)) @@ -375,18 +386,18 @@ func (t *TaskHandlersTestSuite) TestWorkflowTask_BinaryChecksum() { func (t *TaskHandlersTestSuite) TestWorkflowTask_ActivityTaskScheduled() { // Schedule an activity and see if we complete workflow. taskList := "tl1" - testEvents := []*s.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &s.WorkflowExecutionStartedEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), - createTestEventDecisionTaskScheduled(2, &s.DecisionTaskScheduledEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskCompleted(4, &s.DecisionTaskCompletedEventAttributes{ScheduledEventId: common.Int64Ptr(2)}), - createTestEventActivityTaskScheduled(5, &s.ActivityTaskScheduledEventAttributes{ - ActivityId: common.StringPtr("0"), - ActivityType: &s.ActivityType{Name: common.StringPtr("Greeter_Activity")}, - TaskList: &s.TaskList{Name: &taskList}, + createTestEventDecisionTaskCompleted(4, &apiv1.DecisionTaskCompletedEventAttributes{ScheduledEventId: 2}), + createTestEventActivityTaskScheduled(5, &apiv1.ActivityTaskScheduledEventAttributes{ + ActivityId: "0", + ActivityType: &apiv1.ActivityType{Name: "Greeter_Activity"}, + TaskList: &apiv1.TaskList{Name: taskList}, }), - createTestEventActivityTaskStarted(6, &s.ActivityTaskStartedEventAttributes{}), - createTestEventActivityTaskCompleted(7, &s.ActivityTaskCompletedEventAttributes{ScheduledEventId: common.Int64Ptr(5)}), + createTestEventActivityTaskStarted(6, &apiv1.ActivityTaskStartedEventAttributes{}), + createTestEventActivityTaskCompleted(7, &apiv1.ActivityTaskCompletedEventAttributes{ScheduledEventId: 5}), createTestEventDecisionTaskStarted(8), } task := createWorkflowTask(testEvents[0:3], 0, "HelloWorld_Workflow") @@ -397,44 +408,42 @@ func (t *TaskHandlersTestSuite) TestWorkflowTask_ActivityTaskScheduled() { } taskHandler := newWorkflowTaskHandler(testDomain, params, nil, t.registry) request, err := taskHandler.ProcessWorkflowTask(&workflowTask{task: task}, nil) - response := request.(*s.RespondDecisionTaskCompletedRequest) + response := request.(*apiv1.RespondDecisionTaskCompletedRequest) t.NoError(err) t.NotNil(response) t.Equal(1, len(response.Decisions)) - t.Equal(s.DecisionTypeScheduleActivityTask, response.Decisions[0].GetDecisionType()) - t.NotNil(response.Decisions[0].ScheduleActivityTaskDecisionAttributes) + t.NotNil(response.Decisions[0].GetScheduleActivityTaskDecisionAttributes()) // Schedule an activity and see if we complete workflow, Having only one last decision. task = createWorkflowTask(testEvents, 3, "HelloWorld_Workflow") request, err = taskHandler.ProcessWorkflowTask(&workflowTask{task: task}, nil) - response = request.(*s.RespondDecisionTaskCompletedRequest) + response = request.(*apiv1.RespondDecisionTaskCompletedRequest) t.NoError(err) t.NotNil(response) t.Equal(1, len(response.Decisions)) - t.Equal(s.DecisionTypeCompleteWorkflowExecution, response.Decisions[0].GetDecisionType()) - t.NotNil(response.Decisions[0].CompleteWorkflowExecutionDecisionAttributes) + t.NotNil(response.Decisions[0].GetCompleteWorkflowExecutionDecisionAttributes()) } func (t *TaskHandlersTestSuite) TestWorkflowTask_QueryWorkflow_Sticky() { // Schedule an activity and see if we complete workflow. taskList := "sticky-tl" - execution := &s.WorkflowExecution{ - WorkflowId: common.StringPtr("fake-workflow-id"), - RunId: common.StringPtr(uuid.New()), + execution := &apiv1.WorkflowExecution{ + WorkflowId: "fake-workflow-id", + RunId: uuid.New(), } - testEvents := []*s.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &s.WorkflowExecutionStartedEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), - createTestEventDecisionTaskScheduled(2, &s.DecisionTaskScheduledEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskCompleted(4, &s.DecisionTaskCompletedEventAttributes{ScheduledEventId: common.Int64Ptr(2)}), - createTestEventActivityTaskScheduled(5, &s.ActivityTaskScheduledEventAttributes{ - ActivityId: common.StringPtr("0"), - ActivityType: &s.ActivityType{Name: common.StringPtr("Greeter_Activity")}, - TaskList: &s.TaskList{Name: &taskList}, + createTestEventDecisionTaskCompleted(4, &apiv1.DecisionTaskCompletedEventAttributes{ScheduledEventId: 2}), + createTestEventActivityTaskScheduled(5, &apiv1.ActivityTaskScheduledEventAttributes{ + ActivityId: "0", + ActivityType: &apiv1.ActivityType{Name: "Greeter_Activity"}, + TaskList: &apiv1.TaskList{Name: taskList}, }), - createTestEventActivityTaskStarted(6, &s.ActivityTaskStartedEventAttributes{}), - createTestEventActivityTaskCompleted(7, &s.ActivityTaskCompletedEventAttributes{ScheduledEventId: common.Int64Ptr(5)}), + createTestEventActivityTaskStarted(6, &apiv1.ActivityTaskStartedEventAttributes{}), + createTestEventActivityTaskCompleted(7, &apiv1.ActivityTaskCompletedEventAttributes{ScheduledEventId: 5}), } params := workerExecutionParameters{ TaskList: taskList, @@ -445,18 +454,17 @@ func (t *TaskHandlersTestSuite) TestWorkflowTask_QueryWorkflow_Sticky() { // first make progress on the workflow task := createWorkflowTask(testEvents[0:1], 0, "HelloWorld_Workflow") - task.StartedEventId = common.Int64Ptr(1) + task.StartedEventId = 1 task.WorkflowExecution = execution request, err := taskHandler.ProcessWorkflowTask(&workflowTask{task: task}, nil) - response := request.(*s.RespondDecisionTaskCompletedRequest) + response := request.(*apiv1.RespondDecisionTaskCompletedRequest) t.NoError(err) t.NotNil(response) t.Equal(1, len(response.Decisions)) - t.Equal(s.DecisionTypeScheduleActivityTask, response.Decisions[0].GetDecisionType()) - t.NotNil(response.Decisions[0].ScheduleActivityTaskDecisionAttributes) + t.NotNil(response.Decisions[0].GetScheduleActivityTaskDecisionAttributes()) // then check the current state using query task - task = createQueryTask([]*s.HistoryEvent{}, 6, "HelloWorld_Workflow", queryType) + task = createQueryTask([]*apiv1.HistoryEvent{}, 6, "HelloWorld_Workflow", queryType) task.WorkflowExecution = execution queryResp, err := taskHandler.ProcessWorkflowTask(&workflowTask{task: task}, nil) t.NoError(err) @@ -466,18 +474,18 @@ func (t *TaskHandlersTestSuite) TestWorkflowTask_QueryWorkflow_Sticky() { func (t *TaskHandlersTestSuite) TestWorkflowTask_QueryWorkflow_NonSticky() { // Schedule an activity and see if we complete workflow. taskList := "tl1" - testEvents := []*s.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &s.WorkflowExecutionStartedEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), - createTestEventDecisionTaskScheduled(2, &s.DecisionTaskScheduledEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskCompleted(4, &s.DecisionTaskCompletedEventAttributes{ScheduledEventId: common.Int64Ptr(2)}), - createTestEventActivityTaskScheduled(5, &s.ActivityTaskScheduledEventAttributes{ - ActivityId: common.StringPtr("0"), - ActivityType: &s.ActivityType{Name: common.StringPtr("Greeter_Activity")}, - TaskList: &s.TaskList{Name: &taskList}, + createTestEventDecisionTaskCompleted(4, &apiv1.DecisionTaskCompletedEventAttributes{ScheduledEventId: 2}), + createTestEventActivityTaskScheduled(5, &apiv1.ActivityTaskScheduledEventAttributes{ + ActivityId: "0", + ActivityType: &apiv1.ActivityType{Name: "Greeter_Activity"}, + TaskList: &apiv1.TaskList{Name: taskList}, }), - createTestEventActivityTaskStarted(6, &s.ActivityTaskStartedEventAttributes{}), - createTestEventActivityTaskCompleted(7, &s.ActivityTaskCompletedEventAttributes{ScheduledEventId: common.Int64Ptr(5)}), + createTestEventActivityTaskStarted(6, &apiv1.ActivityTaskStartedEventAttributes{}), + createTestEventActivityTaskCompleted(7, &apiv1.ActivityTaskCompletedEventAttributes{ScheduledEventId: 5}), createTestEventDecisionTaskStarted(8), createTestEventWorkflowExecutionSignaled(9, "test-signal"), } @@ -518,19 +526,19 @@ func (t *TaskHandlersTestSuite) TestWorkflowTask_QueryWorkflow_NonSticky() { taskHandler = newWorkflowTaskHandler(testDomain, params, nil, t.registry) response, _ = taskHandler.ProcessWorkflowTask(&workflowTask{task: task}, nil) t.NotNil(response) - queryResp, ok := response.(*s.RespondQueryTaskCompletedRequest) + queryResp, ok := response.(*apiv1.RespondQueryTaskCompletedRequest) t.True(ok) - t.NotNil(queryResp.ErrorMessage) - t.Contains(*queryResp.ErrorMessage, "unknown queryType") + t.NotNil(queryResp.Result.ErrorMessage) + t.Contains(queryResp.Result.ErrorMessage, "unknown queryType") } func (t *TaskHandlersTestSuite) verifyQueryResult(response interface{}, expectedResult string) { t.NotNil(response) - queryResp, ok := response.(*s.RespondQueryTaskCompletedRequest) + queryResp, ok := response.(*apiv1.RespondQueryTaskCompletedRequest) t.True(ok) - t.Nil(queryResp.ErrorMessage) - t.NotNil(queryResp.QueryResult) - encodedValue := newEncodedValue(queryResp.QueryResult, nil) + t.Empty(queryResp.Result.ErrorMessage) + t.NotNil(queryResp.Result.Answer) + encodedValue := newEncodedValue(queryResp.Result.Answer.GetData(), nil) var queryResult string err := encodedValue.Get(&queryResult) t.NoError(err) @@ -539,15 +547,15 @@ func (t *TaskHandlersTestSuite) verifyQueryResult(response interface{}, expected func (t *TaskHandlersTestSuite) TestCacheEvictionWhenErrorOccurs() { taskList := "taskList" - testEvents := []*s.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &s.WorkflowExecutionStartedEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), - createTestEventDecisionTaskScheduled(2, &s.DecisionTaskScheduledEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskCompleted(4, &s.DecisionTaskCompletedEventAttributes{ScheduledEventId: common.Int64Ptr(2)}), - createTestEventActivityTaskScheduled(5, &s.ActivityTaskScheduledEventAttributes{ - ActivityId: common.StringPtr("0"), - ActivityType: &s.ActivityType{Name: common.StringPtr("pkg.Greeter_Activity")}, - TaskList: &s.TaskList{Name: &taskList}, + createTestEventDecisionTaskCompleted(4, &apiv1.DecisionTaskCompletedEventAttributes{ScheduledEventId: 2}), + createTestEventActivityTaskScheduled(5, &apiv1.ActivityTaskScheduledEventAttributes{ + ActivityId: "0", + ActivityType: &apiv1.ActivityType{Name: "pkg.Greeter_Activity"}, + TaskList: &apiv1.TaskList{Name: taskList}, }), } params := workerExecutionParameters{ @@ -559,7 +567,7 @@ func (t *TaskHandlersTestSuite) TestCacheEvictionWhenErrorOccurs() { taskHandler := newWorkflowTaskHandler(testDomain, params, nil, t.registry) // now change the history event so it does not match to decision produced via replay - testEvents[4].ActivityTaskScheduledEventAttributes.ActivityType.Name = common.StringPtr("some-other-activity") + testEvents[4].GetActivityTaskScheduledEventAttributes().ActivityType.Name = "some-other-activity" task := createWorkflowTask(testEvents, 3, "HelloWorld_Workflow") // newWorkflowTaskWorkerInternal will set the laTunnel in taskHandler, without it, ProcessWorkflowTask() // will fail as it can't find laTunnel in getWorkflowCache(). @@ -576,12 +584,12 @@ func (t *TaskHandlersTestSuite) TestCacheEvictionWhenErrorOccurs() { func (t *TaskHandlersTestSuite) TestWithMissingHistoryEvents() { taskList := "taskList" - testEvents := []*s.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &s.WorkflowExecutionStartedEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), - createTestEventDecisionTaskScheduled(2, &s.DecisionTaskScheduledEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskCompleted(4, &s.DecisionTaskCompletedEventAttributes{ScheduledEventId: common.Int64Ptr(2)}), - createTestEventDecisionTaskScheduled(6, &s.DecisionTaskScheduledEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), + createTestEventDecisionTaskCompleted(4, &apiv1.DecisionTaskCompletedEventAttributes{ScheduledEventId: 2}), + createTestEventDecisionTaskScheduled(6, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(7), } params := workerExecutionParameters{ @@ -610,18 +618,18 @@ func (t *TaskHandlersTestSuite) TestWithMissingHistoryEvents() { func (t *TaskHandlersTestSuite) TestWithTruncatedHistory() { taskList := "taskList" - testEvents := []*s.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &s.WorkflowExecutionStartedEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), - createTestEventDecisionTaskScheduled(2, &s.DecisionTaskScheduledEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskFailed(4, &s.DecisionTaskFailedEventAttributes{ScheduledEventId: common.Int64Ptr(2)}), - createTestEventDecisionTaskScheduled(5, &s.DecisionTaskScheduledEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), + createTestEventDecisionTaskFailed(4, &apiv1.DecisionTaskFailedEventAttributes{ScheduledEventId: 2}), + createTestEventDecisionTaskScheduled(5, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(6), - createTestEventDecisionTaskCompleted(7, &s.DecisionTaskCompletedEventAttributes{ScheduledEventId: common.Int64Ptr(5)}), - createTestEventActivityTaskScheduled(8, &s.ActivityTaskScheduledEventAttributes{ - ActivityId: common.StringPtr("0"), - ActivityType: &s.ActivityType{Name: common.StringPtr("pkg.Greeter_Activity")}, - TaskList: &s.TaskList{Name: &taskList}, + createTestEventDecisionTaskCompleted(7, &apiv1.DecisionTaskCompletedEventAttributes{ScheduledEventId: 5}), + createTestEventActivityTaskScheduled(8, &apiv1.ActivityTaskScheduledEventAttributes{ + ActivityId: "0", + ActivityType: &apiv1.ActivityType{Name: "pkg.Greeter_Activity"}, + TaskList: &apiv1.TaskList{Name: taskList}, }), } params := workerExecutionParameters{ @@ -644,7 +652,7 @@ func (t *TaskHandlersTestSuite) TestWithTruncatedHistory() { for i, tc := range testCases { taskHandler := newWorkflowTaskHandler(testDomain, params, nil, t.registry) task := createWorkflowTask(testEvents, tc.previousStartedEventID, "HelloWorld_Workflow") - task.StartedEventId = common.Int64Ptr(tc.startedEventID) + task.StartedEventId = tc.startedEventID // newWorkflowTaskWorkerInternal will set the laTunnel in taskHandler, without it, ProcessWorkflowTask() // will fail as it can't find laTunnel in getWorkflowCache(). newWorkflowTaskWorkerInternal(taskHandler, t.service, testDomain, params, make(chan struct{}), nil) @@ -693,9 +701,9 @@ func (t *TaskHandlersTestSuite) testSideEffectDeferHelper(disableSticky bool) { ) taskList := "taskList" - testEvents := []*s.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &s.WorkflowExecutionStartedEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), - createTestEventDecisionTaskScheduled(2, &s.DecisionTaskScheduledEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(3), } @@ -728,15 +736,15 @@ func (t *TaskHandlersTestSuite) testSideEffectDeferHelper(disableSticky bool) { func (t *TaskHandlersTestSuite) TestWorkflowTask_NondeterministicDetection() { taskList := "taskList" - testEvents := []*s.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &s.WorkflowExecutionStartedEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), - createTestEventDecisionTaskScheduled(2, &s.DecisionTaskScheduledEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskCompleted(4, &s.DecisionTaskCompletedEventAttributes{ScheduledEventId: common.Int64Ptr(2)}), - createTestEventActivityTaskScheduled(5, &s.ActivityTaskScheduledEventAttributes{ - ActivityId: common.StringPtr("0"), - ActivityType: &s.ActivityType{Name: common.StringPtr("pkg.Greeter_Activity")}, - TaskList: &s.TaskList{Name: &taskList}, + createTestEventDecisionTaskCompleted(4, &apiv1.DecisionTaskCompletedEventAttributes{ScheduledEventId: 2}), + createTestEventActivityTaskScheduled(5, &apiv1.ActivityTaskScheduledEventAttributes{ + ActivityId: "0", + ActivityType: &apiv1.ActivityType{Name: "pkg.Greeter_Activity"}, + TaskList: &apiv1.TaskList{Name: taskList}, }), } task := createWorkflowTask(testEvents, 3, "HelloWorld_Workflow") @@ -751,13 +759,13 @@ func (t *TaskHandlersTestSuite) TestWorkflowTask_NondeterministicDetection() { taskHandler := newWorkflowTaskHandler(testDomain, params, nil, t.registry) request, err := taskHandler.ProcessWorkflowTask(&workflowTask{task: task}, nil) - response := request.(*s.RespondDecisionTaskCompletedRequest) + response := request.(*apiv1.RespondDecisionTaskCompletedRequest) // there should be no error as the history events matched the decisions. t.NoError(err) t.NotNil(response) // now change the history event so it does not match to decision produced via replay - testEvents[4].ActivityTaskScheduledEventAttributes.ActivityType.Name = common.StringPtr("some-other-activity") + testEvents[4].GetActivityTaskScheduledEventAttributes().ActivityType.Name = "some-other-activity" task = createWorkflowTask(testEvents, 3, "HelloWorld_Workflow") // newWorkflowTaskWorkerInternal will set the laTunnel in taskHandler, without it, ProcessWorkflowTask() // will fail as it can't find laTunnel in getWorkflowCache(). @@ -777,18 +785,18 @@ func (t *TaskHandlersTestSuite) TestWorkflowTask_NondeterministicDetection() { // because it will indicate non determinism in the request. t.NoError(err) // Verify that request is a RespondDecisionTaskCompleteRequest - response, ok := request.(*s.RespondDecisionTaskCompletedRequest) + response, ok := request.(*apiv1.RespondDecisionTaskCompletedRequest) t.True(ok) // Verify there's at least 1 decision // and the last last decision is to fail workflow // and contains proper justification.(i.e. nondeterminism). t.True(len(response.Decisions) > 0) closeDecision := response.Decisions[len(response.Decisions)-1] - t.Equal(*closeDecision.DecisionType, s.DecisionTypeFailWorkflowExecution) - t.Contains(*closeDecision.FailWorkflowExecutionDecisionAttributes.Reason, "NonDeterministicWorkflowPolicyFailWorkflow") + t.NotNil(closeDecision.GetFailWorkflowExecutionDecisionAttributes()) + t.Contains(closeDecision.GetFailWorkflowExecutionDecisionAttributes().Failure.GetReason(), "NonDeterministicWorkflowPolicyFailWorkflow") // now with different package name to activity type - testEvents[4].ActivityTaskScheduledEventAttributes.ActivityType.Name = common.StringPtr("new-package.Greeter_Activity") + testEvents[4].GetActivityTaskScheduledEventAttributes().ActivityType.Name = "new-package.Greeter_Activity" task = createWorkflowTask(testEvents, 3, "HelloWorld_Workflow") request, err = taskHandler.ProcessWorkflowTask(&workflowTask{task: task}, nil) t.NoError(err) @@ -797,9 +805,9 @@ func (t *TaskHandlersTestSuite) TestWorkflowTask_NondeterministicDetection() { func (t *TaskHandlersTestSuite) TestWorkflowTask_WorkflowReturnsPanicError() { taskList := "taskList" - testEvents := []*s.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &s.WorkflowExecutionStartedEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), - createTestEventDecisionTaskScheduled(2, &s.DecisionTaskScheduledEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(3), } task := createWorkflowTask(testEvents, 3, "ReturnPanicWorkflow") @@ -814,20 +822,20 @@ func (t *TaskHandlersTestSuite) TestWorkflowTask_WorkflowReturnsPanicError() { request, err := taskHandler.ProcessWorkflowTask(&workflowTask{task: task}, nil) t.NoError(err) t.NotNil(request) - r, ok := request.(*s.RespondDecisionTaskCompletedRequest) + r, ok := request.(*apiv1.RespondDecisionTaskCompletedRequest) t.True(ok) - t.EqualValues(s.DecisionTypeFailWorkflowExecution, r.Decisions[0].GetDecisionType()) - attr := r.Decisions[0].FailWorkflowExecutionDecisionAttributes - t.EqualValues("cadenceInternal:Panic", attr.GetReason()) - details := string(attr.Details) + t.NotNil(r.Decisions[0].GetFailWorkflowExecutionDecisionAttributes()) + attr := r.Decisions[0].GetFailWorkflowExecutionDecisionAttributes() + t.EqualValues("cadenceInternal:Panic", attr.Failure.GetReason()) + details := string(attr.Failure.GetDetails()) t.True(strings.HasPrefix(details, "\"panicError"), details) } func (t *TaskHandlersTestSuite) TestWorkflowTask_WorkflowPanics() { taskList := "taskList" - testEvents := []*s.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &s.WorkflowExecutionStartedEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), - createTestEventDecisionTaskScheduled(2, &s.DecisionTaskScheduledEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(3), } task := createWorkflowTask(testEvents, 3, "PanicWorkflow") @@ -842,10 +850,10 @@ func (t *TaskHandlersTestSuite) TestWorkflowTask_WorkflowPanics() { request, err := taskHandler.ProcessWorkflowTask(&workflowTask{task: task}, nil) t.NoError(err) t.NotNil(request) - r, ok := request.(*s.RespondDecisionTaskFailedRequest) + r, ok := request.(*apiv1.RespondDecisionTaskFailedRequest) t.True(ok) - t.EqualValues("WORKFLOW_WORKER_UNHANDLED_FAILURE", r.Cause.String()) - t.EqualValues("panicError", string(r.Details)) + t.EqualValues(apiv1.DecisionTaskFailedCause_DECISION_TASK_FAILED_CAUSE_WORKFLOW_WORKER_UNHANDLED_FAILURE, r.Cause) + t.EqualValues("panicError", string(r.Details.GetData())) } func (t *TaskHandlersTestSuite) TestGetWorkflowInfo() { @@ -854,9 +862,9 @@ func (t *TaskHandlersTestSuite) TestGetWorkflowInfo() { parentRunID := "parentRun" cronSchedule := "5 4 * * *" continuedRunID := uuid.New() - parentExecution := &s.WorkflowExecution{ - WorkflowId: &parentID, - RunId: &parentRunID, + parentExecution := &apiv1.WorkflowExecution{ + WorkflowId: parentID, + RunId: parentRunID, } parentDomain := "parentDomain" var attempt int32 = 123 @@ -865,28 +873,30 @@ func (t *TaskHandlersTestSuite) TestGetWorkflowInfo() { workflowType := "GetWorkflowInfoWorkflow" lastCompletionResult, err := getDefaultDataConverter().ToData("lastCompletionData") t.NoError(err) - retryPolicy := &s.RetryPolicy{ - InitialIntervalInSeconds: common.Int32Ptr(1), - BackoffCoefficient: common.Float64Ptr(1.0), - MaximumIntervalInSeconds: common.Int32Ptr(1), - MaximumAttempts: common.Int32Ptr(3), - } - startedEventAttributes := &s.WorkflowExecutionStartedEventAttributes{ - Input: lastCompletionResult, - TaskList: &s.TaskList{Name: &taskList}, - ParentWorkflowExecution: parentExecution, - CronSchedule: &cronSchedule, - ContinuedExecutionRunId: &continuedRunID, - ParentWorkflowDomain: &parentDomain, - Attempt: &attempt, - ExecutionStartToCloseTimeoutSeconds: &executionTimeout, - TaskStartToCloseTimeoutSeconds: &taskTimeout, - LastCompletionResult: lastCompletionResult, - RetryPolicy: retryPolicy, - } - testEvents := []*s.HistoryEvent{ + retryPolicy := &apiv1.RetryPolicy{ + InitialInterval: api.DurationToProto(time.Second * 1), + BackoffCoefficient: 1.0, + MaximumInterval: api.DurationToProto(time.Second * 1), + MaximumAttempts: 3, + } + startedEventAttributes := &apiv1.WorkflowExecutionStartedEventAttributes{ + Input: &apiv1.Payload{Data: lastCompletionResult}, + TaskList: &apiv1.TaskList{Name: taskList}, + ParentExecutionInfo: &apiv1.ParentExecutionInfo{ + DomainName: parentDomain, + WorkflowExecution: parentExecution, + }, + CronSchedule: cronSchedule, + ContinuedExecutionRunId: continuedRunID, + Attempt: attempt, + ExecutionStartToCloseTimeout: api.SecondsToProto(executionTimeout), + TaskStartToCloseTimeout: api.SecondsToProto(taskTimeout), + LastCompletionResult: &apiv1.Payload{Data: lastCompletionResult}, + RetryPolicy: retryPolicy, + } + testEvents := []*apiv1.HistoryEvent{ createTestEventWorkflowExecutionStarted(1, startedEventAttributes), - createTestEventDecisionTaskScheduled(2, &s.DecisionTaskScheduledEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(3), } task := createWorkflowTask(testEvents, 3, workflowType) @@ -901,12 +911,12 @@ func (t *TaskHandlersTestSuite) TestGetWorkflowInfo() { request, err := taskHandler.ProcessWorkflowTask(&workflowTask{task: task}, nil) t.NoError(err) t.NotNil(request) - r, ok := request.(*s.RespondDecisionTaskCompletedRequest) + r, ok := request.(*apiv1.RespondDecisionTaskCompletedRequest) t.True(ok) - t.EqualValues(s.DecisionTypeCompleteWorkflowExecution, r.Decisions[0].GetDecisionType()) - attr := r.Decisions[0].CompleteWorkflowExecutionDecisionAttributes + t.NotNil(r.Decisions[0].GetCompleteWorkflowExecutionDecisionAttributes()) + attr := r.Decisions[0].GetCompleteWorkflowExecutionDecisionAttributes() var result WorkflowInfo - t.NoError(getDefaultDataConverter().FromData(attr.Result, &result)) + t.NoError(getDefaultDataConverter().FromData(attr.Result.GetData(), &result)) t.EqualValues(taskList, result.TaskListName) t.EqualValues(parentID, result.ParentWorkflowExecution.ID) t.EqualValues(parentRunID, result.ParentWorkflowExecution.RunID) @@ -932,8 +942,8 @@ func (t *TaskHandlersTestSuite) TestConsistentQuery_InvalidQueryTask() { taskHandler := newWorkflowTaskHandler(testDomain, params, nil, t.registry) task := createWorkflowTask(nil, 3, "HelloWorld_Workflow") - task.Query = &s.WorkflowQuery{} - task.Queries = map[string]*s.WorkflowQuery{"query_id": {}} + task.Query = &apiv1.WorkflowQuery{} + task.Queries = map[string]*apiv1.WorkflowQuery{"query_id": {}} newWorkflowTaskWorkerInternal(taskHandler, t.service, testDomain, params, make(chan struct{}), nil) // query and queries are both specified so this is an invalid task request, err := taskHandler.ProcessWorkflowTask(&workflowTask{task: task}, nil) @@ -953,23 +963,23 @@ func (t *TaskHandlersTestSuite) TestConsistentQuery_Success() { t.NoError(err) signal, err := getDefaultDataConverter().ToData("signal data") t.NoError(err) - testEvents := []*s.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &s.WorkflowExecutionStartedEventAttributes{ - TaskList: &s.TaskList{Name: &taskList}, - Input: numberOfSignalsToComplete, + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{ + TaskList: &apiv1.TaskList{Name: taskList}, + Input: &apiv1.Payload{Data: numberOfSignalsToComplete}, }), - createTestEventDecisionTaskScheduled(2, &s.DecisionTaskScheduledEventAttributes{}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskCompleted(4, &s.DecisionTaskCompletedEventAttributes{ - ScheduledEventId: common.Int64Ptr(2), BinaryChecksum: common.StringPtr(checksum1)}), + createTestEventDecisionTaskCompleted(4, &apiv1.DecisionTaskCompletedEventAttributes{ + ScheduledEventId: 2, BinaryChecksum: checksum1}), createTestEventWorkflowExecutionSignaledWithPayload(5, signalCh, signal), - createTestEventDecisionTaskScheduled(6, &s.DecisionTaskScheduledEventAttributes{}), + createTestEventDecisionTaskScheduled(6, &apiv1.DecisionTaskScheduledEventAttributes{}), createTestEventDecisionTaskStarted(7), } - queries := map[string]*s.WorkflowQuery{ - "id1": {QueryType: common.StringPtr(queryType)}, - "id2": {QueryType: common.StringPtr(errQueryType)}, + queries := map[string]*apiv1.WorkflowQuery{ + "id1": {QueryType: queryType}, + "id2": {QueryType: errQueryType}, } task := createWorkflowTaskWithQueries(testEvents[0:3], 0, "QuerySignalWorkflow", queries) @@ -981,18 +991,18 @@ func (t *TaskHandlersTestSuite) TestConsistentQuery_Success() { taskHandler := newWorkflowTaskHandler(testDomain, params, nil, t.registry) request, err := taskHandler.ProcessWorkflowTask(&workflowTask{task: task}, nil) - response := request.(*s.RespondDecisionTaskCompletedRequest) + response := request.(*apiv1.RespondDecisionTaskCompletedRequest) t.NoError(err) t.NotNil(response) t.Len(response.Decisions, 0) - expectedQueryResults := map[string]*s.WorkflowQueryResult{ + expectedQueryResults := map[string]*apiv1.WorkflowQueryResult{ "id1": { - ResultType: common.QueryResultTypePtr(s.QueryResultTypeAnswered), - Answer: []byte(fmt.Sprintf("\"%v\"\n", startingQueryValue)), + ResultType: apiv1.QueryResultType_QUERY_RESULT_TYPE_ANSWERED, + Answer: &apiv1.Payload{Data: []byte(fmt.Sprintf("\"%v\"\n", startingQueryValue))}, }, "id2": { - ResultType: common.QueryResultTypePtr(s.QueryResultTypeFailed), - ErrorMessage: common.StringPtr(queryErr), + ResultType: apiv1.QueryResultType_QUERY_RESULT_TYPE_FAILED, + ErrorMessage: queryErr, }, } t.assertQueryResultsEqual(expectedQueryResults, response.QueryResults) @@ -1000,40 +1010,40 @@ func (t *TaskHandlersTestSuite) TestConsistentQuery_Success() { secondTask := createWorkflowTaskWithQueries(testEvents, 3, "QuerySignalWorkflow", queries) secondTask.WorkflowExecution.RunId = task.WorkflowExecution.RunId request, err = taskHandler.ProcessWorkflowTask(&workflowTask{task: secondTask}, nil) - response = request.(*s.RespondDecisionTaskCompletedRequest) + response = request.(*apiv1.RespondDecisionTaskCompletedRequest) t.NoError(err) t.NotNil(response) t.Len(response.Decisions, 1) - expectedQueryResults = map[string]*s.WorkflowQueryResult{ + expectedQueryResults = map[string]*apiv1.WorkflowQueryResult{ "id1": { - ResultType: common.QueryResultTypePtr(s.QueryResultTypeAnswered), - Answer: []byte(fmt.Sprintf("\"%v\"\n", "signal data")), + ResultType: apiv1.QueryResultType_QUERY_RESULT_TYPE_ANSWERED, + Answer: &apiv1.Payload{Data: []byte(fmt.Sprintf("\"%v\"\n", "signal data"))}, }, "id2": { - ResultType: common.QueryResultTypePtr(s.QueryResultTypeFailed), - ErrorMessage: common.StringPtr(queryErr), + ResultType: apiv1.QueryResultType_QUERY_RESULT_TYPE_FAILED, + ErrorMessage: queryErr, }, } t.assertQueryResultsEqual(expectedQueryResults, response.QueryResults) // clean up workflow left in cache - getWorkflowCache().Delete(*task.WorkflowExecution.RunId) + getWorkflowCache().Delete(task.WorkflowExecution.RunId) } -func (t *TaskHandlersTestSuite) assertQueryResultsEqual(expected map[string]*s.WorkflowQueryResult, actual map[string]*s.WorkflowQueryResult) { +func (t *TaskHandlersTestSuite) assertQueryResultsEqual(expected map[string]*apiv1.WorkflowQueryResult, actual map[string]*apiv1.WorkflowQueryResult) { t.Equal(len(expected), len(actual)) for expectedID, expectedResult := range expected { t.Contains(actual, expectedID) - t.True(expectedResult.Equals(actual[expectedID])) + t.Equal(expectedResult, actual[expectedID]) } } func (t *TaskHandlersTestSuite) TestWorkflowTask_CancelActivityBeforeSent() { // Schedule an activity and see if we complete workflow. taskList := "tl1" - testEvents := []*s.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &s.WorkflowExecutionStartedEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), - createTestEventDecisionTaskScheduled(2, &s.DecisionTaskScheduledEventAttributes{}), + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{}), createTestEventDecisionTaskStarted(3), } task := createWorkflowTask(testEvents, 0, "HelloWorld_WorkflowCancel") @@ -1045,20 +1055,19 @@ func (t *TaskHandlersTestSuite) TestWorkflowTask_CancelActivityBeforeSent() { } taskHandler := newWorkflowTaskHandler(testDomain, params, nil, t.registry) request, err := taskHandler.ProcessWorkflowTask(&workflowTask{task: task}, nil) - response := request.(*s.RespondDecisionTaskCompletedRequest) + response := request.(*apiv1.RespondDecisionTaskCompletedRequest) t.NoError(err) t.NotNil(response) t.Equal(1, len(response.Decisions)) - t.Equal(s.DecisionTypeCompleteWorkflowExecution, response.Decisions[0].GetDecisionType()) - t.NotNil(response.Decisions[0].CompleteWorkflowExecutionDecisionAttributes) + t.NotNil(response.Decisions[0].GetCompleteWorkflowExecutionDecisionAttributes()) } func (t *TaskHandlersTestSuite) TestWorkflowTask_PageToken() { // Schedule a decision activity and see if we complete workflow. taskList := "tl1" - testEvents := []*s.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &s.WorkflowExecutionStartedEventAttributes{TaskList: &s.TaskList{Name: &taskList}}), - createTestEventDecisionTaskScheduled(2, &s.DecisionTaskScheduledEventAttributes{}), + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{}), } task := createWorkflowTask(testEvents, 0, "HelloWorld_Workflow") task.NextPageToken = []byte("token") @@ -1069,18 +1078,18 @@ func (t *TaskHandlersTestSuite) TestWorkflowTask_PageToken() { Logger: t.logger, } - nextEvents := []*s.HistoryEvent{ + nextEvents := []*apiv1.HistoryEvent{ createTestEventDecisionTaskStarted(3), } historyIterator := &historyIteratorImpl{ - iteratorFunc: func(nextToken []byte) (*s.History, []byte, error) { - return &s.History{nextEvents}, nil, nil + iteratorFunc: func(nextToken []byte) (*apiv1.History, []byte, error) { + return &apiv1.History{Events: nextEvents}, nil, nil }, } taskHandler := newWorkflowTaskHandler(testDomain, params, nil, t.registry) request, err := taskHandler.ProcessWorkflowTask(&workflowTask{task: task, historyIterator: historyIterator}, nil) - response := request.(*s.RespondDecisionTaskCompletedRequest) + response := request.(*apiv1.RespondDecisionTaskCompletedRequest) t.NoError(err) t.NotNil(response) } @@ -1114,14 +1123,14 @@ func (t *TaskHandlersTestSuite) TestLocalActivityRetry_DecisionHeartbeatFail() { ) decisionTaskStartedEvent := createTestEventDecisionTaskStarted(3) - decisionTaskStartedEvent.Timestamp = common.Int64Ptr(time.Now().UnixNano()) - testEvents := []*s.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &s.WorkflowExecutionStartedEventAttributes{ + decisionTaskStartedEvent.EventTime = api.TimeToProto(time.Now()) + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{ // make sure the timeout is same as the backoff interval - TaskStartToCloseTimeoutSeconds: common.Int32Ptr(backoffIntervalInSeconds), - TaskList: &s.TaskList{Name: &testWorkflowTaskTasklist}}, + TaskStartToCloseTimeout: api.SecondsToProto(backoffIntervalInSeconds), + TaskList: &apiv1.TaskList{Name: testWorkflowTaskTasklist}}, ), - createTestEventDecisionTaskScheduled(2, &s.DecisionTaskScheduledEventAttributes{}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{}), decisionTaskStartedEvent, } @@ -1165,7 +1174,7 @@ func (t *TaskHandlersTestSuite) TestLocalActivityRetry_DecisionHeartbeatFail() { laResultCh: laResultCh, }, func(response interface{}, startTime time.Time) (*workflowTask, error) { - return nil, &s.EntityNotExistsError{Message: "Decision task not found."} + return nil, &api.EntityNotExistsError{Message: "Decision task not found."} }) t.Nil(response) t.Error(err) @@ -1178,10 +1187,9 @@ func (t *TaskHandlersTestSuite) TestLocalActivityRetry_DecisionHeartbeatFail() { func (t *TaskHandlersTestSuite) TestHeartBeat_NoError() { mockCtrl := gomock.NewController(t.T()) - mockService := workflowservicetest.NewMockClient(mockCtrl) + mockService := api.NewMockInterface(mockCtrl) - cancelRequested := false - heartbeatResponse := s.RecordActivityTaskHeartbeatResponse{CancelRequested: &cancelRequested} + heartbeatResponse := apiv1.RecordActivityTaskHeartbeatResponse{CancelRequested: false} mockService.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), gomock.Any(), callOptions...).Return(&heartbeatResponse, nil) cadenceInvoker := &cadenceInvoker{ @@ -1207,20 +1215,19 @@ func (r *recordHeartbeatRequestMatcher) String() string { } func (r *recordHeartbeatRequestMatcher) Matches(x interface{}) bool { - req, ok := x.(*s.RecordActivityTaskHeartbeatRequest) + req, ok := x.(*apiv1.RecordActivityTaskHeartbeatRequest) if !ok { return false } - return reflect.DeepEqual(r.details, req.Details) + return reflect.DeepEqual(r.details, req.Details.GetData()) } func (t *TaskHandlersTestSuite) TestHeartBeat_Interleaved() { mockCtrl := gomock.NewController(t.T()) - mockService := workflowservicetest.NewMockClient(mockCtrl) + mockService := api.NewMockInterface(mockCtrl) - cancelRequested := false - heartbeatResponse := s.RecordActivityTaskHeartbeatResponse{CancelRequested: &cancelRequested} + heartbeatResponse := apiv1.RecordActivityTaskHeartbeatResponse{CancelRequested: false} mockService.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), newHeartbeatRequestMatcher([]byte("1")), callOptions...).Return(&heartbeatResponse, nil).Times(3) mockService.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), newHeartbeatRequestMatcher([]byte("2")), callOptions...).Return(&heartbeatResponse, nil).Times(3) @@ -1254,9 +1261,9 @@ func (t *TaskHandlersTestSuite) TestHeartBeat_Interleaved() { func (t *TaskHandlersTestSuite) TestHeartBeat_NilResponseWithError() { mockCtrl := gomock.NewController(t.T()) - mockService := workflowservicetest.NewMockClient(mockCtrl) + mockService := api.NewMockInterface(mockCtrl) - entityNotExistsError := &s.EntityNotExistsError{} + entityNotExistsError := &api.EntityNotExistsError{} mockService.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), gomock.Any(), callOptions...).Return(nil, entityNotExistsError) cadenceInvoker := newServiceInvoker( @@ -1269,15 +1276,15 @@ func (t *TaskHandlersTestSuite) TestHeartBeat_NilResponseWithError() { heartbeatErr := cadenceInvoker.BatchHeartbeat(nil) t.NotNil(heartbeatErr) - _, ok := (heartbeatErr).(*s.EntityNotExistsError) + _, ok := (heartbeatErr).(*api.EntityNotExistsError) t.True(ok, "heartbeatErr must be EntityNotExistsError.") } func (t *TaskHandlersTestSuite) TestHeartBeat_NilResponseWithDomainNotActiveError() { mockCtrl := gomock.NewController(t.T()) - mockService := workflowservicetest.NewMockClient(mockCtrl) + mockService := api.NewMockInterface(mockCtrl) - domainNotActiveError := &s.DomainNotActiveError{} + domainNotActiveError := &api.DomainNotActiveError{} mockService.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), gomock.Any(), callOptions...).Return(nil, domainNotActiveError) called := false @@ -1293,7 +1300,7 @@ func (t *TaskHandlersTestSuite) TestHeartBeat_NilResponseWithDomainNotActiveErro heartbeatErr := cadenceInvoker.BatchHeartbeat(nil) t.NotNil(heartbeatErr) - _, ok := (heartbeatErr).(*s.DomainNotActiveError) + _, ok := (heartbeatErr).(*api.DomainNotActiveError) t.True(ok, "heartbeatErr must be DomainNotActiveError.") t.True(called) } @@ -1353,7 +1360,7 @@ func (t *TaskHandlersTestSuite) TestActivityExecutionDeadline() { registry.addActivityWithLock(a.ActivityType().Name, a) mockCtrl := gomock.NewController(t.T()) - mockService := workflowservicetest.NewMockClient(mockCtrl) + mockService := api.NewMockInterface(mockCtrl) for i, d := range deadlineTests { a.d = d.actWaitDuration @@ -1363,22 +1370,22 @@ func (t *TaskHandlersTestSuite) TestActivityExecutionDeadline() { Tracer: opentracing.NoopTracer{}, } activityHandler := newActivityTaskHandler(mockService, wep, registry) - pats := &s.PollForActivityTaskResponse{ + pats := &apiv1.PollForActivityTaskResponse{ TaskToken: []byte("token"), - WorkflowExecution: &s.WorkflowExecution{ - WorkflowId: common.StringPtr("wID"), - RunId: common.StringPtr("rID")}, - ActivityType: &s.ActivityType{Name: common.StringPtr("test")}, - ActivityId: common.StringPtr(uuid.New()), - ScheduledTimestamp: common.Int64Ptr(d.ScheduleTS.UnixNano()), - ScheduledTimestampOfThisAttempt: common.Int64Ptr(d.ScheduleTS.UnixNano()), - ScheduleToCloseTimeoutSeconds: common.Int32Ptr(d.ScheduleDuration), - StartedTimestamp: common.Int64Ptr(d.StartTS.UnixNano()), - StartToCloseTimeoutSeconds: common.Int32Ptr(d.StartDuration), - WorkflowType: &s.WorkflowType{ - Name: common.StringPtr("wType"), + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: "wID", + RunId: "rID"}, + ActivityType: &apiv1.ActivityType{Name: "test"}, + ActivityId: uuid.New(), + ScheduledTime: api.TimeToProto(d.ScheduleTS), + ScheduledTimeOfThisAttempt: api.TimeToProto(d.ScheduleTS), + ScheduleToCloseTimeout: api.SecondsToProto(d.ScheduleDuration), + StartedTime: api.TimeToProto(d.StartTS), + StartToCloseTimeout: api.SecondsToProto(d.StartDuration), + WorkflowType: &apiv1.WorkflowType{ + Name: "wType", }, - WorkflowDomain: common.StringPtr("domain"), + WorkflowDomain: "domain", } td := fmt.Sprintf("testIndex: %v, testDetails: %v", i, d) r, err := activityHandler.Execute(tasklist, pats) @@ -1411,7 +1418,7 @@ func (t *TaskHandlersTestSuite) TestActivityExecutionWorkerStop() { ) mockCtrl := gomock.NewController(t.T()) - mockService := workflowservicetest.NewMockClient(mockCtrl) + mockService := api.NewMockInterface(mockCtrl) workerStopCh := make(chan struct{}, 1) ctx, cancel := context.WithCancel(context.Background()) wep := workerExecutionParameters{ @@ -1422,22 +1429,22 @@ func (t *TaskHandlersTestSuite) TestActivityExecutionWorkerStop() { WorkerStopChannel: workerStopCh, } activityHandler := newActivityTaskHandler(mockService, wep, registry) - pats := &s.PollForActivityTaskResponse{ + pats := &apiv1.PollForActivityTaskResponse{ TaskToken: []byte("token"), - WorkflowExecution: &s.WorkflowExecution{ - WorkflowId: common.StringPtr("wID"), - RunId: common.StringPtr("rID")}, - ActivityType: &s.ActivityType{Name: common.StringPtr("test")}, - ActivityId: common.StringPtr(uuid.New()), - ScheduledTimestamp: common.Int64Ptr(time.Now().UnixNano()), - ScheduledTimestampOfThisAttempt: common.Int64Ptr(time.Now().UnixNano()), - ScheduleToCloseTimeoutSeconds: common.Int32Ptr(1), - StartedTimestamp: common.Int64Ptr(time.Now().UnixNano()), - StartToCloseTimeoutSeconds: common.Int32Ptr(1), - WorkflowType: &s.WorkflowType{ - Name: common.StringPtr("wType"), + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: "wID", + RunId: "rID"}, + ActivityType: &apiv1.ActivityType{Name: "test"}, + ActivityId: uuid.New(), + ScheduledTime: api.TimeToProto(time.Now()), + ScheduledTimeOfThisAttempt: api.TimeToProto(time.Now()), + ScheduleToCloseTimeout: api.SecondsToProto(1), + StartedTime: api.TimeToProto(time.Now()), + StartToCloseTimeout: api.SecondsToProto(1), + WorkflowType: &apiv1.WorkflowType{ + Name: "wType", }, - WorkflowDomain: common.StringPtr("domain"), + WorkflowDomain: "domain", } close(workerStopCh) r, err := activityHandler.Execute(tasklist, pats) @@ -1446,15 +1453,15 @@ func (t *TaskHandlersTestSuite) TestActivityExecutionWorkerStop() { } func Test_NonDeterministicCheck(t *testing.T) { - decisionTypes := s.DecisionType_Values() + decisionTypes := (&apiv1.Decision{}).XXX_OneofWrappers() require.Equal(t, 13, len(decisionTypes), "If you see this error, you are adding new decision type. "+ "Before updating the number to make this test pass, please make sure you update isDecisionMatchEvent() method "+ "to check the new decision type. Otherwise the replay will fail on the new decision event.") - eventTypes := s.EventType_Values() + eventTypes := (&apiv1.HistoryEvent{}).XXX_OneofWrappers() decisionEventTypeCount := 0 for _, et := range eventTypes { - if isDecisionEvent(et) { + if isDecisionEventAttributes(et) { decisionEventTypeCount++ } } @@ -1464,53 +1471,56 @@ func Test_NonDeterministicCheck(t *testing.T) { } func Test_IsDecisionMatchEvent_UpsertWorkflowSearchAttributes(t *testing.T) { - diType := s.DecisionTypeUpsertWorkflowSearchAttributes - eType := s.EventTypeUpsertWorkflowSearchAttributes strictMode := false testCases := []struct { name string - decision *s.Decision - event *s.HistoryEvent + decision *apiv1.Decision + event *apiv1.HistoryEvent expected bool }{ { name: "event type not match", - decision: &s.Decision{ - DecisionType: &diType, - UpsertWorkflowSearchAttributesDecisionAttributes: &s.UpsertWorkflowSearchAttributesDecisionAttributes{ - SearchAttributes: &s.SearchAttributes{}, + decision: &apiv1.Decision{ + Attributes: &apiv1.Decision_UpsertWorkflowSearchAttributesDecisionAttributes{ + UpsertWorkflowSearchAttributesDecisionAttributes: &apiv1.UpsertWorkflowSearchAttributesDecisionAttributes{ + SearchAttributes: &apiv1.SearchAttributes{}, + }, }, }, - event: &s.HistoryEvent{}, + event: &apiv1.HistoryEvent{}, expected: false, }, { name: "attributes not match", - decision: &s.Decision{ - DecisionType: &diType, - UpsertWorkflowSearchAttributesDecisionAttributes: &s.UpsertWorkflowSearchAttributesDecisionAttributes{ - SearchAttributes: &s.SearchAttributes{}, + decision: &apiv1.Decision{ + Attributes: &apiv1.Decision_UpsertWorkflowSearchAttributesDecisionAttributes{ + UpsertWorkflowSearchAttributesDecisionAttributes: &apiv1.UpsertWorkflowSearchAttributesDecisionAttributes{ + SearchAttributes: &apiv1.SearchAttributes{}, + }, }, }, - event: &s.HistoryEvent{ - EventType: &eType, - UpsertWorkflowSearchAttributesEventAttributes: &s.UpsertWorkflowSearchAttributesEventAttributes{}, + event: &apiv1.HistoryEvent{ + Attributes: &apiv1.HistoryEvent_UpsertWorkflowSearchAttributesEventAttributes{ + UpsertWorkflowSearchAttributesEventAttributes: &apiv1.UpsertWorkflowSearchAttributesEventAttributes{}, + }, }, expected: true, }, { name: "attributes match", - decision: &s.Decision{ - DecisionType: &diType, - UpsertWorkflowSearchAttributesDecisionAttributes: &s.UpsertWorkflowSearchAttributesDecisionAttributes{ - SearchAttributes: &s.SearchAttributes{}, + decision: &apiv1.Decision{ + Attributes: &apiv1.Decision_UpsertWorkflowSearchAttributesDecisionAttributes{ + UpsertWorkflowSearchAttributesDecisionAttributes: &apiv1.UpsertWorkflowSearchAttributesDecisionAttributes{ + SearchAttributes: &apiv1.SearchAttributes{}, + }, }, }, - event: &s.HistoryEvent{ - EventType: &eType, - UpsertWorkflowSearchAttributesEventAttributes: &s.UpsertWorkflowSearchAttributesEventAttributes{ - SearchAttributes: &s.SearchAttributes{}, + event: &apiv1.HistoryEvent{ + Attributes: &apiv1.HistoryEvent_UpsertWorkflowSearchAttributesEventAttributes{ + UpsertWorkflowSearchAttributesEventAttributes: &apiv1.UpsertWorkflowSearchAttributesEventAttributes{ + SearchAttributes: &apiv1.SearchAttributes{}, + }, }, }, expected: true, @@ -1527,21 +1537,23 @@ func Test_IsDecisionMatchEvent_UpsertWorkflowSearchAttributes(t *testing.T) { testCases = []struct { name string - decision *s.Decision - event *s.HistoryEvent + decision *apiv1.Decision + event *apiv1.HistoryEvent expected bool }{ { name: "attributes not match", - decision: &s.Decision{ - DecisionType: &diType, - UpsertWorkflowSearchAttributesDecisionAttributes: &s.UpsertWorkflowSearchAttributesDecisionAttributes{ - SearchAttributes: &s.SearchAttributes{}, + decision: &apiv1.Decision{ + Attributes: &apiv1.Decision_UpsertWorkflowSearchAttributesDecisionAttributes{ + UpsertWorkflowSearchAttributesDecisionAttributes: &apiv1.UpsertWorkflowSearchAttributesDecisionAttributes{ + SearchAttributes: &apiv1.SearchAttributes{}, + }, }, }, - event: &s.HistoryEvent{ - EventType: &eType, - UpsertWorkflowSearchAttributesEventAttributes: &s.UpsertWorkflowSearchAttributesEventAttributes{}, + event: &apiv1.HistoryEvent{ + Attributes: &apiv1.HistoryEvent_UpsertWorkflowSearchAttributesEventAttributes{ + UpsertWorkflowSearchAttributesEventAttributes: &apiv1.UpsertWorkflowSearchAttributesEventAttributes{}, + }, }, expected: false, }, @@ -1557,8 +1569,8 @@ func Test_IsDecisionMatchEvent_UpsertWorkflowSearchAttributes(t *testing.T) { func Test_IsSearchAttributesMatched(t *testing.T) { testCases := []struct { name string - lhs *s.SearchAttributes - rhs *s.SearchAttributes + lhs *apiv1.SearchAttributes + rhs *apiv1.SearchAttributes expected bool }{ { @@ -1570,38 +1582,38 @@ func Test_IsSearchAttributesMatched(t *testing.T) { { name: "left nil", lhs: nil, - rhs: &s.SearchAttributes{}, + rhs: &apiv1.SearchAttributes{}, expected: false, }, { name: "right nil", - lhs: &s.SearchAttributes{}, + lhs: &apiv1.SearchAttributes{}, rhs: nil, expected: false, }, { name: "not match", - lhs: &s.SearchAttributes{ - IndexedFields: map[string][]byte{ - "key1": []byte("1"), - "key2": []byte("abc"), + lhs: &apiv1.SearchAttributes{ + IndexedFields: map[string]*apiv1.Payload{ + "key1": {Data: []byte("1")}, + "key2": {Data: []byte("abc")}, }, }, - rhs: &s.SearchAttributes{}, + rhs: &apiv1.SearchAttributes{}, expected: false, }, { name: "match", - lhs: &s.SearchAttributes{ - IndexedFields: map[string][]byte{ - "key1": []byte("1"), - "key2": []byte("abc"), + lhs: &apiv1.SearchAttributes{ + IndexedFields: map[string]*apiv1.Payload{ + "key1": {Data: []byte("1")}, + "key2": {Data: []byte("abc")}, }, }, - rhs: &s.SearchAttributes{ - IndexedFields: map[string][]byte{ - "key2": []byte("abc"), - "key1": []byte("1"), + rhs: &apiv1.SearchAttributes{ + IndexedFields: map[string]*apiv1.Payload{ + "key2": {Data: []byte("abc")}, + "key1": {Data: []byte("1")}, }, }, expected: true, diff --git a/internal/internal_task_pollers.go b/internal/internal_task_pollers.go index 7751cc0ea..c32f746b7 100644 --- a/internal/internal_task_pollers.go +++ b/internal/internal_task_pollers.go @@ -29,15 +29,15 @@ import ( "sync" "time" + "github.com/gogo/protobuf/types" "github.com/opentracing/opentracing-go" "github.com/pborman/uuid" "github.com/uber-go/tally" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" - s "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" - "go.uber.org/cadence/v1/internal/common/backoff" - "go.uber.org/cadence/v1/internal/common/metrics" - "go.uber.org/cadence/v1/internal/common/serializer" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/internal/common/backoff" + "go.uber.org/cadence/v2/internal/common/metrics" + "go.uber.org/cadence/v2/internal/common/serializer" "go.uber.org/zap" ) @@ -69,7 +69,7 @@ type ( domain string taskListName string identity string - service workflowserviceclient.Interface + service api.Interface taskHandler WorkflowTaskHandler ldaTunnel *locallyDispatchedActivityTunnel metricsScope *metrics.TaggedScope @@ -91,7 +91,7 @@ type ( domain string taskListName string identity string - service workflowserviceclient.Interface + service api.Interface taskHandler ActivityTaskHandler metricsScope *metrics.TaggedScope logger *zap.Logger @@ -105,11 +105,11 @@ type ( } historyIteratorImpl struct { - iteratorFunc func(nextPageToken []byte) (*s.History, []byte, error) - execution *s.WorkflowExecution + iteratorFunc func(nextPageToken []byte) (*apiv1.History, []byte, error) + execution *apiv1.WorkflowExecution nextPageToken []byte domain string - service workflowserviceclient.Interface + service api.Interface metricsScope tally.Scope startedEventID int64 maxEventID int64 @@ -265,7 +265,7 @@ func (bp *basePoller) doPoll(pollFunc func(ctx context.Context) (interface{}, er func newWorkflowTaskPoller( taskHandler WorkflowTaskHandler, ldaTunnel *locallyDispatchedActivityTunnel, - service workflowserviceclient.Interface, + service api.Interface, domain string, params workerExecutionParameters, ) *workflowTaskPoller { @@ -327,7 +327,7 @@ func (wtp *workflowTaskPoller) processWorkflowTask(task *workflowTask) error { defer close(doneCh) for { - var response *s.RespondDecisionTaskCompletedResponse + var response *apiv1.RespondDecisionTaskCompletedResponse startTime := time.Now() task.doneCh = doneCh task.laResultCh = laResultCh @@ -375,16 +375,16 @@ func (wtp *workflowTaskPoller) processResetStickinessTask(rst *resetStickinessTa wtp.metricsScope.Counter(metrics.StickyCacheEvict).Inc(1) if _, err := wtp.service.ResetStickyTaskList(tchCtx, rst.task, opt...); err != nil { wtp.logger.Warn("ResetStickyTaskList failed", - zap.String(tagWorkflowID, rst.task.Execution.GetWorkflowId()), - zap.String(tagRunID, rst.task.Execution.GetRunId()), + zap.String(tagWorkflowID, rst.task.WorkflowExecution.GetWorkflowId()), + zap.String(tagRunID, rst.task.WorkflowExecution.GetRunId()), zap.Error(err)) - return err + return api.ConvertError(err) } return nil } -func (wtp *workflowTaskPoller) RespondTaskCompletedWithMetrics(completedRequest interface{}, taskErr error, task *s.PollForDecisionTaskResponse, startTime time.Time) (response *s.RespondDecisionTaskCompletedResponse, err error) { +func (wtp *workflowTaskPoller) RespondTaskCompletedWithMetrics(completedRequest interface{}, taskErr error, task *apiv1.PollForDecisionTaskResponse, startTime time.Time) (response *apiv1.RespondDecisionTaskCompletedResponse, err error) { metricsScope := wtp.metricsScope.GetTaggedScope(tagWorkflowType, task.WorkflowType.GetName()) if taskErr != nil { @@ -412,7 +412,7 @@ func (wtp *workflowTaskPoller) RespondTaskCompletedWithMetrics(completedRequest return } -func (wtp *workflowTaskPoller) RespondTaskCompleted(completedRequest interface{}, task *s.PollForDecisionTaskResponse) (response *s.RespondDecisionTaskCompletedResponse, err error) { +func (wtp *workflowTaskPoller) RespondTaskCompleted(completedRequest interface{}, task *apiv1.PollForDecisionTaskResponse) (response *apiv1.RespondDecisionTaskCompletedResponse, err error) { ctx := context.Background() // Respond task completion. err = backoff.Retry(ctx, @@ -421,48 +421,49 @@ func (wtp *workflowTaskPoller) RespondTaskCompleted(completedRequest interface{} defer cancel() var err1 error switch request := completedRequest.(type) { - case *s.RespondDecisionTaskFailedRequest: + case *apiv1.RespondDecisionTaskFailedRequest: // Only fail decision on first attempt, subsequent failure on the same decision task will timeout. // This is to avoid spin on the failed decision task. Checking Attempt not nil for older server. - if task.Attempt != nil && task.GetAttempt() == 0 { - err1 = wtp.service.RespondDecisionTaskFailed(tchCtx, request, opt...) + if task.GetAttempt() == 0 { + _, err1 = wtp.service.RespondDecisionTaskFailed(tchCtx, request, opt...) + err1 = api.ConvertError(err1) if err1 != nil { traceLog(func() { wtp.logger.Debug("RespondDecisionTaskFailed failed.", zap.Error(err1)) }) } } - case *s.RespondDecisionTaskCompletedRequest: + case *apiv1.RespondDecisionTaskCompletedRequest: if request.StickyAttributes == nil && !wtp.disableStickyExecution { - request.StickyAttributes = &s.StickyExecutionAttributes{ - WorkerTaskList: &s.TaskList{Name: common.StringPtr(getWorkerTaskList(wtp.stickyUUID))}, - ScheduleToStartTimeoutSeconds: common.Int32Ptr(common.Int32Ceil(wtp.StickyScheduleToStartTimeout.Seconds())), + request.StickyAttributes = &apiv1.StickyExecutionAttributes{ + WorkerTaskList: &apiv1.TaskList{Name: getWorkerTaskList(wtp.stickyUUID)}, + ScheduleToStartTimeout: api.DurationToProto(wtp.StickyScheduleToStartTimeout), } } else { - request.ReturnNewDecisionTask = common.BoolPtr(false) + request.ReturnNewDecisionTask = false } var activityTasks []*locallyDispatchedActivityTask if wtp.ldaTunnel != nil { for _, decision := range request.Decisions { - attr := decision.ScheduleActivityTaskDecisionAttributes + attr := decision.GetScheduleActivityTaskDecisionAttributes() if attr != nil && wtp.taskListName == attr.TaskList.GetName() { // assume the activity type is in registry otherwise the activity would be failed and retried from server activityTask := &locallyDispatchedActivityTask{ - readyCh: make(chan bool, 1), - ActivityId: attr.ActivityId, - ActivityType: attr.ActivityType, - Input: attr.Input, - Header: attr.Header, - WorkflowDomain: common.StringPtr(wtp.domain), - ScheduleToCloseTimeoutSeconds: attr.ScheduleToCloseTimeoutSeconds, - StartToCloseTimeoutSeconds: attr.StartToCloseTimeoutSeconds, - HeartbeatTimeoutSeconds: attr.HeartbeatTimeoutSeconds, - WorkflowExecution: task.WorkflowExecution, - WorkflowType: task.WorkflowType, + readyCh: make(chan bool, 1), + ActivityId: attr.ActivityId, + ActivityType: attr.ActivityType, + Input: attr.Input, + Header: attr.Header, + WorkflowDomain: wtp.domain, + ScheduleToCloseTimeout: attr.ScheduleToCloseTimeout, + StartToCloseTimeout: attr.StartToCloseTimeout, + HeartbeatTimeout: attr.HeartbeatTimeout, + WorkflowExecution: task.WorkflowExecution, + WorkflowType: task.WorkflowType, } if wtp.ldaTunnel.sendTask(activityTask) { wtp.metricsScope.Counter(metrics.ActivityLocalDispatchSucceedCounter).Inc(1) - decision.ScheduleActivityTaskDecisionAttributes.RequestLocalDispatch = common.BoolPtr(true) + decision.GetScheduleActivityTaskDecisionAttributes().RequestLocalDispatch = true activityTasks = append(activityTasks, activityTask) } else { // all pollers are busy - no room to optimize @@ -475,10 +476,10 @@ func (wtp *workflowTaskPoller) RespondTaskCompleted(completedRequest interface{} for _, at := range activityTasks { started := false if response != nil && err1 == nil { - if adl, ok := response.ActivitiesToDispatchLocally[*at.ActivityId]; ok { - at.ScheduledTimestamp = adl.ScheduledTimestamp - at.StartedTimestamp = adl.StartedTimestamp - at.ScheduledTimestampOfThisAttempt = adl.ScheduledTimestampOfThisAttempt + if adl, ok := response.ActivitiesToDispatchLocally[at.ActivityId]; ok { + at.ScheduledTime = adl.ScheduledTime + at.StartedTime = adl.StartedTime + at.ScheduledTimeOfThisAttempt = adl.ScheduledTimeOfThisAttempt at.TaskToken = adl.TaskToken started = true } @@ -487,14 +488,16 @@ func (wtp *workflowTaskPoller) RespondTaskCompleted(completedRequest interface{} } }() response, err1 = wtp.service.RespondDecisionTaskCompleted(tchCtx, request, opt...) + err1 = api.ConvertError(err1) if err1 != nil { traceLog(func() { wtp.logger.Debug("RespondDecisionTaskCompleted failed.", zap.Error(err1)) }) } - case *s.RespondQueryTaskCompletedRequest: - err1 = wtp.service.RespondQueryTaskCompleted(tchCtx, request, opt...) + case *apiv1.RespondQueryTaskCompletedRequest: + _, err1 = wtp.service.RespondQueryTaskCompleted(tchCtx, request, opt...) + err1 = api.ConvertError(err1) if err1 != nil { traceLog(func() { wtp.logger.Debug("RespondQueryTaskCompleted failed.", zap.Error(err1)) @@ -687,13 +690,13 @@ Wait_Result: return &localActivityResult{result: laResult, err: err, task: task} } -func (wtp *workflowTaskPoller) release(kind s.TaskListKind) { +func (wtp *workflowTaskPoller) release(kind apiv1.TaskListKind) { if wtp.disableStickyExecution { return } wtp.requestLock.Lock() - if kind == s.TaskListKindSticky { + if kind == apiv1.TaskListKind_TASK_LIST_KIND_STICKY { wtp.pendingStickyPollCount-- } else { wtp.pendingRegularPollCount-- @@ -701,8 +704,8 @@ func (wtp *workflowTaskPoller) release(kind s.TaskListKind) { wtp.requestLock.Unlock() } -func (wtp *workflowTaskPoller) updateBacklog(taskListKind s.TaskListKind, backlogCountHint int64) { - if taskListKind == s.TaskListKindNormal || wtp.disableStickyExecution { +func (wtp *workflowTaskPoller) updateBacklog(taskListKind apiv1.TaskListKind, backlogCountHint int64) { + if taskListKind == apiv1.TaskListKind_TASK_LIST_KIND_NORMAL || wtp.disableStickyExecution { // we only care about sticky backlog for now. return } @@ -718,30 +721,29 @@ func (wtp *workflowTaskPoller) updateBacklog(taskListKind s.TaskListKind, backlo // 2.1) if sticky task list has backlog, always prefer to process sticky task first // 2.2) poll from the task list that has less pending requests (prefer sticky when they are the same). // TODO: make this more smart to auto adjust based on poll latency -func (wtp *workflowTaskPoller) getNextPollRequest() (request *s.PollForDecisionTaskRequest) { +func (wtp *workflowTaskPoller) getNextPollRequest() (request *apiv1.PollForDecisionTaskRequest) { taskListName := wtp.taskListName - taskListKind := s.TaskListKindNormal + taskListKind := apiv1.TaskListKind_TASK_LIST_KIND_NORMAL if !wtp.disableStickyExecution { wtp.requestLock.Lock() if wtp.stickyBacklog > 0 || wtp.pendingStickyPollCount <= wtp.pendingRegularPollCount { wtp.pendingStickyPollCount++ taskListName = getWorkerTaskList(wtp.stickyUUID) - taskListKind = s.TaskListKindSticky + taskListKind = apiv1.TaskListKind_TASK_LIST_KIND_STICKY } else { wtp.pendingRegularPollCount++ } wtp.requestLock.Unlock() } - taskList := s.TaskList{ - Name: common.StringPtr(taskListName), - Kind: common.TaskListKindPtr(taskListKind), - } - return &s.PollForDecisionTaskRequest{ - Domain: common.StringPtr(wtp.domain), - TaskList: common.TaskListPtr(taskList), - Identity: common.StringPtr(wtp.identity), - BinaryChecksum: common.StringPtr(getBinaryChecksum()), + return &apiv1.PollForDecisionTaskRequest{ + Domain: wtp.domain, + TaskList: &apiv1.TaskList{ + Name: taskListName, + Kind: taskListKind, + }, + Identity: wtp.identity, + BinaryChecksum: getBinaryChecksum(), } } @@ -758,6 +760,7 @@ func (wtp *workflowTaskPoller) poll(ctx context.Context) (interface{}, error) { defer wtp.release(request.TaskList.GetKind()) response, err := wtp.service.PollForDecisionTask(ctx, request, yarpcCallOptions...) + err = api.ConvertError(err) if err != nil { if isServiceTransientError(err) { wtp.metricsScope.Counter(metrics.DecisionPollTransientFailedCounter).Inc(1) @@ -793,12 +796,14 @@ func (wtp *workflowTaskPoller) poll(ctx context.Context) (interface{}, error) { metricsScope.Counter(metrics.DecisionPollSucceedCounter).Inc(1) metricsScope.Timer(metrics.DecisionPollLatency).Record(time.Now().Sub(startTime)) - scheduledToStartLatency := time.Duration(response.GetStartedTimestamp() - response.GetScheduledTimestamp()) + startedTime := api.TimeFromProto(response.StartedTime) + scheduledTime := api.TimeFromProto(response.ScheduledTime) + scheduledToStartLatency := startedTime.Sub(scheduledTime) metricsScope.Timer(metrics.DecisionScheduledToStartLatency).Record(scheduledToStartLatency) return task, nil } -func (wtp *workflowTaskPoller) toWorkflowTask(response *s.PollForDecisionTaskResponse) *workflowTask { +func (wtp *workflowTaskPoller) toWorkflowTask(response *apiv1.PollForDecisionTaskResponse) *workflowTask { startEventID := response.GetStartedEventId() nextEventID := response.GetNextEventId() if nextEventID != 0 && @@ -826,7 +831,7 @@ func (wtp *workflowTaskPoller) toWorkflowTask(response *s.PollForDecisionTaskRes return task } -func (h *historyIteratorImpl) GetNextPage() (*s.History, error) { +func (h *historyIteratorImpl) GetNextPage() (*apiv1.History, error) { if h.iteratorFunc == nil { h.iteratorFunc = newGetHistoryPageFunc( context.Background(), @@ -856,29 +861,29 @@ func (h *historyIteratorImpl) HasNextPage() bool { func newGetHistoryPageFunc( ctx context.Context, - service workflowserviceclient.Interface, + service api.Interface, domain string, - execution *s.WorkflowExecution, + execution *apiv1.WorkflowExecution, atDecisionTaskCompletedEventID int64, maxEventID int64, metricsScope tally.Scope, -) func(nextPageToken []byte) (*s.History, []byte, error) { - return func(nextPageToken []byte) (*s.History, []byte, error) { +) func(nextPageToken []byte) (*apiv1.History, []byte, error) { + return func(nextPageToken []byte) (*apiv1.History, []byte, error) { metricsScope.Counter(metrics.WorkflowGetHistoryCounter).Inc(1) startTime := time.Now() - var resp *s.GetWorkflowExecutionHistoryResponse + var resp *apiv1.GetWorkflowExecutionHistoryResponse err := backoff.Retry(ctx, func() error { tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() var err1 error - resp, err1 = service.GetWorkflowExecutionHistory(tchCtx, &s.GetWorkflowExecutionHistoryRequest{ - Domain: common.StringPtr(domain), - Execution: execution, - NextPageToken: nextPageToken, + resp, err1 = service.GetWorkflowExecutionHistory(tchCtx, &apiv1.GetWorkflowExecutionHistoryRequest{ + Domain: domain, + WorkflowExecution: execution, + NextPageToken: nextPageToken, }, opt...) - return err1 + return api.ConvertError(err1) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) if err != nil { metricsScope.Counter(metrics.WorkflowGetHistoryFailedCounter).Inc(1) @@ -888,11 +893,11 @@ func newGetHistoryPageFunc( metricsScope.Counter(metrics.WorkflowGetHistorySucceedCounter).Inc(1) metricsScope.Timer(metrics.WorkflowGetHistoryLatency).Record(time.Now().Sub(startTime)) - var h *s.History + var h *apiv1.History if resp.RawHistory != nil { var err1 error - h, err1 = serializer.DeserializeBlobDataToHistoryEvents(resp.RawHistory, s.HistoryEventFilterTypeAllEvent) + h, err1 = serializer.DeserializeBlobDataToHistoryEvents(resp.RawHistory, apiv1.EventFilterType_EVENT_FILTER_TYPE_ALL_EVENT) if err1 != nil { return nil, nil, err1 } @@ -908,7 +913,7 @@ func newGetHistoryPageFunc( if shouldTruncateHistory(h, atDecisionTaskCompletedEventID) { first := h.Events[0].GetEventId() // eventIds start from 1 h.Events = h.Events[:atDecisionTaskCompletedEventID-first+1] - if h.Events[len(h.Events)-1].GetEventType() != s.EventTypeDecisionTaskCompleted { + if h.Events[len(h.Events)-1].GetDecisionTaskCompletedEventAttributes() == nil { return nil, nil, fmt.Errorf("newGetHistoryPageFunc: atDecisionTaskCompletedEventID(%v) "+ "points to event that is not DecisionTaskCompleted", atDecisionTaskCompletedEventID) } @@ -928,7 +933,7 @@ func newGetHistoryPageFunc( } } -func shouldTruncateHistory(h *s.History, maxEventID int64) bool { +func shouldTruncateHistory(h *apiv1.History, maxEventID int64) bool { size := len(h.Events) return size > 0 && maxEventID > 0 && h.Events[size-1].GetEventId() > maxEventID } @@ -937,7 +942,7 @@ func isQueryTask(atDecisionTaskCompletedEventID int64) bool { return atDecisionTaskCompletedEventID == 0 } -func newActivityTaskPoller(taskHandler ActivityTaskHandler, service workflowserviceclient.Interface, +func newActivityTaskPoller(taskHandler ActivityTaskHandler, service api.Interface, domain string, params workerExecutionParameters) *activityTaskPoller { activityTaskPoller := &activityTaskPoller{ @@ -955,7 +960,7 @@ func newActivityTaskPoller(taskHandler ActivityTaskHandler, service workflowserv } // Poll for a single activity task from the service -func (atp *activityTaskPoller) poll(ctx context.Context) (*s.PollForActivityTaskResponse, time.Time, error) { +func (atp *activityTaskPoller) poll(ctx context.Context) (*apiv1.PollForActivityTaskResponse, time.Time, error) { atp.metricsScope.Counter(metrics.ActivityPollCounter).Inc(1) startTime := time.Now() @@ -963,13 +968,14 @@ func (atp *activityTaskPoller) poll(ctx context.Context) (*s.PollForActivityTask traceLog(func() { atp.logger.Debug("activityTaskPoller::Poll") }) - request := &s.PollForActivityTaskRequest{ - Domain: common.StringPtr(atp.domain), - TaskList: common.TaskListPtr(s.TaskList{Name: common.StringPtr(atp.taskListName)}), - Identity: common.StringPtr(atp.identity), - TaskListMetadata: &s.TaskListMetadata{MaxTasksPerSecond: &atp.activitiesPerSecond}, + request := &apiv1.PollForActivityTaskRequest{ + Domain: atp.domain, + TaskList: &apiv1.TaskList{Name: atp.taskListName}, + Identity: atp.identity, + TaskListMetadata: &apiv1.TaskListMetadata{MaxTasksPerSecond: &types.DoubleValue{Value: atp.activitiesPerSecond}}, } response, err := atp.service.PollForActivityTask(ctx, request, yarpcCallOptions...) + err = api.ConvertError(err) if err != nil { if isServiceTransientError(err) { @@ -987,7 +993,7 @@ func (atp *activityTaskPoller) poll(ctx context.Context) (*s.PollForActivityTask return response, startTime, err } -type pollFunc func(ctx context.Context) (*s.PollForActivityTaskResponse, time.Time, error) +type pollFunc func(ctx context.Context) (*apiv1.PollForActivityTaskResponse, time.Time, error) func (atp *activityTaskPoller) pollWithMetricsFunc( pollFunc pollFunc) func(ctx context.Context) (interface{}, error) { @@ -995,7 +1001,7 @@ func (atp *activityTaskPoller) pollWithMetricsFunc( } func (atp *activityTaskPoller) pollWithMetrics(ctx context.Context, - pollFunc func(ctx context.Context) (*s.PollForActivityTaskResponse, time.Time, error)) (interface{}, error) { + pollFunc func(ctx context.Context) (*apiv1.PollForActivityTaskResponse, time.Time, error)) (interface{}, error) { response, startTime, err := pollFunc(ctx) if err != nil { @@ -1011,7 +1017,9 @@ func (atp *activityTaskPoller) pollWithMetrics(ctx context.Context, metricsScope.Counter(metrics.ActivityPollSucceedCounter).Inc(1) metricsScope.Timer(metrics.ActivityPollLatency).Record(time.Now().Sub(startTime)) - scheduledToStartLatency := time.Duration(response.GetStartedTimestamp() - response.GetScheduledTimestampOfThisAttempt()) + startedTime := api.TimeFromProto(response.StartedTime) + scheduledTimeOfThisAttempt := api.TimeFromProto(response.ScheduledTimeOfThisAttempt) + scheduledToStartLatency := startedTime.Sub(scheduledTimeOfThisAttempt) metricsScope.Timer(metrics.ActivityScheduledToStartLatency).Record(scheduledToStartLatency) return &activityTask{task: response, pollStartTime: startTime}, nil @@ -1079,7 +1087,7 @@ func (atp *activityTaskPoller) ProcessTask(task interface{}) error { return nil } -func newLocallyDispatchedActivityTaskPoller(taskHandler ActivityTaskHandler, service workflowserviceclient.Interface, +func newLocallyDispatchedActivityTaskPoller(taskHandler ActivityTaskHandler, service api.Interface, domain string, params workerExecutionParameters) *locallyDispatchedActivityTaskPoller { locallyDispatchedActivityTaskPoller := &locallyDispatchedActivityTaskPoller{ activityTaskPoller: *newActivityTaskPoller(taskHandler, service, domain, params), @@ -1099,7 +1107,7 @@ func (atp *locallyDispatchedActivityTaskPoller) PollTask() (interface{}, error) return activityTask, nil } -func (atp *locallyDispatchedActivityTaskPoller) pollLocallyDispatchedActivity(ctx context.Context) (*s.PollForActivityTaskResponse, time.Time, error) { +func (atp *locallyDispatchedActivityTaskPoller) pollLocallyDispatchedActivity(ctx context.Context) (*apiv1.PollForActivityTaskResponse, time.Time, error) { task := atp.ldaTunnel.getTask() atp.metricsScope.Counter(metrics.LocallyDispatchedActivityPollCounter).Inc(1) // consider to remove the poll latency metric for local dispatch as unnecessary @@ -1111,26 +1119,26 @@ func (atp *locallyDispatchedActivityTaskPoller) pollLocallyDispatchedActivity(ct // to be backwards compatible, update total poll counter if optimization succeeded only atp.metricsScope.Counter(metrics.ActivityPollCounter).Inc(1) atp.metricsScope.Counter(metrics.LocallyDispatchedActivityPollSucceedCounter).Inc(1) - response := &s.PollForActivityTaskResponse{} + response := &apiv1.PollForActivityTaskResponse{} response.ActivityId = task.ActivityId response.ActivityType = task.ActivityType response.Header = task.Header response.Input = task.Input response.WorkflowExecution = task.WorkflowExecution - response.ScheduledTimestampOfThisAttempt = task.ScheduledTimestampOfThisAttempt - response.ScheduledTimestamp = task.ScheduledTimestamp - response.ScheduleToCloseTimeoutSeconds = task.ScheduleToCloseTimeoutSeconds - response.StartedTimestamp = task.StartedTimestamp - response.StartToCloseTimeoutSeconds = task.StartToCloseTimeoutSeconds - response.HeartbeatTimeoutSeconds = task.HeartbeatTimeoutSeconds + response.ScheduledTimeOfThisAttempt = task.ScheduledTimeOfThisAttempt + response.ScheduledTime = task.ScheduledTime + response.ScheduleToCloseTimeout = task.ScheduleToCloseTimeout + response.StartedTime = task.StartedTime + response.StartToCloseTimeout = task.StartToCloseTimeout + response.HeartbeatTimeout = task.HeartbeatTimeout response.TaskToken = task.TaskToken response.WorkflowType = task.WorkflowType response.WorkflowDomain = task.WorkflowDomain - response.Attempt = common.Int32Ptr(0) + response.Attempt = 0 return response, startTime, nil } -func reportActivityComplete(ctx context.Context, service workflowserviceclient.Interface, request interface{}, metricsScope tally.Scope) error { +func reportActivityComplete(ctx context.Context, service api.Interface, request interface{}, metricsScope tally.Scope) error { if request == nil { // nothing to report return nil @@ -1138,38 +1146,41 @@ func reportActivityComplete(ctx context.Context, service workflowserviceclient.I var reportErr error switch request := request.(type) { - case *s.RespondActivityTaskCanceledRequest: + case *apiv1.RespondActivityTaskCanceledRequest: reportErr = backoff.Retry(ctx, func() error { tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() - return service.RespondActivityTaskCanceled(tchCtx, request, opt...) + _, err := service.RespondActivityTaskCanceled(tchCtx, request, opt...) + return api.ConvertError(err) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) - case *s.RespondActivityTaskFailedRequest: + case *apiv1.RespondActivityTaskFailedRequest: reportErr = backoff.Retry(ctx, func() error { tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() - return service.RespondActivityTaskFailed(tchCtx, request, opt...) + _, err := service.RespondActivityTaskFailed(tchCtx, request, opt...) + return api.ConvertError(err) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) - case *s.RespondActivityTaskCompletedRequest: + case *apiv1.RespondActivityTaskCompletedRequest: reportErr = backoff.Retry(ctx, func() error { tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() - return service.RespondActivityTaskCompleted(tchCtx, request, opt...) + _, err := service.RespondActivityTaskCompleted(tchCtx, request, opt...) + return api.ConvertError(err) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) } if reportErr == nil { switch request.(type) { - case *s.RespondActivityTaskCanceledRequest: + case *apiv1.RespondActivityTaskCanceledRequest: metricsScope.Counter(metrics.ActivityTaskCanceledCounter).Inc(1) - case *s.RespondActivityTaskFailedRequest: + case *apiv1.RespondActivityTaskFailedRequest: metricsScope.Counter(metrics.ActivityTaskFailedCounter).Inc(1) - case *s.RespondActivityTaskCompletedRequest: + case *apiv1.RespondActivityTaskCompletedRequest: metricsScope.Counter(metrics.ActivityTaskCompletedCounter).Inc(1) } } @@ -1177,7 +1188,7 @@ func reportActivityComplete(ctx context.Context, service workflowserviceclient.I return reportErr } -func reportActivityCompleteByID(ctx context.Context, service workflowserviceclient.Interface, request interface{}, metricsScope tally.Scope) error { +func reportActivityCompleteByID(ctx context.Context, service api.Interface, request interface{}, metricsScope tally.Scope) error { if request == nil { // nothing to report return nil @@ -1185,38 +1196,41 @@ func reportActivityCompleteByID(ctx context.Context, service workflowserviceclie var reportErr error switch request := request.(type) { - case *s.RespondActivityTaskCanceledByIDRequest: + case *apiv1.RespondActivityTaskCanceledByIDRequest: reportErr = backoff.Retry(ctx, func() error { tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() - return service.RespondActivityTaskCanceledByID(tchCtx, request, opt...) + _, err := service.RespondActivityTaskCanceledByID(tchCtx, request, opt...) + return api.ConvertError(err) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) - case *s.RespondActivityTaskFailedByIDRequest: + case *apiv1.RespondActivityTaskFailedByIDRequest: reportErr = backoff.Retry(ctx, func() error { tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() - return service.RespondActivityTaskFailedByID(tchCtx, request, opt...) + _, err := service.RespondActivityTaskFailedByID(tchCtx, request, opt...) + return api.ConvertError(err) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) - case *s.RespondActivityTaskCompletedByIDRequest: + case *apiv1.RespondActivityTaskCompletedByIDRequest: reportErr = backoff.Retry(ctx, func() error { tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() - return service.RespondActivityTaskCompletedByID(tchCtx, request, opt...) + _, err := service.RespondActivityTaskCompletedByID(tchCtx, request, opt...) + return api.ConvertError(err) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) } if reportErr == nil { switch request.(type) { - case *s.RespondActivityTaskCanceledByIDRequest: + case *apiv1.RespondActivityTaskCanceledByIDRequest: metricsScope.Counter(metrics.ActivityTaskCanceledByIDCounter).Inc(1) - case *s.RespondActivityTaskFailedByIDRequest: + case *apiv1.RespondActivityTaskFailedByIDRequest: metricsScope.Counter(metrics.ActivityTaskFailedByIDCounter).Inc(1) - case *s.RespondActivityTaskCompletedByIDRequest: + case *apiv1.RespondActivityTaskCompletedByIDRequest: metricsScope.Counter(metrics.ActivityTaskCompletedByIDCounter).Inc(1) } } @@ -1233,25 +1247,27 @@ func convertActivityResultToRespondRequest(identity string, taskToken, result [] } if err == nil { - return &s.RespondActivityTaskCompletedRequest{ + return &apiv1.RespondActivityTaskCompletedRequest{ TaskToken: taskToken, - Result: result, - Identity: common.StringPtr(identity)} + Result: &apiv1.Payload{Data: result}, + Identity: identity} } reason, details := getErrorDetails(err, dataConverter) if _, ok := err.(*CanceledError); ok || err == context.Canceled { - return &s.RespondActivityTaskCanceledRequest{ + return &apiv1.RespondActivityTaskCanceledRequest{ TaskToken: taskToken, - Details: details, - Identity: common.StringPtr(identity)} + Details: &apiv1.Payload{Data: details}, + Identity: identity} } - return &s.RespondActivityTaskFailedRequest{ + return &apiv1.RespondActivityTaskFailedRequest{ TaskToken: taskToken, - Reason: common.StringPtr(reason), - Details: details, - Identity: common.StringPtr(identity)} + Failure: &apiv1.Failure{ + Reason: reason, + Details: details, + }, + Identity: identity} } func convertActivityResultToRespondRequestByID(identity, domain, workflowID, runID, activityID string, @@ -1263,32 +1279,40 @@ func convertActivityResultToRespondRequestByID(identity, domain, workflowID, run } if err == nil { - return &s.RespondActivityTaskCompletedByIDRequest{ - Domain: common.StringPtr(domain), - WorkflowID: common.StringPtr(workflowID), - RunID: common.StringPtr(runID), - ActivityID: common.StringPtr(activityID), - Result: result, - Identity: common.StringPtr(identity)} + return &apiv1.RespondActivityTaskCompletedByIDRequest{ + Domain: domain, + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: workflowID, + RunId: runID, + }, + ActivityId: activityID, + Result: &apiv1.Payload{Data: result}, + Identity: identity} } reason, details := getErrorDetails(err, dataConverter) if _, ok := err.(*CanceledError); ok || err == context.Canceled { - return &s.RespondActivityTaskCanceledByIDRequest{ - Domain: common.StringPtr(domain), - WorkflowID: common.StringPtr(workflowID), - RunID: common.StringPtr(runID), - ActivityID: common.StringPtr(activityID), + return &apiv1.RespondActivityTaskCanceledByIDRequest{ + Domain: domain, + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: workflowID, + RunId: runID, + }, + ActivityId: activityID, + Details: &apiv1.Payload{Data: details}, + Identity: identity} + } + + return &apiv1.RespondActivityTaskFailedByIDRequest{ + Domain: domain, + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: workflowID, + RunId: runID, + }, + ActivityId: activityID, + Failure: &apiv1.Failure{ + Reason: reason, Details: details, - Identity: common.StringPtr(identity)} - } - - return &s.RespondActivityTaskFailedByIDRequest{ - Domain: common.StringPtr(domain), - WorkflowID: common.StringPtr(workflowID), - RunID: common.StringPtr(runID), - ActivityID: common.StringPtr(activityID), - Reason: common.StringPtr(reason), - Details: details, - Identity: common.StringPtr(identity)} + }, + Identity: identity} } diff --git a/internal/internal_utils.go b/internal/internal_utils.go index 8fa877b74..ce440018a 100644 --- a/internal/internal_utils.go +++ b/internal/internal_utils.go @@ -24,6 +24,7 @@ package internal import ( "context" + "errors" "fmt" "os" "os/signal" @@ -32,9 +33,8 @@ import ( "time" "github.com/uber-go/tally" - s "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" - "go.uber.org/cadence/v1/internal/common/metrics" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/common/metrics" "go.uber.org/yarpc" ) @@ -157,20 +157,6 @@ func getWorkerTaskList(stickyUUID string) string { return fmt.Sprintf("%s:%s", getHostName(), stickyUUID) } -// ActivityTypePtr makes a copy and returns the pointer to a ActivityType. -func activityTypePtr(v ActivityType) *s.ActivityType { - return &s.ActivityType{Name: common.StringPtr(v.Name)} -} - -func flowWorkflowTypeFrom(v s.WorkflowType) WorkflowType { - return WorkflowType{Name: v.GetName()} -} - -// WorkflowTypePtr makes a copy and returns the pointer to a WorkflowType. -func workflowTypePtr(t WorkflowType) *s.WorkflowType { - return &s.WorkflowType{Name: common.StringPtr(t.Name)} -} - // getErrorDetails gets reason and details. func getErrorDetails(err error, dataConverter DataConverter) (string, []byte) { switch err := err.(type) { @@ -224,7 +210,7 @@ func getErrorDetails(err error, dataConverter DataConverter) (string, []byte) { if err0 != nil { panic(err0) } - return fmt.Sprintf("%v %v", errReasonTimeout, err.timeoutType), data + return fmt.Sprintf("%v %v", errReasonTimeout, timeoutTypeString(err.timeoutType)), data default: // will be convert to GenericError when receiving from server. return errReasonGeneric, []byte(err.Error()) @@ -282,12 +268,25 @@ func getMetricsScopeForLocalActivity(ts *metrics.TaggedScope, workflowType, loca return ts.GetTaggedScope(tagWorkflowType, workflowType, tagLocalActivityType, localActivityType) } -func getTimeoutTypeFromErrReason(reason string) (s.TimeoutType, error) { +func getTimeoutTypeFromErrReason(reason string) (apiv1.TimeoutType, error) { timeoutTypeStr := reason[strings.Index(reason, " ")+1:] - var timeoutType s.TimeoutType - if err := timeoutType.UnmarshalText([]byte(timeoutTypeStr)); err != nil { - // this happens when the timeout error reason is constructed by an prior constructed by prior client version - return 0, err + + switch timeoutTypeStr { + case "START_TO_CLOSE": return apiv1.TimeoutType_TIMEOUT_TYPE_START_TO_CLOSE, nil + case "SCHEDULE_TO_START": return apiv1.TimeoutType_TIMEOUT_TYPE_SCHEDULE_TO_START, nil + case "SCHEDULE_TO_CLOSE": return apiv1.TimeoutType_TIMEOUT_TYPE_SCHEDULE_TO_CLOSE, nil + case "HEARTBEAT": return apiv1.TimeoutType_TIMEOUT_TYPE_HEARTBEAT, nil } - return timeoutType, nil + // this happens when the timeout error reason is constructed by an prior constructed by prior client version + return 0, errors.New("invalid TimeoutType") } + +func timeoutTypeString(timeoutType apiv1.TimeoutType) string { + switch timeoutType { + case apiv1.TimeoutType_TIMEOUT_TYPE_START_TO_CLOSE: return "START_TO_CLOSE" + case apiv1.TimeoutType_TIMEOUT_TYPE_SCHEDULE_TO_START: return "SCHEDULE_TO_START" + case apiv1.TimeoutType_TIMEOUT_TYPE_SCHEDULE_TO_CLOSE: return "SCHEDULE_TO_CLOSE" + case apiv1.TimeoutType_TIMEOUT_TYPE_HEARTBEAT: return "HEARTBEAT" + } + return "INVALID" +} \ No newline at end of file diff --git a/internal/internal_utils_test.go b/internal/internal_utils_test.go index 8d3e66d57..34a81090f 100644 --- a/internal/internal_utils_test.go +++ b/internal/internal_utils_test.go @@ -26,7 +26,7 @@ import ( "time" "github.com/stretchr/testify/require" - s "go.uber.org/cadence/v1/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" ) func TestChannelBuilderOptions(t *testing.T) { @@ -121,16 +121,16 @@ func TestGetErrorDetails_TimeoutError(t *testing.T) { require.NoError(t, err) val := newEncodedValues(details, dc).(*EncodedValues) - timeoutErr1 := NewTimeoutError(s.TimeoutTypeScheduleToStart, val) + timeoutErr1 := NewTimeoutError(apiv1.TimeoutType_TIMEOUT_TYPE_SCHEDULE_TO_START, val) reason, data := getErrorDetails(timeoutErr1, dc) - require.Equal(t, fmt.Sprintf("%v %v", errReasonTimeout, s.TimeoutTypeScheduleToStart), reason) + require.Equal(t, fmt.Sprintf("%v %v", errReasonTimeout, timeoutTypeString(apiv1.TimeoutType_TIMEOUT_TYPE_SCHEDULE_TO_START)), reason) require.Equal(t, val.values, data) - timeoutErr2 := NewTimeoutError(s.TimeoutTypeHeartbeat, testErrorDetails4) + timeoutErr2 := NewTimeoutError(apiv1.TimeoutType_TIMEOUT_TYPE_HEARTBEAT, testErrorDetails4) val2, err := encodeArgs(dc, []interface{}{testErrorDetails4}) require.NoError(t, err) reason, data = getErrorDetails(timeoutErr2, dc) - require.Equal(t, fmt.Sprintf("%v %v", errReasonTimeout, s.TimeoutTypeHeartbeat), reason) + require.Equal(t, fmt.Sprintf("%v %v", errReasonTimeout, timeoutTypeString(apiv1.TimeoutType_TIMEOUT_TYPE_HEARTBEAT)), reason) require.Equal(t, val2, data) } @@ -140,7 +140,7 @@ func TestConstructError_TimeoutError(t *testing.T) { details, err := dc.ToData(testErrorDetails1) require.NoError(t, err) - reason := fmt.Sprintf("%v %v", errReasonTimeout, s.TimeoutTypeHeartbeat) + reason := fmt.Sprintf("%v %v", errReasonTimeout, timeoutTypeString(apiv1.TimeoutType_TIMEOUT_TYPE_HEARTBEAT)) constructedErr := constructError(reason, details, dc) timeoutErr, ok := constructedErr.(*TimeoutError) require.True(t, ok) @@ -152,10 +152,10 @@ func TestConstructError_TimeoutError(t *testing.T) { // Backward compatibility test reason = errReasonTimeout - details, err = dc.ToData(s.TimeoutTypeHeartbeat) + details, err = dc.ToData(apiv1.TimeoutType_TIMEOUT_TYPE_HEARTBEAT) constructedErr = constructError(reason, details, dc) timeoutErr, ok = constructedErr.(*TimeoutError) require.True(t, ok) - require.Equal(t, s.TimeoutTypeHeartbeat, timeoutErr.TimeoutType()) + require.Equal(t, apiv1.TimeoutType_TIMEOUT_TYPE_HEARTBEAT, timeoutErr.TimeoutType()) require.False(t, timeoutErr.HasDetails()) } diff --git a/internal/internal_worker.go b/internal/internal_worker.go index 4a4f802fb..fd630613e 100644 --- a/internal/internal_worker.go +++ b/internal/internal_worker.go @@ -41,11 +41,11 @@ import ( "github.com/opentracing/opentracing-go" "github.com/pborman/uuid" "github.com/uber-go/tally" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common/backoff" - "go.uber.org/cadence/v1/internal/common/metrics" - "go.uber.org/cadence/v1/internal/common/util" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/internal/common/backoff" + "go.uber.org/cadence/v2/internal/common/metrics" + "go.uber.org/cadence/v2/internal/common/util" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) @@ -79,7 +79,7 @@ type ( // task list names they might have to manage 'n' workers for 'n' task lists. workflowWorker struct { executionParameters workerExecutionParameters - workflowService workflowserviceclient.Interface + workflowService api.Interface domain string poller taskPoller // taskPoller to poll and process the tasks. worker *baseWorker @@ -92,7 +92,7 @@ type ( // TODO: Worker doing heartbeating automatically while activity task is running activityWorker struct { executionParameters workerExecutionParameters - workflowService workflowserviceclient.Interface + workflowService api.Interface domain string poller taskPoller worker *baseWorker @@ -194,7 +194,7 @@ type ( // newWorkflowWorker returns an instance of the workflow worker. func newWorkflowWorker( - service workflowserviceclient.Interface, + service api.Interface, domain string, params workerExecutionParameters, ppMgr pressurePointMgr, @@ -234,18 +234,19 @@ func ensureRequiredParams(params *workerExecutionParameters) { // verifyDomainExist does a DescribeDomain operation on the specified domain with backoff/retry // It returns an error, if the server returns an EntityNotExist or BadRequest error // On any other transient error, this method will just return success -func verifyDomainExist(client workflowserviceclient.Interface, domain string, logger *zap.Logger) error { +func verifyDomainExist(client api.Interface, domain string, logger *zap.Logger) error { ctx := context.Background() descDomainOp := func() error { tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() - _, err := client.DescribeDomain(tchCtx, &shared.DescribeDomainRequest{Name: &domain}, opt...) + _, err := client.DescribeDomain(tchCtx, &apiv1.DescribeDomainRequest{DescribeBy: &apiv1.DescribeDomainRequest_Name{Name: domain}}, opt...) + err = api.ConvertError(err) if err != nil { - if _, ok := err.(*shared.EntityNotExistsError); ok { + if _, ok := err.(*api.EntityNotExistsError); ok { logger.Error("domain does not exist", zap.String("domain", domain), zap.Error(err)) return err } - if _, ok := err.(*shared.BadRequestError); ok { + if _, ok := err.(*api.BadRequestError); ok { logger.Error("domain does not exist", zap.String("domain", domain), zap.Error(err)) return err } @@ -264,7 +265,7 @@ func verifyDomainExist(client workflowserviceclient.Interface, domain string, lo } func newWorkflowWorkerInternal( - service workflowserviceclient.Interface, + service api.Interface, domain string, params workerExecutionParameters, ppMgr pressurePointMgr, @@ -287,7 +288,7 @@ func newWorkflowWorkerInternal( func newWorkflowTaskWorkerInternal( taskHandler WorkflowTaskHandler, - service workflowserviceclient.Interface, + service api.Interface, domain string, params workerExecutionParameters, stopC chan struct{}, @@ -387,7 +388,7 @@ func (ww *workflowWorker) Stop() { ww.worker.Stop() } -func newSessionWorker(service workflowserviceclient.Interface, +func newSessionWorker(service api.Interface, domain string, params workerExecutionParameters, overrides *workerOverrides, @@ -444,7 +445,7 @@ func (sw *sessionWorker) Stop() { } func newActivityWorker( - service workflowserviceclient.Interface, + service api.Interface, domain string, params workerExecutionParameters, overrides *workerOverrides, @@ -479,7 +480,7 @@ func newActivityWorker( } func newActivityTaskWorker( - service workflowserviceclient.Interface, + service api.Interface, domain string, workerParams workerExecutionParameters, sessionTokenBucket *sessionTokenBucket, @@ -985,7 +986,7 @@ func (aw *aggregatedWorker) Stop() { // poller size. The typical RTT (round-trip time) is below 1ms within data center. And the poll API latency is about 5ms. // With 2 poller, we could achieve around 300~400 RPS. func newAggregatedWorker( - service workflowserviceclient.Interface, + service api.Interface, domain string, taskList string, options WorkerOptions, diff --git a/internal/internal_worker_base.go b/internal/internal_worker_base.go index 5fd5cafcc..c71d20f62 100644 --- a/internal/internal_worker_base.go +++ b/internal/internal_worker_base.go @@ -33,10 +33,11 @@ import ( "time" "github.com/uber-go/tally" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common/backoff" - "go.uber.org/cadence/v1/internal/common/metrics" - "go.uber.org/cadence/v1/internal/common/util" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/internal/common/backoff" + "go.uber.org/cadence/v2/internal/common/metrics" + "go.uber.org/cadence/v2/internal/common/util" "go.uber.org/zap" "go.uber.org/zap/zapcore" "golang.org/x/time/rate" @@ -97,7 +98,7 @@ type ( // WorkflowDefinition wraps the code that can execute a workflow. workflowDefinition interface { - Execute(env workflowEnvironment, header *shared.Header, input []byte) + Execute(env workflowEnvironment, header *apiv1.Header, input []byte) // Called for each non timed out startDecision event. // Executed after all history events since the previous decision are applied to workflowDefinition OnDecisionTaskStarted() @@ -292,8 +293,8 @@ func isNonRetriableError(err error) bool { return false } switch err.(type) { - case *shared.BadRequestError, - *shared.ClientVersionNotSupportedError: + case *api.BadRequestError, + *api.ClientVersionNotSupportedError: return true } return false diff --git a/internal/internal_worker_interfaces_test.go b/internal/internal_worker_interfaces_test.go index dfb37ebad..d0f99ba5b 100644 --- a/internal/internal_worker_interfaces_test.go +++ b/internal/internal_worker_interfaces_test.go @@ -30,8 +30,8 @@ import ( "github.com/golang/mock/gomock" "github.com/opentracing/opentracing-go" "github.com/stretchr/testify/suite" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowservicetest" - m "go.uber.org/cadence/v1/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" "go.uber.org/zap" ) @@ -53,7 +53,7 @@ type ( InterfacesTestSuite struct { suite.Suite mockCtrl *gomock.Controller - service *workflowservicetest.MockClient + service *api.MockInterface } ) @@ -167,7 +167,7 @@ func TestInterfacesTestSuite(t *testing.T) { func (s *InterfacesTestSuite) SetupTest() { s.mockCtrl = gomock.NewController(s.T()) - s.service = workflowservicetest.NewMockClient(s.mockCtrl) + s.service = api.NewMockInterface(s.mockCtrl) } func (s *InterfacesTestSuite) TearDownTest() { @@ -186,21 +186,21 @@ func (s *InterfacesTestSuite) TestInterface() { Tracer: opentracing.NoopTracer{}, } - domainStatus := m.DomainStatusRegistered - domainDesc := &m.DescribeDomainResponse{ - DomainInfo: &m.DomainInfo{ - Name: &domain, - Status: &domainStatus, + domainStatus := apiv1.DomainStatus_DOMAIN_STATUS_REGISTERED + domainDesc := &apiv1.DescribeDomainResponse{ + Domain: &apiv1.Domain{ + Name: domain, + Status: domainStatus, }, } // mocks s.service.EXPECT().DescribeDomain(gomock.Any(), gomock.Any(), callOptions...).Return(domainDesc, nil).AnyTimes() - s.service.EXPECT().PollForActivityTask(gomock.Any(), gomock.Any(), callOptions...).Return(&m.PollForActivityTaskResponse{}, nil).AnyTimes() - s.service.EXPECT().RespondActivityTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).Return(nil).AnyTimes() - s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(&m.PollForDecisionTaskResponse{}, nil).AnyTimes() + s.service.EXPECT().PollForActivityTask(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.PollForActivityTaskResponse{}, nil).AnyTimes() + s.service.EXPECT().RespondActivityTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).AnyTimes() + s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.PollForDecisionTaskResponse{}, nil).AnyTimes() s.service.EXPECT().RespondDecisionTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).AnyTimes() - s.service.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), callOptions...).Return(&m.StartWorkflowExecutionResponse{}, nil).AnyTimes() + s.service.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.StartWorkflowExecutionResponse{}, nil).AnyTimes() registry := newRegistry() // Launch worker. diff --git a/internal/internal_worker_test.go b/internal/internal_worker_test.go index 27fda842d..75989e898 100644 --- a/internal/internal_worker_test.go +++ b/internal/internal_worker_test.go @@ -31,15 +31,15 @@ import ( "testing" "time" + "github.com/gogo/protobuf/types" "github.com/golang/mock/gomock" "github.com/opentracing/opentracing-go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/uber-go/tally" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowservicetest" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" "go.uber.org/yarpc" "go.uber.org/zap" "go.uber.org/zap/zaptest" @@ -98,7 +98,7 @@ func testInternalWorkerRegisterWithTestEnv(env *TestWorkflowEnvironment) { type internalWorkerTestSuite struct { suite.Suite mockCtrl *gomock.Controller - service *workflowservicetest.MockClient + service *api.MockInterface registry *registry } @@ -112,7 +112,7 @@ func TestInternalWorkerTestSuite(t *testing.T) { func (s *internalWorkerTestSuite) SetupTest() { s.mockCtrl = gomock.NewController(s.T()) - s.service = workflowservicetest.NewMockClient(s.mockCtrl) + s.service = api.NewMockInterface(s.mockCtrl) } func (s *internalWorkerTestSuite) TearDownTest() { @@ -125,12 +125,12 @@ func getTestLogger(t *testing.T) *zap.Logger { func (s *internalWorkerTestSuite) testDecisionTaskHandlerHelper(params workerExecutionParameters) { taskList := "taskList1" - testEvents := []*shared.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &shared.WorkflowExecutionStartedEventAttributes{ - TaskList: &shared.TaskList{Name: common.StringPtr(taskList)}, - Input: testEncodeFunctionArgs(params.DataConverter), + testEvents := []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{ + TaskList: &apiv1.TaskList{Name: taskList}, + Input: &apiv1.Payload{Data: testEncodeFunctionArgs(params.DataConverter)}, }), - createTestEventDecisionTaskScheduled(2, &shared.DecisionTaskScheduledEventAttributes{}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{}), createTestEventDecisionTaskStarted(3), } @@ -138,11 +138,11 @@ func (s *internalWorkerTestSuite) testDecisionTaskHandlerHelper(params workerExe workflowID := "testID" runID := "testRunID" - task := &shared.PollForDecisionTaskResponse{ - WorkflowExecution: &shared.WorkflowExecution{WorkflowId: &workflowID, RunId: &runID}, - WorkflowType: &shared.WorkflowType{Name: &workflowType}, - History: &shared.History{Events: testEvents}, - PreviousStartedEventId: common.Int64Ptr(0), + task := &apiv1.PollForDecisionTaskResponse{ + WorkflowExecution: &apiv1.WorkflowExecution{WorkflowId: workflowID, RunId: runID}, + WorkflowType: &apiv1.WorkflowType{Name: workflowType}, + History: &apiv1.History{Events: testEvents}, + PreviousStartedEventId: &types.Int64Value{Value: 0}, } r := newWorkflowTaskHandler(testDomain, params, nil, s.registry) @@ -220,7 +220,7 @@ func (s *internalWorkerTestSuite) TestCreateShadowWorker() { func (s *internalWorkerTestSuite) TestCreateWorkerRun() { // Create service endpoint mockCtrl := gomock.NewController(s.T()) - service := workflowservicetest.NewMockClient(mockCtrl) + service := api.NewMockInterface(mockCtrl) worker := createWorker(service) var wg sync.WaitGroup @@ -251,18 +251,18 @@ func (s *internalWorkerTestSuite) TestWorkerStartFailsWithInvalidDomain() { domainErr error isErrFatal bool }{ - {&shared.EntityNotExistsError{}, true}, - {&shared.BadRequestError{}, true}, - {&shared.InternalServiceError{}, false}, + {&api.EntityNotExistsError{}, true}, + {&api.BadRequestError{}, true}, + {&api.InternalServiceError{}, false}, {errors.New("unknown"), false}, } mockCtrl := gomock.NewController(t) for _, tc := range testCases { - service := workflowservicetest.NewMockClient(mockCtrl) + service := api.NewMockInterface(mockCtrl) service.EXPECT().DescribeDomain(gomock.Any(), gomock.Any(), callOptions...).Return(nil, tc.domainErr).Do( - func(ctx context.Context, request *shared.DescribeDomainRequest, opts ...yarpc.CallOption) { + func(ctx context.Context, request *apiv1.DescribeDomainRequest, opts ...yarpc.CallOption) { // log }).Times(2) @@ -313,11 +313,11 @@ type mockPollForActivityTaskRequest struct { } func (m *mockPollForActivityTaskRequest) Matches(x interface{}) bool { - v, ok := x.(*shared.PollForActivityTaskRequest) + v, ok := x.(*apiv1.PollForActivityTaskRequest) if !ok { return false } - return *(v.TaskListMetadata.MaxTasksPerSecond) == m.tps + return v.TaskListMetadata.MaxTasksPerSecond.Value == m.tps } func (m *mockPollForActivityTaskRequest) String() string { @@ -325,39 +325,39 @@ func (m *mockPollForActivityTaskRequest) String() string { } func createWorker( - service *workflowservicetest.MockClient, + service *api.MockInterface, ) *aggregatedWorker { return createWorkerWithThrottle(service, float64(0.0), nil, nil) } func createShadowWorker( - service *workflowservicetest.MockClient, + service *api.MockInterface, shadowOptions *ShadowOptions, ) *aggregatedWorker { return createWorkerWithThrottle(service, float64(0.0), nil, shadowOptions) } func createWorkerWithThrottle( - service *workflowservicetest.MockClient, + service *api.MockInterface, activitiesPerSecond float64, dc DataConverter, shadowOptions *ShadowOptions, ) *aggregatedWorker { domain := "testDomain" - domainStatus := shared.DomainStatusRegistered - domainDesc := &shared.DescribeDomainResponse{ - DomainInfo: &shared.DomainInfo{ - Name: &domain, - Status: &domainStatus, + domainStatus := apiv1.DomainStatus_DOMAIN_STATUS_REGISTERED + domainDesc := &apiv1.DescribeDomainResponse{ + Domain: &apiv1.Domain{ + Name: domain, + Status: domainStatus, }, } // mocks service.EXPECT().DescribeDomain(gomock.Any(), gomock.Any(), callOptions...).Return(domainDesc, nil).Do( - func(ctx context.Context, request *shared.DescribeDomainRequest, opts ...yarpc.CallOption) { + func(ctx context.Context, request *apiv1.DescribeDomainRequest, opts ...yarpc.CallOption) { // log }).AnyTimes() - activityTask := &shared.PollForActivityTaskResponse{} + activityTask := &apiv1.PollForActivityTaskResponse{} expectedActivitiesPerSecond := activitiesPerSecond if expectedActivitiesPerSecond == 0.0 { expectedActivitiesPerSecond = defaultTaskListActivitiesPerSecond @@ -365,9 +365,9 @@ func createWorkerWithThrottle( service.EXPECT().PollForActivityTask( gomock.Any(), ofPollForActivityTaskRequest(expectedActivitiesPerSecond), callOptions..., ).Return(activityTask, nil).AnyTimes() - service.EXPECT().RespondActivityTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).Return(nil).AnyTimes() + service.EXPECT().RespondActivityTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).AnyTimes() - decisionTask := &shared.PollForDecisionTaskResponse{} + decisionTask := &apiv1.PollForDecisionTaskResponse{} service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(decisionTask, nil).AnyTimes() service.EXPECT().RespondDecisionTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).AnyTimes() @@ -395,27 +395,26 @@ func createWorkerWithThrottle( } func createWorkerWithDataConverter( - service *workflowservicetest.MockClient, + service *api.MockInterface, ) *aggregatedWorker { return createWorkerWithThrottle(service, float64(0.0), newTestDataConverter(), nil) } func (s *internalWorkerTestSuite) testCompleteActivityHelper(opt *ClientOptions) { t := s.T() - mockService := s.service domain := "testDomain" - wfClient := NewClient(mockService, domain, opt) + wfClient := NewClient(s.service, domain, opt) var completedRequest, canceledRequest, failedRequest interface{} - mockService.EXPECT().RespondActivityTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).Return(nil).Do( - func(ctx context.Context, request *shared.RespondActivityTaskCompletedRequest, opts ...yarpc.CallOption) { + s.service.EXPECT().RespondActivityTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).Do( + func(ctx context.Context, request *apiv1.RespondActivityTaskCompletedRequest, opts ...yarpc.CallOption) { completedRequest = request }) - mockService.EXPECT().RespondActivityTaskCanceled(gomock.Any(), gomock.Any(), callOptions...).Return(nil).Do( - func(ctx context.Context, request *shared.RespondActivityTaskCanceledRequest, opts ...yarpc.CallOption) { + s.service.EXPECT().RespondActivityTaskCanceled(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).Do( + func(ctx context.Context, request *apiv1.RespondActivityTaskCanceledRequest, opts ...yarpc.CallOption) { canceledRequest = request }) - mockService.EXPECT().RespondActivityTaskFailed(gomock.Any(), gomock.Any(), callOptions...).Return(nil).Do( - func(ctx context.Context, request *shared.RespondActivityTaskFailedRequest, opts ...yarpc.CallOption) { + s.service.EXPECT().RespondActivityTaskFailed(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).Do( + func(ctx context.Context, request *apiv1.RespondActivityTaskFailedRequest, opts ...yarpc.CallOption) { failedRequest = request }) @@ -440,20 +439,19 @@ func (s *internalWorkerTestSuite) TestCompleteActivity_WithDataConverter() { func (s *internalWorkerTestSuite) TestCompleteActivityById() { t := s.T() - mockService := s.service domain := "testDomain" - wfClient := NewClient(mockService, domain, nil) + wfClient := NewClient(s.service, domain, nil) var completedRequest, canceledRequest, failedRequest interface{} - mockService.EXPECT().RespondActivityTaskCompletedByID(gomock.Any(), gomock.Any(), callOptions...).Return(nil).Do( - func(ctx context.Context, request *shared.RespondActivityTaskCompletedByIDRequest, opts ...yarpc.CallOption) { + s.service.EXPECT().RespondActivityTaskCompletedByID(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).Do( + func(ctx context.Context, request *apiv1.RespondActivityTaskCompletedByIDRequest, opts ...yarpc.CallOption) { completedRequest = request }) - mockService.EXPECT().RespondActivityTaskCanceledByID(gomock.Any(), gomock.Any(), callOptions...).Return(nil).Do( - func(ctx context.Context, request *shared.RespondActivityTaskCanceledByIDRequest, opts ...yarpc.CallOption) { + s.service.EXPECT().RespondActivityTaskCanceledByID(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).Do( + func(ctx context.Context, request *apiv1.RespondActivityTaskCanceledByIDRequest, opts ...yarpc.CallOption) { canceledRequest = request }) - mockService.EXPECT().RespondActivityTaskFailedByID(gomock.Any(), gomock.Any(), callOptions...).Return(nil).Do( - func(ctx context.Context, request *shared.RespondActivityTaskFailedByIDRequest, opts ...yarpc.CallOption) { + s.service.EXPECT().RespondActivityTaskFailedByID(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).Do( + func(ctx context.Context, request *apiv1.RespondActivityTaskFailedByIDRequest, opts ...yarpc.CallOption) { failedRequest = request }) @@ -474,11 +472,10 @@ func (s *internalWorkerTestSuite) TestCompleteActivityById() { func (s *internalWorkerTestSuite) TestRecordActivityHeartbeat() { domain := "testDomain" wfClient := NewClient(s.service, domain, nil) - var heartbeatRequest *shared.RecordActivityTaskHeartbeatRequest - cancelRequested := false - heartbeatResponse := shared.RecordActivityTaskHeartbeatResponse{CancelRequested: &cancelRequested} + var heartbeatRequest *apiv1.RecordActivityTaskHeartbeatRequest + heartbeatResponse := apiv1.RecordActivityTaskHeartbeatResponse{CancelRequested: false} s.service.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), gomock.Any(), callOptions...).Return(&heartbeatResponse, nil). - Do(func(ctx context.Context, request *shared.RecordActivityTaskHeartbeatRequest, opts ...yarpc.CallOption) { + Do(func(ctx context.Context, request *apiv1.RecordActivityTaskHeartbeatRequest, opts ...yarpc.CallOption) { heartbeatRequest = request }).Times(2) @@ -493,18 +490,17 @@ func (s *internalWorkerTestSuite) TestRecordActivityHeartbeat_WithDataConverter( dc := newTestDataConverter() opt := &ClientOptions{DataConverter: dc} wfClient := NewClient(s.service, domain, opt) - var heartbeatRequest *shared.RecordActivityTaskHeartbeatRequest - cancelRequested := false - heartbeatResponse := shared.RecordActivityTaskHeartbeatResponse{CancelRequested: &cancelRequested} + var heartbeatRequest *apiv1.RecordActivityTaskHeartbeatRequest + heartbeatResponse := apiv1.RecordActivityTaskHeartbeatResponse{CancelRequested: false} detail1 := "testStack" detail2 := testStruct{"abc", 123} detail3 := 4 encodedDetail, err := dc.ToData(detail1, detail2, detail3) require.Nil(t, err) s.service.EXPECT().RecordActivityTaskHeartbeat(gomock.Any(), gomock.Any(), callOptions...).Return(&heartbeatResponse, nil). - Do(func(ctx context.Context, request *shared.RecordActivityTaskHeartbeatRequest, opts ...yarpc.CallOption) { + Do(func(ctx context.Context, request *apiv1.RecordActivityTaskHeartbeatRequest, opts ...yarpc.CallOption) { heartbeatRequest = request - require.Equal(t, encodedDetail, request.Details) + require.Equal(t, encodedDetail, request.Details.GetData()) }).Times(1) wfClient.RecordActivityHeartbeat(context.Background(), nil, detail1, detail2, detail3) @@ -514,11 +510,10 @@ func (s *internalWorkerTestSuite) TestRecordActivityHeartbeat_WithDataConverter( func (s *internalWorkerTestSuite) TestRecordActivityHeartbeatByID() { domain := "testDomain" wfClient := NewClient(s.service, domain, nil) - var heartbeatRequest *shared.RecordActivityTaskHeartbeatByIDRequest - cancelRequested := false - heartbeatResponse := shared.RecordActivityTaskHeartbeatResponse{CancelRequested: &cancelRequested} + var heartbeatRequest *apiv1.RecordActivityTaskHeartbeatByIDRequest + heartbeatResponse := apiv1.RecordActivityTaskHeartbeatByIDResponse{CancelRequested: false} s.service.EXPECT().RecordActivityTaskHeartbeatByID(gomock.Any(), gomock.Any(), callOptions...).Return(&heartbeatResponse, nil). - Do(func(ctx context.Context, request *shared.RecordActivityTaskHeartbeatByIDRequest, opts ...yarpc.CallOption) { + Do(func(ctx context.Context, request *apiv1.RecordActivityTaskHeartbeatByIDRequest, opts ...yarpc.CallOption) { heartbeatRequest = request }).Times(2) @@ -609,30 +604,30 @@ func (w activitiesCallingOptionsWorkflow) Execute(ctx Context, input []byte) (re require.True(w.t, **rStruct2Ptr == testActivityResult{Index: 10}) // By names. - err = ExecuteActivity(ctx, "go.uber.org/cadence/v1/internal.testActivityByteArgs", input).Get(ctx, nil) + err = ExecuteActivity(ctx, "go.uber.org/cadence/v2/internal.testActivityByteArgs", input).Get(ctx, nil) require.NoError(w.t, err, err) err = ExecuteActivity(ctx, "testActivityMultipleArgs", 2, []string{"test"}, true).Get(ctx, nil) require.NoError(w.t, err, err) - err = ExecuteActivity(ctx, "go.uber.org/cadence/v1/internal.testActivityNoResult", 2, "test").Get(ctx, nil) + err = ExecuteActivity(ctx, "go.uber.org/cadence/v2/internal.testActivityNoResult", 2, "test").Get(ctx, nil) require.NoError(w.t, err, err) - err = ExecuteActivity(ctx, "go.uber.org/cadence/v1/internal.testActivityNoContextArg", 2, "test").Get(ctx, nil) + err = ExecuteActivity(ctx, "go.uber.org/cadence/v2/internal.testActivityNoContextArg", 2, "test").Get(ctx, nil) require.NoError(w.t, err, err) - f = ExecuteActivity(ctx, "go.uber.org/cadence/v1/internal.testActivityReturnString") + f = ExecuteActivity(ctx, "go.uber.org/cadence/v2/internal.testActivityReturnString") err = f.Get(ctx, &rString) require.NoError(w.t, err, err) require.Equal(w.t, "testActivity", rString, rString) - f = ExecuteActivity(ctx, "go.uber.org/cadence/v1/internal.testActivityReturnEmptyString") + f = ExecuteActivity(ctx, "go.uber.org/cadence/v2/internal.testActivityReturnEmptyString") var r2sString string err = f.Get(ctx, &r2String) require.NoError(w.t, err, err) require.Equal(w.t, "", r2sString) - f = ExecuteActivity(ctx, "go.uber.org/cadence/v1/internal.testActivityReturnEmptyStruct") + f = ExecuteActivity(ctx, "go.uber.org/cadence/v2/internal.testActivityReturnEmptyStruct") err = f.Get(ctx, &r2Struct) require.NoError(w.t, err, err) require.Equal(w.t, testActivityResult{}, r2Struct) @@ -1165,15 +1160,15 @@ func TestIsNonRetriableError(t *testing.T) { expected: false, }, { - err: &shared.ServiceBusyError{}, + err: &api.ServiceBusyError{}, expected: false, }, { - err: &shared.BadRequestError{}, + err: &api.BadRequestError{}, expected: true, }, { - err: &shared.ClientVersionNotSupportedError{}, + err: &api.ClientVersionNotSupportedError{}, expected: true, }, } diff --git a/internal/internal_workers_test.go b/internal/internal_workers_test.go index c3ab76df6..2e5f44d60 100644 --- a/internal/internal_workers_test.go +++ b/internal/internal_workers_test.go @@ -27,13 +27,13 @@ import ( "testing" "time" + "github.com/gogo/protobuf/types" "github.com/golang/mock/gomock" "github.com/pborman/uuid" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/suite" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowservicetest" - m "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" "go.uber.org/yarpc" "go.uber.org/zap" ) @@ -47,7 +47,7 @@ func newNoResponseActivityTaskHandler() *noResponseActivityTaskHandler { return &noResponseActivityTaskHandler{isExecuteCalled: make(chan struct{})} } -func (ath noResponseActivityTaskHandler) Execute(taskList string, task *m.PollForActivityTaskResponse) (interface{}, error) { +func (ath noResponseActivityTaskHandler) Execute(taskList string, task *apiv1.PollForActivityTaskResponse) (interface{}, error) { close(ath.isExecuteCalled) c := make(chan struct{}) <-c @@ -63,14 +63,14 @@ type ( WorkersTestSuite struct { suite.Suite mockCtrl *gomock.Controller - service *workflowservicetest.MockClient + service *api.MockInterface } ) // Test suite. func (s *WorkersTestSuite) SetupTest() { s.mockCtrl = gomock.NewController(s.T()) - s.service = workflowservicetest.NewMockClient(s.mockCtrl) + s.service = api.NewMockInterface(s.mockCtrl) } func (s *WorkersTestSuite) TearDownTest() { @@ -91,7 +91,7 @@ func (s *WorkersTestSuite) TestWorkflowWorker() { logger, _ := zap.NewDevelopment() s.service.EXPECT().DescribeDomain(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil) - s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(&m.PollForDecisionTaskResponse{}, nil).AnyTimes() + s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.PollForDecisionTaskResponse{}, nil).AnyTimes() s.service.EXPECT().RespondDecisionTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).AnyTimes() ctx, cancel := context.WithCancel(context.Background()) @@ -125,8 +125,8 @@ func (s *WorkersTestSuite) testActivityWorker(useLocallyDispatched bool) { logger, _ := zap.NewDevelopment() s.service.EXPECT().DescribeDomain(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil) - s.service.EXPECT().PollForActivityTask(gomock.Any(), gomock.Any(), callOptions...).Return(&m.PollForActivityTaskResponse{}, nil).AnyTimes() - s.service.EXPECT().RespondActivityTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).Return(nil).AnyTimes() + s.service.EXPECT().PollForActivityTask(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.PollForActivityTaskResponse{}, nil).AnyTimes() + s.service.EXPECT().RespondActivityTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).AnyTimes() executionParameters := workerExecutionParameters{ TaskList: "testTaskList", @@ -148,27 +148,27 @@ func (s *WorkersTestSuite) TestActivityWorkerStop() { domain := "testDomain" logger, _ := zap.NewDevelopment() - pats := &m.PollForActivityTaskResponse{ + pats := &apiv1.PollForActivityTaskResponse{ TaskToken: []byte("token"), - WorkflowExecution: &m.WorkflowExecution{ - WorkflowId: common.StringPtr("wID"), - RunId: common.StringPtr("rID")}, - ActivityType: &m.ActivityType{Name: common.StringPtr("test")}, - ActivityId: common.StringPtr(uuid.New()), - ScheduledTimestamp: common.Int64Ptr(time.Now().UnixNano()), - ScheduledTimestampOfThisAttempt: common.Int64Ptr(time.Now().UnixNano()), - ScheduleToCloseTimeoutSeconds: common.Int32Ptr(1), - StartedTimestamp: common.Int64Ptr(time.Now().UnixNano()), - StartToCloseTimeoutSeconds: common.Int32Ptr(1), - WorkflowType: &m.WorkflowType{ - Name: common.StringPtr("wType"), + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: "wID", + RunId: "rID"}, + ActivityType: &apiv1.ActivityType{Name: "test"}, + ActivityId: uuid.New(), + ScheduledTime: api.TimeToProto(time.Now()), + ScheduledTimeOfThisAttempt: api.TimeToProto(time.Now()), + ScheduleToCloseTimeout: api.SecondsToProto(1), + StartedTime: api.TimeToProto(time.Now()), + StartToCloseTimeout: api.SecondsToProto(1), + WorkflowType: &apiv1.WorkflowType{ + Name: "wType", }, - WorkflowDomain: common.StringPtr("domain"), + WorkflowDomain: "domain", } s.service.EXPECT().DescribeDomain(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil) s.service.EXPECT().PollForActivityTask(gomock.Any(), gomock.Any(), callOptions...).Return(pats, nil).AnyTimes() - s.service.EXPECT().RespondActivityTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).Return(nil).AnyTimes() + s.service.EXPECT().RespondActivityTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).AnyTimes() stopC := make(chan struct{}) ctx, cancel := context.WithCancel(context.Background()) @@ -207,7 +207,7 @@ func (s *WorkersTestSuite) TestPollForDecisionTask_InternalServiceError() { domain := "testDomain" s.service.EXPECT().DescribeDomain(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil) - s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(&m.PollForDecisionTaskResponse{}, &m.InternalServiceError{}).AnyTimes() + s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.PollForDecisionTaskResponse{}, &api.InternalServiceError{}).AnyTimes() executionParameters := workerExecutionParameters{ TaskList: "testDecisionTaskList", @@ -251,82 +251,85 @@ func (s *WorkersTestSuite) TestLongRunningDecisionTask() { domain := "testDomain" taskList := "long-running-decision-tl" - testEvents := []*m.HistoryEvent{ + testEvents := []*apiv1.HistoryEvent{ { - EventId: common.Int64Ptr(1), - EventType: common.EventTypePtr(m.EventTypeWorkflowExecutionStarted), - WorkflowExecutionStartedEventAttributes: &m.WorkflowExecutionStartedEventAttributes{ - TaskList: &m.TaskList{Name: &taskList}, - ExecutionStartToCloseTimeoutSeconds: common.Int32Ptr(10), - TaskStartToCloseTimeoutSeconds: common.Int32Ptr(2), - WorkflowType: &m.WorkflowType{Name: common.StringPtr("long-running-decision-workflow-type")}, + EventId: 1, + Attributes: &apiv1.HistoryEvent_WorkflowExecutionStartedEventAttributes{ + WorkflowExecutionStartedEventAttributes: &apiv1.WorkflowExecutionStartedEventAttributes{ + TaskList: &apiv1.TaskList{Name: taskList}, + ExecutionStartToCloseTimeout: api.SecondsToProto(10), + TaskStartToCloseTimeout: api.SecondsToProto(2), + WorkflowType: &apiv1.WorkflowType{Name: "long-running-decision-workflow-type"}, + }, }, }, - createTestEventDecisionTaskScheduled(2, &m.DecisionTaskScheduledEventAttributes{TaskList: &m.TaskList{Name: &taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskCompleted(4, &m.DecisionTaskCompletedEventAttributes{ScheduledEventId: common.Int64Ptr(2)}), + createTestEventDecisionTaskCompleted(4, &apiv1.DecisionTaskCompletedEventAttributes{ScheduledEventId: 2}), { - EventId: common.Int64Ptr(5), - EventType: common.EventTypePtr(m.EventTypeMarkerRecorded), - MarkerRecordedEventAttributes: &m.MarkerRecordedEventAttributes{ - MarkerName: common.StringPtr(localActivityMarkerName), - Details: s.createLocalActivityMarkerDataForTest("0"), - DecisionTaskCompletedEventId: common.Int64Ptr(4), + EventId: 5, + Attributes: &apiv1.HistoryEvent_MarkerRecordedEventAttributes{ + MarkerRecordedEventAttributes: &apiv1.MarkerRecordedEventAttributes{ + MarkerName: localActivityMarkerName, + Details: &apiv1.Payload{Data: s.createLocalActivityMarkerDataForTest("0")}, + DecisionTaskCompletedEventId: 4, + }, }, }, - createTestEventDecisionTaskScheduled(6, &m.DecisionTaskScheduledEventAttributes{TaskList: &m.TaskList{Name: &taskList}}), + createTestEventDecisionTaskScheduled(6, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(7), - createTestEventDecisionTaskCompleted(8, &m.DecisionTaskCompletedEventAttributes{ScheduledEventId: common.Int64Ptr(2)}), + createTestEventDecisionTaskCompleted(8, &apiv1.DecisionTaskCompletedEventAttributes{ScheduledEventId: 2}), { - EventId: common.Int64Ptr(9), - EventType: common.EventTypePtr(m.EventTypeMarkerRecorded), - MarkerRecordedEventAttributes: &m.MarkerRecordedEventAttributes{ - MarkerName: common.StringPtr(localActivityMarkerName), - Details: s.createLocalActivityMarkerDataForTest("1"), - DecisionTaskCompletedEventId: common.Int64Ptr(8), + EventId: 9, + Attributes: &apiv1.HistoryEvent_MarkerRecordedEventAttributes{ + MarkerRecordedEventAttributes: &apiv1.MarkerRecordedEventAttributes{ + MarkerName: localActivityMarkerName, + Details: &apiv1.Payload{Data: s.createLocalActivityMarkerDataForTest("1")}, + DecisionTaskCompletedEventId: 8, + }, }, }, - createTestEventDecisionTaskScheduled(10, &m.DecisionTaskScheduledEventAttributes{TaskList: &m.TaskList{Name: &taskList}}), + createTestEventDecisionTaskScheduled(10, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(11), } s.service.EXPECT().DescribeDomain(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).AnyTimes() - task := &m.PollForDecisionTaskResponse{ + task := &apiv1.PollForDecisionTaskResponse{ TaskToken: []byte("test-token"), - WorkflowExecution: &m.WorkflowExecution{ - WorkflowId: common.StringPtr("long-running-decision-workflow-id"), - RunId: common.StringPtr("long-running-decision-workflow-run-id"), + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: "long-running-decision-workflow-id", + RunId: "long-running-decision-workflow-run-id", }, - WorkflowType: &m.WorkflowType{ - Name: common.StringPtr("long-running-decision-workflow-type"), + WorkflowType: &apiv1.WorkflowType{ + Name: "long-running-decision-workflow-type", }, - PreviousStartedEventId: common.Int64Ptr(0), - StartedEventId: common.Int64Ptr(3), - History: &m.History{Events: testEvents[0:3]}, + PreviousStartedEventId: &types.Int64Value{Value: 0}, + StartedEventId: 3, + History: &apiv1.History{Events: testEvents[0:3]}, NextPageToken: nil, - NextEventId: common.Int64Ptr(4), + NextEventId: 4, } s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(task, nil).Times(1) - s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(&m.PollForDecisionTaskResponse{}, &m.InternalServiceError{}).AnyTimes() + s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.PollForDecisionTaskResponse{}, &api.InternalServiceError{}).AnyTimes() respondCounter := 0 - s.service.EXPECT().RespondDecisionTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(ctx context.Context, request *m.RespondDecisionTaskCompletedRequest, opts ...yarpc.CallOption, - ) (success *m.RespondDecisionTaskCompletedResponse, err error) { + s.service.EXPECT().RespondDecisionTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(ctx context.Context, request *apiv1.RespondDecisionTaskCompletedRequest, opts ...yarpc.CallOption, + ) (success *apiv1.RespondDecisionTaskCompletedResponse, err error) { respondCounter++ switch respondCounter { case 1: s.Equal(1, len(request.Decisions)) - s.Equal(m.DecisionTypeRecordMarker, request.Decisions[0].GetDecisionType()) - *task.PreviousStartedEventId = 3 - *task.StartedEventId = 7 + s.NotNil(request.Decisions[0].GetRecordMarkerDecisionAttributes()) + task.PreviousStartedEventId = &types.Int64Value{Value: 3} + task.StartedEventId = 7 task.History.Events = testEvents[3:7] - return &m.RespondDecisionTaskCompletedResponse{DecisionTask: task}, nil + return &apiv1.RespondDecisionTaskCompletedResponse{DecisionTask: task}, nil case 2: s.Equal(2, len(request.Decisions)) - s.Equal(m.DecisionTypeRecordMarker, request.Decisions[0].GetDecisionType()) - s.Equal(m.DecisionTypeCompleteWorkflowExecution, request.Decisions[1].GetDecisionType()) - *task.PreviousStartedEventId = 7 - *task.StartedEventId = 11 + s.NotNil(request.Decisions[0].GetRecordMarkerDecisionAttributes()) + s.NotNil(request.Decisions[1].GetCompleteWorkflowExecutionDecisionAttributes()) + task.PreviousStartedEventId = &types.Int64Value{Value: 7} + task.StartedEventId = 11 task.History.Events = testEvents[7:11] close(doneCh) return nil, nil @@ -398,114 +401,117 @@ func (s *WorkersTestSuite) TestQueryTask_WorkflowCacheEvicted() { return nil } - testEvents := []*m.HistoryEvent{ + testEvents := []*apiv1.HistoryEvent{ { - EventId: common.Int64Ptr(1), - EventType: common.EventTypePtr(m.EventTypeWorkflowExecutionStarted), - WorkflowExecutionStartedEventAttributes: &m.WorkflowExecutionStartedEventAttributes{ - TaskList: &m.TaskList{Name: &taskList}, - ExecutionStartToCloseTimeoutSeconds: common.Int32Ptr(180), - TaskStartToCloseTimeoutSeconds: common.Int32Ptr(2), - WorkflowType: &m.WorkflowType{Name: common.StringPtr(workflowType)}, + EventId: 1, + Attributes: &apiv1.HistoryEvent_WorkflowExecutionStartedEventAttributes{ + WorkflowExecutionStartedEventAttributes: &apiv1.WorkflowExecutionStartedEventAttributes{ + TaskList: &apiv1.TaskList{Name: taskList}, + ExecutionStartToCloseTimeout: api.SecondsToProto(180), + TaskStartToCloseTimeout: api.SecondsToProto(2), + WorkflowType: &apiv1.WorkflowType{Name: workflowType}, + }, }, }, - createTestEventDecisionTaskScheduled(2, &m.DecisionTaskScheduledEventAttributes{TaskList: &m.TaskList{Name: &taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskCompleted(4, &m.DecisionTaskCompletedEventAttributes{ScheduledEventId: common.Int64Ptr(2)}), + createTestEventDecisionTaskCompleted(4, &apiv1.DecisionTaskCompletedEventAttributes{ScheduledEventId: 2}), { - EventId: common.Int64Ptr(5), - EventType: common.EventTypePtr(m.EventTypeTimerStarted), - TimerStartedEventAttributes: &m.TimerStartedEventAttributes{ - TimerId: common.StringPtr("0"), - StartToFireTimeoutSeconds: common.Int64Ptr(120), - DecisionTaskCompletedEventId: common.Int64Ptr(4), + EventId: 5, + Attributes: &apiv1.HistoryEvent_TimerStartedEventAttributes{ + TimerStartedEventAttributes: &apiv1.TimerStartedEventAttributes{ + TimerId: "0", + StartToFireTimeout: api.SecondsToProto(120), + DecisionTaskCompletedEventId: 4, + }, }, }, { - EventId: common.Int64Ptr(6), - EventType: common.EventTypePtr(m.EventTypeTimerFired), - TimerFiredEventAttributes: &m.TimerFiredEventAttributes{ - TimerId: common.StringPtr("0"), - StartedEventId: common.Int64Ptr(5), + EventId: 6, + Attributes: &apiv1.HistoryEvent_TimerFiredEventAttributes{ + TimerFiredEventAttributes: &apiv1.TimerFiredEventAttributes{ + TimerId: "0", + StartedEventId: 5, + }, }, }, - createTestEventDecisionTaskScheduled(7, &m.DecisionTaskScheduledEventAttributes{TaskList: &m.TaskList{Name: &taskList}}), + createTestEventDecisionTaskScheduled(7, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(8), - createTestEventDecisionTaskCompleted(9, &m.DecisionTaskCompletedEventAttributes{ScheduledEventId: common.Int64Ptr(2)}), - createTestEventActivityTaskScheduled(10, &m.ActivityTaskScheduledEventAttributes{ - ActivityId: common.StringPtr("1"), - ActivityType: &m.ActivityType{ - Name: common.StringPtr(activityType), + createTestEventDecisionTaskCompleted(9, &apiv1.DecisionTaskCompletedEventAttributes{ScheduledEventId: 2}), + createTestEventActivityTaskScheduled(10, &apiv1.ActivityTaskScheduledEventAttributes{ + ActivityId: "1", + ActivityType: &apiv1.ActivityType{ + Name: activityType, }, - Domain: common.StringPtr(domain), - TaskList: &m.TaskList{ - Name: common.StringPtr(taskList), + Domain: domain, + TaskList: &apiv1.TaskList{ + Name: taskList, }, - ScheduleToStartTimeoutSeconds: common.Int32Ptr(10), - StartToCloseTimeoutSeconds: common.Int32Ptr(10), - DecisionTaskCompletedEventId: common.Int64Ptr(9), + ScheduleToStartTimeout: api.SecondsToProto(10), + StartToCloseTimeout: api.SecondsToProto(10), + DecisionTaskCompletedEventId: 9, }), } s.service.EXPECT().DescribeDomain(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).AnyTimes() - task := &m.PollForDecisionTaskResponse{ + task := &apiv1.PollForDecisionTaskResponse{ TaskToken: []byte("test-token"), - WorkflowExecution: &m.WorkflowExecution{ - WorkflowId: common.StringPtr(workflowID), - RunId: common.StringPtr(runID), + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: workflowID, + RunId: runID, }, - WorkflowType: &m.WorkflowType{ - Name: common.StringPtr(workflowType), + WorkflowType: &apiv1.WorkflowType{ + Name: workflowType, }, - PreviousStartedEventId: common.Int64Ptr(0), - StartedEventId: common.Int64Ptr(3), - History: &m.History{Events: testEvents[0:3]}, + PreviousStartedEventId: &types.Int64Value{Value: 0}, + StartedEventId: 3, + History: &apiv1.History{Events: testEvents[0:3]}, NextPageToken: nil, - NextEventId: common.Int64Ptr(4), + NextEventId: 4, } s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(task, nil).Times(1) - s.service.EXPECT().RespondDecisionTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(ctx context.Context, request *m.RespondDecisionTaskCompletedRequest, opts ...yarpc.CallOption, - ) (success *m.RespondDecisionTaskCompletedResponse, err error) { + s.service.EXPECT().RespondDecisionTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(ctx context.Context, request *apiv1.RespondDecisionTaskCompletedRequest, opts ...yarpc.CallOption, + ) (success *apiv1.RespondDecisionTaskCompletedResponse, err error) { s.Equal(1, len(request.Decisions)) - s.Equal(m.DecisionTypeStartTimer, request.Decisions[0].GetDecisionType()) - return &m.RespondDecisionTaskCompletedResponse{}, nil + s.NotNil(request.Decisions[0].GetStartTimerDecisionAttributes()) + return &apiv1.RespondDecisionTaskCompletedResponse{}, nil }).Times(1) - queryTask := &m.PollForDecisionTaskResponse{ + queryTask := &apiv1.PollForDecisionTaskResponse{ TaskToken: []byte("test-token"), - WorkflowExecution: &m.WorkflowExecution{ - WorkflowId: common.StringPtr(workflowID), - RunId: common.StringPtr(runID), + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: workflowID, + RunId: runID, }, - WorkflowType: &m.WorkflowType{ - Name: common.StringPtr(workflowType), + WorkflowType: &apiv1.WorkflowType{ + Name: workflowType, }, - PreviousStartedEventId: common.Int64Ptr(3), - History: &m.History{}, // sticky query, so there's no history + PreviousStartedEventId: &types.Int64Value{Value: 3}, + History: &apiv1.History{}, // sticky query, so there's no history NextPageToken: nil, - NextEventId: common.Int64Ptr(5), - Query: &m.WorkflowQuery{ - QueryType: common.StringPtr(queryType), + NextEventId: 5, + Query: &apiv1.WorkflowQuery{ + QueryType: queryType, }, } - s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(ctx context.Context, request *m.PollForDecisionTaskRequest, opts ...yarpc.CallOption, - ) (success *m.PollForDecisionTaskResponse, err error) { + s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(ctx context.Context, request *apiv1.PollForDecisionTaskRequest, opts ...yarpc.CallOption, + ) (success *apiv1.PollForDecisionTaskResponse, err error) { getWorkflowCache().Delete(runID) // force remove the workflow state return queryTask, nil }).Times(1) - s.service.EXPECT().ResetStickyTaskList(gomock.Any(), gomock.Any(), callOptions...).Return(&m.ResetStickyTaskListResponse{}, nil).AnyTimes() - s.service.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&m.GetWorkflowExecutionHistoryResponse{ - History: &m.History{Events: testEvents}, // workflow has made progress, return all available events + s.service.EXPECT().ResetStickyTaskList(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.ResetStickyTaskListResponse{}, nil).AnyTimes() + s.service.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.GetWorkflowExecutionHistoryResponse{ + History: &apiv1.History{Events: testEvents}, // workflow has made progress, return all available events }, nil).Times(1) dc := getDefaultDataConverter() expectedResult, err := dc.ToData("waiting on timer") s.NoError(err) - s.service.EXPECT().RespondQueryTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(ctx context.Context, request *m.RespondQueryTaskCompletedRequest, opts ...yarpc.CallOption) error { - s.Equal(m.QueryTaskCompletedTypeCompleted, request.GetCompletedType()) - s.Equal(expectedResult, request.GetQueryResult()) + s.service.EXPECT().RespondQueryTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(ctx context.Context, request *apiv1.RespondQueryTaskCompletedRequest, opts ...yarpc.CallOption) error { + s.Equal(apiv1.QueryResultType_QUERY_RESULT_TYPE_ANSWERED, request.Result.GetResultType()) + s.Equal(expectedResult, request.Result.Answer.GetData()) close(doneCh) return nil }).Times(1) - s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(&m.PollForDecisionTaskResponse{}, &m.InternalServiceError{}).AnyTimes() + s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.PollForDecisionTaskResponse{}, &api.InternalServiceError{}).AnyTimes() options := WorkerOptions{ Logger: zap.NewNop(), @@ -557,74 +563,77 @@ func (s *WorkersTestSuite) TestMultipleLocalActivities() { domain := "testDomain" taskList := "multiple-local-activities-tl" - testEvents := []*m.HistoryEvent{ + testEvents := []*apiv1.HistoryEvent{ { - EventId: common.Int64Ptr(1), - EventType: common.EventTypePtr(m.EventTypeWorkflowExecutionStarted), - WorkflowExecutionStartedEventAttributes: &m.WorkflowExecutionStartedEventAttributes{ - TaskList: &m.TaskList{Name: &taskList}, - ExecutionStartToCloseTimeoutSeconds: common.Int32Ptr(10), - TaskStartToCloseTimeoutSeconds: common.Int32Ptr(3), - WorkflowType: &m.WorkflowType{Name: common.StringPtr("multiple-local-activities-workflow-type")}, + EventId: 1, + Attributes: &apiv1.HistoryEvent_WorkflowExecutionStartedEventAttributes{ + WorkflowExecutionStartedEventAttributes: &apiv1.WorkflowExecutionStartedEventAttributes{ + TaskList: &apiv1.TaskList{Name: taskList}, + ExecutionStartToCloseTimeout: api.SecondsToProto(10), + TaskStartToCloseTimeout: api.SecondsToProto(3), + WorkflowType: &apiv1.WorkflowType{Name: "multiple-local-activities-workflow-type"}, + }, }, }, - createTestEventDecisionTaskScheduled(2, &m.DecisionTaskScheduledEventAttributes{TaskList: &m.TaskList{Name: &taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskCompleted(4, &m.DecisionTaskCompletedEventAttributes{ScheduledEventId: common.Int64Ptr(2)}), + createTestEventDecisionTaskCompleted(4, &apiv1.DecisionTaskCompletedEventAttributes{ScheduledEventId: 2}), { - EventId: common.Int64Ptr(5), - EventType: common.EventTypePtr(m.EventTypeMarkerRecorded), - MarkerRecordedEventAttributes: &m.MarkerRecordedEventAttributes{ - MarkerName: common.StringPtr(localActivityMarkerName), - Details: s.createLocalActivityMarkerDataForTest("0"), - DecisionTaskCompletedEventId: common.Int64Ptr(4), + EventId: 5, + Attributes: &apiv1.HistoryEvent_MarkerRecordedEventAttributes{ + MarkerRecordedEventAttributes: &apiv1.MarkerRecordedEventAttributes{ + MarkerName: localActivityMarkerName, + Details: &apiv1.Payload{Data: s.createLocalActivityMarkerDataForTest("0")}, + DecisionTaskCompletedEventId: 4, + }, }, }, - createTestEventDecisionTaskScheduled(6, &m.DecisionTaskScheduledEventAttributes{TaskList: &m.TaskList{Name: &taskList}}), + createTestEventDecisionTaskScheduled(6, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(7), - createTestEventDecisionTaskCompleted(8, &m.DecisionTaskCompletedEventAttributes{ScheduledEventId: common.Int64Ptr(2)}), + createTestEventDecisionTaskCompleted(8, &apiv1.DecisionTaskCompletedEventAttributes{ScheduledEventId: 2}), { - EventId: common.Int64Ptr(9), - EventType: common.EventTypePtr(m.EventTypeMarkerRecorded), - MarkerRecordedEventAttributes: &m.MarkerRecordedEventAttributes{ - MarkerName: common.StringPtr(localActivityMarkerName), - Details: s.createLocalActivityMarkerDataForTest("1"), - DecisionTaskCompletedEventId: common.Int64Ptr(8), + EventId: 9, + Attributes: &apiv1.HistoryEvent_MarkerRecordedEventAttributes{ + MarkerRecordedEventAttributes: &apiv1.MarkerRecordedEventAttributes{ + MarkerName: localActivityMarkerName, + Details: &apiv1.Payload{Data: s.createLocalActivityMarkerDataForTest("1")}, + DecisionTaskCompletedEventId: 8, + }, }, }, - createTestEventDecisionTaskScheduled(10, &m.DecisionTaskScheduledEventAttributes{TaskList: &m.TaskList{Name: &taskList}}), + createTestEventDecisionTaskScheduled(10, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(11), } s.service.EXPECT().DescribeDomain(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).AnyTimes() - task := &m.PollForDecisionTaskResponse{ + task := &apiv1.PollForDecisionTaskResponse{ TaskToken: []byte("test-token"), - WorkflowExecution: &m.WorkflowExecution{ - WorkflowId: common.StringPtr("multiple-local-activities-workflow-id"), - RunId: common.StringPtr("multiple-local-activities-workflow-run-id"), + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: "multiple-local-activities-workflow-id", + RunId: "multiple-local-activities-workflow-run-id", }, - WorkflowType: &m.WorkflowType{ - Name: common.StringPtr("multiple-local-activities-workflow-type"), + WorkflowType: &apiv1.WorkflowType{ + Name: "multiple-local-activities-workflow-type", }, - PreviousStartedEventId: common.Int64Ptr(0), - StartedEventId: common.Int64Ptr(3), - History: &m.History{Events: testEvents[0:3]}, + PreviousStartedEventId: &types.Int64Value{Value: 0}, + StartedEventId: 3, + History: &apiv1.History{Events: testEvents[0:3]}, NextPageToken: nil, - NextEventId: common.Int64Ptr(4), + NextEventId: 4, } s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(task, nil).Times(1) - s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(&m.PollForDecisionTaskResponse{}, &m.InternalServiceError{}).AnyTimes() + s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.PollForDecisionTaskResponse{}, &api.InternalServiceError{}).AnyTimes() respondCounter := 0 - s.service.EXPECT().RespondDecisionTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(ctx context.Context, request *m.RespondDecisionTaskCompletedRequest, opts ...yarpc.CallOption, - ) (success *m.RespondDecisionTaskCompletedResponse, err error) { + s.service.EXPECT().RespondDecisionTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(ctx context.Context, request *apiv1.RespondDecisionTaskCompletedRequest, opts ...yarpc.CallOption, + ) (success *apiv1.RespondDecisionTaskCompletedResponse, err error) { respondCounter++ switch respondCounter { case 1: s.Equal(3, len(request.Decisions)) - s.Equal(m.DecisionTypeRecordMarker, request.Decisions[0].GetDecisionType()) - *task.PreviousStartedEventId = 3 - *task.StartedEventId = 7 + s.NotNil(request.Decisions[0].GetRecordMarkerDecisionAttributes()) + task.PreviousStartedEventId = &types.Int64Value{Value: 3} + task.StartedEventId = 7 task.History.Events = testEvents[3:11] close(doneCh) return nil, nil @@ -695,60 +704,61 @@ func (s *WorkersTestSuite) TestLocallyDispatchedActivity() { domain := "testDomain" workflowType := "locally-dispatched-activity-workflow-type" taskList := "locally-dispatched-activity-tl" - testEvents := []*m.HistoryEvent{ + testEvents := []*apiv1.HistoryEvent{ { - EventId: common.Int64Ptr(1), - EventType: common.EventTypePtr(m.EventTypeWorkflowExecutionStarted), - WorkflowExecutionStartedEventAttributes: &m.WorkflowExecutionStartedEventAttributes{ - TaskList: &m.TaskList{Name: &taskList}, - ExecutionStartToCloseTimeoutSeconds: common.Int32Ptr(10), - TaskStartToCloseTimeoutSeconds: common.Int32Ptr(2), - WorkflowType: &m.WorkflowType{Name: common.StringPtr(workflowType)}, + EventId: 1, + Attributes: &apiv1.HistoryEvent_WorkflowExecutionStartedEventAttributes{ + WorkflowExecutionStartedEventAttributes: &apiv1.WorkflowExecutionStartedEventAttributes{ + TaskList: &apiv1.TaskList{Name: taskList}, + ExecutionStartToCloseTimeout: api.SecondsToProto(10), + TaskStartToCloseTimeout: api.SecondsToProto(2), + WorkflowType: &apiv1.WorkflowType{Name: workflowType}, + }, }, }, - createTestEventDecisionTaskScheduled(2, &m.DecisionTaskScheduledEventAttributes{TaskList: &m.TaskList{Name: &taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(3), } s.service.EXPECT().DescribeDomain(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).AnyTimes() - task := &m.PollForDecisionTaskResponse{ + task := &apiv1.PollForDecisionTaskResponse{ TaskToken: []byte("test-token"), - WorkflowExecution: &m.WorkflowExecution{ - WorkflowId: common.StringPtr("locally-dispatched-activity-workflow-id"), - RunId: common.StringPtr("locally-dispatched-activity-workflow-run-id"), + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: "locally-dispatched-activity-workflow-id", + RunId: "locally-dispatched-activity-workflow-run-id", }, - WorkflowType: &m.WorkflowType{ - Name: common.StringPtr(workflowType), + WorkflowType: &apiv1.WorkflowType{ + Name: workflowType, }, - PreviousStartedEventId: common.Int64Ptr(0), - StartedEventId: common.Int64Ptr(3), - History: &m.History{Events: testEvents[0:3]}, + PreviousStartedEventId: &types.Int64Value{Value: 0}, + StartedEventId: 3, + History: &apiv1.History{Events: testEvents[0:3]}, NextPageToken: nil, - NextEventId: common.Int64Ptr(4), + NextEventId: 4, } s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(task, nil).Times(1) - s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(&m.PollForDecisionTaskResponse{}, &m.InternalServiceError{}).AnyTimes() + s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.PollForDecisionTaskResponse{}, &api.InternalServiceError{}).AnyTimes() s.service.EXPECT().PollForActivityTask(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).AnyTimes() - s.service.EXPECT().RespondDecisionTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(ctx context.Context, request *m.RespondDecisionTaskCompletedRequest, opts ...yarpc.CallOption, - ) (success *m.RespondDecisionTaskCompletedResponse, err error) { + s.service.EXPECT().RespondDecisionTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(ctx context.Context, request *apiv1.RespondDecisionTaskCompletedRequest, opts ...yarpc.CallOption, + ) (success *apiv1.RespondDecisionTaskCompletedResponse, err error) { s.Equal(1, len(request.Decisions)) - activitiesToDispatchLocally := make(map[string]*m.ActivityLocalDispatchInfo) + activitiesToDispatchLocally := make(map[string]*apiv1.ActivityLocalDispatchInfo) d := request.Decisions[0] - s.Equal(m.DecisionTypeScheduleActivityTask, d.GetDecisionType()) - activitiesToDispatchLocally[*d.ScheduleActivityTaskDecisionAttributes.ActivityId] = - &m.ActivityLocalDispatchInfo{ - ActivityId: d.ScheduleActivityTaskDecisionAttributes.ActivityId, - ScheduledTimestamp: common.Int64Ptr(time.Now().UnixNano()), - ScheduledTimestampOfThisAttempt: common.Int64Ptr(time.Now().UnixNano()), - StartedTimestamp: common.Int64Ptr(time.Now().UnixNano()), - TaskToken: []byte("test-token")} - return &m.RespondDecisionTaskCompletedResponse{ActivitiesToDispatchLocally: activitiesToDispatchLocally}, nil + s.NotNil(d.GetScheduleActivityTaskDecisionAttributes()) + activitiesToDispatchLocally[d.GetScheduleActivityTaskDecisionAttributes().ActivityId] = + &apiv1.ActivityLocalDispatchInfo{ + ActivityId: d.GetScheduleActivityTaskDecisionAttributes().ActivityId, + ScheduledTime: api.TimeToProto(time.Now()), + ScheduledTimeOfThisAttempt: api.TimeToProto(time.Now()), + StartedTime: api.TimeToProto(time.Now()), + TaskToken: []byte("test-token")} + return &apiv1.RespondDecisionTaskCompletedResponse{ActivitiesToDispatchLocally: activitiesToDispatchLocally}, nil }).Times(1) - s.service.EXPECT().RespondActivityTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(ctx context.Context, request *m.RespondActivityTaskCompletedRequest, opts ...yarpc.CallOption, - ) error { + s.service.EXPECT().RespondActivityTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(ctx context.Context, request *apiv1.RespondActivityTaskCompletedRequest, opts ...yarpc.CallOption, + ) (*apiv1.RespondActivityTaskCompletedResponse, error) { defer close(doneCh) isActivityResponseCompleted = true - return nil + return nil, nil }).Times(1) options := WorkerOptions{ @@ -803,18 +813,19 @@ func (s *WorkersTestSuite) TestMultipleLocallyDispatchedActivity() { domain := "testDomain" workflowType := "locally-dispatched-multiple-activity-workflow-type" taskList := "locally-dispatched-multiple-activity-tl" - testEvents := []*m.HistoryEvent{ + testEvents := []*apiv1.HistoryEvent{ { - EventId: common.Int64Ptr(1), - EventType: common.EventTypePtr(m.EventTypeWorkflowExecutionStarted), - WorkflowExecutionStartedEventAttributes: &m.WorkflowExecutionStartedEventAttributes{ - TaskList: &m.TaskList{Name: &taskList}, - ExecutionStartToCloseTimeoutSeconds: common.Int32Ptr(10), - TaskStartToCloseTimeoutSeconds: common.Int32Ptr(2), - WorkflowType: &m.WorkflowType{Name: common.StringPtr(workflowType)}, + EventId: 1, + Attributes: &apiv1.HistoryEvent_WorkflowExecutionStartedEventAttributes{ + WorkflowExecutionStartedEventAttributes: &apiv1.WorkflowExecutionStartedEventAttributes{ + TaskList: &apiv1.TaskList{Name: taskList}, + ExecutionStartToCloseTimeout: api.SecondsToProto(10), + TaskStartToCloseTimeout: api.SecondsToProto(2), + WorkflowType: &apiv1.WorkflowType{Name: workflowType}, + }, }, }, - createTestEventDecisionTaskScheduled(2, &m.DecisionTaskScheduledEventAttributes{TaskList: &m.TaskList{Name: &taskList}}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{TaskList: &apiv1.TaskList{Name: taskList}}), createTestEventDecisionTaskStarted(3), } @@ -824,50 +835,50 @@ func (s *WorkersTestSuite) TestMultipleLocallyDispatchedActivity() { } s.service.EXPECT().DescribeDomain(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).AnyTimes() - task := &m.PollForDecisionTaskResponse{ + task := &apiv1.PollForDecisionTaskResponse{ TaskToken: []byte("test-token"), - WorkflowExecution: &m.WorkflowExecution{ - WorkflowId: common.StringPtr("locally-dispatched-multiple-activity-workflow-id"), - RunId: common.StringPtr("locally-dispatched-multiple-activity-workflow-run-id"), + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: "locally-dispatched-multiple-activity-workflow-id", + RunId: "locally-dispatched-multiple-activity-workflow-run-id", }, - WorkflowType: &m.WorkflowType{ - Name: common.StringPtr(workflowType), + WorkflowType: &apiv1.WorkflowType{ + Name: workflowType, }, - PreviousStartedEventId: common.Int64Ptr(0), - StartedEventId: common.Int64Ptr(3), - History: &m.History{Events: testEvents[0:3]}, + PreviousStartedEventId: &types.Int64Value{Value: 0}, + StartedEventId: 3, + History: &apiv1.History{Events: testEvents[0:3]}, NextPageToken: nil, - NextEventId: common.Int64Ptr(4), + NextEventId: 4, } s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(task, nil).Times(1) - s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(&m.PollForDecisionTaskResponse{}, &m.InternalServiceError{}).AnyTimes() + s.service.EXPECT().PollForDecisionTask(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.PollForDecisionTaskResponse{}, &api.InternalServiceError{}).AnyTimes() s.service.EXPECT().PollForActivityTask(gomock.Any(), gomock.Any(), callOptions...).Return(nil, nil).AnyTimes() - s.service.EXPECT().RespondDecisionTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(ctx context.Context, request *m.RespondDecisionTaskCompletedRequest, opts ...yarpc.CallOption, - ) (success *m.RespondDecisionTaskCompletedResponse, err error) { + s.service.EXPECT().RespondDecisionTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(ctx context.Context, request *apiv1.RespondDecisionTaskCompletedRequest, opts ...yarpc.CallOption, + ) (success *apiv1.RespondDecisionTaskCompletedResponse, err error) { s.Equal(int(activityCount), len(request.Decisions)) - activitiesToDispatchLocally := make(map[string]*m.ActivityLocalDispatchInfo) + activitiesToDispatchLocally := make(map[string]*apiv1.ActivityLocalDispatchInfo) for _, d := range request.Decisions { - s.Equal(m.DecisionTypeScheduleActivityTask, d.GetDecisionType()) - activitiesToDispatchLocally[*d.ScheduleActivityTaskDecisionAttributes.ActivityId] = - &m.ActivityLocalDispatchInfo{ - ActivityId: d.ScheduleActivityTaskDecisionAttributes.ActivityId, - ScheduledTimestamp: common.Int64Ptr(time.Now().UnixNano()), - ScheduledTimestampOfThisAttempt: common.Int64Ptr(time.Now().UnixNano()), - StartedTimestamp: common.Int64Ptr(time.Now().UnixNano()), - TaskToken: []byte("test-token")} + s.NotNil(d.GetScheduleActivityTaskDecisionAttributes()) + activitiesToDispatchLocally[d.GetScheduleActivityTaskDecisionAttributes().ActivityId] = + &apiv1.ActivityLocalDispatchInfo{ + ActivityId: d.GetScheduleActivityTaskDecisionAttributes().ActivityId, + ScheduledTime: api.TimeToProto(time.Now()), + ScheduledTimeOfThisAttempt: api.TimeToProto(time.Now()), + StartedTime: api.TimeToProto(time.Now()), + TaskToken: []byte("test-token")} } - return &m.RespondDecisionTaskCompletedResponse{ActivitiesToDispatchLocally: activitiesToDispatchLocally}, nil + return &apiv1.RespondDecisionTaskCompletedResponse{ActivitiesToDispatchLocally: activitiesToDispatchLocally}, nil }).Times(1) var activityResponseCompletedCount uint32 = 0 - s.service.EXPECT().RespondActivityTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(ctx context.Context, request *m.RespondActivityTaskCompletedRequest, opts ...yarpc.CallOption, - ) error { + s.service.EXPECT().RespondActivityTaskCompleted(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(ctx context.Context, request *apiv1.RespondActivityTaskCompletedRequest, opts ...yarpc.CallOption, + ) (*apiv1.RespondActivityTaskCompletedResponse, error) { defer func() { if atomic.LoadUint32(&activityResponseCompletedCount) == activityCount { close(doneCh) } }() atomic.AddUint32(&activityResponseCompletedCount, 1) - return nil + return nil, nil }).MinTimes(1) worker := newAggregatedWorker(s.service, domain, taskList, options) diff --git a/internal/internal_workflow.go b/internal/internal_workflow.go index f01debbaa..8733a4c74 100644 --- a/internal/internal_workflow.go +++ b/internal/internal_workflow.go @@ -35,11 +35,10 @@ import ( "github.com/robfig/cron" "go.uber.org/atomic" - "go.uber.org/cadence/v1/.gen/go/shared" - s "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" - "go.uber.org/cadence/v1/internal/common/metrics" - "go.uber.org/cadence/v1/internal/common/util" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/common" + "go.uber.org/cadence/v2/internal/common/metrics" + "go.uber.org/cadence/v2/internal/common/util" "go.uber.org/zap" ) @@ -177,7 +176,7 @@ type ( queryHandlers map[string]func([]byte) ([]byte, error) workflowIDReusePolicy WorkflowIDReusePolicy dataConverter DataConverter - retryPolicy *shared.RetryPolicy + retryPolicy *apiv1.RetryPolicy cronSchedule string contextPropagators []ContextPropagator memo map[string]interface{} @@ -189,7 +188,7 @@ type ( workflowOptions workflowType *WorkflowType input []byte - header *shared.Header + header *apiv1.Header attempt int32 // used by test framework to support child workflow retry scheduledTime time.Time // used by test framework to support child workflow retry lastCompletionResult []byte // used by test framework to support cron @@ -451,7 +450,7 @@ func newWorkflowInterceptors( return interceptor, envInterceptor } -func (d *syncWorkflowDefinition) Execute(env workflowEnvironment, header *shared.Header, input []byte) { +func (d *syncWorkflowDefinition) Execute(env workflowEnvironment, header *apiv1.Header, input []byte) { interceptors, envInterceptor := newWorkflowInterceptors(env, env.GetWorkflowInterceptors()) dispatcher, rootCtx := newDispatcher(newWorkflowContext(env, interceptors, envInterceptor), func(ctx Context) { r := &workflowResult{} @@ -1177,7 +1176,7 @@ func getValidatedWorkflowOptions(ctx Context) (*workflowOptions, error) { return nil, errors.New("missing or negative DecisionTaskStartToCloseTimeout") } if *p.taskStartToCloseTimeoutSeconds == 0 { - p.taskStartToCloseTimeoutSeconds = common.Int32Ptr(defaultDecisionTaskTimeoutInSecs) + p.taskStartToCloseTimeoutSeconds = common.Int32Ptr(common.Int32Ceil(defaultDecisionTaskTimeout.Seconds())) } if p.executionStartToCloseTimeoutSeconds == nil || *p.executionStartToCloseTimeoutSeconds <= 0 { return nil, errors.New("missing or invalid ExecutionStartToCloseTimeout") @@ -1242,9 +1241,9 @@ func getContextPropagatorsFromWorkflowContext(ctx Context) []ContextPropagator { return options.contextPropagators } -func getHeadersFromContext(ctx Context) *shared.Header { - header := &s.Header{ - Fields: make(map[string][]byte), +func getHeadersFromContext(ctx Context) *apiv1.Header { + header := &apiv1.Header{ + Fields: make(map[string]*apiv1.Payload), } contextPropagators := getContextPropagatorsFromWorkflowContext(ctx) for _, ctxProp := range contextPropagators { diff --git a/internal/internal_workflow_client.go b/internal/internal_workflow_client.go index c3d9efb70..339ee3c7d 100644 --- a/internal/internal_workflow_client.go +++ b/internal/internal_workflow_client.go @@ -29,17 +29,17 @@ import ( "reflect" "time" - "go.uber.org/cadence/v1/internal/common/serializer" - "github.com/opentracing/opentracing-go" "github.com/pborman/uuid" "github.com/uber-go/tally" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" - s "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" - "go.uber.org/cadence/v1/internal/common/backoff" - "go.uber.org/cadence/v1/internal/common/metrics" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/internal/common" + "go.uber.org/cadence/v2/internal/common/backoff" + "go.uber.org/cadence/v2/internal/common/metrics" + "go.uber.org/cadence/v2/internal/common/serializer" + "go.uber.org/cadence/v2/internal/common/util" ) // Assert that structs do indeed implement the interfaces @@ -47,7 +47,7 @@ var _ Client = (*workflowClient)(nil) var _ DomainClient = (*domainClient)(nil) const ( - defaultDecisionTaskTimeoutInSecs = 10 + defaultDecisionTaskTimeout = 10 * time.Second defaultGetHistoryTimeoutInSecs = 25 ) @@ -58,7 +58,7 @@ var ( type ( // workflowClient is the client for starting a workflow execution. workflowClient struct { - workflowService workflowserviceclient.Interface + workflowService api.Interface domain string registry *registry metricsScope *metrics.TaggedScope @@ -70,7 +70,7 @@ type ( // domainClient is the client for managing domains. domainClient struct { - workflowService workflowserviceclient.Interface + workflowService api.Interface metricsScope tally.Scope identity string } @@ -118,7 +118,7 @@ type ( // - EntityNotExistsError // - BadRequestError // - InternalServiceError - Next() (*s.HistoryEvent, error) + Next() (*apiv1.HistoryEvent, error) } // historyEventIteratorImpl is the implementation of HistoryEventIterator @@ -127,13 +127,13 @@ type ( initialized bool // local cached history events and corresponding consuming index nextEventIndex int - events []*s.HistoryEvent + events []*apiv1.HistoryEvent // token to get next page of history events nexttoken []byte // err when getting next page of history events err error // func which use a next token to get next page of history events - paginate func(nexttoken []byte) (*s.GetWorkflowExecutionHistoryResponse, error) + paginate func(nexttoken []byte) (*apiv1.GetWorkflowExecutionHistoryResponse, error) } ) @@ -160,17 +160,17 @@ func (wc *workflowClient) StartWorkflow( return nil, errors.New("missing TaskList") } - executionTimeout := common.Int32Ceil(options.ExecutionStartToCloseTimeout.Seconds()) + executionTimeout := options.ExecutionStartToCloseTimeout if executionTimeout <= 0 { return nil, errors.New("missing or invalid ExecutionStartToCloseTimeout") } - decisionTaskTimeout := common.Int32Ceil(options.DecisionTaskStartToCloseTimeout.Seconds()) + decisionTaskTimeout := options.DecisionTaskStartToCloseTimeout if decisionTaskTimeout < 0 { return nil, errors.New("negative DecisionTaskStartToCloseTimeout provided") } if decisionTaskTimeout == 0 { - decisionTaskTimeout = defaultDecisionTaskTimeoutInSecs + decisionTaskTimeout = defaultDecisionTaskTimeout } // Validate type and its arguments. @@ -189,8 +189,8 @@ func (wc *workflowClient) StartWorkflow( return nil, err } - delayStartSeconds := common.Int32Ceil(options.DelayStart.Seconds()) - if delayStartSeconds < 0 { + delayStart := options.DelayStart + if delayStart < 0 { return nil, errors.New("Invalid DelayStart option") } @@ -208,26 +208,26 @@ func (wc *workflowClient) StartWorkflow( header := wc.getWorkflowHeader(ctx) // run propagators to extract information about tracing and other stuff, store in headers field - startRequest := &s.StartWorkflowExecutionRequest{ - Domain: common.StringPtr(wc.domain), - RequestId: common.StringPtr(uuid.New()), - WorkflowId: common.StringPtr(workflowID), - WorkflowType: workflowTypePtr(*workflowType), - TaskList: common.TaskListPtr(s.TaskList{Name: common.StringPtr(options.TaskList)}), - Input: input, - ExecutionStartToCloseTimeoutSeconds: common.Int32Ptr(executionTimeout), - TaskStartToCloseTimeoutSeconds: common.Int32Ptr(decisionTaskTimeout), - Identity: common.StringPtr(wc.identity), - WorkflowIdReusePolicy: options.WorkflowIDReusePolicy.toThriftPtr(), - RetryPolicy: convertRetryPolicy(options.RetryPolicy), - CronSchedule: common.StringPtr(options.CronSchedule), - Memo: memo, - SearchAttributes: searchAttr, - Header: header, - DelayStartSeconds: common.Int32Ptr(delayStartSeconds), - } - - var response *s.StartWorkflowExecutionResponse + startRequest := &apiv1.StartWorkflowExecutionRequest{ + Domain: wc.domain, + RequestId: uuid.New(), + WorkflowId: workflowID, + WorkflowType: &apiv1.WorkflowType{Name: workflowType.Name}, + TaskList: &apiv1.TaskList{Name: options.TaskList}, + Input: &apiv1.Payload{Data: input}, + ExecutionStartToCloseTimeout: api.DurationToProto(executionTimeout), + TaskStartToCloseTimeout: api.DurationToProto(decisionTaskTimeout), + Identity: wc.identity, + WorkflowIdReusePolicy: options.WorkflowIDReusePolicy.toProto(), + RetryPolicy: convertRetryPolicy(options.RetryPolicy), + CronSchedule: options.CronSchedule, + Memo: memo, + SearchAttributes: searchAttr, + Header: header, + DelayStart: api.DurationToProto(delayStart), + } + + var response *apiv1.StartWorkflowExecutionResponse // Start creating workflow request. err = backoff.Retry(ctx, @@ -237,7 +237,7 @@ func (wc *workflowClient) StartWorkflow( var err1 error response, err1 = wc.workflowService.StartWorkflowExecution(tchCtx, startRequest, opt...) - return err1 + return api.ConvertError(err1) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) if err != nil { @@ -272,8 +272,8 @@ func (wc *workflowClient) ExecuteWorkflow(ctx context.Context, options StartWork var workflowID string executionInfo, err := wc.StartWorkflow(ctx, options, workflow, args...) if err != nil { - if alreadyStartedErr, ok := err.(*s.WorkflowExecutionAlreadyStartedError); ok { - runID = alreadyStartedErr.GetRunId() + if alreadyStartedErr, ok := err.(*api.WorkflowExecutionAlreadyStartedError); ok { + runID = alreadyStartedErr.RunID // Assumption is that AlreadyStarted is never returned when options.ID is empty as UUID generated by // StartWorkflow is not going to collide ever. workflowID = options.ID @@ -286,7 +286,7 @@ func (wc *workflowClient) ExecuteWorkflow(ctx context.Context, options StartWork } iterFn := func(fnCtx context.Context, fnRunID string) HistoryEventIterator { - return wc.GetWorkflowHistory(fnCtx, workflowID, fnRunID, true, s.HistoryEventFilterTypeCloseEvent) + return wc.GetWorkflowHistory(fnCtx, workflowID, fnRunID, true, apiv1.EventFilterType_EVENT_FILTER_TYPE_CLOSE_EVENT) } return &workflowRunImpl{ @@ -307,7 +307,7 @@ func (wc *workflowClient) ExecuteWorkflow(ctx context.Context, options StartWork func (wc *workflowClient) GetWorkflow(ctx context.Context, workflowID string, runID string) WorkflowRun { iterFn := func(fnCtx context.Context, fnRunID string) HistoryEventIterator { - return wc.GetWorkflowHistory(fnCtx, workflowID, fnRunID, true, s.HistoryEventFilterTypeCloseEvent) + return wc.GetWorkflowHistory(fnCtx, workflowID, fnRunID, true, apiv1.EventFilterType_EVENT_FILTER_TYPE_CLOSE_EVENT) } return &workflowRunImpl{ @@ -326,24 +326,7 @@ func (wc *workflowClient) SignalWorkflow(ctx context.Context, workflowID string, if err != nil { return err } - - request := &s.SignalWorkflowExecutionRequest{ - Domain: common.StringPtr(wc.domain), - WorkflowExecution: &s.WorkflowExecution{ - WorkflowId: common.StringPtr(workflowID), - RunId: getRunID(runID), - }, - SignalName: common.StringPtr(signalName), - Input: input, - Identity: common.StringPtr(wc.identity), - } - - return backoff.Retry(ctx, - func() error { - tchCtx, cancel, opt := newChannelContext(ctx) - defer cancel() - return wc.workflowService.SignalWorkflowExecution(tchCtx, request, opt...) - }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) + return signalWorkflow(ctx, wc.workflowService, wc.identity, wc.domain, workflowID, runID, signalName, input) } // SignalWithStartWorkflow sends a signal to a running workflow. @@ -364,17 +347,17 @@ func (wc *workflowClient) SignalWithStartWorkflow(ctx context.Context, workflowI return nil, errors.New("missing TaskList") } - executionTimeout := common.Int32Ceil(options.ExecutionStartToCloseTimeout.Seconds()) + executionTimeout := options.ExecutionStartToCloseTimeout if executionTimeout <= 0 { return nil, errors.New("missing or invalid ExecutionStartToCloseTimeout") } - decisionTaskTimeout := common.Int32Ceil(options.DecisionTaskStartToCloseTimeout.Seconds()) + decisionTaskTimeout := options.DecisionTaskStartToCloseTimeout if decisionTaskTimeout < 0 { return nil, errors.New("negative DecisionTaskStartToCloseTimeout provided") } if decisionTaskTimeout == 0 { - decisionTaskTimeout = defaultDecisionTaskTimeoutInSecs + decisionTaskTimeout = defaultDecisionTaskTimeout } // Validate type and its arguments. @@ -393,8 +376,8 @@ func (wc *workflowClient) SignalWithStartWorkflow(ctx context.Context, workflowI return nil, err } - delayStartSeconds := common.Int32Ceil(options.DelayStart.Seconds()) - if delayStartSeconds < 0 { + delayStart := options.DelayStart + if delayStart < 0 { return nil, errors.New("Invalid DelayStart option") } @@ -405,28 +388,30 @@ func (wc *workflowClient) SignalWithStartWorkflow(ctx context.Context, workflowI // get workflow headers from the context header := wc.getWorkflowHeader(ctx) - signalWithStartRequest := &s.SignalWithStartWorkflowExecutionRequest{ - Domain: common.StringPtr(wc.domain), - RequestId: common.StringPtr(uuid.New()), - WorkflowId: common.StringPtr(workflowID), - WorkflowType: workflowTypePtr(*workflowType), - TaskList: common.TaskListPtr(s.TaskList{Name: common.StringPtr(options.TaskList)}), - Input: input, - ExecutionStartToCloseTimeoutSeconds: common.Int32Ptr(executionTimeout), - TaskStartToCloseTimeoutSeconds: common.Int32Ptr(decisionTaskTimeout), - SignalName: common.StringPtr(signalName), - SignalInput: signalInput, - Identity: common.StringPtr(wc.identity), - RetryPolicy: convertRetryPolicy(options.RetryPolicy), - CronSchedule: common.StringPtr(options.CronSchedule), - Memo: memo, - SearchAttributes: searchAttr, - WorkflowIdReusePolicy: options.WorkflowIDReusePolicy.toThriftPtr(), - Header: header, - DelayStartSeconds: common.Int32Ptr(delayStartSeconds), - } - - var response *s.StartWorkflowExecutionResponse + signalWithStartRequest := &apiv1.SignalWithStartWorkflowExecutionRequest{ + SignalName: signalName, + SignalInput: &apiv1.Payload{Data: signalInput}, + StartRequest: &apiv1.StartWorkflowExecutionRequest{ + Domain: wc.domain, + RequestId: uuid.New(), + WorkflowId: workflowID, + WorkflowType: &apiv1.WorkflowType{Name: workflowType.Name}, + TaskList: &apiv1.TaskList{Name: options.TaskList}, + Input: &apiv1.Payload{Data: input}, + ExecutionStartToCloseTimeout: api.DurationToProto(executionTimeout), + TaskStartToCloseTimeout: api.DurationToProto(decisionTaskTimeout), + Identity: wc.identity, + RetryPolicy: convertRetryPolicy(options.RetryPolicy), + CronSchedule: options.CronSchedule, + Memo: memo, + SearchAttributes: searchAttr, + WorkflowIdReusePolicy: options.WorkflowIDReusePolicy.toProto(), + Header: header, + DelayStart: api.DurationToProto(delayStart), + }, + } + + var response *apiv1.SignalWithStartWorkflowExecutionResponse // Start creating workflow request. err = backoff.Retry(ctx, @@ -436,7 +421,7 @@ func (wc *workflowClient) SignalWithStartWorkflow(ctx context.Context, workflowI var err1 error response, err1 = wc.workflowService.SignalWithStartWorkflowExecution(tchCtx, signalWithStartRequest, opt...) - return err1 + return api.ConvertError(err1) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) if err != nil { @@ -458,20 +443,21 @@ func (wc *workflowClient) SignalWithStartWorkflow(ctx context.Context, workflowI // workflowID is required, other parameters are optional. // If runID is omit, it will terminate currently running workflow (if there is one) based on the workflowID. func (wc *workflowClient) CancelWorkflow(ctx context.Context, workflowID string, runID string) error { - request := &s.RequestCancelWorkflowExecutionRequest{ - Domain: common.StringPtr(wc.domain), - WorkflowExecution: &s.WorkflowExecution{ - WorkflowId: common.StringPtr(workflowID), - RunId: getRunID(runID), + request := &apiv1.RequestCancelWorkflowExecutionRequest{ + Domain: wc.domain, + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: workflowID, + RunId: runID, }, - Identity: common.StringPtr(wc.identity), + Identity: wc.identity, } return backoff.Retry(ctx, func() error { tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() - return wc.workflowService.RequestCancelWorkflowExecution(tchCtx, request, opt...) + _, err := wc.workflowService.RequestCancelWorkflowExecution(tchCtx, request, opt...) + return api.ConvertError(err) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) } @@ -479,22 +465,23 @@ func (wc *workflowClient) CancelWorkflow(ctx context.Context, workflowID string, // workflowID is required, other parameters are optional. // If runID is omit, it will terminate currently running workflow (if there is one) based on the workflowID. func (wc *workflowClient) TerminateWorkflow(ctx context.Context, workflowID string, runID string, reason string, details []byte) error { - request := &s.TerminateWorkflowExecutionRequest{ - Domain: common.StringPtr(wc.domain), - WorkflowExecution: &s.WorkflowExecution{ - WorkflowId: common.StringPtr(workflowID), - RunId: getRunID(runID), + request := &apiv1.TerminateWorkflowExecutionRequest{ + Domain: wc.domain, + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: workflowID, + RunId: runID, }, - Reason: common.StringPtr(reason), - Details: details, - Identity: common.StringPtr(wc.identity), + Reason: reason, + Details: &apiv1.Payload{Data: details}, + Identity: wc.identity, } err := backoff.Retry(ctx, func() error { tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() - return wc.workflowService.TerminateWorkflowExecution(tchCtx, request, opt...) + _, err := wc.workflowService.TerminateWorkflowExecution(tchCtx, request, opt...) + return api.ConvertError(err) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) return err @@ -506,24 +493,24 @@ func (wc *workflowClient) GetWorkflowHistory( workflowID string, runID string, isLongPoll bool, - filterType s.HistoryEventFilterType, + filterType apiv1.EventFilterType, ) HistoryEventIterator { domain := wc.domain - paginate := func(nextToken []byte) (*s.GetWorkflowExecutionHistoryResponse, error) { - request := &s.GetWorkflowExecutionHistoryRequest{ - Domain: common.StringPtr(domain), - Execution: &s.WorkflowExecution{ - WorkflowId: common.StringPtr(workflowID), - RunId: getRunID(runID), + paginate := func(nextToken []byte) (*apiv1.GetWorkflowExecutionHistoryResponse, error) { + request := &apiv1.GetWorkflowExecutionHistoryRequest{ + Domain: domain, + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: workflowID, + RunId: runID, }, - WaitForNewEvent: common.BoolPtr(isLongPoll), - HistoryEventFilterType: &filterType, + WaitForNewEvent: isLongPoll, + HistoryEventFilterType: filterType, NextPageToken: nextToken, - SkipArchival: common.BoolPtr(isLongPoll), + SkipArchival: isLongPoll, } - var response *s.GetWorkflowExecutionHistoryResponse + var response *apiv1.GetWorkflowExecutionHistoryResponse var err error Loop: for { @@ -537,6 +524,7 @@ func (wc *workflowClient) GetWorkflowHistory( }) defer cancel() response, err1 = wc.workflowService.GetWorkflowExecutionHistory(tchCtx, request, opt...) + err1 = api.ConvertError(err1) if err1 != nil { return err1 @@ -575,10 +563,10 @@ func (wc *workflowClient) GetWorkflowHistory( } func isEntityNonExistFromPassive(err error) bool { - if nonExistError, ok := err.(*s.EntityNotExistsError); ok { - return nonExistError.GetActiveCluster() != "" && - nonExistError.GetCurrentCluster() != "" && - nonExistError.GetActiveCluster() != nonExistError.GetCurrentCluster() + if nonExistError, ok := err.(*api.EntityNotExistsError); ok { + return nonExistError.ActiveCluster != "" && + nonExistError.CurrentCluster != "" && + nonExistError.ActiveCluster != nonExistError.CurrentCluster } return false @@ -652,18 +640,18 @@ func (wc *workflowClient) RecordActivityHeartbeatByID(ctx context.Context, // - BadRequestError // - InternalServiceError // - EntityNotExistError -func (wc *workflowClient) ListClosedWorkflow(ctx context.Context, request *s.ListClosedWorkflowExecutionsRequest) (*s.ListClosedWorkflowExecutionsResponse, error) { +func (wc *workflowClient) ListClosedWorkflow(ctx context.Context, request *apiv1.ListClosedWorkflowExecutionsRequest) (*apiv1.ListClosedWorkflowExecutionsResponse, error) { if len(request.GetDomain()) == 0 { - request.Domain = common.StringPtr(wc.domain) + request.Domain = wc.domain } - var response *s.ListClosedWorkflowExecutionsResponse + var response *apiv1.ListClosedWorkflowExecutionsResponse err := backoff.Retry(ctx, func() error { var err1 error tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() response, err1 = wc.workflowService.ListClosedWorkflowExecutions(tchCtx, request, opt...) - return err1 + return api.ConvertError(err1) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) if err != nil { return nil, err @@ -676,18 +664,18 @@ func (wc *workflowClient) ListClosedWorkflow(ctx context.Context, request *s.Lis // - BadRequestError // - InternalServiceError // - EntityNotExistError -func (wc *workflowClient) ListOpenWorkflow(ctx context.Context, request *s.ListOpenWorkflowExecutionsRequest) (*s.ListOpenWorkflowExecutionsResponse, error) { +func (wc *workflowClient) ListOpenWorkflow(ctx context.Context, request *apiv1.ListOpenWorkflowExecutionsRequest) (*apiv1.ListOpenWorkflowExecutionsResponse, error) { if len(request.GetDomain()) == 0 { - request.Domain = common.StringPtr(wc.domain) + request.Domain = wc.domain } - var response *s.ListOpenWorkflowExecutionsResponse + var response *apiv1.ListOpenWorkflowExecutionsResponse err := backoff.Retry(ctx, func() error { var err1 error tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() response, err1 = wc.workflowService.ListOpenWorkflowExecutions(tchCtx, request, opt...) - return err1 + return api.ConvertError(err1) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) if err != nil { return nil, err @@ -696,18 +684,18 @@ func (wc *workflowClient) ListOpenWorkflow(ctx context.Context, request *s.ListO } // ListWorkflow implementation -func (wc *workflowClient) ListWorkflow(ctx context.Context, request *s.ListWorkflowExecutionsRequest) (*s.ListWorkflowExecutionsResponse, error) { +func (wc *workflowClient) ListWorkflow(ctx context.Context, request *apiv1.ListWorkflowExecutionsRequest) (*apiv1.ListWorkflowExecutionsResponse, error) { if len(request.GetDomain()) == 0 { - request.Domain = common.StringPtr(wc.domain) + request.Domain = wc.domain } - var response *s.ListWorkflowExecutionsResponse + var response *apiv1.ListWorkflowExecutionsResponse err := backoff.Retry(ctx, func() error { var err1 error tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() response, err1 = wc.workflowService.ListWorkflowExecutions(tchCtx, request, opt...) - return err1 + return api.ConvertError(err1) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) if err != nil { return nil, err @@ -716,11 +704,11 @@ func (wc *workflowClient) ListWorkflow(ctx context.Context, request *s.ListWorkf } // ListArchivedWorkflow implementation -func (wc *workflowClient) ListArchivedWorkflow(ctx context.Context, request *s.ListArchivedWorkflowExecutionsRequest) (*s.ListArchivedWorkflowExecutionsResponse, error) { +func (wc *workflowClient) ListArchivedWorkflow(ctx context.Context, request *apiv1.ListArchivedWorkflowExecutionsRequest) (*apiv1.ListArchivedWorkflowExecutionsResponse, error) { if len(request.GetDomain()) == 0 { - request.Domain = common.StringPtr(wc.domain) + request.Domain = wc.domain } - var response *s.ListArchivedWorkflowExecutionsResponse + var response *apiv1.ListArchivedWorkflowExecutionsResponse err := backoff.Retry(ctx, func() error { var err1 error @@ -739,7 +727,7 @@ func (wc *workflowClient) ListArchivedWorkflow(ctx context.Context, request *s.L tchCtx, cancel, opt := newChannelContext(ctx, chanTimeout(timeout)) defer cancel() response, err1 = wc.workflowService.ListArchivedWorkflowExecutions(tchCtx, request, opt...) - return err1 + return api.ConvertError(err1) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) if err != nil { return nil, err @@ -748,18 +736,18 @@ func (wc *workflowClient) ListArchivedWorkflow(ctx context.Context, request *s.L } // ScanWorkflow implementation -func (wc *workflowClient) ScanWorkflow(ctx context.Context, request *s.ListWorkflowExecutionsRequest) (*s.ListWorkflowExecutionsResponse, error) { +func (wc *workflowClient) ScanWorkflow(ctx context.Context, request *apiv1.ScanWorkflowExecutionsRequest) (*apiv1.ScanWorkflowExecutionsResponse, error) { if len(request.GetDomain()) == 0 { - request.Domain = common.StringPtr(wc.domain) + request.Domain = wc.domain } - var response *s.ListWorkflowExecutionsResponse + var response *apiv1.ScanWorkflowExecutionsResponse err := backoff.Retry(ctx, func() error { var err1 error tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() response, err1 = wc.workflowService.ScanWorkflowExecutions(tchCtx, request, opt...) - return err1 + return api.ConvertError(err1) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) if err != nil { return nil, err @@ -768,18 +756,18 @@ func (wc *workflowClient) ScanWorkflow(ctx context.Context, request *s.ListWorkf } // CountWorkflow implementation -func (wc *workflowClient) CountWorkflow(ctx context.Context, request *s.CountWorkflowExecutionsRequest) (*s.CountWorkflowExecutionsResponse, error) { +func (wc *workflowClient) CountWorkflow(ctx context.Context, request *apiv1.CountWorkflowExecutionsRequest) (*apiv1.CountWorkflowExecutionsResponse, error) { if len(request.GetDomain()) == 0 { - request.Domain = common.StringPtr(wc.domain) + request.Domain = wc.domain } - var response *s.CountWorkflowExecutionsResponse + var response *apiv1.CountWorkflowExecutionsResponse err := backoff.Retry(ctx, func() error { var err1 error tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() response, err1 = wc.workflowService.CountWorkflowExecutions(tchCtx, request, opt...) - return err1 + return api.ConvertError(err1) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) if err != nil { return nil, err @@ -788,18 +776,18 @@ func (wc *workflowClient) CountWorkflow(ctx context.Context, request *s.CountWor } // ResetWorkflow implementation -func (wc *workflowClient) ResetWorkflow(ctx context.Context, request *s.ResetWorkflowExecutionRequest) (*s.ResetWorkflowExecutionResponse, error) { +func (wc *workflowClient) ResetWorkflow(ctx context.Context, request *apiv1.ResetWorkflowExecutionRequest) (*apiv1.ResetWorkflowExecutionResponse, error) { if len(request.GetDomain()) == 0 { - request.Domain = common.StringPtr(wc.domain) + request.Domain = wc.domain } - var response *s.ResetWorkflowExecutionResponse + var response *apiv1.ResetWorkflowExecutionResponse err := backoff.Retry(ctx, func() error { var err1 error tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() response, err1 = wc.workflowService.ResetWorkflowExecution(tchCtx, request, opt...) - return err1 + return api.ConvertError(err1) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) if err != nil { return nil, err @@ -808,15 +796,15 @@ func (wc *workflowClient) ResetWorkflow(ctx context.Context, request *s.ResetWor } // GetSearchAttributes implementation -func (wc *workflowClient) GetSearchAttributes(ctx context.Context) (*s.GetSearchAttributesResponse, error) { - var response *s.GetSearchAttributesResponse +func (wc *workflowClient) GetSearchAttributes(ctx context.Context) (*apiv1.GetSearchAttributesResponse, error) { + var response *apiv1.GetSearchAttributesResponse err := backoff.Retry(ctx, func() error { var err1 error tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() - response, err1 = wc.workflowService.GetSearchAttributes(tchCtx, opt...) - return err1 + response, err1 = wc.workflowService.GetSearchAttributes(tchCtx, &apiv1.GetSearchAttributesRequest{}, opt...) + return api.ConvertError(err1) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) if err != nil { return nil, err @@ -829,22 +817,22 @@ func (wc *workflowClient) GetSearchAttributes(ctx context.Context) (*s.GetSearch // - BadRequestError // - InternalServiceError // - EntityNotExistError -func (wc *workflowClient) DescribeWorkflowExecution(ctx context.Context, workflowID, runID string) (*s.DescribeWorkflowExecutionResponse, error) { - request := &s.DescribeWorkflowExecutionRequest{ - Domain: common.StringPtr(wc.domain), - Execution: &s.WorkflowExecution{ - WorkflowId: common.StringPtr(workflowID), - RunId: common.StringPtr(runID), +func (wc *workflowClient) DescribeWorkflowExecution(ctx context.Context, workflowID, runID string) (*apiv1.DescribeWorkflowExecutionResponse, error) { + request := &apiv1.DescribeWorkflowExecutionRequest{ + Domain: wc.domain, + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: workflowID, + RunId: runID, }, } - var response *s.DescribeWorkflowExecutionResponse + var response *apiv1.DescribeWorkflowExecutionResponse err := backoff.Retry(ctx, func() error { var err1 error tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() response, err1 = wc.workflowService.DescribeWorkflowExecution(tchCtx, request, opt...) - return err1 + return api.ConvertError(err1) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) if err != nil { return nil, err @@ -899,12 +887,12 @@ type QueryWorkflowWithOptionsRequest struct { // QueryRejectCondition is an optional field used to reject queries based on workflow state. // QueryRejectConditionNotOpen will reject queries to workflows which are not open // QueryRejectConditionNotCompletedCleanly will reject queries to workflows which completed in any state other than completed (e.g. terminated, canceled timeout etc...) - QueryRejectCondition *s.QueryRejectCondition + QueryRejectCondition apiv1.QueryRejectCondition // QueryConsistencyLevel is an optional field used to control the consistency level. // QueryConsistencyLevelEventual means that query will eventually reflect up to date state of a workflow. // QueryConsistencyLevelStrong means that query will reflect a workflow state of having applied all events which came before the query. - QueryConsistencyLevel *s.QueryConsistencyLevel + QueryConsistencyLevel apiv1.QueryConsistencyLevel } // QueryWorkflowWithOptionsResponse is the response to QueryWorkflowWithOptions @@ -914,7 +902,7 @@ type QueryWorkflowWithOptionsResponse struct { QueryResult Value // QueryRejected contains information about the query rejection. - QueryRejected *s.QueryRejected + QueryRejected *apiv1.QueryRejected } // QueryWorkflowWithOptions queries a given workflow execution and returns the query result synchronously. @@ -932,28 +920,28 @@ func (wc *workflowClient) QueryWorkflowWithOptions(ctx context.Context, request return nil, err } } - req := &s.QueryWorkflowRequest{ - Domain: common.StringPtr(wc.domain), - Execution: &s.WorkflowExecution{ - WorkflowId: common.StringPtr(request.WorkflowID), - RunId: getRunID(request.RunID), + req := &apiv1.QueryWorkflowRequest{ + Domain: wc.domain, + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: request.WorkflowID, + RunId: request.RunID, }, - Query: &s.WorkflowQuery{ - QueryType: common.StringPtr(request.QueryType), - QueryArgs: input, + Query: &apiv1.WorkflowQuery{ + QueryType: request.QueryType, + QueryArgs: &apiv1.Payload{Data: input}, }, QueryRejectCondition: request.QueryRejectCondition, QueryConsistencyLevel: request.QueryConsistencyLevel, } - var resp *s.QueryWorkflowResponse + var resp *apiv1.QueryWorkflowResponse err := backoff.Retry(ctx, func() error { tchCtx, cancel, opt := newChannelContextForQuery(ctx) defer cancel() var err error resp, err = wc.workflowService.QueryWorkflow(tchCtx, req, opt...) - return err + return api.ConvertError(err) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) if err != nil { return nil, err @@ -967,7 +955,7 @@ func (wc *workflowClient) QueryWorkflowWithOptions(ctx context.Context, request } return &QueryWorkflowWithOptionsResponse{ QueryRejected: nil, - QueryResult: newEncodedValue(resp.QueryResult, wc.dataConverter), + QueryResult: newEncodedValue(resp.QueryResult.GetData(), wc.dataConverter), }, nil } @@ -979,21 +967,21 @@ func (wc *workflowClient) QueryWorkflowWithOptions(ctx context.Context, request // - BadRequestError // - InternalServiceError // - EntityNotExistError -func (wc *workflowClient) DescribeTaskList(ctx context.Context, tasklist string, tasklistType s.TaskListType) (*s.DescribeTaskListResponse, error) { - request := &s.DescribeTaskListRequest{ - Domain: common.StringPtr(wc.domain), - TaskList: &s.TaskList{Name: common.StringPtr(tasklist)}, - TaskListType: &tasklistType, +func (wc *workflowClient) DescribeTaskList(ctx context.Context, tasklist string, tasklistType apiv1.TaskListType) (*apiv1.DescribeTaskListResponse, error) { + request := &apiv1.DescribeTaskListRequest{ + Domain: wc.domain, + TaskList: &apiv1.TaskList{Name: tasklist}, + TaskListType: tasklistType, } - var resp *s.DescribeTaskListResponse + var resp *apiv1.DescribeTaskListResponse err := backoff.Retry(ctx, func() error { tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() var err error resp, err = wc.workflowService.DescribeTaskList(tchCtx, request, opt...) - return err + return api.ConvertError(err) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) if err != nil { return nil, err @@ -1002,9 +990,9 @@ func (wc *workflowClient) DescribeTaskList(ctx context.Context, tasklist string, return resp, nil } -func (wc *workflowClient) getWorkflowHeader(ctx context.Context) *s.Header { - header := &s.Header{ - Fields: make(map[string][]byte), +func (wc *workflowClient) getWorkflowHeader(ctx context.Context) *apiv1.Header { + header := &apiv1.Header{ + Fields: make(map[string]*apiv1.Payload), } writer := NewHeaderWriter(header) for _, ctxProp := range wc.contextPropagators { @@ -1018,12 +1006,13 @@ func (wc *workflowClient) getWorkflowHeader(ctx context.Context) *s.Header { // - DomainAlreadyExistsError // - BadRequestError // - InternalServiceError -func (dc *domainClient) Register(ctx context.Context, request *s.RegisterDomainRequest) error { +func (dc *domainClient) Register(ctx context.Context, request *apiv1.RegisterDomainRequest) error { return backoff.Retry(ctx, func() error { tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() - return dc.workflowService.RegisterDomain(tchCtx, request, opt...) + _, err := dc.workflowService.RegisterDomain(tchCtx, request, opt...) + return api.ConvertError(err) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) } @@ -1035,19 +1024,19 @@ func (dc *domainClient) Register(ctx context.Context, request *s.RegisterDomainR // - EntityNotExistsError // - BadRequestError // - InternalServiceError -func (dc *domainClient) Describe(ctx context.Context, name string) (*s.DescribeDomainResponse, error) { - request := &s.DescribeDomainRequest{ - Name: common.StringPtr(name), +func (dc *domainClient) Describe(ctx context.Context, name string) (*apiv1.DescribeDomainResponse, error) { + request := &apiv1.DescribeDomainRequest{ + DescribeBy: &apiv1.DescribeDomainRequest_Name{Name: name}, } - var response *s.DescribeDomainResponse + var response *apiv1.DescribeDomainResponse err := backoff.Retry(ctx, func() error { tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() var err error response, err = dc.workflowService.DescribeDomain(tchCtx, request, opt...) - return err + return api.ConvertError(err) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) if err != nil { return nil, err @@ -1060,13 +1049,13 @@ func (dc *domainClient) Describe(ctx context.Context, name string) (*s.DescribeD // - EntityNotExistsError // - BadRequestError // - InternalServiceError -func (dc *domainClient) Update(ctx context.Context, request *s.UpdateDomainRequest) error { +func (dc *domainClient) Update(ctx context.Context, request *apiv1.UpdateDomainRequest) error { return backoff.Retry(ctx, func() error { tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() _, err := dc.workflowService.UpdateDomain(tchCtx, request, opt...) - return err + return api.ConvertError(err) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError) } @@ -1104,7 +1093,7 @@ func (iter *historyEventIteratorImpl) HasNext() bool { return false } -func (iter *historyEventIteratorImpl) Next() (*s.HistoryEvent, error) { +func (iter *historyEventIteratorImpl) Next() (*apiv1.HistoryEvent, error) { // if caller call the Next() when iteration is over, just return nil, nil if !iter.HasNext() { panic("HistoryEventIterator Next() called without checking HasNext()") @@ -1144,9 +1133,9 @@ func (workflowRun *workflowRunImpl) Get(ctx context.Context, valuePtr interface{ return err } - switch closeEvent.GetEventType() { - case s.EventTypeWorkflowExecutionCompleted: - attributes := closeEvent.WorkflowExecutionCompletedEventAttributes + switch attr := closeEvent.Attributes.(type){ + case *apiv1.HistoryEvent_WorkflowExecutionCompletedEventAttributes: + attributes := attr.WorkflowExecutionCompletedEventAttributes if valuePtr == nil || attributes.Result == nil { return nil } @@ -1154,57 +1143,57 @@ func (workflowRun *workflowRunImpl) Get(ctx context.Context, valuePtr interface{ if rf.Type().Kind() != reflect.Ptr { return errors.New("value parameter is not a pointer") } - err = deSerializeFunctionResult(workflowRun.workflowFn, attributes.Result, valuePtr, workflowRun.dataConverter, workflowRun.registry) - case s.EventTypeWorkflowExecutionFailed: - attributes := closeEvent.WorkflowExecutionFailedEventAttributes - err = constructError(attributes.GetReason(), attributes.Details, workflowRun.dataConverter) - case s.EventTypeWorkflowExecutionCanceled: - attributes := closeEvent.WorkflowExecutionCanceledEventAttributes - details := newEncodedValues(attributes.Details, workflowRun.dataConverter) + err = deSerializeFunctionResult(workflowRun.workflowFn, attributes.Result.GetData(), valuePtr, workflowRun.dataConverter, workflowRun.registry) + case *apiv1.HistoryEvent_WorkflowExecutionFailedEventAttributes: + attributes := attr.WorkflowExecutionFailedEventAttributes + err = constructError(attributes.Failure.GetReason(), attributes.Failure.GetDetails(), workflowRun.dataConverter) + case *apiv1.HistoryEvent_WorkflowExecutionCanceledEventAttributes: + attributes := attr.WorkflowExecutionCanceledEventAttributes + details := newEncodedValues(attributes.Details.GetData(), workflowRun.dataConverter) err = NewCanceledError(details) - case s.EventTypeWorkflowExecutionTerminated: + case *apiv1.HistoryEvent_WorkflowExecutionTerminatedEventAttributes: err = newTerminatedError() - case s.EventTypeWorkflowExecutionTimedOut: - attributes := closeEvent.WorkflowExecutionTimedOutEventAttributes + case *apiv1.HistoryEvent_WorkflowExecutionTimedOutEventAttributes: + attributes := attr.WorkflowExecutionTimedOutEventAttributes err = NewTimeoutError(attributes.GetTimeoutType()) - case s.EventTypeWorkflowExecutionContinuedAsNew: - attributes := closeEvent.WorkflowExecutionContinuedAsNewEventAttributes + case *apiv1.HistoryEvent_WorkflowExecutionContinuedAsNewEventAttributes: + attributes := attr.WorkflowExecutionContinuedAsNewEventAttributes workflowRun.currentRunID = attributes.GetNewExecutionRunId() return workflowRun.Get(ctx, valuePtr) default: - err = fmt.Errorf("Unexpected event type %s when handling workflow execution result", closeEvent.GetEventType()) + err = fmt.Errorf("Unexpected event type %s when handling workflow execution result", util.GetHistoryEventType(closeEvent)) } return err } -func getWorkflowMemo(input map[string]interface{}, dc DataConverter) (*s.Memo, error) { +func getWorkflowMemo(input map[string]interface{}, dc DataConverter) (*apiv1.Memo, error) { if input == nil { return nil, nil } - memo := make(map[string][]byte) + memo := make(map[string]*apiv1.Payload) for k, v := range input { memoBytes, err := encodeArg(dc, v) if err != nil { return nil, fmt.Errorf("encode workflow memo error: %v", err.Error()) } - memo[k] = memoBytes + memo[k] = &apiv1.Payload{Data: memoBytes} } - return &s.Memo{Fields: memo}, nil + return &apiv1.Memo{Fields: memo}, nil } -func serializeSearchAttributes(input map[string]interface{}) (*s.SearchAttributes, error) { +func serializeSearchAttributes(input map[string]interface{}) (*apiv1.SearchAttributes, error) { if input == nil { return nil, nil } - attr := make(map[string][]byte) + attr := make(map[string]*apiv1.Payload) for k, v := range input { attrBytes, err := json.Marshal(v) if err != nil { return nil, fmt.Errorf("encode search attribute [%s] error: %v", k, err) } - attr[k] = attrBytes + attr[k] = &apiv1.Payload{Data: attrBytes} } - return &s.SearchAttributes{IndexedFields: attr}, nil + return &apiv1.SearchAttributes{IndexedFields: attr}, nil } diff --git a/internal/internal_workflow_client_test.go b/internal/internal_workflow_client_test.go index 733745e06..85631cc75 100644 --- a/internal/internal_workflow_client_test.go +++ b/internal/internal_workflow_client_test.go @@ -24,20 +24,19 @@ import ( "encoding/json" "errors" "fmt" - "go.uber.org/cadence/v1/internal/common/serializer" "log" "os" "testing" "time" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowservicetest" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/internal/common/metrics" + "go.uber.org/cadence/v2/internal/common/serializer" "github.com/golang/mock/gomock" "github.com/pborman/uuid" "github.com/stretchr/testify/suite" - "go.uber.org/cadence/v1/internal/common/metrics" ) const ( @@ -58,7 +57,7 @@ type ( historyEventIteratorSuite struct { suite.Suite mockCtrl *gomock.Controller - workflowServiceClient *workflowservicetest.MockClient + workflowServiceClient *api.MockInterface wfClient *workflowClient } ) @@ -143,7 +142,7 @@ func (s *historyEventIteratorSuite) SetupSuite() { func (s *historyEventIteratorSuite) SetupTest() { // Create service endpoint s.mockCtrl = gomock.NewController(s.T()) - s.workflowServiceClient = workflowservicetest.NewMockClient(s.mockCtrl) + s.workflowServiceClient = api.NewMockInterface(s.mockCtrl) s.wfClient = &workflowClient{ workflowService: s.workflowServiceClient, @@ -156,39 +155,39 @@ func (s *historyEventIteratorSuite) TearDownTest() { } func (s *historyEventIteratorSuite) TestIterator_NoError() { - filterType := shared.HistoryEventFilterTypeAllEvent + filterType := apiv1.EventFilterType_EVENT_FILTER_TYPE_ALL_EVENT request1 := getGetWorkflowExecutionHistoryRequest(filterType) - response1 := &shared.GetWorkflowExecutionHistoryResponse{ - History: &shared.History{ - Events: []*shared.HistoryEvent{ + response1 := &apiv1.GetWorkflowExecutionHistoryResponse{ + History: &apiv1.History{ + Events: []*apiv1.HistoryEvent{ // dummy history event - &shared.HistoryEvent{}, + &apiv1.HistoryEvent{}, }, }, NextPageToken: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, } request2 := getGetWorkflowExecutionHistoryRequest(filterType) request2.NextPageToken = response1.NextPageToken - response2 := &shared.GetWorkflowExecutionHistoryResponse{ - History: &shared.History{ - Events: []*shared.HistoryEvent{ + response2 := &apiv1.GetWorkflowExecutionHistoryResponse{ + History: &apiv1.History{ + Events: []*apiv1.HistoryEvent{ // dummy history event - &shared.HistoryEvent{}, + &apiv1.HistoryEvent{}, }, }, NextPageToken: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, } - dummyEvent := []*shared.HistoryEvent{ + dummyEvent := []*apiv1.HistoryEvent{ // dummy history event - &shared.HistoryEvent{}, + &apiv1.HistoryEvent{}, } blobData := serializeEvents(dummyEvent) request3 := getGetWorkflowExecutionHistoryRequest(filterType) request3.NextPageToken = response2.NextPageToken - response3 := &shared.GetWorkflowExecutionHistoryResponse{ - RawHistory: []*shared.DataBlob{ + response3 := &apiv1.GetWorkflowExecutionHistoryResponse{ + RawHistory: []*apiv1.DataBlob{ // dummy history event blobData, }, @@ -199,8 +198,8 @@ func (s *historyEventIteratorSuite) TestIterator_NoError() { s.workflowServiceClient.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), request2, gomock.Any()).Return(response2, nil).Times(1) s.workflowServiceClient.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), request3, gomock.Any()).Return(response3, nil).Times(1) - events := []*shared.HistoryEvent{} - iter := s.wfClient.GetWorkflowHistory(context.Background(), workflowID, runID, true, shared.HistoryEventFilterTypeAllEvent) + events := []*apiv1.HistoryEvent{} + iter := s.wfClient.GetWorkflowHistory(context.Background(), workflowID, runID, true, apiv1.EventFilterType_EVENT_FILTER_TYPE_ALL_EVENT) for iter.HasNext() { event, err := iter.Next() s.Nil(err) @@ -210,36 +209,36 @@ func (s *historyEventIteratorSuite) TestIterator_NoError() { } func (s *historyEventIteratorSuite) TestIterator_NoError_EmptyPage() { - filterType := shared.HistoryEventFilterTypeAllEvent + filterType := apiv1.EventFilterType_EVENT_FILTER_TYPE_ALL_EVENT request1 := getGetWorkflowExecutionHistoryRequest(filterType) - response1 := &shared.GetWorkflowExecutionHistoryResponse{ - History: &shared.History{ - Events: []*shared.HistoryEvent{}, + response1 := &apiv1.GetWorkflowExecutionHistoryResponse{ + History: &apiv1.History{ + Events: []*apiv1.HistoryEvent{}, }, NextPageToken: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, } request2 := getGetWorkflowExecutionHistoryRequest(filterType) request2.NextPageToken = response1.NextPageToken - response2 := &shared.GetWorkflowExecutionHistoryResponse{ - History: &shared.History{ - Events: []*shared.HistoryEvent{ + response2 := &apiv1.GetWorkflowExecutionHistoryResponse{ + History: &apiv1.History{ + Events: []*apiv1.HistoryEvent{ // dummy history event - &shared.HistoryEvent{}, + &apiv1.HistoryEvent{}, }, }, NextPageToken: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, } - dummyEvent := []*shared.HistoryEvent{ + dummyEvent := []*apiv1.HistoryEvent{ // dummy history event - &shared.HistoryEvent{}, + &apiv1.HistoryEvent{}, } blobData := serializeEvents(dummyEvent) request3 := getGetWorkflowExecutionHistoryRequest(filterType) request3.NextPageToken = response2.NextPageToken - response3 := &shared.GetWorkflowExecutionHistoryResponse{ - RawHistory: []*shared.DataBlob{ + response3 := &apiv1.GetWorkflowExecutionHistoryResponse{ + RawHistory: []*apiv1.DataBlob{ // dummy history event blobData, }, @@ -250,8 +249,8 @@ func (s *historyEventIteratorSuite) TestIterator_NoError_EmptyPage() { s.workflowServiceClient.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), request2, gomock.Any()).Return(response2, nil).Times(1) s.workflowServiceClient.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), request3, gomock.Any()).Return(response3, nil).Times(1) - events := []*shared.HistoryEvent{} - iter := s.wfClient.GetWorkflowHistory(context.Background(), workflowID, runID, true, shared.HistoryEventFilterTypeAllEvent) + events := []*apiv1.HistoryEvent{} + iter := s.wfClient.GetWorkflowHistory(context.Background(), workflowID, runID, true, apiv1.EventFilterType_EVENT_FILTER_TYPE_ALL_EVENT) for iter.HasNext() { event, err := iter.Next() s.Nil(err) @@ -261,13 +260,13 @@ func (s *historyEventIteratorSuite) TestIterator_NoError_EmptyPage() { } func (s *historyEventIteratorSuite) TestIterator_Error() { - filterType := shared.HistoryEventFilterTypeAllEvent + filterType := apiv1.EventFilterType_EVENT_FILTER_TYPE_ALL_EVENT request1 := getGetWorkflowExecutionHistoryRequest(filterType) - response1 := &shared.GetWorkflowExecutionHistoryResponse{ - History: &shared.History{ - Events: []*shared.HistoryEvent{ + response1 := &apiv1.GetWorkflowExecutionHistoryResponse{ + History: &apiv1.History{ + Events: []*apiv1.HistoryEvent{ // dummy history event - &shared.HistoryEvent{}, + &apiv1.HistoryEvent{}, }, }, NextPageToken: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, @@ -277,14 +276,14 @@ func (s *historyEventIteratorSuite) TestIterator_Error() { s.workflowServiceClient.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), request1, gomock.Any()).Return(response1, nil).Times(1) - iter := s.wfClient.GetWorkflowHistory(context.Background(), workflowID, runID, true, shared.HistoryEventFilterTypeAllEvent) + iter := s.wfClient.GetWorkflowHistory(context.Background(), workflowID, runID, true, apiv1.EventFilterType_EVENT_FILTER_TYPE_ALL_EVENT) s.True(iter.HasNext()) event, err := iter.Next() s.NotNil(event) s.Nil(err) - s.workflowServiceClient.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), request2, gomock.Any()).Return(nil, &shared.EntityNotExistsError{}).Times(1) + s.workflowServiceClient.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), request2, gomock.Any()).Return(nil, &api.EntityNotExistsError{}).Times(1) s.True(iter.HasNext()) event, err = iter.Next() @@ -298,7 +297,7 @@ type ( workflowRunSuite struct { suite.Suite mockCtrl *gomock.Controller - workflowServiceClient *workflowservicetest.MockClient + workflowServiceClient *api.MockInterface workflowClient Client } ) @@ -321,7 +320,7 @@ func (s *workflowRunSuite) TearDownSuite() { func (s *workflowRunSuite) SetupTest() { // Create service endpoint s.mockCtrl = gomock.NewController(s.T()) - s.workflowServiceClient = workflowservicetest.NewMockClient(s.mockCtrl) + s.workflowServiceClient = api.NewMockInterface(s.mockCtrl) metricsScope := metrics.NewTaggedScope(nil) options := &ClientOptions{ @@ -336,23 +335,23 @@ func (s *workflowRunSuite) TearDownTest() { } func (s *workflowRunSuite) TestExecuteWorkflow_NoDup_Success() { - createResponse := &shared.StartWorkflowExecutionResponse{ - RunId: common.StringPtr(runID), + createResponse := &apiv1.StartWorkflowExecutionResponse{ + RunId: runID, } s.workflowServiceClient.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(createResponse, nil).Times(1) - filterType := shared.HistoryEventFilterTypeCloseEvent - eventType := shared.EventTypeWorkflowExecutionCompleted + filterType := apiv1.EventFilterType_EVENT_FILTER_TYPE_CLOSE_EVENT workflowResult := time.Hour * 59 encodedResult, _ := encodeArg(getDefaultDataConverter(), workflowResult) getRequest := getGetWorkflowExecutionHistoryRequest(filterType) - getResponse := &shared.GetWorkflowExecutionHistoryResponse{ - History: &shared.History{ - Events: []*shared.HistoryEvent{ - &shared.HistoryEvent{ - EventType: &eventType, - WorkflowExecutionCompletedEventAttributes: &shared.WorkflowExecutionCompletedEventAttributes{ - Result: encodedResult, + getResponse := &apiv1.GetWorkflowExecutionHistoryResponse{ + History: &apiv1.History{ + Events: []*apiv1.HistoryEvent{ + { + Attributes: &apiv1.HistoryEvent_WorkflowExecutionCompletedEventAttributes{ + WorkflowExecutionCompletedEventAttributes: &apiv1.WorkflowExecutionCompletedEventAttributes{ + Result: &apiv1.Payload{Data: encodedResult}, + }, }, }, }, @@ -381,28 +380,28 @@ func (s *workflowRunSuite) TestExecuteWorkflow_NoDup_Success() { } func (s *workflowRunSuite) TestExecuteWorkflow_NoDup_RawHistory_Success() { - createResponse := &shared.StartWorkflowExecutionResponse{ - RunId: common.StringPtr(runID), + createResponse := &apiv1.StartWorkflowExecutionResponse{ + RunId: runID, } s.workflowServiceClient.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(createResponse, nil).Times(1) - filterType := shared.HistoryEventFilterTypeCloseEvent - eventType := shared.EventTypeWorkflowExecutionCompleted + filterType := apiv1.EventFilterType_EVENT_FILTER_TYPE_CLOSE_EVENT workflowResult := time.Hour * 59 encodedResult, _ := encodeArg(getDefaultDataConverter(), workflowResult) - events := []*shared.HistoryEvent{ - &shared.HistoryEvent{ - EventType: &eventType, - WorkflowExecutionCompletedEventAttributes: &shared.WorkflowExecutionCompletedEventAttributes{ - Result: encodedResult, + events := []*apiv1.HistoryEvent{ + { + Attributes: &apiv1.HistoryEvent_WorkflowExecutionCompletedEventAttributes{ + WorkflowExecutionCompletedEventAttributes: &apiv1.WorkflowExecutionCompletedEventAttributes{ + Result: &apiv1.Payload{Data: encodedResult}, + }, }, }, } blobData := serializeEvents(events) getRequest := getGetWorkflowExecutionHistoryRequest(filterType) - getResponse := &shared.GetWorkflowExecutionHistoryResponse{ - RawHistory: []*shared.DataBlob{ + getResponse := &apiv1.GetWorkflowExecutionHistoryResponse{ + RawHistory: []*apiv1.DataBlob{ blobData, }, NextPageToken: nil, @@ -429,24 +428,24 @@ func (s *workflowRunSuite) TestExecuteWorkflow_NoDup_RawHistory_Success() { } func (s *workflowRunSuite) TestExecuteWorkflowWorkflowExecutionAlreadyStartedError() { - alreadyStartedErr := &shared.WorkflowExecutionAlreadyStartedError{ - RunId: common.StringPtr(runID), - Message: common.StringPtr("Already Started"), - StartRequestId: common.StringPtr(uuid.NewRandom().String()), + alreadyStartedErr := &api.WorkflowExecutionAlreadyStartedError{ + RunID: runID, + Message: "Already Started", + StartRequestID: uuid.NewRandom().String(), } s.workflowServiceClient.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Return(nil, alreadyStartedErr).Times(1) - eventType := shared.EventTypeWorkflowExecutionCompleted workflowResult := time.Hour * 59 encodedResult, _ := encodeArg(nil, workflowResult) - getResponse := &shared.GetWorkflowExecutionHistoryResponse{ - History: &shared.History{ - Events: []*shared.HistoryEvent{ + getResponse := &apiv1.GetWorkflowExecutionHistoryResponse{ + History: &apiv1.History{ + Events: []*apiv1.HistoryEvent{ { - EventType: &eventType, - WorkflowExecutionCompletedEventAttributes: &shared.WorkflowExecutionCompletedEventAttributes{ - Result: encodedResult, + Attributes: &apiv1.HistoryEvent_WorkflowExecutionCompletedEventAttributes{ + WorkflowExecutionCompletedEventAttributes: &apiv1.WorkflowExecutionCompletedEventAttributes{ + Result: &apiv1.Payload{Data: encodedResult}, + }, }, }, }, @@ -455,10 +454,9 @@ func (s *workflowRunSuite) TestExecuteWorkflowWorkflowExecutionAlreadyStartedErr } getHistory := s.workflowServiceClient.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Return(getResponse, nil).Times(1) - getHistory.Do(func(ctx interface{}, getRequest *shared.GetWorkflowExecutionHistoryRequest, opt1 interface{}, opt2 interface{}, opt3 interface{}) { - workflowID := getRequest.Execution.WorkflowId - s.NotNil(workflowID) - s.NotEmpty(*workflowID) + getHistory.Do(func(ctx interface{}, getRequest *apiv1.GetWorkflowExecutionHistoryRequest, opt1 interface{}, opt2 interface{}, opt3 interface{}) { + workflowID := getRequest.WorkflowExecution.WorkflowId + s.NotEmpty(workflowID) }) workflowRun, err := s.workflowClient.ExecuteWorkflow( @@ -481,40 +479,39 @@ func (s *workflowRunSuite) TestExecuteWorkflowWorkflowExecutionAlreadyStartedErr } func (s *workflowRunSuite) TestExecuteWorkflowWorkflowExecutionAlreadyStartedError_RawHistory() { - alreadyStartedErr := &shared.WorkflowExecutionAlreadyStartedError{ - RunId: common.StringPtr(runID), - Message: common.StringPtr("Already Started"), - StartRequestId: common.StringPtr(uuid.NewRandom().String()), + alreadyStartedErr := &api.WorkflowExecutionAlreadyStartedError{ + RunID: runID, + Message: "Already Started", + StartRequestID: uuid.NewRandom().String(), } s.workflowServiceClient.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Return(nil, alreadyStartedErr).Times(1) - eventType := shared.EventTypeWorkflowExecutionCompleted workflowResult := time.Hour * 59 encodedResult, _ := encodeArg(nil, workflowResult) - events := []*shared.HistoryEvent{ + events := []*apiv1.HistoryEvent{ { - EventType: &eventType, - WorkflowExecutionCompletedEventAttributes: &shared.WorkflowExecutionCompletedEventAttributes{ - Result: encodedResult, + Attributes: &apiv1.HistoryEvent_WorkflowExecutionCompletedEventAttributes{ + WorkflowExecutionCompletedEventAttributes: &apiv1.WorkflowExecutionCompletedEventAttributes{ + Result: &apiv1.Payload{Data: encodedResult}, + }, }, }, } blobData := serializeEvents(events) - getResponse := &shared.GetWorkflowExecutionHistoryResponse{ - RawHistory: []*shared.DataBlob{ + getResponse := &apiv1.GetWorkflowExecutionHistoryResponse{ + RawHistory: []*apiv1.DataBlob{ blobData, }, NextPageToken: nil, } getHistory := s.workflowServiceClient.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Return(getResponse, nil).Times(1) - getHistory.Do(func(ctx interface{}, getRequest *shared.GetWorkflowExecutionHistoryRequest, opt1 interface{}, opt2 interface{}, opt3 interface{}) { - workflowID := getRequest.Execution.WorkflowId - s.NotNil(workflowID) - s.NotEmpty(*workflowID) + getHistory.Do(func(ctx interface{}, getRequest *apiv1.GetWorkflowExecutionHistoryRequest, opt1 interface{}, opt2 interface{}, opt3 interface{}) { + workflowID := getRequest.WorkflowExecution.WorkflowId + s.NotEmpty(workflowID) }) workflowRun, err := s.workflowClient.ExecuteWorkflow( @@ -539,33 +536,32 @@ func (s *workflowRunSuite) TestExecuteWorkflowWorkflowExecutionAlreadyStartedErr // Test for the bug in ExecuteWorkflow. // When Options.ID was empty then GetWorkflowExecutionHistory was called with an empty WorkflowID. func (s *workflowRunSuite) TestExecuteWorkflow_NoIdInOptions() { - createResponse := &shared.StartWorkflowExecutionResponse{ - RunId: common.StringPtr(runID), + createResponse := &apiv1.StartWorkflowExecutionResponse{ + RunId: runID, } s.workflowServiceClient.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(createResponse, nil).Times(1) - eventType := shared.EventTypeWorkflowExecutionCompleted workflowResult := time.Hour * 59 encodedResult, _ := encodeArg(nil, workflowResult) - getResponse := &shared.GetWorkflowExecutionHistoryResponse{ - History: &shared.History{ - Events: []*shared.HistoryEvent{ + getResponse := &apiv1.GetWorkflowExecutionHistoryResponse{ + History: &apiv1.History{ + Events: []*apiv1.HistoryEvent{ { - EventType: &eventType, - WorkflowExecutionCompletedEventAttributes: &shared.WorkflowExecutionCompletedEventAttributes{ - Result: encodedResult, + Attributes: &apiv1.HistoryEvent_WorkflowExecutionCompletedEventAttributes{ + WorkflowExecutionCompletedEventAttributes: &apiv1.WorkflowExecutionCompletedEventAttributes{ + Result: &apiv1.Payload{Data: encodedResult}, + }, }, }, }, }, NextPageToken: nil, } - var wid *string + var wid string getHistory := s.workflowServiceClient.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(getResponse, nil).Times(1) - getHistory.Do(func(ctx interface{}, getRequest *shared.GetWorkflowExecutionHistoryRequest, opt1 interface{}, opt2 interface{}, opt3 interface{}) { - wid = getRequest.Execution.WorkflowId - s.NotNil(wid) - s.NotEmpty(*wid) + getHistory.Do(func(ctx interface{}, getRequest *apiv1.GetWorkflowExecutionHistoryRequest, opt1 interface{}, opt2 interface{}, opt3 interface{}) { + wid = getRequest.WorkflowExecution.WorkflowId + s.NotEmpty(wid) }) workflowRun, err := s.workflowClient.ExecuteWorkflow( @@ -583,42 +579,41 @@ func (s *workflowRunSuite) TestExecuteWorkflow_NoIdInOptions() { err = workflowRun.Get(context.Background(), &decodedResult) s.Nil(err) s.Equal(workflowResult, decodedResult) - s.Equal(workflowRun.GetID(), *wid) + s.Equal(workflowRun.GetID(), wid) } // Test for the bug in ExecuteWorkflow in the case of raw history returned from API. // When Options.ID was empty then GetWorkflowExecutionHistory was called with an empty WorkflowID. func (s *workflowRunSuite) TestExecuteWorkflow_NoIdInOptions_RawHistory() { - createResponse := &shared.StartWorkflowExecutionResponse{ - RunId: common.StringPtr(runID), + createResponse := &apiv1.StartWorkflowExecutionResponse{ + RunId: runID, } s.workflowServiceClient.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(createResponse, nil).Times(1) - eventType := shared.EventTypeWorkflowExecutionCompleted workflowResult := time.Hour * 59 encodedResult, _ := encodeArg(nil, workflowResult) - events := []*shared.HistoryEvent{ + events := []*apiv1.HistoryEvent{ { - EventType: &eventType, - WorkflowExecutionCompletedEventAttributes: &shared.WorkflowExecutionCompletedEventAttributes{ - Result: encodedResult, + Attributes: &apiv1.HistoryEvent_WorkflowExecutionCompletedEventAttributes{ + WorkflowExecutionCompletedEventAttributes: &apiv1.WorkflowExecutionCompletedEventAttributes{ + Result: &apiv1.Payload{Data: encodedResult}, + }, }, }, } blobData := serializeEvents(events) - getResponse := &shared.GetWorkflowExecutionHistoryResponse{ - RawHistory: []*shared.DataBlob{ + getResponse := &apiv1.GetWorkflowExecutionHistoryResponse{ + RawHistory: []*apiv1.DataBlob{ blobData, }, NextPageToken: nil, } - var wid *string + var wid string getHistory := s.workflowServiceClient.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(getResponse, nil).Times(1) - getHistory.Do(func(ctx interface{}, getRequest *shared.GetWorkflowExecutionHistoryRequest, opt1 interface{}, opt2 interface{}, opt3 interface{}) { - wid = getRequest.Execution.WorkflowId - s.NotNil(wid) - s.NotEmpty(*wid) + getHistory.Do(func(ctx interface{}, getRequest *apiv1.GetWorkflowExecutionHistoryRequest, opt1 interface{}, opt2 interface{}, opt3 interface{}) { + wid = getRequest.WorkflowExecution.WorkflowId + s.NotEmpty(wid) }) workflowRun, err := s.workflowClient.ExecuteWorkflow( @@ -636,27 +631,27 @@ func (s *workflowRunSuite) TestExecuteWorkflow_NoIdInOptions_RawHistory() { err = workflowRun.Get(context.Background(), &decodedResult) s.Nil(err) s.Equal(workflowResult, decodedResult) - s.Equal(workflowRun.GetID(), *wid) + s.Equal(workflowRun.GetID(), wid) } func (s *workflowRunSuite) TestExecuteWorkflow_NoDup_Cancelled() { - createResponse := &shared.StartWorkflowExecutionResponse{ - RunId: common.StringPtr(runID), + createResponse := &apiv1.StartWorkflowExecutionResponse{ + RunId: runID, } s.workflowServiceClient.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(createResponse, nil).Times(1) - filterType := shared.HistoryEventFilterTypeCloseEvent - eventType := shared.EventTypeWorkflowExecutionCanceled + filterType := apiv1.EventFilterType_EVENT_FILTER_TYPE_CLOSE_EVENT details := "some details" encodedDetails, _ := encodeArg(getDefaultDataConverter(), details) getRequest := getGetWorkflowExecutionHistoryRequest(filterType) - getResponse := &shared.GetWorkflowExecutionHistoryResponse{ - History: &shared.History{ - Events: []*shared.HistoryEvent{ - &shared.HistoryEvent{ - EventType: &eventType, - WorkflowExecutionCanceledEventAttributes: &shared.WorkflowExecutionCanceledEventAttributes{ - Details: encodedDetails, + getResponse := &apiv1.GetWorkflowExecutionHistoryResponse{ + History: &apiv1.History{ + Events: []*apiv1.HistoryEvent{ + { + Attributes: &apiv1.HistoryEvent_WorkflowExecutionCanceledEventAttributes{ + WorkflowExecutionCanceledEventAttributes: &apiv1.WorkflowExecutionCanceledEventAttributes{ + Details: &apiv1.Payload{Data: encodedDetails}, + }, }, }, }, @@ -687,26 +682,28 @@ func (s *workflowRunSuite) TestExecuteWorkflow_NoDup_Cancelled() { } func (s *workflowRunSuite) TestExecuteWorkflow_NoDup_Failed() { - createResponse := &shared.StartWorkflowExecutionResponse{ - RunId: common.StringPtr(runID), + createResponse := &apiv1.StartWorkflowExecutionResponse{ + RunId: runID, } s.workflowServiceClient.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(createResponse, nil).Times(1) - filterType := shared.HistoryEventFilterTypeCloseEvent - eventType := shared.EventTypeWorkflowExecutionFailed + filterType := apiv1.EventFilterType_EVENT_FILTER_TYPE_CLOSE_EVENT reason := "some reason" details := "some details" dataConverter := getDefaultDataConverter() encodedDetails, _ := encodeArg(dataConverter, details) getRequest := getGetWorkflowExecutionHistoryRequest(filterType) - getResponse := &shared.GetWorkflowExecutionHistoryResponse{ - History: &shared.History{ - Events: []*shared.HistoryEvent{ - &shared.HistoryEvent{ - EventType: &eventType, - WorkflowExecutionFailedEventAttributes: &shared.WorkflowExecutionFailedEventAttributes{ - Reason: common.StringPtr(reason), - Details: encodedDetails, + getResponse := &apiv1.GetWorkflowExecutionHistoryResponse{ + History: &apiv1.History{ + Events: []*apiv1.HistoryEvent{ + { + Attributes: &apiv1.HistoryEvent_WorkflowExecutionFailedEventAttributes{ + WorkflowExecutionFailedEventAttributes: &apiv1.WorkflowExecutionFailedEventAttributes{ + Failure: &apiv1.Failure{ + Reason: reason, + Details: encodedDetails, + }, + }, }, }, }, @@ -735,20 +732,20 @@ func (s *workflowRunSuite) TestExecuteWorkflow_NoDup_Failed() { } func (s *workflowRunSuite) TestExecuteWorkflow_NoDup_Terminated() { - createResponse := &shared.StartWorkflowExecutionResponse{ - RunId: common.StringPtr(runID), + createResponse := &apiv1.StartWorkflowExecutionResponse{ + RunId: runID, } s.workflowServiceClient.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(createResponse, nil).Times(1) - filterType := shared.HistoryEventFilterTypeCloseEvent - eventType := shared.EventTypeWorkflowExecutionTerminated + filterType := apiv1.EventFilterType_EVENT_FILTER_TYPE_CLOSE_EVENT getRequest := getGetWorkflowExecutionHistoryRequest(filterType) - getResponse := &shared.GetWorkflowExecutionHistoryResponse{ - History: &shared.History{ - Events: []*shared.HistoryEvent{ - &shared.HistoryEvent{ - EventType: &eventType, - WorkflowExecutionTerminatedEventAttributes: &shared.WorkflowExecutionTerminatedEventAttributes{}, + getResponse := &apiv1.GetWorkflowExecutionHistoryResponse{ + History: &apiv1.History{ + Events: []*apiv1.HistoryEvent{ + { + Attributes: &apiv1.HistoryEvent_WorkflowExecutionTerminatedEventAttributes{ + WorkflowExecutionTerminatedEventAttributes: &apiv1.WorkflowExecutionTerminatedEventAttributes{}, + }, }, }, }, @@ -776,22 +773,22 @@ func (s *workflowRunSuite) TestExecuteWorkflow_NoDup_Terminated() { } func (s *workflowRunSuite) TestExecuteWorkflow_NoDup_TimedOut() { - createResponse := &shared.StartWorkflowExecutionResponse{ - RunId: common.StringPtr(runID), + createResponse := &apiv1.StartWorkflowExecutionResponse{ + RunId: runID, } s.workflowServiceClient.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(createResponse, nil).Times(1) - filterType := shared.HistoryEventFilterTypeCloseEvent - eventType := shared.EventTypeWorkflowExecutionTimedOut - timeType := shared.TimeoutTypeScheduleToStart + filterType := apiv1.EventFilterType_EVENT_FILTER_TYPE_CLOSE_EVENT + timeType := apiv1.TimeoutType_TIMEOUT_TYPE_SCHEDULE_TO_START getRequest := getGetWorkflowExecutionHistoryRequest(filterType) - getResponse := &shared.GetWorkflowExecutionHistoryResponse{ - History: &shared.History{ - Events: []*shared.HistoryEvent{ - &shared.HistoryEvent{ - EventType: &eventType, - WorkflowExecutionTimedOutEventAttributes: &shared.WorkflowExecutionTimedOutEventAttributes{ - TimeoutType: &timeType, + getResponse := &apiv1.GetWorkflowExecutionHistoryResponse{ + History: &apiv1.History{ + Events: []*apiv1.HistoryEvent{ + { + Attributes: &apiv1.HistoryEvent_WorkflowExecutionTimedOutEventAttributes{ + WorkflowExecutionTimedOutEventAttributes: &apiv1.WorkflowExecutionTimedOutEventAttributes{ + TimeoutType: timeType, + }, }, }, }, @@ -823,22 +820,22 @@ func (s *workflowRunSuite) TestExecuteWorkflow_NoDup_TimedOut() { } func (s *workflowRunSuite) TestExecuteWorkflow_NoDup_ContinueAsNew() { - createResponse := &shared.StartWorkflowExecutionResponse{ - RunId: common.StringPtr(runID), + createResponse := &apiv1.StartWorkflowExecutionResponse{ + RunId: runID, } s.workflowServiceClient.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(createResponse, nil).Times(1) newRunID := "some other random run ID" - filterType := shared.HistoryEventFilterTypeCloseEvent - eventType1 := shared.EventTypeWorkflowExecutionContinuedAsNew + filterType := apiv1.EventFilterType_EVENT_FILTER_TYPE_CLOSE_EVENT getRequest1 := getGetWorkflowExecutionHistoryRequest(filterType) - getResponse1 := &shared.GetWorkflowExecutionHistoryResponse{ - History: &shared.History{ - Events: []*shared.HistoryEvent{ - &shared.HistoryEvent{ - EventType: &eventType1, - WorkflowExecutionContinuedAsNewEventAttributes: &shared.WorkflowExecutionContinuedAsNewEventAttributes{ - NewExecutionRunId: common.StringPtr(newRunID), + getResponse1 := &apiv1.GetWorkflowExecutionHistoryResponse{ + History: &apiv1.History{ + Events: []*apiv1.HistoryEvent{ + { + Attributes: &apiv1.HistoryEvent_WorkflowExecutionContinuedAsNewEventAttributes{ + WorkflowExecutionContinuedAsNewEventAttributes: &apiv1.WorkflowExecutionContinuedAsNewEventAttributes{ + NewExecutionRunId: newRunID, + }, }, }, }, @@ -849,16 +846,16 @@ func (s *workflowRunSuite) TestExecuteWorkflow_NoDup_ContinueAsNew() { workflowResult := time.Hour * 59 encodedResult, _ := encodeArg(getDefaultDataConverter(), workflowResult) - eventType2 := shared.EventTypeWorkflowExecutionCompleted getRequest2 := getGetWorkflowExecutionHistoryRequest(filterType) - getRequest2.Execution.RunId = common.StringPtr(newRunID) - getResponse2 := &shared.GetWorkflowExecutionHistoryResponse{ - History: &shared.History{ - Events: []*shared.HistoryEvent{ - &shared.HistoryEvent{ - EventType: &eventType2, - WorkflowExecutionCompletedEventAttributes: &shared.WorkflowExecutionCompletedEventAttributes{ - Result: encodedResult, + getRequest2.WorkflowExecution.RunId = newRunID + getResponse2 := &apiv1.GetWorkflowExecutionHistoryResponse{ + History: &apiv1.History{ + Events: []*apiv1.HistoryEvent{ + { + Attributes: &apiv1.HistoryEvent_WorkflowExecutionCompletedEventAttributes{ + WorkflowExecutionCompletedEventAttributes: &apiv1.WorkflowExecutionCompletedEventAttributes{ + Result: &apiv1.Payload{Data: encodedResult}, + }, }, }, }, @@ -887,18 +884,18 @@ func (s *workflowRunSuite) TestExecuteWorkflow_NoDup_ContinueAsNew() { } func (s *workflowRunSuite) TestGetWorkflow() { - filterType := shared.HistoryEventFilterTypeCloseEvent - eventType := shared.EventTypeWorkflowExecutionCompleted + filterType := apiv1.EventFilterType_EVENT_FILTER_TYPE_CLOSE_EVENT workflowResult := time.Hour * 59 encodedResult, _ := encodeArg(getDefaultDataConverter(), workflowResult) getRequest := getGetWorkflowExecutionHistoryRequest(filterType) - getResponse := &shared.GetWorkflowExecutionHistoryResponse{ - History: &shared.History{ - Events: []*shared.HistoryEvent{ - &shared.HistoryEvent{ - EventType: &eventType, - WorkflowExecutionCompletedEventAttributes: &shared.WorkflowExecutionCompletedEventAttributes{ - Result: encodedResult, + getResponse := &apiv1.GetWorkflowExecutionHistoryResponse{ + History: &apiv1.History{ + Events: []*apiv1.HistoryEvent{ + { + Attributes: &apiv1.HistoryEvent_WorkflowExecutionCompletedEventAttributes{ + WorkflowExecutionCompletedEventAttributes: &apiv1.WorkflowExecutionCompletedEventAttributes{ + Result: &apiv1.Payload{Data: encodedResult}, + }, }, }, }, @@ -923,18 +920,18 @@ func (s *workflowRunSuite) TestGetWorkflow() { s.Equal(workflowResult, decodedResult) } -func getGetWorkflowExecutionHistoryRequest(filterType shared.HistoryEventFilterType) *shared.GetWorkflowExecutionHistoryRequest { +func getGetWorkflowExecutionHistoryRequest(filterType apiv1.EventFilterType) *apiv1.GetWorkflowExecutionHistoryRequest { isLongPoll := true - request := &shared.GetWorkflowExecutionHistoryRequest{ - Domain: common.StringPtr(domain), - Execution: &shared.WorkflowExecution{ - WorkflowId: common.StringPtr(workflowID), - RunId: getRunID(runID), + request := &apiv1.GetWorkflowExecutionHistoryRequest{ + Domain: domain, + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: workflowID, + RunId: runID, }, - WaitForNewEvent: common.BoolPtr(isLongPoll), - HistoryEventFilterType: &filterType, - SkipArchival: common.BoolPtr(true), + WaitForNewEvent: isLongPoll, + HistoryEventFilterType: filterType, + SkipArchival: true, } return request @@ -945,7 +942,7 @@ type ( workflowClientTestSuite struct { suite.Suite mockCtrl *gomock.Controller - service *workflowservicetest.MockClient + service *api.MockInterface client Client } ) @@ -962,7 +959,7 @@ func (s *workflowClientTestSuite) SetupSuite() { func (s *workflowClientTestSuite) SetupTest() { s.mockCtrl = gomock.NewController(s.T()) - s.service = workflowservicetest.NewMockClient(s.mockCtrl) + s.service = api.NewMockInterface(s.mockCtrl) s.client = NewClient(s.service, domain, nil) } @@ -980,8 +977,8 @@ func (s *workflowClientTestSuite) TestSignalWithStartWorkflow() { DecisionTaskStartToCloseTimeout: timeoutInSeconds, } - createResponse := &shared.StartWorkflowExecutionResponse{ - RunId: common.StringPtr(runID), + createResponse := &apiv1.SignalWithStartWorkflowExecutionResponse{ + RunId: runID, } s.service.EXPECT().SignalWithStartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any()).Return(createResponse, nil).Times(2) @@ -1013,8 +1010,8 @@ func (s *workflowClientTestSuite) TestSignalWithStartWorkflow_Error() { s.Nil(resp) options.ExecutionStartToCloseTimeout = timeoutInSeconds - createResponse := &shared.StartWorkflowExecutionResponse{ - RunId: common.StringPtr(runID), + createResponse := &apiv1.SignalWithStartWorkflowExecutionResponse{ + RunId: runID, } s.service.EXPECT().SignalWithStartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any()).Return(createResponse, nil) resp, err = s.client.SignalWithStartWorkflow(context.Background(), workflowID, signalName, signalInput, @@ -1036,8 +1033,8 @@ func (s *workflowClientTestSuite) TestStartWorkflow() { return "result" } - createResponse := &shared.StartWorkflowExecutionResponse{ - RunId: common.StringPtr(runID), + createResponse := &apiv1.StartWorkflowExecutionResponse{ + RunId: runID, } s.service.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any()).Return(createResponse, nil) @@ -1066,8 +1063,8 @@ func (s *workflowClientTestSuite) TestStartWorkflow_WithContext() { return fmt.Errorf("context did not propagate to workflow") } - createResponse := &shared.StartWorkflowExecutionResponse{ - RunId: common.StringPtr(runID), + createResponse := &apiv1.StartWorkflowExecutionResponse{ + RunId: runID, } s.service.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any()).Return(createResponse, nil) @@ -1092,16 +1089,16 @@ func (s *workflowClientTestSuite) TestStartWorkflow_WithDataConverter() { } input := []byte("test") - createResponse := &shared.StartWorkflowExecutionResponse{ - RunId: common.StringPtr(runID), + createResponse := &apiv1.StartWorkflowExecutionResponse{ + RunId: runID, } s.service.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any()).Return(createResponse, nil). - Do(func(_ interface{}, req *shared.StartWorkflowExecutionRequest, _ ...interface{}) { + Do(func(_ interface{}, req *apiv1.StartWorkflowExecutionRequest, _ ...interface{}) { dc := client.dataConverter encodedArg, _ := dc.ToData(input) - s.Equal(req.Input, encodedArg) + s.Equal(req.Input.Data, encodedArg) var decodedArg []byte - dc.FromData(req.Input, &decodedArg) + dc.FromData(req.Input.Data, &decodedArg) s.Equal(input, decodedArg) }) @@ -1129,23 +1126,23 @@ func (s *workflowClientTestSuite) TestStartWorkflow_WithMemoAndSearchAttr() { wf := func(ctx Context) string { return "result" } - startResp := &shared.StartWorkflowExecutionResponse{} + startResp := &apiv1.StartWorkflowExecutionResponse{} s.service.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any()).Return(startResp, nil). - Do(func(_ interface{}, req *shared.StartWorkflowExecutionRequest, _ ...interface{}) { + Do(func(_ interface{}, req *apiv1.StartWorkflowExecutionRequest, _ ...interface{}) { var resultMemo, resultAttr string - err := json.Unmarshal(req.Memo.Fields["testMemo"], &resultMemo) + err := json.Unmarshal(req.Memo.Fields["testMemo"].Data, &resultMemo) s.NoError(err) s.Equal("memo value", resultMemo) - err = json.Unmarshal(req.SearchAttributes.IndexedFields["testAttr"], &resultAttr) + err = json.Unmarshal(req.SearchAttributes.IndexedFields["testAttr"].Data, &resultAttr) s.NoError(err) s.Equal("attr value", resultAttr) }) s.client.StartWorkflow(context.Background(), options, wf) } -func (s *workflowClientTestSuite) SignalWithStartWorkflowWithMemoAndSearchAttr() { +func (s *workflowClientTestSuite) TestSignalWithStartWorkflow_WithMemoAndSearchAttr() { memo := map[string]interface{}{ "testMemo": "memo value", } @@ -1163,17 +1160,16 @@ func (s *workflowClientTestSuite) SignalWithStartWorkflowWithMemoAndSearchAttr() wf := func(ctx Context) string { return "result" } - startResp := &shared.StartWorkflowExecutionResponse{} + startResp := &apiv1.SignalWithStartWorkflowExecutionResponse{} - s.service.EXPECT().SignalWithStartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any(), - gomock.Any(), gomock.Any(), gomock.Any()).Return(startResp, nil). - Do(func(_ interface{}, req *shared.SignalWithStartWorkflowExecutionRequest, _ ...interface{}) { + s.service.EXPECT().SignalWithStartWorkflowExecution(gomock.Any(), gomock.Any(), gomock.Any()).Return(startResp, nil). + Do(func(_ interface{}, req *apiv1.SignalWithStartWorkflowExecutionRequest, _ ...interface{}) { var resultMemo, resultAttr string - err := json.Unmarshal(req.Memo.Fields["testMemo"], &resultMemo) + err := json.Unmarshal(req.StartRequest.Memo.Fields["testMemo"].Data, &resultMemo) s.NoError(err) s.Equal("memo value", resultMemo) - err = json.Unmarshal(req.SearchAttributes.IndexedFields["testAttr"], &resultAttr) + err = json.Unmarshal(req.StartRequest.SearchAttributes.IndexedFields["testAttr"].Data, &resultAttr) s.NoError(err) s.Equal("attr value", resultAttr) }) @@ -1198,7 +1194,7 @@ func (s *workflowClientTestSuite) TestGetWorkflowMemo() { s.NotNil(result3) s.Equal(1, len(result3.Fields)) var resultString string - decodeArg(nil, result3.Fields["t1"], &resultString) + decodeArg(nil, result3.Fields["t1"].GetData(), &resultString) s.Equal("v1", resultString) input1["non-serializable"] = make(chan int) @@ -1224,7 +1220,7 @@ func (s *workflowClientTestSuite) TestSerializeSearchAttributes() { s.NotNil(result3) s.Equal(1, len(result3.IndexedFields)) var resultString string - decodeArg(nil, result3.IndexedFields["t1"], &resultString) + decodeArg(nil, result3.IndexedFields["t1"].GetData(), &resultString) s.Equal("v1", resultString) input1["non-serializable"] = make(chan int) @@ -1233,20 +1229,20 @@ func (s *workflowClientTestSuite) TestSerializeSearchAttributes() { } func (s *workflowClientTestSuite) TestListWorkflow() { - request := &shared.ListWorkflowExecutionsRequest{} - response := &shared.ListWorkflowExecutionsResponse{} + request := &apiv1.ListWorkflowExecutionsRequest{} + response := &apiv1.ListWorkflowExecutionsResponse{} s.service.EXPECT().ListWorkflowExecutions(gomock.Any(), gomock.Any(), gomock.Any()).Return(response, nil). - Do(func(_ interface{}, req *shared.ListWorkflowExecutionsRequest, _ ...interface{}) { + Do(func(_ interface{}, req *apiv1.ListWorkflowExecutionsRequest, _ ...interface{}) { s.Equal(domain, request.GetDomain()) }) resp, err := s.client.ListWorkflow(context.Background(), request) s.Nil(err) s.Equal(response, resp) - responseErr := &shared.BadRequestError{} - request.Domain = common.StringPtr("another") + responseErr := &api.BadRequestError{} + request.Domain = "another" s.service.EXPECT().ListWorkflowExecutions(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, responseErr). - Do(func(_ interface{}, req *shared.ListWorkflowExecutionsRequest, _ ...interface{}) { + Do(func(_ interface{}, req *apiv1.ListWorkflowExecutionsRequest, _ ...interface{}) { s.Equal("another", request.GetDomain()) }) resp, err = s.client.ListWorkflow(context.Background(), request) @@ -1254,10 +1250,10 @@ func (s *workflowClientTestSuite) TestListWorkflow() { } func (s *workflowClientTestSuite) TestListArchivedWorkflow() { - request := &shared.ListArchivedWorkflowExecutionsRequest{} - response := &shared.ListArchivedWorkflowExecutionsResponse{} + request := &apiv1.ListArchivedWorkflowExecutionsRequest{} + response := &apiv1.ListArchivedWorkflowExecutionsResponse{} s.service.EXPECT().ListArchivedWorkflowExecutions(gomock.Any(), gomock.Any(), gomock.Any()).Return(response, nil). - Do(func(_ interface{}, req *shared.ListArchivedWorkflowExecutionsRequest, _ ...interface{}) { + Do(func(_ interface{}, req *apiv1.ListArchivedWorkflowExecutionsRequest, _ ...interface{}) { s.Equal(domain, request.GetDomain()) }) ctxWithTimeout, cancel := context.WithTimeout(context.Background(), time.Minute) @@ -1266,10 +1262,10 @@ func (s *workflowClientTestSuite) TestListArchivedWorkflow() { s.Nil(err) s.Equal(response, resp) - responseErr := &shared.BadRequestError{} - request.Domain = common.StringPtr("another") + responseErr := &api.BadRequestError{} + request.Domain = "another" s.service.EXPECT().ListArchivedWorkflowExecutions(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, responseErr). - Do(func(_ interface{}, req *shared.ListArchivedWorkflowExecutionsRequest, _ ...interface{}) { + Do(func(_ interface{}, req *apiv1.ListArchivedWorkflowExecutionsRequest, _ ...interface{}) { s.Equal("another", request.GetDomain()) }) resp, err = s.client.ListArchivedWorkflow(ctxWithTimeout, request) @@ -1277,20 +1273,20 @@ func (s *workflowClientTestSuite) TestListArchivedWorkflow() { } func (s *workflowClientTestSuite) TestScanWorkflow() { - request := &shared.ListWorkflowExecutionsRequest{} - response := &shared.ListWorkflowExecutionsResponse{} + request := &apiv1.ScanWorkflowExecutionsRequest{} + response := &apiv1.ScanWorkflowExecutionsResponse{} s.service.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), gomock.Any()).Return(response, nil). - Do(func(_ interface{}, req *shared.ListWorkflowExecutionsRequest, _ ...interface{}) { + Do(func(_ interface{}, req *apiv1.ScanWorkflowExecutionsRequest, _ ...interface{}) { s.Equal(domain, request.GetDomain()) }) resp, err := s.client.ScanWorkflow(context.Background(), request) s.Nil(err) s.Equal(response, resp) - responseErr := &shared.BadRequestError{} - request.Domain = common.StringPtr("another") + responseErr := &api.BadRequestError{} + request.Domain = "another" s.service.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, responseErr). - Do(func(_ interface{}, req *shared.ListWorkflowExecutionsRequest, _ ...interface{}) { + Do(func(_ interface{}, req *apiv1.ScanWorkflowExecutionsRequest, _ ...interface{}) { s.Equal("another", request.GetDomain()) }) resp, err = s.client.ScanWorkflow(context.Background(), request) @@ -1298,20 +1294,20 @@ func (s *workflowClientTestSuite) TestScanWorkflow() { } func (s *workflowClientTestSuite) TestCountWorkflow() { - request := &shared.CountWorkflowExecutionsRequest{} - response := &shared.CountWorkflowExecutionsResponse{} + request := &apiv1.CountWorkflowExecutionsRequest{} + response := &apiv1.CountWorkflowExecutionsResponse{} s.service.EXPECT().CountWorkflowExecutions(gomock.Any(), gomock.Any(), gomock.Any()).Return(response, nil). - Do(func(_ interface{}, req *shared.CountWorkflowExecutionsRequest, _ ...interface{}) { + Do(func(_ interface{}, req *apiv1.CountWorkflowExecutionsRequest, _ ...interface{}) { s.Equal(domain, request.GetDomain()) }) resp, err := s.client.CountWorkflow(context.Background(), request) s.Nil(err) s.Equal(response, resp) - responseErr := &shared.BadRequestError{} - request.Domain = common.StringPtr("another") + responseErr := &api.BadRequestError{} + request.Domain = "another" s.service.EXPECT().CountWorkflowExecutions(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, responseErr). - Do(func(_ interface{}, req *shared.CountWorkflowExecutionsRequest, _ ...interface{}) { + Do(func(_ interface{}, req *apiv1.CountWorkflowExecutionsRequest, _ ...interface{}) { s.Equal("another", request.GetDomain()) }) resp, err = s.client.CountWorkflow(context.Background(), request) @@ -1319,24 +1315,24 @@ func (s *workflowClientTestSuite) TestCountWorkflow() { } func (s *workflowClientTestSuite) TestGetSearchAttributes() { - response := &shared.GetSearchAttributesResponse{} - s.service.EXPECT().GetSearchAttributes(gomock.Any(), gomock.Any()).Return(response, nil) + response := &apiv1.GetSearchAttributesResponse{} + s.service.EXPECT().GetSearchAttributes(gomock.Any(), gomock.Any(), gomock.Any()).Return(response, nil) resp, err := s.client.GetSearchAttributes(context.Background()) s.Nil(err) s.Equal(response, resp) - responseErr := &shared.BadRequestError{} - s.service.EXPECT().GetSearchAttributes(gomock.Any(), gomock.Any()).Return(nil, responseErr) + responseErr := &api.BadRequestError{} + s.service.EXPECT().GetSearchAttributes(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, responseErr) resp, err = s.client.GetSearchAttributes(context.Background()) s.Equal(responseErr, err) } -func serializeEvents(events []*shared.HistoryEvent) *shared.DataBlob { +func serializeEvents(events []*apiv1.HistoryEvent) *apiv1.DataBlob { - blob, _ := serializer.SerializeBatchEvents(events, shared.EncodingTypeThriftRW) + blob, _ := serializer.SerializeBatchEvents(events, apiv1.EncodingType_ENCODING_TYPE_PROTO3) - return &shared.DataBlob{ - EncodingType: shared.EncodingTypeThriftRW.Ptr(), + return &apiv1.DataBlob{ + EncodingType: apiv1.EncodingType_ENCODING_TYPE_PROTO3, Data: blob.Data, } } diff --git a/internal/internal_workflow_test.go b/internal/internal_workflow_test.go index 1ce72a947..41056b9e4 100644 --- a/internal/internal_workflow_test.go +++ b/internal/internal_workflow_test.go @@ -31,7 +31,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - "go.uber.org/cadence/v1/internal/common/metrics" + "go.uber.org/cadence/v2/internal/common/metrics" "go.uber.org/zap" ) @@ -208,7 +208,7 @@ func TestWorkflowPanic(t *testing.T) { require.NotNil(t, env.GetWorkflowError()) resultErr := env.GetWorkflowError().(*PanicError) require.EqualValues(t, "simulated", resultErr.Error()) - require.Contains(t, resultErr.StackTrace(), "cadence/v1/internal.splitJoinActivityWorkflow") + require.Contains(t, resultErr.StackTrace(), "cadence/v2/internal.splitJoinActivityWorkflow") } func TestWorkflowReturnsPanic(t *testing.T) { @@ -930,7 +930,7 @@ func getMemoTest(ctx Context) (result string, err error) { if !ok { return "", errors.New("no memo found") } - err = NewValue(val).Get(&result) + err = NewValue(val.GetData()).Get(&result) return result, err } @@ -1121,7 +1121,7 @@ func (s *WorkflowUnitTest) Test_waitGroupNegativeCounterPanicsWorkflowTest() { resultErr := env.GetWorkflowError().(*PanicError) s.EqualValues("negative WaitGroup counter", resultErr.Error()) - s.Contains(resultErr.StackTrace(), "cadence/v1/internal.waitGroupNegativeCounterPanicsWorkflowTest") + s.Contains(resultErr.StackTrace(), "cadence/v2/internal.waitGroupNegativeCounterPanicsWorkflowTest") } func (s *WorkflowUnitTest) Test_WaitGroupMultipleConcurrentWaitsPanicsWorkflowTest() { @@ -1133,7 +1133,7 @@ func (s *WorkflowUnitTest) Test_WaitGroupMultipleConcurrentWaitsPanicsWorkflowTe resultErr := env.GetWorkflowError().(*PanicError) s.EqualValues("WaitGroup is reused before previous Wait has returned", resultErr.Error()) - s.Contains(resultErr.StackTrace(), "cadence/v1/internal.waitGroupMultipleConcurrentWaitsPanicsWorkflowTest") + s.Contains(resultErr.StackTrace(), "cadence/v2/internal.waitGroupMultipleConcurrentWaitsPanicsWorkflowTest") } func (s *WorkflowUnitTest) Test_WaitGroupMultipleWaitsWorkflowTest() { diff --git a/internal/internal_workflow_testsuite.go b/internal/internal_workflow_testsuite.go index 7ef570f85..a91fed7c4 100644 --- a/internal/internal_workflow_testsuite.go +++ b/internal/internal_workflow_testsuite.go @@ -36,11 +36,10 @@ import ( "github.com/robfig/cron" "github.com/stretchr/testify/mock" "github.com/uber-go/tally" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowservicetest" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" - "go.uber.org/cadence/v1/internal/common/metrics" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/internal/common" + "go.uber.org/cadence/v2/internal/common/metrics" "go.uber.org/yarpc" "go.uber.org/zap" ) @@ -118,7 +117,7 @@ type ( taskListSpecificActivities map[string]*taskListSpecificActivity mock *mock.Mock - service workflowserviceclient.Interface + service api.Interface logger *zap.Logger metricsScope *metrics.TaggedScope ctxProps []ContextPropagator @@ -128,7 +127,7 @@ type ( callbackChannel chan testCallbackHandle testTimeout time.Duration - header *shared.Header + header *apiv1.Header counterID int activities map[string]*testActivityHandle @@ -280,9 +279,9 @@ func newTestWorkflowEnvironmentImpl(s *WorkflowTestSuite, parentRegistry *regist // setup mock service mockCtrl := gomock.NewController(&testReporter{logger: env.logger}) - mockService := workflowservicetest.NewMockClient(mockCtrl) + mockService := api.NewMockInterface(mockCtrl) - mockHeartbeatFn := func(c context.Context, r *shared.RecordActivityTaskHeartbeatRequest, opts ...yarpc.CallOption) error { + mockHeartbeatFn := func(c context.Context, r *apiv1.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.getActivityHandle(activityID) @@ -290,13 +289,13 @@ func newTestWorkflowEnvironmentImpl(s *WorkflowTestSuite, parentRegistry *regist if !ok { env.logger.Debug("RecordActivityTaskHeartbeat: ActivityID not found, could be already completed or cancelled.", zap.String(tagActivityID, activityID)) - return &shared.EntityNotExistsError{} + return &api.EntityNotExistsError{} } - activityHandle.heartbeatDetails = r.Details + activityHandle.heartbeatDetails = r.Details.GetData() activityInfo := env.getActivityInfo(activityID, activityHandle.activityType) env.postCallback(func() { if env.onActivityHeartbeatListener != nil { - env.onActivityHeartbeatListener(activityInfo, newEncodedValues(r.Details, env.GetDataConverter())) + env.onActivityHeartbeatListener(activityInfo, newEncodedValues(r.Details.GetData(), env.GetDataConverter())) } }, false) @@ -309,12 +308,12 @@ func newTestWorkflowEnvironmentImpl(s *WorkflowTestSuite, parentRegistry *regist 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) { + Return(&apiv1.RecordActivityTaskHeartbeatResponse{CancelRequested: false}, nil) + em.Do(func(ctx context.Context, r *apiv1.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) + // em.Return(&apiv1.RecordActivityTaskHeartbeatResponse{CancelRequested: false}, err) mockHeartbeatFn(ctx, r, opts...) }).AnyTimes() @@ -387,18 +386,18 @@ func (env *testWorkflowEnvironmentImpl) newTestWorkflowEnvironmentForChild(param if workflowHandler, ok := env.runningWorkflows[params.workflowID]; ok { // duplicate workflow ID if !workflowHandler.handled { - return nil, &shared.WorkflowExecutionAlreadyStartedError{ - Message: common.StringPtr("Workflow execution already started"), + return nil, &api.WorkflowExecutionAlreadyStartedError{ + Message: "Workflow execution already started", } } if params.workflowIDReusePolicy == WorkflowIDReusePolicyRejectDuplicate { - return nil, &shared.WorkflowExecutionAlreadyStartedError{ - Message: common.StringPtr("Workflow execution already started"), + return nil, &api.WorkflowExecutionAlreadyStartedError{ + Message: "Workflow execution already started", } } if workflowHandler.err == nil && params.workflowIDReusePolicy == WorkflowIDReusePolicyAllowDuplicateFailedOnly { - return nil, &shared.WorkflowExecutionAlreadyStartedError{ - Message: common.StringPtr("Workflow execution already started"), + return nil, &api.WorkflowExecutionAlreadyStartedError{ + Message: "Workflow execution already started", } } } @@ -571,7 +570,7 @@ func (env *testWorkflowEnvironmentImpl) executeActivityWithOptions( params, ) - task.HeartbeatDetails = env.heartbeatDetails + task.HeartbeatDetails = &apiv1.Payload{Data: env.heartbeatDetails} // ensure activityFn is registered to defaultTestTaskList taskHandler := env.newTestActivityTaskHandler(defaultTestTaskList, env.GetDataConverter()) @@ -579,7 +578,7 @@ func (env *testWorkflowEnvironmentImpl) executeActivityWithOptions( if err != nil { if err == context.DeadlineExceeded { env.logger.Debug(fmt.Sprintf("Activity %v timed out", task.ActivityType.Name)) - return nil, NewTimeoutError(shared.TimeoutTypeStartToClose, context.DeadlineExceeded.Error()) + return nil, NewTimeoutError(apiv1.TimeoutType_TIMEOUT_TYPE_START_TO_CLOSE, context.DeadlineExceeded.Error()) } topLine := fmt.Sprintf("activity for %s [panic]:", defaultTestTaskList) st := getStackTraceRaw(topLine, 7, 0) @@ -591,13 +590,13 @@ func (env *testWorkflowEnvironmentImpl) executeActivityWithOptions( } switch request := result.(type) { - case *shared.RespondActivityTaskCanceledRequest: - details := newEncodedValues(request.Details, env.GetDataConverter()) + case *apiv1.RespondActivityTaskCanceledRequest: + details := newEncodedValues(request.GetDetails().GetData(), env.GetDataConverter()) return nil, NewCanceledError(details) - case *shared.RespondActivityTaskFailedRequest: - return nil, constructError(request.GetReason(), request.Details, env.GetDataConverter()) - case *shared.RespondActivityTaskCompletedRequest: - return newEncodedValue(request.Result, env.GetDataConverter()), nil + case *apiv1.RespondActivityTaskFailedRequest: + return nil, constructError(request.GetFailure().GetReason(), request.GetFailure().GetDetails(), env.GetDataConverter()) + case *apiv1.RespondActivityTaskCompletedRequest: + return newEncodedValue(request.GetResult().GetData(), env.GetDataConverter()), nil default: // will never happen return nil, fmt.Errorf("unsupported respond type %T", result) @@ -829,7 +828,7 @@ func (env *testWorkflowEnvironmentImpl) Complete(result []byte, err error) { if err != nil { switch err := err.(type) { - case *CanceledError, *ContinueAsNewError, *TimeoutError, *shared.WorkflowExecutionAlreadyStartedError: + case *CanceledError, *ContinueAsNewError, *TimeoutError, *api.WorkflowExecutionAlreadyStartedError: env.testError = err case *workflowPanicError: env.testError = newPanicError(err.value, err.stackTrace) @@ -911,10 +910,10 @@ func (h *testWorkflowHandle) rerun(asChild bool) bool { if params.retryPolicy != nil && env.testError != nil { errReason, _ := getErrorDetails(env.testError, env.GetDataConverter()) var expireTime time.Time - if params.retryPolicy.GetExpirationIntervalInSeconds() > 0 { - expireTime = params.scheduledTime.Add(time.Second * time.Duration(params.retryPolicy.GetExpirationIntervalInSeconds())) + if api.DurationFromProto(params.retryPolicy.ExpirationInterval) > 0 { + expireTime = params.scheduledTime.Add(api.DurationFromProto(params.retryPolicy.ExpirationInterval)) } - backoff := getRetryBackoffFromThriftRetryPolicy(params.retryPolicy, env.workflowInfo.Attempt, errReason, env.Now(), expireTime) + backoff := getRetryBackoffFromProtoRetryPolicy(params.retryPolicy, env.workflowInfo.Attempt, errReason, env.Now(), expireTime) if backoff > 0 { // remove the current child workflow from the pending child workflow map because // the childWorkflowID will be the same for retry run. @@ -1052,16 +1051,19 @@ func (env *testWorkflowEnvironmentImpl) ExecuteActivity(parameters executeActivi defer func() { panicErr := recover() if result == nil && panicErr == nil { - reason := "activity called runtime.Goexit" - result = &shared.RespondActivityTaskFailedRequest{ - Reason: &reason, + result = &apiv1.RespondActivityTaskFailedRequest{ + Failure: &apiv1.Failure{ + Reason: "activity called runtime.Goexit", + }, } } else if panicErr != nil { reason := errReasonPanic details, _ := env.GetDataConverter().ToData(fmt.Sprintf("%v", panicErr)) - result = &shared.RespondActivityTaskFailedRequest{ - Reason: &reason, - Details: details, + result = &apiv1.RespondActivityTaskFailedRequest{ + Failure: &apiv1.Failure{ + Reason: reason, + Details: details, + }, } } // post activity result to workflow dispatcher @@ -1098,11 +1100,11 @@ func (env *testWorkflowEnvironmentImpl) makeUniqueID(id string) string { func (env *testWorkflowEnvironmentImpl) executeActivityWithRetryForTest( taskHandler ActivityTaskHandler, parameters executeActivityParams, - task *shared.PollForActivityTaskResponse, + task *apiv1.PollForActivityTaskResponse, ) (result interface{}) { var expireTime time.Time - if parameters.RetryPolicy != nil && parameters.RetryPolicy.GetExpirationIntervalInSeconds() > 0 { - expireTime = env.Now().Add(time.Second * time.Duration(parameters.RetryPolicy.GetExpirationIntervalInSeconds())) + if parameters.RetryPolicy != nil && api.DurationFromProto(parameters.RetryPolicy.ExpirationInterval) > 0 { + expireTime = env.Now().Add(api.DurationFromProto(parameters.RetryPolicy.ExpirationInterval)) } for { @@ -1116,9 +1118,9 @@ func (env *testWorkflowEnvironmentImpl) executeActivityWithRetryForTest( } // check if a retry is needed - if request, ok := result.(*shared.RespondActivityTaskFailedRequest); ok && parameters.RetryPolicy != nil { - p := fromThriftRetryPolicy(parameters.RetryPolicy) - backoff := getRetryBackoffWithNowTime(p, task.GetAttempt(), *request.Reason, env.Now(), expireTime) + if request, ok := result.(*apiv1.RespondActivityTaskFailedRequest); ok && parameters.RetryPolicy != nil { + p := fromProtoRetryPolicy(parameters.RetryPolicy) + backoff := getRetryBackoffWithNowTime(p, task.GetAttempt(), request.Failure.Reason, env.Now(), expireTime) if backoff > 0 { // need a retry waitCh := make(chan struct{}) @@ -1127,10 +1129,10 @@ func (env *testWorkflowEnvironmentImpl) executeActivityWithRetryForTest( // is enqueued. env.registerDelayedCallback(func() { env.runningCount++ - task.Attempt = common.Int32Ptr(task.GetAttempt() + 1) + task.Attempt = task.GetAttempt() + 1 activityID := string(task.TaskToken) if ah, ok := env.getActivityHandle(activityID); ok { - task.HeartbeatDetails = ah.heartbeatDetails + task.HeartbeatDetails = &apiv1.Payload{Data: ah.heartbeatDetails} } close(waitCh) }, backoff) @@ -1148,23 +1150,23 @@ func (env *testWorkflowEnvironmentImpl) executeActivityWithRetryForTest( return } -func fromThriftRetryPolicy(p *shared.RetryPolicy) *RetryPolicy { +func fromProtoRetryPolicy(p *apiv1.RetryPolicy) *RetryPolicy { return &RetryPolicy{ - InitialInterval: time.Second * time.Duration(p.GetInitialIntervalInSeconds()), + InitialInterval: api.DurationFromProto(p.InitialInterval), BackoffCoefficient: p.GetBackoffCoefficient(), - MaximumInterval: time.Second * time.Duration(p.GetMaximumIntervalInSeconds()), - ExpirationInterval: time.Second * time.Duration(p.GetExpirationIntervalInSeconds()), + MaximumInterval: api.DurationFromProto(p.MaximumInterval), + ExpirationInterval: api.DurationFromProto(p.ExpirationInterval), MaximumAttempts: p.GetMaximumAttempts(), - NonRetriableErrorReasons: p.NonRetriableErrorReasons, + NonRetriableErrorReasons: p.NonRetryableErrorReasons, } } -func getRetryBackoffFromThriftRetryPolicy(tp *shared.RetryPolicy, attempt int32, errReason string, now, expireTime time.Time) time.Duration { +func getRetryBackoffFromProtoRetryPolicy(tp *apiv1.RetryPolicy, attempt int32, errReason string, now, expireTime time.Time) time.Duration { if tp == nil { return noRetryBackoff } - p := fromThriftRetryPolicy(tp) + p := fromProtoRetryPolicy(tp) return getRetryBackoffWithNowTime(p, attempt, errReason, now, expireTime) } @@ -1253,19 +1255,19 @@ func (env *testWorkflowEnvironmentImpl) handleActivityResult(activityID string, var err error switch request := result.(type) { - case *shared.RespondActivityTaskCanceledRequest: - details := newEncodedValues(request.Details, dataConverter) + case *apiv1.RespondActivityTaskCanceledRequest: + details := newEncodedValues(request.Details.GetData(), dataConverter) err = NewCanceledError(details) activityHandle.callback(nil, err) - case *shared.RespondActivityTaskFailedRequest: - err = constructError(*request.Reason, request.Details, dataConverter) + case *apiv1.RespondActivityTaskFailedRequest: + err = constructError(request.Failure.GetReason(), request.Failure.GetDetails(), dataConverter) activityHandle.callback(nil, err) - case *shared.RespondActivityTaskCompletedRequest: - blob = request.Result + case *apiv1.RespondActivityTaskCompletedRequest: + blob = request.Result.GetData() activityHandle.callback(blob, nil) default: if result == context.DeadlineExceeded { - err = NewTimeoutError(shared.TimeoutTypeStartToClose, context.DeadlineExceeded.Error()) + err = NewTimeoutError(apiv1.TimeoutType_TIMEOUT_TYPE_START_TO_CLOSE, context.DeadlineExceeded.Error()) activityHandle.callback(nil, err) } else { panic(fmt.Sprintf("unsupported respond type %T", result)) @@ -1666,26 +1668,26 @@ func (env *testWorkflowEnvironmentImpl) newTestActivityTaskHandler(taskList stri return taskHandler } -func newTestActivityTask(workflowID, runID, activityID, workflowTypeName, domainName string, params executeActivityParams) *shared.PollForActivityTaskResponse { - task := &shared.PollForActivityTaskResponse{ - WorkflowExecution: &shared.WorkflowExecution{ - WorkflowId: common.StringPtr(workflowID), - RunId: common.StringPtr(runID), +func newTestActivityTask(workflowID, runID, activityID, workflowTypeName, domainName string, params executeActivityParams) *apiv1.PollForActivityTaskResponse { + task := &apiv1.PollForActivityTaskResponse{ + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: workflowID, + RunId: runID, }, - ActivityId: common.StringPtr(activityID), - TaskToken: []byte(activityID), // use activityID as TaskToken so we can map TaskToken in heartbeat calls. - ActivityType: &shared.ActivityType{Name: common.StringPtr(params.ActivityType.Name)}, - Input: params.Input, - ScheduledTimestamp: common.Int64Ptr(time.Now().UnixNano()), - ScheduleToCloseTimeoutSeconds: common.Int32Ptr(params.ScheduleToCloseTimeoutSeconds), - ScheduledTimestampOfThisAttempt: common.Int64Ptr(time.Now().UnixNano()), - StartedTimestamp: common.Int64Ptr(time.Now().UnixNano()), - StartToCloseTimeoutSeconds: common.Int32Ptr(params.StartToCloseTimeoutSeconds), - HeartbeatTimeoutSeconds: common.Int32Ptr(params.HeartbeatTimeoutSeconds), - WorkflowType: &shared.WorkflowType{ - Name: common.StringPtr(workflowTypeName), + ActivityId: activityID, + TaskToken: []byte(activityID), // use activityID as TaskToken so we can map TaskToken in heartbeat calls. + ActivityType: &apiv1.ActivityType{Name: params.ActivityType.Name}, + Input: &apiv1.Payload{Data: params.Input}, + ScheduledTime: api.TimeToProto(time.Now()), + ScheduleToCloseTimeout: api.SecondsToProto(params.ScheduleToCloseTimeoutSeconds), + ScheduledTimeOfThisAttempt: api.TimeToProto(time.Now()), + StartedTime: api.TimeToProto(time.Now()), + StartToCloseTimeout: api.SecondsToProto(params.StartToCloseTimeoutSeconds), + HeartbeatTimeout: api.SecondsToProto(params.HeartbeatTimeoutSeconds), + WorkflowType: &apiv1.WorkflowType{ + Name: workflowTypeName, }, - WorkflowDomain: common.StringPtr(domainName), + WorkflowDomain: domainName, Header: params.Header, } return task @@ -2039,7 +2041,7 @@ func (env *testWorkflowEnvironmentImpl) signalWorkflowByID(workflowID, signalNam if workflowHandle, ok := env.runningWorkflows[workflowID]; ok { if workflowHandle.handled { - return &shared.WorkflowExecutionAlreadyCompletedError{Message: fmt.Sprintf("Workflow %v already completed", workflowID)} + return &api.WorkflowExecutionAlreadyCompletedError{Message: fmt.Sprintf("Workflow %v already completed", workflowID)} } workflowHandle.env.postCallback(func() { workflowHandle.env.signalHandler(signalName, data) @@ -2047,7 +2049,7 @@ func (env *testWorkflowEnvironmentImpl) signalWorkflowByID(workflowID, signalNam return nil } - return &shared.EntityNotExistsError{Message: fmt.Sprintf("Workflow %v not exists", workflowID)} + return &api.EntityNotExistsError{Message: fmt.Sprintf("Workflow %v not exists", workflowID)} } func (env *testWorkflowEnvironmentImpl) queryWorkflow(queryType string, args ...interface{}) (Value, error) { diff --git a/internal/internal_workflow_testsuite_test.go b/internal/internal_workflow_testsuite_test.go index 9356c70e8..ef4713ae2 100644 --- a/internal/internal_workflow_testsuite_test.go +++ b/internal/internal_workflow_testsuite_test.go @@ -33,8 +33,8 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/suite" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" "go.uber.org/zap" ) @@ -56,8 +56,8 @@ func (s *WorkflowTestSuiteUnitTest) SetupSuite() { s.localActivityOptions = LocalActivityOptions{ ScheduleToCloseTimeout: time.Second * 3, } - s.header = &shared.Header{ - Fields: map[string][]byte{"test": []byte("test-data")}, + s.header = &apiv1.Header{ + Fields: map[string]*apiv1.Payload{"test": {Data: []byte("test-data")}}, } s.ctxProps = []ContextPropagator{NewStringMapPropagator([]string{"test"})} } @@ -387,9 +387,9 @@ func (s *WorkflowTestSuiteUnitTest) Test_ActivityWithHeaderContext() { return "", errors.New("value not found from ctx") } - s.SetHeader(&shared.Header{ - Fields: map[string][]byte{ - testHeader: []byte("test-data"), + s.SetHeader(&apiv1.Header{ + Fields: map[string]*apiv1.Payload{ + testHeader: {Data: []byte("test-data")}, }, }) @@ -1245,7 +1245,7 @@ func (s *WorkflowTestSuiteUnitTest) Test_GetVersion() { changeVersionsBytes, ok := wfInfo.SearchAttributes.IndexedFields[CadenceChangeVersion] s.True(ok) var changeVersions []string - err = json.Unmarshal(changeVersionsBytes, &changeVersions) + err = json.Unmarshal(changeVersionsBytes.GetData(), &changeVersions) s.NoError(err) s.Equal(1, len(changeVersions)) s.Equal("test_change_id-2", changeVersions[0]) @@ -1305,7 +1305,7 @@ func (s *WorkflowTestSuiteUnitTest) Test_MockGetVersion() { changeVersionsBytes, ok := wfInfo.SearchAttributes.IndexedFields[CadenceChangeVersion] s.True(ok) var changeVersions []string - err = json.Unmarshal(changeVersionsBytes, &changeVersions) + err = json.Unmarshal(changeVersionsBytes.GetData(), &changeVersions) s.NoError(err) s.Equal(2, len(changeVersions)) s.Equal("change_2-2", changeVersions[0]) @@ -1371,7 +1371,7 @@ func (s *WorkflowTestSuiteUnitTest) Test_MockUpsertSearchAttributes() { s.NotNil(wfInfo.SearchAttributes) valBytes := wfInfo.SearchAttributes.IndexedFields["CustomIntField"] var result int - NewValue(valBytes).Get(&result) + NewValue(valBytes.GetData()).Get(&result) s.Equal(1, result) return nil @@ -1429,34 +1429,34 @@ func (s *WorkflowTestSuiteUnitTest) Test_MockUpsertSearchAttributes_OnError() { func (s *WorkflowTestSuiteUnitTest) Test_ActivityWithThriftTypes() { actualValues := []string{} - retVal := &shared.WorkflowExecution{WorkflowId: common.StringPtr("retwID2"), RunId: common.StringPtr("retrID2")} + retVal := &apiv1.WorkflowExecution{WorkflowId: "retwID2", RunId: "retrID2"} // Passing one argument - activitySingleFn := func(ctx context.Context, wf *shared.WorkflowExecution) (*shared.WorkflowExecution, error) { + activitySingleFn := func(ctx context.Context, wf *apiv1.WorkflowExecution) (*apiv1.WorkflowExecution, error) { actualValues = append(actualValues, wf.GetWorkflowId()) actualValues = append(actualValues, wf.GetRunId()) return retVal, nil } - input := &shared.WorkflowExecution{WorkflowId: common.StringPtr("wID1"), RunId: common.StringPtr("rID1")} + input := &apiv1.WorkflowExecution{WorkflowId: "wID1", RunId: "rID1"} env := s.NewTestActivityEnvironment() env.RegisterActivity(activitySingleFn) blob, err := env.ExecuteActivity(activitySingleFn, input) s.NoError(err) - var ret *shared.WorkflowExecution + var ret *apiv1.WorkflowExecution blob.Get(&ret) s.Equal(retVal, ret) // Passing more than one argument - activityDoubleArgFn := func(ctx context.Context, wf *shared.WorkflowExecution, t *shared.WorkflowType) (*shared.WorkflowExecution, error) { + activityDoubleArgFn := func(ctx context.Context, wf *apiv1.WorkflowExecution, t *apiv1.WorkflowType) (*apiv1.WorkflowExecution, error) { actualValues = append(actualValues, wf.GetWorkflowId()) actualValues = append(actualValues, wf.GetRunId()) actualValues = append(actualValues, t.GetName()) return retVal, nil } - input = &shared.WorkflowExecution{WorkflowId: common.StringPtr("wID2"), RunId: common.StringPtr("rID3")} - wt := &shared.WorkflowType{Name: common.StringPtr("wType")} + input = &apiv1.WorkflowExecution{WorkflowId: "wID2", RunId: "rID3"} + wt := &apiv1.WorkflowType{Name: "wType"} env = s.NewTestActivityEnvironment() env.RegisterActivity(activityDoubleArgFn) blob, err = env.ExecuteActivity(activityDoubleArgFn, input, wt) @@ -1610,9 +1610,9 @@ func (s *WorkflowTestSuiteUnitTest) Test_WorkflowHeaderContext() { } s.SetContextPropagators([]ContextPropagator{NewStringMapPropagator([]string{testHeader})}) - s.SetHeader(&shared.Header{ - Fields: map[string][]byte{ - testHeader: []byte("test-data"), + s.SetHeader(&apiv1.Header{ + Fields: map[string]*apiv1.Payload{ + testHeader: {Data: []byte("test-data")}, }, }) @@ -1654,9 +1654,9 @@ func (s *WorkflowTestSuiteUnitTest) Test_ChildWorkflowContextPropagation() { } s.SetContextPropagators([]ContextPropagator{NewStringMapPropagator([]string{testHeader})}) - s.SetHeader(&shared.Header{ - Fields: map[string][]byte{ - testHeader: []byte("test-data"), + s.SetHeader(&apiv1.Header{ + Fields: map[string]*apiv1.Payload{ + testHeader: {Data: []byte("test-data")}, }, }) @@ -2763,9 +2763,9 @@ func (s *WorkflowTestSuiteUnitTest) Test_MockChildWorkflowAlreadyRunning() { err := ExecuteChildWorkflow(ctx, childWorkflowFn).Get(ctx, nil) s.Error(err) - alreadySytartedErr, ok := err.(*shared.WorkflowExecutionAlreadyStartedError) + alreadySytartedErr, ok := err.(*api.WorkflowExecutionAlreadyStartedError) s.True(ok) - s.Equal(runID, *alreadySytartedErr.RunId) + s.Equal(runID, alreadySytartedErr.RunID) return nil } @@ -2775,8 +2775,8 @@ func (s *WorkflowTestSuiteUnitTest) Test_MockChildWorkflowAlreadyRunning() { RegisterWorkflow(workflowFn) env.OnWorkflow(childWorkflowFn, mock.Anything). - Return(&shared.WorkflowExecutionAlreadyStartedError{ - RunId: &runID, + Return(&api.WorkflowExecutionAlreadyStartedError{ + RunID: runID, }) env.ExecuteWorkflow(workflowFn) @@ -2799,7 +2799,7 @@ func (s *WorkflowTestSuiteUnitTest) Test_ChildWorkflowAlreadyRunning() { err = f2.Get(ctx1, &result2) s.Error(err) - _, ok := err.(*shared.WorkflowExecutionAlreadyStartedError) + _, ok := err.(*api.WorkflowExecutionAlreadyStartedError) s.True(ok) return result1 + " " + result2, nil @@ -2999,7 +2999,7 @@ func (s *WorkflowTestSuiteUnitTest) Test_ActivityTimeoutWithDetails() { count := 0 timeoutFn := func() error { count++ - return NewTimeoutError(shared.TimeoutTypeStartToClose, testErrorDetails1) + return NewTimeoutError(apiv1.TimeoutType_TIMEOUT_TYPE_START_TO_CLOSE, testErrorDetails1) } timeoutWf := func(ctx Context) error { @@ -3027,7 +3027,7 @@ func (s *WorkflowTestSuiteUnitTest) Test_ActivityTimeoutWithDetails() { s.Error(err) timeoutErr, ok := err.(*TimeoutError) s.True(ok) - s.Equal(shared.TimeoutTypeStartToClose, timeoutErr.TimeoutType()) + s.Equal(apiv1.TimeoutType_TIMEOUT_TYPE_START_TO_CLOSE, timeoutErr.TimeoutType()) s.True(timeoutErr.HasDetails()) var details string err = timeoutErr.Details(&details) @@ -3042,7 +3042,7 @@ func (s *WorkflowTestSuiteUnitTest) Test_ActivityTimeoutWithDetails() { s.Error(err) timeoutErr, ok = err.(*TimeoutError) s.True(ok) - s.Equal(shared.TimeoutTypeStartToClose, timeoutErr.TimeoutType()) + s.Equal(apiv1.TimeoutType_TIMEOUT_TYPE_START_TO_CLOSE, timeoutErr.TimeoutType()) s.True(timeoutErr.HasDetails()) err = timeoutErr.Details(&details) s.NoError(err) @@ -3073,7 +3073,7 @@ func (s *WorkflowTestSuiteUnitTest) Test_ActivityDeadlineExceeded() { s.Error(err) timeoutErr, ok := err.(*TimeoutError) s.True(ok) - s.Equal(shared.TimeoutTypeStartToClose, timeoutErr.TimeoutType()) + s.Equal(apiv1.TimeoutType_TIMEOUT_TYPE_START_TO_CLOSE, timeoutErr.TimeoutType()) s.True(timeoutErr.HasDetails()) var details string err = timeoutErr.Details(&details) diff --git a/internal/query_builder.go b/internal/query_builder.go index 7024e9aed..eb7fa04db 100644 --- a/internal/query_builder.go +++ b/internal/query_builder.go @@ -25,8 +25,6 @@ import ( "math" "strings" "time" - - "go.uber.org/cadence/v1/.gen/go/shared" ) type ( @@ -41,21 +39,19 @@ const ( WorkflowStatusClosed WorkflowStatus = "CLOSED" // WorkflowStatusALL is the WorkflowStatus for all workflows WorkflowStatusALL WorkflowStatus = "ALL" -) -var ( // WorkflowStatusCompleted is the WorkflowStatus for completed workflow - WorkflowStatusCompleted = WorkflowStatus(shared.WorkflowExecutionCloseStatusCompleted.String()) + WorkflowStatusCompleted WorkflowStatus = "COMPLETED" // WorkflowStatusFailed is the WorkflowStatus for failed workflows - WorkflowStatusFailed = WorkflowStatus(shared.WorkflowExecutionCloseStatusFailed.String()) + WorkflowStatusFailed WorkflowStatus = "FAILED" // WorkflowStatusCanceled is the WorkflowStatus for canceled workflows - WorkflowStatusCanceled = WorkflowStatus(shared.WorkflowExecutionCloseStatusCanceled.String()) + WorkflowStatusCanceled WorkflowStatus = "CANCELED" // WorkflowStatusTerminated is the WorkflowStatus for terminated workflows - WorkflowStatusTerminated = WorkflowStatus(shared.WorkflowExecutionCloseStatusTerminated.String()) + WorkflowStatusTerminated WorkflowStatus = "TERMINATED" // WorkflowStatusContinuedAsNew is the WorkflowStatus for continuedAsNew workflows - WorkflowStatusContinuedAsNew = WorkflowStatus(shared.WorkflowExecutionCloseStatusContinuedAsNew.String()) + WorkflowStatusContinuedAsNew WorkflowStatus = "CONTINUED_AS_NEW" // WorkflowStatusTimedOut is the WorkflowStatus for timedout workflows - WorkflowStatusTimedOut = WorkflowStatus(shared.WorkflowExecutionCloseStatusTimedOut.String()) + WorkflowStatusTimedOut WorkflowStatus = "TIMED_OUT" ) const ( diff --git a/internal/registry_test.go b/internal/registry_test.go index 3ac8b0592..80b5488f2 100644 --- a/internal/registry_test.go +++ b/internal/registry_test.go @@ -40,7 +40,7 @@ func TestWorkflowRegistration(t *testing.T) { { msg: "register workflow function", register: func(r *registry) { r.RegisterWorkflow(testWorkflowFunction) }, - workflowType: "go.uber.org/cadence/v1/internal.testWorkflowFunction", + workflowType: "go.uber.org/cadence/v2/internal.testWorkflowFunction", resolveByFunction: testWorkflowFunction, }, { @@ -63,8 +63,8 @@ func TestWorkflowRegistration(t *testing.T) { { msg: "register workflow struct function (backwards compatible)", register: func(r *registry) { r.RegisterWorkflow(w.Method) }, - workflowType: "go.uber.org/cadence/v1/internal.(*testWorkflowStruct).Method", - altWorkflowType: "go.uber.org/cadence/v1/internal.(*testWorkflowStruct).Method-fm", + workflowType: "go.uber.org/cadence/v2/internal.(*testWorkflowStruct).Method", + altWorkflowType: "go.uber.org/cadence/v2/internal.(*testWorkflowStruct).Method-fm", resolveByFunction: w.Method, }, { @@ -81,7 +81,7 @@ func TestWorkflowRegistration(t *testing.T) { r.RegisterWorkflow(testWorkflowFunction) r.RegisterWorkflowWithOptions(testWorkflowFunction, RegisterWorkflowOptions{DisableAlreadyRegisteredCheck: true}) }, - workflowType: "go.uber.org/cadence/v1/internal.testWorkflowFunction", + workflowType: "go.uber.org/cadence/v2/internal.testWorkflowFunction", resolveByFunction: testWorkflowFunction, }, { @@ -144,7 +144,7 @@ func TestActivityRegistration(t *testing.T) { { msg: "register activity function", register: func(r *registry) { r.RegisterActivity(testActivityFunction) }, - activityType: "go.uber.org/cadence/v1/internal.testActivityFunction", + activityType: "go.uber.org/cadence/v2/internal.testActivityFunction", resolveByFunction: testActivityFunction, }, { @@ -167,8 +167,8 @@ func TestActivityRegistration(t *testing.T) { { msg: "register activity struct", register: func(r *registry) { r.RegisterActivity(&testActivityStruct{}) }, - activityType: "go.uber.org/cadence/v1/internal.(*testActivityStruct).Method", - altActivityType: "go.uber.org/cadence/v1/internal.(*testActivityStruct).Method-fm", + activityType: "go.uber.org/cadence/v2/internal.(*testActivityStruct).Method", + altActivityType: "go.uber.org/cadence/v2/internal.(*testActivityStruct).Method-fm", resolveByFunction: (&testActivityStruct{}).Method, }, { @@ -203,7 +203,7 @@ func TestActivityRegistration(t *testing.T) { r.RegisterActivity(&testActivityStruct{}) r.RegisterActivityWithOptions(&testActivityStruct{}, RegisterActivityOptions{DisableAlreadyRegisteredCheck: true}) }, - activityType: "go.uber.org/cadence/v1/internal.(*testActivityStruct).Method", + activityType: "go.uber.org/cadence/v2/internal.(*testActivityStruct).Method", resolveByFunction: (&testActivityStruct{}).Method, }, { diff --git a/internal/session.go b/internal/session.go index 2ab83be5d..7b7a0614c 100644 --- a/internal/session.go +++ b/internal/session.go @@ -28,7 +28,7 @@ import ( "time" "github.com/pborman/uuid" - "go.uber.org/cadence/v1/internal/common/backoff" + "go.uber.org/cadence/v2/internal/common/backoff" "go.uber.org/zap" ) @@ -540,9 +540,20 @@ func (env *sessionEnvironmentImpl) AddSessionToken() { func (env *sessionEnvironmentImpl) SignalCreationResponse(ctx context.Context, sessionID string) error { activityEnv := getActivityEnv(ctx) - client := activityEnv.serviceInvoker.GetClient(activityEnv.workflowDomain, &ClientOptions{}) - return client.SignalWorkflow(ctx, activityEnv.workflowExecution.ID, activityEnv.workflowExecution.RunID, - sessionID, env.getCreationResponse()) + + signalInput, err := encodeArg(getDefaultDataConverter(), env.getCreationResponse()) + if err != nil { + return err + } + + return activityEnv.serviceInvoker.SignalWorkflow( + ctx, + activityEnv.workflowDomain, + activityEnv.workflowExecution.ID, + activityEnv.workflowExecution.RunID, + sessionID, + signalInput, + ) } func (env *sessionEnvironmentImpl) getCreationResponse() *sessionCreationResponse { diff --git a/internal/testdata/localActivities.json b/internal/testdata/localActivities.json index 5ad05db50..5e9b1261e 100644 --- a/internal/testdata/localActivities.json +++ b/internal/testdata/localActivities.json @@ -7,7 +7,7 @@ "taskId": 1049501, "workflowExecutionStartedEventAttributes": { "workflowType": { - "name": "go.uber.org/cadence/v1/internal.localActivitiesCallingOptionsWorkflow.Execute" + "name": "go.uber.org/cadence/v2/internal.localActivitiesCallingOptionsWorkflow.Execute" }, "taskList": { "name": "tl-1" diff --git a/internal/testdata/parentWF.json b/internal/testdata/parentWF.json index 28789885e..e26901b7f 100644 --- a/internal/testdata/parentWF.json +++ b/internal/testdata/parentWF.json @@ -6,7 +6,7 @@ "taskId": 50331648, "workflowExecutionStartedEventAttributes": { "workflowType": { - "name": "go.uber.org/cadence/v1/internal.testReplayWorkflowFromFileParent" + "name": "go.uber.org/cadence/v2/internal.testReplayWorkflowFromFileParent" }, "taskList": { "name": "childWorkflowGroup" @@ -66,7 +66,7 @@ "domain": "samples-domain", "workflowId": "child_workflow:0ea65eda-a0db-4a59-bef3-dce48e8484f8", "workflowType": { - "name": "go.uber.org/cadence/v1/internal.testReplayWorkflowFromFile" + "name": "go.uber.org/cadence/v2/internal.testReplayWorkflowFromFile" }, "taskList": { "name": "childWorkflowGroup" diff --git a/internal/testdata/sampleHistory.json b/internal/testdata/sampleHistory.json index af15bff8d..d715e4579 100644 --- a/internal/testdata/sampleHistory.json +++ b/internal/testdata/sampleHistory.json @@ -5,7 +5,7 @@ "eventType": "WorkflowExecutionStarted", "workflowExecutionStartedEventAttributes": { "workflowType": { - "name": "go.uber.org/cadence/v1/internal.testReplayWorkflowFromFile" + "name": "go.uber.org/cadence/v2/internal.testReplayWorkflowFromFile" }, "taskList": { "name": "taskList1" @@ -54,7 +54,7 @@ "activityTaskScheduledEventAttributes": { "activityId": "0", "activityType": { - "name": "go.uber.org/cadence/v1/internal.testActivityMultipleArgs" + "name": "go.uber.org/cadence/v2/internal.testActivityMultipleArgs" }, "taskList": { "name": "taskList1" diff --git a/internal/tracer_test.go b/internal/tracer_test.go index 726ecf5eb..45ebcbc9d 100644 --- a/internal/tracer_test.go +++ b/internal/tracer_test.go @@ -28,7 +28,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" jaeger_config "github.com/uber/jaeger-client-go/config" - "go.uber.org/cadence/v1/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" "go.uber.org/zap" ) @@ -42,8 +42,8 @@ func TestTracingContextPropagator(t *testing.T) { span := tracer.StartSpan("test-operation") ctx := context.Background() ctx = opentracing.ContextWithSpan(ctx, span) - header := &shared.Header{ - Fields: map[string][]byte{}, + header := &apiv1.Header{ + Fields: map[string]*apiv1.Payload{}, } err = ctxProp.Inject(ctx, NewHeaderWriter(header)) @@ -61,8 +61,8 @@ func TestTracingContextPropagatorNoSpan(t *testing.T) { t.Parallel() ctxProp := NewTracingContextPropagator(zap.NewNop(), opentracing.NoopTracer{}) - header := &shared.Header{ - Fields: map[string][]byte{}, + header := &apiv1.Header{ + Fields: map[string]*apiv1.Payload{}, } err := ctxProp.Inject(context.Background(), NewHeaderWriter(header)) require.NoError(t, err) @@ -82,8 +82,8 @@ func TestTracingContextPropagatorWorkflowContext(t *testing.T) { span := tracer.StartSpan("test-operation") assert.NotNil(t, span.Context()) ctx := contextWithSpan(Background(), span.Context()) - header := &shared.Header{ - Fields: map[string][]byte{}, + header := &apiv1.Header{ + Fields: map[string]*apiv1.Payload{}, } err = ctxProp.InjectFromWorkflow(ctx, NewHeaderWriter(header)) @@ -106,8 +106,8 @@ func TestTracingContextPropagatorWorkflowContextNoSpan(t *testing.T) { t.Parallel() ctxProp := NewTracingContextPropagator(zap.NewNop(), opentracing.NoopTracer{}) - header := &shared.Header{ - Fields: map[string][]byte{}, + header := &apiv1.Header{ + Fields: map[string]*apiv1.Payload{}, } err := ctxProp.InjectFromWorkflow(Background(), NewHeaderWriter(header)) require.NoError(t, err) @@ -130,8 +130,8 @@ func TestConsistentInjectionExtraction(t *testing.T) { span.SetBaggageItem("request-tenancy", baggageVal) assert.NotNil(t, span.Context()) ctx := contextWithSpan(Background(), span.Context()) - header := &shared.Header{ - Fields: map[string][]byte{}, + header := &apiv1.Header{ + Fields: map[string]*apiv1.Payload{}, } err = ctxProp.InjectFromWorkflow(ctx, NewHeaderWriter(header)) require.NoError(t, err) diff --git a/internal/worker.go b/internal/worker.go index b3029f7c4..3bcae0d09 100644 --- a/internal/worker.go +++ b/internal/worker.go @@ -27,8 +27,8 @@ import ( "github.com/opentracing/opentracing-go" "github.com/uber-go/tally" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" - "go.uber.org/cadence/v1/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" "go.uber.org/zap" ) @@ -244,13 +244,13 @@ const ( ) // NewWorker creates an instance of worker for managing workflow and activity executions. -// service - thrift connection to the cadence server. +// service - API interface to the cadence server. // domain - the name of the cadence domain. // taskList - is the task list name you use to identify your client worker, also // identifies group of workflow and activity implementations that are hosted by a single worker process. // options - configure any worker specific options like logger, metrics, identity. func NewWorker( - service workflowserviceclient.Interface, + service api.Interface, domain string, taskList string, options WorkerOptions, @@ -265,7 +265,7 @@ func NewWorker( // This method is kept to maintain backward compatibility and should not be used. func ReplayWorkflowExecution( ctx context.Context, - service workflowserviceclient.Interface, + service api.Interface, logger *zap.Logger, domain string, execution WorkflowExecution, @@ -279,7 +279,7 @@ func ReplayWorkflowExecution( // The logger is an optional parameter. Defaults to the noop logger. // Deprecated: Global workflow replay methods are replaced by equivalent WorkflowReplayer instance methods. // This method is kept to maintain backward compatibility and should not be used. -func ReplayWorkflowHistory(logger *zap.Logger, history *shared.History) error { +func ReplayWorkflowHistory(logger *zap.Logger, history *apiv1.History) error { r := NewWorkflowReplayer() return r.ReplayWorkflowHistory(logger, history) } diff --git a/internal/workflow.go b/internal/workflow.go index 95ea5626a..70873f1f4 100644 --- a/internal/workflow.go +++ b/internal/workflow.go @@ -29,9 +29,10 @@ import ( "time" "github.com/uber-go/tally" - s "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" - "go.uber.org/cadence/v1/internal/common/backoff" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/internal/common" + "go.uber.org/cadence/v2/internal/common/backoff" "go.uber.org/zap" ) @@ -714,9 +715,9 @@ func (wc *workflowEnvironmentInterceptor) ExecuteChildWorkflow(ctx Context, chil return result } -func getWorkflowHeader(ctx Context, ctxProps []ContextPropagator) *s.Header { - header := &s.Header{ - Fields: make(map[string][]byte), +func getWorkflowHeader(ctx Context, ctxProps []ContextPropagator) *apiv1.Header { + header := &apiv1.Header{ + Fields: make(map[string]*apiv1.Payload), } writer := NewHeaderWriter(header) for _, ctxProp := range ctxProps { @@ -739,10 +740,10 @@ type WorkflowInfo struct { ContinuedExecutionRunID *string ParentWorkflowDomain *string ParentWorkflowExecution *WorkflowExecution - Memo *s.Memo // Value can be decoded using data converter (DefaultDataConverter, or custom one if set). - SearchAttributes *s.SearchAttributes // Value can be decoded using DefaultDataConverter. + Memo *apiv1.Memo // Value can be decoded using data converter (DefaultDataConverter, or custom one if set). + SearchAttributes *apiv1.SearchAttributes // Value can be decoded using DefaultDataConverter. BinaryChecksum *string - RetryPolicy *s.RetryPolicy + RetryPolicy *apiv1.RetryPolicy } // GetBinaryChecksum returns the binary checksum(identifier) of this worker @@ -1453,20 +1454,20 @@ func WithRetryPolicy(ctx Context, retryPolicy RetryPolicy) Context { return ctx1 } -func convertRetryPolicy(retryPolicy *RetryPolicy) *s.RetryPolicy { +func convertRetryPolicy(retryPolicy *RetryPolicy) *apiv1.RetryPolicy { if retryPolicy == nil { return nil } if retryPolicy.BackoffCoefficient == 0 { retryPolicy.BackoffCoefficient = backoff.DefaultBackoffCoefficient } - thriftRetryPolicy := s.RetryPolicy{ - InitialIntervalInSeconds: common.Int32Ptr(common.Int32Ceil(retryPolicy.InitialInterval.Seconds())), - MaximumIntervalInSeconds: common.Int32Ptr(common.Int32Ceil(retryPolicy.MaximumInterval.Seconds())), - BackoffCoefficient: &retryPolicy.BackoffCoefficient, - MaximumAttempts: &retryPolicy.MaximumAttempts, - NonRetriableErrorReasons: retryPolicy.NonRetriableErrorReasons, - ExpirationIntervalInSeconds: common.Int32Ptr(common.Int32Ceil(retryPolicy.ExpirationInterval.Seconds())), + return &apiv1.RetryPolicy{ + InitialInterval: api.DurationToProto(retryPolicy.InitialInterval), + MaximumInterval: api.DurationToProto(retryPolicy.MaximumInterval), + BackoffCoefficient: retryPolicy.BackoffCoefficient, + MaximumAttempts: retryPolicy.MaximumAttempts, + NonRetryableErrorReasons: retryPolicy.NonRetriableErrorReasons, + ExpirationInterval: api.DurationToProto(retryPolicy.ExpirationInterval), } - return &thriftRetryPolicy } + diff --git a/internal/workflow_replayer.go b/internal/workflow_replayer.go index 65e96dd90..5473118a0 100644 --- a/internal/workflow_replayer.go +++ b/internal/workflow_replayer.go @@ -29,16 +29,17 @@ import ( "io/ioutil" "math" + "github.com/gogo/protobuf/types" "github.com/golang/mock/gomock" "github.com/opentracing/opentracing-go" "github.com/pborman/uuid" "github.com/uber-go/tally" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowservicetest" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" - "go.uber.org/cadence/v1/internal/common/backoff" - "go.uber.org/cadence/v1/internal/common/serializer" + "go.uber.org/cadence/v2/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/internal/api/thrift" + "go.uber.org/cadence/v2/internal/common/backoff" + "go.uber.org/cadence/v2/internal/common/serializer" "go.uber.org/zap" ) @@ -118,14 +119,14 @@ func (r *WorkflowReplayer) RegisterWorkflowWithOptions(w interface{}, options Re // ReplayWorkflowHistory executes a single decision task for the given history. // Use for testing backwards compatibility of code changes and troubleshooting workflows in a debugger. // The logger is an optional parameter. Defaults to the noop logger. -func (r *WorkflowReplayer) ReplayWorkflowHistory(logger *zap.Logger, history *shared.History) error { +func (r *WorkflowReplayer) ReplayWorkflowHistory(logger *zap.Logger, history *apiv1.History) error { if logger == nil { logger = zap.NewNop() } testReporter := logger.Sugar() controller := gomock.NewController(testReporter) - service := workflowservicetest.NewMockClient(controller) + service := api.NewMockInterface(controller) return r.replayWorkflowHistory(logger, service, replayDomainName, nil, history, nil) } @@ -154,7 +155,7 @@ func (r *WorkflowReplayer) ReplayPartialWorkflowHistoryFromJSONFile(logger *zap. testReporter := logger.Sugar() controller := gomock.NewController(testReporter) - service := workflowservicetest.NewMockClient(controller) + service := api.NewMockInterface(controller) return r.replayWorkflowHistory(logger, service, replayDomainName, nil, history, nil) } @@ -163,21 +164,20 @@ func (r *WorkflowReplayer) ReplayPartialWorkflowHistoryFromJSONFile(logger *zap. // The logger is an optional parameter. Defaults to the noop logger. func (r *WorkflowReplayer) ReplayWorkflowExecution( ctx context.Context, - service workflowserviceclient.Interface, + service api.Interface, logger *zap.Logger, domain string, execution WorkflowExecution, ) error { - sharedExecution := &shared.WorkflowExecution{ - RunId: common.StringPtr(execution.RunID), - WorkflowId: common.StringPtr(execution.ID), - } - request := &shared.GetWorkflowExecutionHistoryRequest{ - Domain: common.StringPtr(domain), - Execution: sharedExecution, + request := &apiv1.GetWorkflowExecutionHistoryRequest{ + Domain: domain, + WorkflowExecution: &apiv1.WorkflowExecution{ + RunId: execution.RunID, + WorkflowId: execution.ID, + }, } - var hResponse *shared.GetWorkflowExecutionHistoryResponse + var hResponse *apiv1.GetWorkflowExecutionHistoryResponse if err := backoff.Retry(ctx, func() error { tchCtx, cancel, opt := newChannelContext(ctx) @@ -186,11 +186,11 @@ func (r *WorkflowReplayer) ReplayWorkflowExecution( hResponse, err = service.GetWorkflowExecutionHistory(tchCtx, request, opt...) cancel() - return err + return api.ConvertError(err) }, createDynamicServiceRetryPolicy(ctx), func(err error) bool { - if _, ok := err.(*shared.InternalServiceError); ok { + if _, ok := err.(*api.InternalServiceError); ok { // treat InternalServiceError as non-retryable, as the workflow history may be corrupted return false } @@ -201,7 +201,7 @@ func (r *WorkflowReplayer) ReplayWorkflowExecution( } if hResponse.RawHistory != nil { - history, err := serializer.DeserializeBlobDataToHistoryEvents(hResponse.RawHistory, shared.HistoryEventFilterTypeAllEvent) + history, err := serializer.DeserializeBlobDataToHistoryEvents(hResponse.RawHistory, apiv1.EventFilterType_EVENT_FILTER_TYPE_ALL_EVENT) if err != nil { return err } @@ -214,10 +214,10 @@ func (r *WorkflowReplayer) ReplayWorkflowExecution( func (r *WorkflowReplayer) replayWorkflowHistory( logger *zap.Logger, - service workflowserviceclient.Interface, + service api.Interface, domain string, execution *WorkflowExecution, - history *shared.History, + history *apiv1.History, nextPageToken []byte, ) error { events := history.Events @@ -228,36 +228,33 @@ func (r *WorkflowReplayer) replayWorkflowHistory( return errReplayHistoryTooShort } first := events[0] - if first.GetEventType() != shared.EventTypeWorkflowExecutionStarted { + attr := first.GetWorkflowExecutionStartedEventAttributes() + if attr == nil { return errReplayInvalidFirstEvent } last := events[len(events)-1] - attr := first.WorkflowExecutionStartedEventAttributes - if attr == nil { - return errReplayCorruptedStartedEvent - } workflowType := attr.WorkflowType if execution == nil { execution = &WorkflowExecution{ ID: replayWorkflowID, RunID: uuid.NewRandom().String(), } - if first.WorkflowExecutionStartedEventAttributes.GetOriginalExecutionRunId() != "" { - execution.RunID = first.WorkflowExecutionStartedEventAttributes.GetOriginalExecutionRunId() + if attr.GetOriginalExecutionRunId() != "" { + execution.RunID = attr.GetOriginalExecutionRunId() } } - task := &shared.PollForDecisionTaskResponse{ - Attempt: common.Int64Ptr(int64(attr.GetAttempt())), + task := &apiv1.PollForDecisionTaskResponse{ + Attempt: int64(attr.GetAttempt()), TaskToken: []byte(replayTaskToken), WorkflowType: workflowType, - WorkflowExecution: &shared.WorkflowExecution{ - WorkflowId: common.StringPtr(execution.ID), - RunId: common.StringPtr(execution.RunID), + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: execution.ID, + RunId: execution.RunID, }, History: history, - PreviousStartedEventId: common.Int64Ptr(replayPreviousStartedEventID), + PreviousStartedEventId: &types.Int64Value{Value: replayPreviousStartedEventID}, NextPageToken: nextPageToken, } if logger == nil { @@ -289,7 +286,7 @@ func (r *WorkflowReplayer) replayWorkflowHistory( return err } - if last.GetEventType() != shared.EventTypeWorkflowExecutionCompleted && last.GetEventType() != shared.EventTypeWorkflowExecutionContinuedAsNew { + if last.GetWorkflowExecutionCompletedEventAttributes() == nil && last.GetWorkflowExecutionContinuedAsNewEventAttributes() == nil { return nil } @@ -298,27 +295,27 @@ func (r *WorkflowReplayer) replayWorkflowHistory( // entire history before starting the replay as otherwise we can't get the last event here. // compare workflow results if resp != nil { - completeReq, ok := resp.(*shared.RespondDecisionTaskCompletedRequest) + completeReq, ok := resp.(*apiv1.RespondDecisionTaskCompletedRequest) if ok { for _, d := range completeReq.Decisions { - if d.GetDecisionType() == shared.DecisionTypeContinueAsNewWorkflowExecution && - last.GetEventType() == shared.EventTypeWorkflowExecutionContinuedAsNew { - inputA := d.ContinueAsNewWorkflowExecutionDecisionAttributes.Input - inputB := last.WorkflowExecutionContinuedAsNewEventAttributes.Input + if d.GetContinueAsNewWorkflowExecutionDecisionAttributes() != nil && + last.GetWorkflowExecutionContinuedAsNewEventAttributes() != nil { + inputA := d.GetContinueAsNewWorkflowExecutionDecisionAttributes().Input.GetData() + inputB := last.GetWorkflowExecutionContinuedAsNewEventAttributes().Input.GetData() if bytes.Compare(inputA, inputB) == 0 { return nil } } - if d.GetDecisionType() == shared.DecisionTypeCompleteWorkflowExecution && - last.GetEventType() == shared.EventTypeWorkflowExecutionCompleted { - resultA := last.WorkflowExecutionCompletedEventAttributes.Result - resultB := d.CompleteWorkflowExecutionDecisionAttributes.Result + if d.GetCompleteWorkflowExecutionDecisionAttributes() != nil && + last.GetWorkflowExecutionCompletedEventAttributes() != nil { + resultA := last.GetWorkflowExecutionCompletedEventAttributes().Result.GetData() + resultB := d.GetCompleteWorkflowExecutionDecisionAttributes().Result.GetData() if bytes.Compare(resultA, resultB) == 0 { return nil } } - if d.GetDecisionType() == shared.DecisionTypeCompleteWorkflowExecution && - last.GetEventType() == shared.EventTypeWorkflowExecutionContinuedAsNew { + if d.GetCompleteWorkflowExecutionDecisionAttributes() != nil && + last.GetWorkflowExecutionContinuedAsNewEventAttributes() != nil { // for cron and retry workflow, decision will be completed workflow and // and server side will convert it to a continue as new event. // there's nothing to compare here @@ -330,25 +327,35 @@ func (r *WorkflowReplayer) replayWorkflowHistory( return fmt.Errorf("replay workflow doesn't return the same result as the last event, resp: %v, last: %v", resp, last) } -func extractHistoryFromFile(jsonfileName string, lastEventID int64) (*shared.History, error) { +func extractHistoryFromFile(jsonfileName string, lastEventID int64) (*apiv1.History, error) { raw, err := ioutil.ReadFile(jsonfileName) if err != nil { return nil, err } - var deserializedEvents []*shared.HistoryEvent + var deserializedEvents []*apiv1.HistoryEvent err = json.Unmarshal(raw, &deserializedEvents) - if err != nil { return nil, err } + // Fallback to Thrift encoding + if len(deserializedEvents) > 0 && deserializedEvents[0].EventId == 0 { + var thriftEvents []*shared.HistoryEvent + err = json.Unmarshal(raw, &thriftEvents) + if err != nil { + return nil, err + } + + deserializedEvents = thrift.ToHistoryEvents(thriftEvents) + } + if lastEventID <= 0 { - return &shared.History{Events: deserializedEvents}, nil + return &apiv1.History{Events: deserializedEvents}, nil } // Caller is potentially asking for subset of history instead of all history events - var events []*shared.HistoryEvent + var events []*apiv1.HistoryEvent for _, event := range deserializedEvents { events = append(events, event) if event.GetEventId() == lastEventID { @@ -357,7 +364,7 @@ func extractHistoryFromFile(jsonfileName string, lastEventID int64) (*shared.His } } - return &shared.History{Events: events}, nil + return &apiv1.History{Events: events}, nil } func augmentReplayOptions( diff --git a/internal/workflow_replayer_test.go b/internal/workflow_replayer_test.go index 546816271..d20658157 100644 --- a/internal/workflow_replayer_test.go +++ b/internal/workflow_replayer_test.go @@ -29,8 +29,7 @@ import ( "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" "go.uber.org/zap" ) @@ -76,8 +75,8 @@ func (s *workflowReplayerSuite) TestReplayWorkflowHistory_Full() { func (s *workflowReplayerSuite) TestReplayWorkflowHistory_Full_ResultMisMatch() { fullHistory := getTestReplayWorkflowFullHistory() completedEvent := fullHistory.Events[len(fullHistory.Events)-1] - s.Equal(shared.EventTypeWorkflowExecutionCompleted, completedEvent.GetEventType()) - completedEvent.WorkflowExecutionCompletedEventAttributes.Result = []byte("some random result") + s.NotNil(completedEvent.GetWorkflowExecutionCompletedEventAttributes()) + completedEvent.GetWorkflowExecutionCompletedEventAttributes().Result = &apiv1.Payload{Data: []byte("some random result")} err := s.replayer.ReplayWorkflowHistory(s.logger, fullHistory) s.Error(err) @@ -86,7 +85,7 @@ func (s *workflowReplayerSuite) TestReplayWorkflowHistory_Full_ResultMisMatch() func (s *workflowReplayerSuite) TestReplayWorkflowHistory_Full_ContinueAsNew() { fullHistory := getTestReplayWorkflowFullHistory() completedEventIdx := len(fullHistory.Events) - 1 - s.Equal(shared.EventTypeWorkflowExecutionCompleted, fullHistory.Events[completedEventIdx].GetEventType()) + s.NotNil(fullHistory.Events[completedEventIdx].GetWorkflowExecutionCompletedEventAttributes()) fullHistory.Events[completedEventIdx] = createTestEventWorkflowExecutionContinuedAsNew(int64(completedEventIdx+1), nil) err := s.replayer.ReplayWorkflowHistory(s.logger, fullHistory) @@ -292,180 +291,180 @@ func (w localActivitiesCallingOptionsWorkflow) Execute(ctx Context, input []byte return []byte("Done"), nil } -func getTestReplayWorkflowFullHistory() *shared.History { - return &shared.History{ - Events: []*shared.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &shared.WorkflowExecutionStartedEventAttributes{ - WorkflowType: &shared.WorkflowType{Name: common.StringPtr("go.uber.org/cadence/v1/internal.testReplayWorkflow")}, - TaskList: &shared.TaskList{Name: common.StringPtr(testTaskList)}, - Input: testEncodeFunctionArgs(getDefaultDataConverter()), +func getTestReplayWorkflowFullHistory() *apiv1.History { + return &apiv1.History{ + Events: []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{ + WorkflowType: &apiv1.WorkflowType{Name: "go.uber.org/cadence/v2/internal.testReplayWorkflow"}, + TaskList: &apiv1.TaskList{Name: testTaskList}, + Input: &apiv1.Payload{Data: testEncodeFunctionArgs(getDefaultDataConverter())}, }), - createTestEventDecisionTaskScheduled(2, &shared.DecisionTaskScheduledEventAttributes{}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskCompleted(4, &shared.DecisionTaskCompletedEventAttributes{}), - createTestEventActivityTaskScheduled(5, &shared.ActivityTaskScheduledEventAttributes{ - ActivityId: common.StringPtr("0"), - ActivityType: &shared.ActivityType{Name: common.StringPtr("testActivity")}, - TaskList: &shared.TaskList{Name: &testTaskList}, + createTestEventDecisionTaskCompleted(4, &apiv1.DecisionTaskCompletedEventAttributes{}), + createTestEventActivityTaskScheduled(5, &apiv1.ActivityTaskScheduledEventAttributes{ + ActivityId: "0", + ActivityType: &apiv1.ActivityType{Name: "testActivity"}, + TaskList: &apiv1.TaskList{Name: testTaskList}, }), - createTestEventActivityTaskStarted(6, &shared.ActivityTaskStartedEventAttributes{ - ScheduledEventId: common.Int64Ptr(5), + createTestEventActivityTaskStarted(6, &apiv1.ActivityTaskStartedEventAttributes{ + ScheduledEventId: 5, }), - createTestEventActivityTaskCompleted(7, &shared.ActivityTaskCompletedEventAttributes{ - ScheduledEventId: common.Int64Ptr(5), - StartedEventId: common.Int64Ptr(6), + createTestEventActivityTaskCompleted(7, &apiv1.ActivityTaskCompletedEventAttributes{ + ScheduledEventId: 5, + StartedEventId: 6, }), - createTestEventDecisionTaskScheduled(8, &shared.DecisionTaskScheduledEventAttributes{}), + createTestEventDecisionTaskScheduled(8, &apiv1.DecisionTaskScheduledEventAttributes{}), createTestEventDecisionTaskStarted(9), - createTestEventDecisionTaskCompleted(10, &shared.DecisionTaskCompletedEventAttributes{ - ScheduledEventId: common.Int64Ptr(8), - StartedEventId: common.Int64Ptr(9), + createTestEventDecisionTaskCompleted(10, &apiv1.DecisionTaskCompletedEventAttributes{ + ScheduledEventId: 8, + StartedEventId: 9, }), - createTestEventWorkflowExecutionCompleted(11, &shared.WorkflowExecutionCompletedEventAttributes{ - DecisionTaskCompletedEventId: common.Int64Ptr(10), + createTestEventWorkflowExecutionCompleted(11, &apiv1.WorkflowExecutionCompletedEventAttributes{ + DecisionTaskCompletedEventId: 10, }), }, } } -func getTestReplayWorkflowPartialHistoryWithDecisionEvents() *shared.History { - return &shared.History{ - Events: []*shared.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &shared.WorkflowExecutionStartedEventAttributes{ - WorkflowType: &shared.WorkflowType{Name: common.StringPtr("go.uber.org/cadence/v1/internal.testReplayWorkflow")}, - TaskList: &shared.TaskList{Name: common.StringPtr(testTaskList)}, - Input: testEncodeFunctionArgs(getDefaultDataConverter()), +func getTestReplayWorkflowPartialHistoryWithDecisionEvents() *apiv1.History { + return &apiv1.History{ + Events: []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{ + WorkflowType: &apiv1.WorkflowType{Name: "go.uber.org/cadence/v2/internal.testReplayWorkflow"}, + TaskList: &apiv1.TaskList{Name: testTaskList}, + Input: &apiv1.Payload{Data: testEncodeFunctionArgs(getDefaultDataConverter())}, }), - createTestEventDecisionTaskScheduled(2, &shared.DecisionTaskScheduledEventAttributes{}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskCompleted(4, &shared.DecisionTaskCompletedEventAttributes{}), - createTestEventActivityTaskScheduled(5, &shared.ActivityTaskScheduledEventAttributes{ - ActivityId: common.StringPtr("0"), - ActivityType: &shared.ActivityType{Name: common.StringPtr("testActivity-fm")}, - TaskList: &shared.TaskList{Name: &testTaskList}, + createTestEventDecisionTaskCompleted(4, &apiv1.DecisionTaskCompletedEventAttributes{}), + createTestEventActivityTaskScheduled(5, &apiv1.ActivityTaskScheduledEventAttributes{ + ActivityId: "0", + ActivityType: &apiv1.ActivityType{Name: "testActivity-fm"}, + TaskList: &apiv1.TaskList{Name: testTaskList}, }), }, } } -func getTestReplayWorkflowPartialHistoryNoDecisionEvents() *shared.History { - return &shared.History{ - Events: []*shared.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &shared.WorkflowExecutionStartedEventAttributes{ - WorkflowType: &shared.WorkflowType{Name: common.StringPtr("go.uber.org/cadence/v1/internal.testReplayWorkflow")}, - TaskList: &shared.TaskList{Name: common.StringPtr(testTaskList)}, - Input: testEncodeFunctionArgs(getDefaultDataConverter()), +func getTestReplayWorkflowPartialHistoryNoDecisionEvents() *apiv1.History { + return &apiv1.History{ + Events: []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{ + WorkflowType: &apiv1.WorkflowType{Name: "go.uber.org/cadence/v2/internal.testReplayWorkflow"}, + TaskList: &apiv1.TaskList{Name: testTaskList}, + Input: &apiv1.Payload{Data: testEncodeFunctionArgs(getDefaultDataConverter())}, }), - createTestEventDecisionTaskScheduled(2, &shared.DecisionTaskScheduledEventAttributes{}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskFailed(4, &shared.DecisionTaskFailedEventAttributes{ScheduledEventId: common.Int64Ptr(2)}), - createTestEventDecisionTaskScheduled(5, &shared.DecisionTaskScheduledEventAttributes{}), + createTestEventDecisionTaskFailed(4, &apiv1.DecisionTaskFailedEventAttributes{ScheduledEventId: 2}), + createTestEventDecisionTaskScheduled(5, &apiv1.DecisionTaskScheduledEventAttributes{}), createTestEventDecisionTaskStarted(6), }, } } -func getTestReplayWorkflowMismatchHistory() *shared.History { - return &shared.History{ - Events: []*shared.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &shared.WorkflowExecutionStartedEventAttributes{ - WorkflowType: &shared.WorkflowType{Name: common.StringPtr("go.uber.org/cadence/v1/internal.testReplayWorkflow")}, - TaskList: &shared.TaskList{Name: common.StringPtr("taskList")}, - Input: testEncodeFunctionArgs(getDefaultDataConverter()), +func getTestReplayWorkflowMismatchHistory() *apiv1.History { + return &apiv1.History{ + Events: []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{ + WorkflowType: &apiv1.WorkflowType{Name: "go.uber.org/cadence/v2/internal.testReplayWorkflow"}, + TaskList: &apiv1.TaskList{Name: "taskList"}, + Input: &apiv1.Payload{Data: testEncodeFunctionArgs(getDefaultDataConverter())}, }), - createTestEventDecisionTaskScheduled(2, &shared.DecisionTaskScheduledEventAttributes{}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskCompleted(4, &shared.DecisionTaskCompletedEventAttributes{}), - createTestEventActivityTaskScheduled(5, &shared.ActivityTaskScheduledEventAttributes{ - ActivityId: common.StringPtr("0"), - ActivityType: &shared.ActivityType{Name: common.StringPtr("unknownActivityType")}, - TaskList: &shared.TaskList{Name: common.StringPtr("taskList")}, + createTestEventDecisionTaskCompleted(4, &apiv1.DecisionTaskCompletedEventAttributes{}), + createTestEventActivityTaskScheduled(5, &apiv1.ActivityTaskScheduledEventAttributes{ + ActivityId: "0", + ActivityType: &apiv1.ActivityType{Name: "unknownActivityType"}, + TaskList: &apiv1.TaskList{Name: "taskList"}, }), }, } } -func getTestReplayWorkflowLocalActivityHistory() *shared.History { - return &shared.History{ - Events: []*shared.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &shared.WorkflowExecutionStartedEventAttributes{ - WorkflowType: &shared.WorkflowType{Name: common.StringPtr("go.uber.org/cadence/v1/internal.testReplayWorkflowLocalActivity")}, - TaskList: &shared.TaskList{Name: common.StringPtr(testTaskList)}, - Input: testEncodeFunctionArgs(getDefaultDataConverter()), +func getTestReplayWorkflowLocalActivityHistory() *apiv1.History { + return &apiv1.History{ + Events: []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{ + WorkflowType: &apiv1.WorkflowType{Name: "go.uber.org/cadence/v2/internal.testReplayWorkflowLocalActivity"}, + TaskList: &apiv1.TaskList{Name: testTaskList}, + Input: &apiv1.Payload{Data: testEncodeFunctionArgs(getDefaultDataConverter())}, }), - createTestEventDecisionTaskScheduled(2, &shared.DecisionTaskScheduledEventAttributes{}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskCompleted(4, &shared.DecisionTaskCompletedEventAttributes{}), + createTestEventDecisionTaskCompleted(4, &apiv1.DecisionTaskCompletedEventAttributes{}), - createTestEventLocalActivity(5, &shared.MarkerRecordedEventAttributes{ - MarkerName: common.StringPtr(localActivityMarkerName), - Details: createLocalActivityMarkerDataForTest("0", "go.uber.org/cadence/v1/internal.testActivity"), - DecisionTaskCompletedEventId: common.Int64Ptr(4), + createTestEventLocalActivity(5, &apiv1.MarkerRecordedEventAttributes{ + MarkerName: localActivityMarkerName, + Details: &apiv1.Payload{Data: createLocalActivityMarkerDataForTest("0", "go.uber.org/cadence/v2/internal.testActivity")}, + DecisionTaskCompletedEventId: 4, }), - createTestEventWorkflowExecutionCompleted(6, &shared.WorkflowExecutionCompletedEventAttributes{ - DecisionTaskCompletedEventId: common.Int64Ptr(4), + createTestEventWorkflowExecutionCompleted(6, &apiv1.WorkflowExecutionCompletedEventAttributes{ + DecisionTaskCompletedEventId: 4, }), }, } } -func getTestReplayWorkflowLocalActivityResultMismatchHistory() *shared.History { - return &shared.History{ - Events: []*shared.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &shared.WorkflowExecutionStartedEventAttributes{ - WorkflowType: &shared.WorkflowType{Name: common.StringPtr("go.uber.org/cadence/v1/internal.testReplayWorkflowLocalActivity")}, - TaskList: &shared.TaskList{Name: common.StringPtr(testTaskList)}, - Input: testEncodeFunctionArgs(getDefaultDataConverter()), +func getTestReplayWorkflowLocalActivityResultMismatchHistory() *apiv1.History { + return &apiv1.History{ + Events: []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{ + WorkflowType: &apiv1.WorkflowType{Name: "go.uber.org/cadence/v2/internal.testReplayWorkflowLocalActivity"}, + TaskList: &apiv1.TaskList{Name: testTaskList}, + Input: &apiv1.Payload{Data: testEncodeFunctionArgs(getDefaultDataConverter())}, }), - createTestEventDecisionTaskScheduled(2, &shared.DecisionTaskScheduledEventAttributes{}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskCompleted(4, &shared.DecisionTaskCompletedEventAttributes{}), + createTestEventDecisionTaskCompleted(4, &apiv1.DecisionTaskCompletedEventAttributes{}), - createTestEventLocalActivity(5, &shared.MarkerRecordedEventAttributes{ - MarkerName: common.StringPtr(localActivityMarkerName), - Details: createLocalActivityMarkerDataForTest("0", ""), - DecisionTaskCompletedEventId: common.Int64Ptr(4), + createTestEventLocalActivity(5, &apiv1.MarkerRecordedEventAttributes{ + MarkerName: localActivityMarkerName, + Details: &apiv1.Payload{Data: createLocalActivityMarkerDataForTest("0", "")}, + DecisionTaskCompletedEventId: 4, }), - createTestEventWorkflowExecutionCompleted(6, &shared.WorkflowExecutionCompletedEventAttributes{ - Result: []byte("some-incorrect-result"), - DecisionTaskCompletedEventId: common.Int64Ptr(4), + createTestEventWorkflowExecutionCompleted(6, &apiv1.WorkflowExecutionCompletedEventAttributes{ + Result: &apiv1.Payload{Data: []byte("some-incorrect-result")}, + DecisionTaskCompletedEventId: 4, }), }, } } -func getTestReplayWorkflowLocalActivityTypeMismatchHistory() *shared.History { - return &shared.History{ - Events: []*shared.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &shared.WorkflowExecutionStartedEventAttributes{ - WorkflowType: &shared.WorkflowType{Name: common.StringPtr("go.uber.org/cadence/v1/internal.testReplayWorkflowLocalActivity")}, - TaskList: &shared.TaskList{Name: common.StringPtr(testTaskList)}, - Input: testEncodeFunctionArgs(getDefaultDataConverter()), +func getTestReplayWorkflowLocalActivityTypeMismatchHistory() *apiv1.History { + return &apiv1.History{ + Events: []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{ + WorkflowType: &apiv1.WorkflowType{Name: "go.uber.org/cadence/v2/internal.testReplayWorkflowLocalActivity"}, + TaskList: &apiv1.TaskList{Name: testTaskList}, + Input: &apiv1.Payload{Data: testEncodeFunctionArgs(getDefaultDataConverter())}, }), - createTestEventDecisionTaskScheduled(2, &shared.DecisionTaskScheduledEventAttributes{}), + createTestEventDecisionTaskScheduled(2, &apiv1.DecisionTaskScheduledEventAttributes{}), createTestEventDecisionTaskStarted(3), - createTestEventDecisionTaskCompleted(4, &shared.DecisionTaskCompletedEventAttributes{}), + createTestEventDecisionTaskCompleted(4, &apiv1.DecisionTaskCompletedEventAttributes{}), - createTestEventLocalActivity(5, &shared.MarkerRecordedEventAttributes{ - MarkerName: common.StringPtr(localActivityMarkerName), - Details: createLocalActivityMarkerDataForTest("0", "different-activity-type"), - DecisionTaskCompletedEventId: common.Int64Ptr(4), + createTestEventLocalActivity(5, &apiv1.MarkerRecordedEventAttributes{ + MarkerName: localActivityMarkerName, + Details: &apiv1.Payload{Data: createLocalActivityMarkerDataForTest("0", "different-activity-type")}, + DecisionTaskCompletedEventId: 4, }), - createTestEventWorkflowExecutionCompleted(6, &shared.WorkflowExecutionCompletedEventAttributes{ - DecisionTaskCompletedEventId: common.Int64Ptr(4), + createTestEventWorkflowExecutionCompleted(6, &apiv1.WorkflowExecutionCompletedEventAttributes{ + DecisionTaskCompletedEventId: 4, }), }, } } -func getTestReplayWorkflowContextPropagatorHistory() *shared.History { +func getTestReplayWorkflowContextPropagatorHistory() *apiv1.History { history := getTestReplayWorkflowFullHistory() - history.Events[0].WorkflowExecutionStartedEventAttributes.WorkflowType.Name = common.StringPtr("go.uber.org/cadence/v1/internal.testReplayWorkflowContextPropagator") - history.Events[0].WorkflowExecutionStartedEventAttributes.Header = &shared.Header{ - Fields: map[string][]byte{testHeader: []byte("testValue")}, + history.Events[0].GetWorkflowExecutionStartedEventAttributes().WorkflowType.Name = "go.uber.org/cadence/v2/internal.testReplayWorkflowContextPropagator" + history.Events[0].GetWorkflowExecutionStartedEventAttributes().Header = &apiv1.Header{ + Fields: map[string]*apiv1.Payload{testHeader: {Data:[]byte("testValue")}}, } return history } diff --git a/internal/workflow_shadower.go b/internal/workflow_shadower.go index fd49c8ffc..41bfb8b2e 100644 --- a/internal/workflow_shadower.go +++ b/internal/workflow_shadower.go @@ -31,10 +31,10 @@ import ( "time" "github.com/facebookgo/clock" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" - "go.uber.org/cadence/v1/.gen/go/shadower" - "go.uber.org/cadence/v1/internal/common" - "go.uber.org/cadence/v1/internal/common/util" + "go.uber.org/cadence/v2/.gen/go/shadower" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/internal/common" + "go.uber.org/cadence/v2/internal/common/util" "go.uber.org/zap" ) @@ -118,7 +118,7 @@ type ( // WorkflowShadower retrieves and replays workflow history from Cadence service // to determine if there's any nondeterministic changes in the workflow definition WorkflowShadower struct { - service workflowserviceclient.Interface + service api.Interface domain string shadowOptions ShadowOptions logger *zap.Logger @@ -148,7 +148,7 @@ const ( // NewWorkflowShadower creates an instance of the WorkflowShadower for testing // The logger is an optional parameter. Defaults to noop logger if not provided and will override the logger in WorkerOptions func NewWorkflowShadower( - service workflowserviceclient.Interface, + service api.Interface, domain string, shadowOptions ShadowOptions, replayOptions ReplayOptions, diff --git a/internal/workflow_shadower_activities.go b/internal/workflow_shadower_activities.go index c1b073b69..aa9294674 100644 --- a/internal/workflow_shadower_activities.go +++ b/internal/workflow_shadower_activities.go @@ -26,12 +26,13 @@ import ( "strings" "time" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" - "go.uber.org/cadence/v1/.gen/go/shadower" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" - "go.uber.org/cadence/v1/internal/common/backoff" - "go.uber.org/cadence/v1/internal/common/metrics" + "go.uber.org/cadence/v2/.gen/go/shadower" + "go.uber.org/cadence/v2/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/internal/common" + "go.uber.org/cadence/v2/internal/common/backoff" + "go.uber.org/cadence/v2/internal/common/metrics" "go.uber.org/zap" ) @@ -58,13 +59,13 @@ func scanWorkflowActivity( params shadower.ScanWorkflowActivityParams, ) (shadower.ScanWorkflowActivityResult, error) { logger := GetActivityLogger(ctx) - service := ctx.Value(serviceClientContextKey).(workflowserviceclient.Interface) + service := ctx.Value(serviceClientContextKey).(api.Interface) scanResult, err := scanWorkflowExecutionsHelper(ctx, service, params, logger) switch err.(type) { - case *shared.EntityNotExistsError: + case *api.EntityNotExistsError: err = NewCustomError(shadower.ErrReasonDomainNotExists, err.Error()) - case *shared.BadRequestError: + case *api.BadRequestError: err = NewCustomError(shadower.ErrReasonInvalidQuery, err.Error()) } return scanResult, err @@ -72,7 +73,7 @@ func scanWorkflowActivity( func scanWorkflowExecutionsHelper( ctx context.Context, - service workflowserviceclient.Interface, + service api.Interface, params shadower.ScanWorkflowActivityParams, logger *zap.Logger, ) (shadower.ScanWorkflowActivityResult, error) { @@ -83,16 +84,16 @@ func scanWorkflowExecutionsHelper( completionTime = now.Add(time.Duration(ratioToCompleteScanWorkflow * float32(activityTimeout))) } - request := &shared.ListWorkflowExecutionsRequest{ - Domain: params.Domain, - Query: params.WorkflowQuery, + request := &apiv1.ScanWorkflowExecutionsRequest{ + Domain: params.GetDomain(), + Query: params.GetWorkflowQuery(), NextPageToken: params.NextPageToken, - PageSize: params.PageSize, + PageSize: params.GetPageSize(), } result := shadower.ScanWorkflowActivityResult{} for { - var resp *shared.ListWorkflowExecutionsResponse + var resp *apiv1.ScanWorkflowExecutionsResponse if err := backoff.Retry(ctx, func() error { tchCtx, cancel, opt := newChannelContext(ctx) @@ -101,7 +102,7 @@ func scanWorkflowExecutionsHelper( resp, err = service.ScanWorkflowExecutions(tchCtx, request, opt...) cancel() - return err + return api.ConvertError(err) }, createDynamicServiceRetryPolicy(ctx), isServiceTransientError, @@ -116,7 +117,10 @@ func scanWorkflowExecutionsHelper( for _, execution := range resp.Executions { if shouldReplay(params.GetSamplingRate()) { - result.Executions = append(result.Executions, execution.Execution) + result.Executions = append(result.Executions, &shared.WorkflowExecution{ + WorkflowId: &execution.WorkflowExecution.WorkflowId, + RunId: &execution.WorkflowExecution.RunId, + }) } } @@ -148,7 +152,7 @@ func replayWorkflowActivity( ) (shadower.ReplayWorkflowActivityResult, error) { logger := GetActivityLogger(ctx) scope := tagScope(GetActivityMetricsScope(ctx), tagDomain, params.GetDomain(), tagTaskList, GetActivityInfo(ctx).TaskList) - service := ctx.Value(serviceClientContextKey).(workflowserviceclient.Interface) + service := ctx.Value(serviceClientContextKey).(api.Interface) replayer := ctx.Value(workflowReplayerContextKey).(*WorkflowReplayer) var progress replayWorkflowActivityProgress @@ -203,7 +207,7 @@ func replayWorkflowActivity( func replayWorkflowExecutionHelper( ctx context.Context, replayer *WorkflowReplayer, - service workflowserviceclient.Interface, + service api.Interface, logger *zap.Logger, domain string, execution WorkflowExecution, diff --git a/internal/workflow_shadower_activities_test.go b/internal/workflow_shadower_activities_test.go index df26bde45..d32239a96 100644 --- a/internal/workflow_shadower_activities_test.go +++ b/internal/workflow_shadower_activities_test.go @@ -30,10 +30,11 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowservicetest" - "go.uber.org/cadence/v1/.gen/go/shadower" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" + "go.uber.org/cadence/v2/.gen/go/shadower" + "go.uber.org/cadence/v2/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/internal/common" "go.uber.org/zap/zaptest" ) @@ -43,11 +44,11 @@ type workflowShadowerActivitiesSuite struct { WorkflowTestSuite controller *gomock.Controller - mockService *workflowservicetest.MockClient + mockService *api.MockInterface env *TestActivityEnvironment testReplayer *WorkflowReplayer - testWorkflowHistory *shared.History + testWorkflowHistory *apiv1.History } func TestWorkflowShadowerActivitiesSuite(t *testing.T) { @@ -59,7 +60,7 @@ func (s *workflowShadowerActivitiesSuite) SetupTest() { s.Assertions = require.New(s.T()) s.controller = gomock.NewController(s.T()) - s.mockService = workflowservicetest.NewMockClient(s.controller) + s.mockService = api.NewMockInterface(s.controller) s.env = s.NewTestActivityEnvironment() s.testReplayer = NewWorkflowReplayer() @@ -87,7 +88,7 @@ func (s *workflowShadowerActivitiesSuite) TearDownTest() { func (s *workflowShadowerActivitiesSuite) TestScanWorkflowActivity_Succeed() { numExecutions := 1000 - s.mockService.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), callOptions...).Return(&shared.ListWorkflowExecutionsResponse{ + s.mockService.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.ScanWorkflowExecutionsResponse{ Executions: newTestWorkflowExecutions(numExecutions), NextPageToken: []byte{1, 2, 3}, }, nil).Times(1) @@ -110,7 +111,7 @@ func (s *workflowShadowerActivitiesSuite) TestScanWorkflowActivity_Succeed() { func (s *workflowShadowerActivitiesSuite) TestScanWorkflowActivity_MinResultSize() { numExecutionsPerScan := 3 - s.mockService.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), callOptions...).Return(&shared.ListWorkflowExecutionsResponse{ + s.mockService.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.ScanWorkflowExecutionsResponse{ Executions: newTestWorkflowExecutions(numExecutionsPerScan), NextPageToken: []byte{1, 2, 3}, }, nil).Times(int(math.Ceil(float64(minScanWorkflowResultSize) / float64(numExecutionsPerScan)))) @@ -132,7 +133,7 @@ func (s *workflowShadowerActivitiesSuite) TestScanWorkflowActivity_MinResultSize func (s *workflowShadowerActivitiesSuite) TestScanWorkflowActivity_CompletionTime() { activityTimeoutSeconds := int32(1) - s.mockService.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), callOptions...).Return(&shared.ListWorkflowExecutionsResponse{ + s.mockService.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.ScanWorkflowExecutionsResponse{ Executions: newTestWorkflowExecutions(1), NextPageToken: []byte{1, 2, 3}, }, nil).MaxTimes(int(time.Duration(activityTimeoutSeconds) * time.Second / scanWorkflowWaitPeriod)) @@ -160,7 +161,7 @@ func (s *workflowShadowerActivitiesSuite) TestScanWorkflowActivity_CompletionTim } func (s *workflowShadowerActivitiesSuite) TestScanWorkflowActivity_InvalidQuery() { - s.mockService.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), callOptions...).Return(nil, &shared.BadRequestError{ + s.mockService.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), callOptions...).Return(nil, &api.BadRequestError{ Message: "invalid query", }).Times(1) @@ -176,7 +177,7 @@ func (s *workflowShadowerActivitiesSuite) TestScanWorkflowActivity_InvalidQuery( func (s *workflowShadowerActivitiesSuite) TestReplayWorkflowExecutionActivity_NoPreviousProgress() { numExecutions := 10 - s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&shared.GetWorkflowExecutionHistoryResponse{ + s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.GetWorkflowExecutionHistoryResponse{ History: s.testWorkflowHistory, }, nil).Times(numExecutions) @@ -204,7 +205,7 @@ func (s *workflowShadowerActivitiesSuite) TestReplayWorkflowExecutionActivity_Wi s.env.SetHeartbeatDetails(progress) numExecutions := 10 - s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&shared.GetWorkflowExecutionHistoryResponse{ + s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.GetWorkflowExecutionHistoryResponse{ History: s.testWorkflowHistory, }, nil).Times(numExecutions - progress.NextExecutionIdx) @@ -231,15 +232,15 @@ func (s *workflowShadowerActivitiesSuite) TestReplayWorkflowExecutionActivity_Ra switch rand.Intn(3) { case 0: numSucceed++ - s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&shared.GetWorkflowExecutionHistoryResponse{ + s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.GetWorkflowExecutionHistoryResponse{ History: s.testWorkflowHistory, }, nil).Times(1) case 1: numSkipped++ - s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(nil, &shared.EntityNotExistsError{}).Times(1) + s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(nil, &api.EntityNotExistsError{}).Times(1) case 2: numFailed++ - s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&shared.GetWorkflowExecutionHistoryResponse{ + s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.GetWorkflowExecutionHistoryResponse{ History: mismatchWorkflowHistory, }, nil).Times(1) } @@ -258,7 +259,7 @@ func (s *workflowShadowerActivitiesSuite) TestReplayWorkflowExecutionActivity_Ra } func (s *workflowShadowerActivitiesSuite) TestReplayWorkflowExecutionActivity_WorkflowNotRegistered() { - s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&shared.GetWorkflowExecutionHistoryResponse{ + s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.GetWorkflowExecutionHistoryResponse{ History: getTestReplayWorkflowLocalActivityHistory(), // this workflow type is not registered }, nil).Times(1) diff --git a/internal/workflow_shadower_test.go b/internal/workflow_shadower_test.go index 0de63bff8..d8329e00c 100644 --- a/internal/workflow_shadower_test.go +++ b/internal/workflow_shadower_test.go @@ -29,9 +29,8 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowservicetest" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" ) type workflowShadowerSuite struct { @@ -39,10 +38,10 @@ type workflowShadowerSuite struct { suite.Suite controller *gomock.Controller - mockService *workflowservicetest.MockClient + mockService *api.MockInterface testShadower *WorkflowShadower - testWorkflowHistory *shared.History + testWorkflowHistory *apiv1.History testTimestamp time.Time } @@ -55,7 +54,7 @@ func (s *workflowShadowerSuite) SetupTest() { s.Assertions = require.New(s.T()) s.controller = gomock.NewController(s.T()) - s.mockService = workflowservicetest.NewMockClient(s.controller) + s.mockService = api.NewMockInterface(s.controller) var err error s.testShadower, err = NewWorkflowShadower(s.mockService, "testDomain", ShadowOptions{}, ReplayOptions{}, nil) @@ -251,13 +250,13 @@ func (s *workflowShadowerSuite) TestShadowWorkerExitCondition_ExpirationTime() { ExpirationInterval: expirationTime, } - s.mockService.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), callOptions...).Return(&shared.ListWorkflowExecutionsResponse{ + s.mockService.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.ScanWorkflowExecutionsResponse{ Executions: newTestWorkflowExecutions(totalWorkflows), NextPageToken: nil, }, nil).Times(1) - s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(...interface{}) (*shared.GetWorkflowExecutionHistoryResponse, error) { + s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn(func(...interface{}) (*apiv1.GetWorkflowExecutionHistoryResponse, error) { s.testShadower.clock.(*clock.Mock).Add(timePerWorkflow) - return &shared.GetWorkflowExecutionHistoryResponse{ + return &apiv1.GetWorkflowExecutionHistoryResponse{ History: s.testWorkflowHistory, }, nil }).Times(int(expirationTime/timePerWorkflow) + 1) @@ -272,11 +271,11 @@ func (s *workflowShadowerSuite) TestShadowWorkerExitCondition_MaxShadowingCount( ShadowCount: maxShadowCount, } - s.mockService.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), callOptions...).Return(&shared.ListWorkflowExecutionsResponse{ + s.mockService.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.ScanWorkflowExecutionsResponse{ Executions: newTestWorkflowExecutions(maxShadowCount * 2), NextPageToken: []byte{1, 2, 3}, }, nil).Times(1) - s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&shared.GetWorkflowExecutionHistoryResponse{ + s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.GetWorkflowExecutionHistoryResponse{ History: s.testWorkflowHistory, }, nil).Times(maxShadowCount) @@ -289,7 +288,7 @@ func (s *workflowShadowerSuite) TestShadowWorker_NormalMode() { totalWorkflows := len(workflowExecutions) * numScan for i := 0; i != numScan; i++ { - scanResp := &shared.ListWorkflowExecutionsResponse{ + scanResp := &apiv1.ScanWorkflowExecutionsResponse{ Executions: workflowExecutions, NextPageToken: []byte{1, 2, 3}, } @@ -299,7 +298,7 @@ func (s *workflowShadowerSuite) TestShadowWorker_NormalMode() { s.mockService.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), callOptions...).Return(scanResp, nil).Times(1) } - s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&shared.GetWorkflowExecutionHistoryResponse{ + s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.GetWorkflowExecutionHistoryResponse{ History: s.testWorkflowHistory, }, nil).Times(totalWorkflows) @@ -317,13 +316,13 @@ func (s *workflowShadowerSuite) TestShadowWorker_ContinuousMode() { } for i := 0; i != numScan; i++ { - scanResp := &shared.ListWorkflowExecutionsResponse{ + scanResp := &apiv1.ScanWorkflowExecutionsResponse{ Executions: workflowExecutions, } s.mockService.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), callOptions...).Return(scanResp, nil).Times(1) } - s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&shared.GetWorkflowExecutionHistoryResponse{ + s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.GetWorkflowExecutionHistoryResponse{ History: s.testWorkflowHistory, }, nil).Times(totalWorkflows) @@ -350,14 +349,14 @@ func (s *workflowShadowerSuite) TestShadowWorker_ContinuousMode() { func (s *workflowShadowerSuite) TestShadowWorker_ReplayFailed() { successfullyReplayed := 5 - s.mockService.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), callOptions...).Return(&shared.ListWorkflowExecutionsResponse{ + s.mockService.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.ScanWorkflowExecutionsResponse{ Executions: newTestWorkflowExecutions(successfullyReplayed * 2), NextPageToken: []byte{1, 2, 3}, }, nil).Times(1) - s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&shared.GetWorkflowExecutionHistoryResponse{ + s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.GetWorkflowExecutionHistoryResponse{ History: s.testWorkflowHistory, }, nil).Times(successfullyReplayed) - s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&shared.GetWorkflowExecutionHistoryResponse{ + s.mockService.EXPECT().GetWorkflowExecutionHistory(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.GetWorkflowExecutionHistoryResponse{ History: getTestReplayWorkflowMismatchHistory(), }, nil).Times(1) @@ -368,18 +367,18 @@ func (s *workflowShadowerSuite) TestShadowWorker_ExpectedReplayError() { testCases := []struct { msg string getHistoryErr error - getHistoryResponse *shared.GetWorkflowExecutionHistoryResponse + getHistoryResponse *apiv1.GetWorkflowExecutionHistoryResponse }{ { msg: "only workflow started event", // for example cron workflow getHistoryErr: nil, - getHistoryResponse: &shared.GetWorkflowExecutionHistoryResponse{ - History: &shared.History{Events: []*shared.HistoryEvent{ - createTestEventWorkflowExecutionStarted(1, &shared.WorkflowExecutionStartedEventAttributes{ - WorkflowType: &shared.WorkflowType{Name: common.StringPtr("testWorkflow")}, - TaskList: &shared.TaskList{Name: common.StringPtr("taskList")}, - Input: testEncodeFunctionArgs(getDefaultDataConverter()), - CronSchedule: common.StringPtr("* * * * *"), + getHistoryResponse: &apiv1.GetWorkflowExecutionHistoryResponse{ + History: &apiv1.History{Events: []*apiv1.HistoryEvent{ + createTestEventWorkflowExecutionStarted(1, &apiv1.WorkflowExecutionStartedEventAttributes{ + WorkflowType: &apiv1.WorkflowType{Name: "testWorkflow"}, + TaskList: &apiv1.TaskList{Name: "taskList"}, + Input: &apiv1.Payload{Data: testEncodeFunctionArgs(getDefaultDataConverter())}, + CronSchedule: "* * * * *", }), }, }, @@ -387,19 +386,19 @@ func (s *workflowShadowerSuite) TestShadowWorker_ExpectedReplayError() { }, { msg: "workflow not exist", - getHistoryErr: &shared.EntityNotExistsError{Message: "Workflow passed retention date"}, + getHistoryErr: &api.EntityNotExistsError{Message: "Workflow passed retention date"}, getHistoryResponse: nil, }, { msg: "corrupted workflow history", // for example cron workflow - getHistoryErr: &shared.InternalServiceError{Message: "History events not continuous"}, + getHistoryErr: &api.InternalServiceError{Message: "History events not continuous"}, getHistoryResponse: nil, }, } for _, test := range testCases { s.T().Run(test.msg, func(t *testing.T) { - s.mockService.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), callOptions...).Return(&shared.ListWorkflowExecutionsResponse{ + s.mockService.EXPECT().ScanWorkflowExecutions(gomock.Any(), gomock.Any(), callOptions...).Return(&apiv1.ScanWorkflowExecutionsResponse{ Executions: newTestWorkflowExecutions(1), NextPageToken: nil, }, nil).Times(1) @@ -410,13 +409,13 @@ func (s *workflowShadowerSuite) TestShadowWorker_ExpectedReplayError() { } } -func newTestWorkflowExecutions(size int) []*shared.WorkflowExecutionInfo { - executions := make([]*shared.WorkflowExecutionInfo, size) +func newTestWorkflowExecutions(size int) []*apiv1.WorkflowExecutionInfo { + executions := make([]*apiv1.WorkflowExecutionInfo, size) for i := 0; i != size; i++ { - executions[i] = &shared.WorkflowExecutionInfo{ - Execution: &shared.WorkflowExecution{ - WorkflowId: common.StringPtr("workflowID"), - RunId: common.StringPtr("runID"), + executions[i] = &apiv1.WorkflowExecutionInfo{ + WorkflowExecution: &apiv1.WorkflowExecution{ + WorkflowId: "workflowID", + RunId: "runID", }, } } diff --git a/internal/workflow_shadower_worker.go b/internal/workflow_shadower_worker.go index 0fa543ff4..0813c2448 100644 --- a/internal/workflow_shadower_worker.go +++ b/internal/workflow_shadower_worker.go @@ -25,11 +25,11 @@ import ( "github.com/opentracing/opentracing-go" "github.com/pborman/uuid" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" - "go.uber.org/cadence/v1/.gen/go/shadower" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" - "go.uber.org/cadence/v1/internal/common/backoff" + "go.uber.org/cadence/v2/.gen/go/shadower" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/internal/common" + "go.uber.org/cadence/v2/internal/common/backoff" "go.uber.org/zap" ) @@ -37,7 +37,7 @@ type ( shadowWorker struct { activityWorker *activityWorker - service workflowserviceclient.Interface + service api.Interface domain string taskList string options ShadowOptions @@ -46,7 +46,7 @@ type ( ) func newShadowWorker( - service workflowserviceclient.Interface, + service api.Interface, domain string, shadowOptions ShadowOptions, params workerExecutionParameters, @@ -150,26 +150,27 @@ func (sw *shadowWorker) startShadowWorkflow() error { return err } - startWorkflowRequest := &shared.StartWorkflowExecutionRequest{ - Domain: common.StringPtr(shadower.LocalDomainName), - WorkflowId: common.StringPtr(sw.domain + shadower.WorkflowIDSuffix), - WorkflowType: workflowTypePtr(*workflowType), - TaskList: &shared.TaskList{ - Name: common.StringPtr(shadower.TaskList), + startWorkflowRequest := &apiv1.StartWorkflowExecutionRequest{ + Domain: shadower.LocalDomainName, + WorkflowId: sw.domain + shadower.WorkflowIDSuffix, + WorkflowType: &apiv1.WorkflowType{Name: workflowType.Name}, + TaskList: &apiv1.TaskList{ + Name: shadower.TaskList, }, - Input: input, - ExecutionStartToCloseTimeoutSeconds: common.Int32Ptr(864000), - TaskStartToCloseTimeoutSeconds: common.Int32Ptr(60), - RequestId: common.StringPtr(uuid.New()), - WorkflowIdReusePolicy: shared.WorkflowIdReusePolicyAllowDuplicate.Ptr(), + Input: &apiv1.Payload{Data: input}, + ExecutionStartToCloseTimeout: api.SecondsToProto(864000), + TaskStartToCloseTimeout: api.SecondsToProto(60), + RequestId: uuid.New(), + WorkflowIdReusePolicy: apiv1.WorkflowIdReusePolicy_WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE, } startWorkflowOp := func() error { tchCtx, cancel, opt := newChannelContext(ctx) defer cancel() _, err := sw.service.StartWorkflowExecution(tchCtx, startWorkflowRequest, opt...) + err = api.ConvertError(err) if err != nil { - if _, ok := err.(*shared.WorkflowExecutionAlreadyStartedError); ok { + if _, ok := err.(*api.WorkflowExecutionAlreadyStartedError); ok { return nil } } diff --git a/internal/workflow_shadower_worker_test.go b/internal/workflow_shadower_worker_test.go index 01eef755c..639ea53f9 100644 --- a/internal/workflow_shadower_worker_test.go +++ b/internal/workflow_shadower_worker_test.go @@ -27,11 +27,9 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowservicetest" - "go.uber.org/cadence/v1/.gen/go/shadower" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal/common" + "go.uber.org/cadence/v2/.gen/go/shadower" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" "go.uber.org/yarpc" ) @@ -40,7 +38,7 @@ type shadowWorkerSuite struct { suite.Suite controller *gomock.Controller - mockService *workflowservicetest.MockClient + mockService *api.MockInterface } func TestShadowWorkerSuite(t *testing.T) { @@ -52,7 +50,7 @@ func (s *shadowWorkerSuite) SetupTest() { s.Assertions = require.New(s.T()) s.controller = gomock.NewController(s.T()) - s.mockService = workflowservicetest.NewMockClient(s.controller) + s.mockService = api.NewMockInterface(s.controller) } func (s *shadowWorkerSuite) TearDownTest() { @@ -79,7 +77,7 @@ func (s *shadowWorkerSuite) TestNewShadowWorker() { // check if background context is updated with necessary components userContext := shadowWorker.activityWorker.executionParameters.UserContext - _, ok = userContext.Value(serviceClientContextKey).(workflowserviceclient.Interface) + _, ok = userContext.Value(serviceClientContextKey).(api.Interface) s.True(ok) _, ok = userContext.Value(workflowReplayerContextKey).(*WorkflowReplayer) s.True(ok) @@ -105,9 +103,9 @@ func (s *shadowWorkerSuite) TestStartShadowWorker_Failed_InvalidShadowOption() { } func (s *shadowWorkerSuite) TestStartShadowWorker_Failed_DomainNotExist() { - s.mockService.EXPECT().DescribeDomain(gomock.Any(), &shared.DescribeDomainRequest{ - Name: common.StringPtr(testDomain), - }, callOptions...).Return(nil, &shared.EntityNotExistsError{}).Times(1) + s.mockService.EXPECT().DescribeDomain(gomock.Any(), &apiv1.DescribeDomainRequest{ + DescribeBy: &apiv1.DescribeDomainRequest_Name{Name: testDomain}, + }, callOptions...).Return(nil, &api.EntityNotExistsError{}).Times(1) shadowWorker := newShadowWorker( s.mockService, @@ -123,9 +121,9 @@ func (s *shadowWorkerSuite) TestStartShadowWorker_Failed_DomainNotExist() { } func (s *shadowWorkerSuite) TestStartShadowWorker_Failed_TaskListNotSpecified() { - s.mockService.EXPECT().DescribeDomain(gomock.Any(), &shared.DescribeDomainRequest{ - Name: common.StringPtr(testDomain), - }, callOptions...).Return(&shared.DescribeDomainResponse{}, nil).Times(1) + s.mockService.EXPECT().DescribeDomain(gomock.Any(), &apiv1.DescribeDomainRequest{ + DescribeBy: &apiv1.DescribeDomainRequest_Name{Name: testDomain}, + }, callOptions...).Return(&apiv1.DescribeDomainResponse{}, nil).Times(1) shadowWorker := newShadowWorker( s.mockService, @@ -139,13 +137,13 @@ func (s *shadowWorkerSuite) TestStartShadowWorker_Failed_TaskListNotSpecified() } func (s *shadowWorkerSuite) TestStartShadowWorker_Failed_StartWorkflowError() { - s.mockService.EXPECT().DescribeDomain(gomock.Any(), &shared.DescribeDomainRequest{ - Name: common.StringPtr(testDomain), - }, callOptions...).Return(&shared.DescribeDomainResponse{}, nil).Times(1) + s.mockService.EXPECT().DescribeDomain(gomock.Any(), &apiv1.DescribeDomainRequest{ + DescribeBy: &apiv1.DescribeDomainRequest_Name{Name: testDomain}, + }, callOptions...).Return(&apiv1.DescribeDomainResponse{}, nil).Times(1) // first return a retryable error to check if retry policy is configured - s.mockService.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), callOptions...).Return(nil, &shared.ServiceBusyError{}).Times(1) + s.mockService.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), callOptions...).Return(nil, &api.ServiceBusyError{}).Times(1) // then return a non-retryable error - s.mockService.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), callOptions...).Return(nil, &shared.BadRequestError{}).Times(1) + s.mockService.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), callOptions...).Return(nil, &api.BadRequestError{}).Times(1) shadowWorker := newShadowWorker( s.mockService, @@ -169,17 +167,17 @@ func (s *shadowWorkerSuite) TestStartShadowWorker_Succeed() { ShadowCount: 100, } - var startRequest *shared.StartWorkflowExecutionRequest - s.mockService.EXPECT().DescribeDomain(gomock.Any(), &shared.DescribeDomainRequest{ - Name: common.StringPtr(testDomain), - }, callOptions...).Return(&shared.DescribeDomainResponse{}, nil).Times(1) - s.mockService.EXPECT().DescribeDomain(gomock.Any(), &shared.DescribeDomainRequest{ - Name: common.StringPtr(shadower.LocalDomainName), - }, callOptions...).Return(&shared.DescribeDomainResponse{}, nil).Times(1) + var startRequest *apiv1.StartWorkflowExecutionRequest + s.mockService.EXPECT().DescribeDomain(gomock.Any(), &apiv1.DescribeDomainRequest{ + DescribeBy: &apiv1.DescribeDomainRequest_Name{Name: testDomain}, + }, callOptions...).Return(&apiv1.DescribeDomainResponse{}, nil).Times(1) + s.mockService.EXPECT().DescribeDomain(gomock.Any(), &apiv1.DescribeDomainRequest{ + DescribeBy: &apiv1.DescribeDomainRequest_Name{Name: shadower.LocalDomainName}, + }, callOptions...).Return(&apiv1.DescribeDomainResponse{}, nil).Times(1) s.mockService.EXPECT().StartWorkflowExecution(gomock.Any(), gomock.Any(), callOptions...).DoAndReturn( - func(_ context.Context, request *shared.StartWorkflowExecutionRequest, _ ...yarpc.CallOption) (*shared.StartWorkflowExecutionResponse, error) { + func(_ context.Context, request *apiv1.StartWorkflowExecutionRequest, _ ...yarpc.CallOption) (*apiv1.StartWorkflowExecutionResponse, error) { startRequest = request - return nil, &shared.WorkflowExecutionAlreadyStartedError{} + return nil, &api.WorkflowExecutionAlreadyStartedError{} }, ).Times(1) @@ -206,11 +204,11 @@ func (s *shadowWorkerSuite) TestStartShadowWorker_Succeed() { s.Equal(testDomain+shadower.WorkflowIDSuffix, startRequest.GetWorkflowId()) s.Equal(shadower.WorkflowName, startRequest.WorkflowType.GetName()) s.Equal(shadower.TaskList, startRequest.TaskList.GetName()) - s.NotZero(startRequest.GetExecutionStartToCloseTimeoutSeconds()) - s.Equal(shared.WorkflowIdReusePolicyAllowDuplicate, startRequest.GetWorkflowIdReusePolicy()) + s.NotZero(startRequest.GetExecutionStartToCloseTimeout()) + s.Equal(apiv1.WorkflowIdReusePolicy_WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE, startRequest.GetWorkflowIdReusePolicy()) var workflowParams shadower.WorkflowParams - getDefaultDataConverter().FromData(startRequest.Input, &workflowParams) + getDefaultDataConverter().FromData(startRequest.Input.GetData(), &workflowParams) s.Equal(testDomain, workflowParams.GetDomain()) s.Equal(generateShadowTaskList(testDomain, testTaskList), workflowParams.GetTaskList()) s.Equal(workflowQuery, workflowParams.GetWorkflowQuery()) diff --git a/internal/workflow_testsuite.go b/internal/workflow_testsuite.go index 57ea28bf5..808882565 100644 --- a/internal/workflow_testsuite.go +++ b/internal/workflow_testsuite.go @@ -29,7 +29,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/uber-go/tally" - "go.uber.org/cadence/v1/.gen/go/shared" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" "go.uber.org/zap" ) @@ -45,7 +45,7 @@ type ( logger *zap.Logger scope tally.Scope ctxProps []ContextPropagator - header *shared.Header + header *apiv1.Header } // TestWorkflowEnvironment is the environment that you use to test workflow @@ -126,7 +126,7 @@ func (s *WorkflowTestSuite) SetContextPropagators(ctxProps []ContextPropagator) // SetHeader sets the headers for this WorkflowTestSuite. If you don't set header, test suite will not pass headers to // the workflow -func (s *WorkflowTestSuite) SetHeader(header *shared.Header) { +func (s *WorkflowTestSuite) SetHeader(header *apiv1.Header) { s.header = header } @@ -247,7 +247,7 @@ func (t *TestWorkflowEnvironment) OnActivity(activity interface{}, args ...inter // ErrMockStartChildWorkflowFailed is special error used to indicate the mocked child workflow should fail to start. // This error is also exposed as public as testsuite.ErrMockStartChildWorkflowFailed -var ErrMockStartChildWorkflowFailed = fmt.Errorf("start child workflow failed: %v", shared.ChildWorkflowExecutionFailedCauseWorkflowAlreadyRunning) +var ErrMockStartChildWorkflowFailed = fmt.Errorf("start child workflow failed: %v", apiv1.ChildWorkflowExecutionFailedCause_CHILD_WORKFLOW_EXECUTION_FAILED_CAUSE_WORKFLOW_ALREADY_RUNNING) // OnWorkflow setup a mock call for workflow. Parameter workflow must be workflow function (func) or workflow name (string). // You must call Return() with appropriate parameters on the returned *MockCallWrapper instance. The supplied parameters to diff --git a/mocks/Client.go b/mocks/Client.go index b59412a7d..18f334091 100644 --- a/mocks/Client.go +++ b/mocks/Client.go @@ -28,12 +28,11 @@ import ( "github.com/stretchr/testify/mock" - "go.uber.org/cadence/v1/.gen/go/shared" - s "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/client" - "go.uber.org/cadence/v1/encoded" - "go.uber.org/cadence/v1/internal" - "go.uber.org/cadence/v1/workflow" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/client" + "go.uber.org/cadence/v2/encoded" + "go.uber.org/cadence/v2/internal" + "go.uber.org/cadence/v2/workflow" ) // Client is an autogenerated mock type for the Client type @@ -84,20 +83,20 @@ func (_m *Client) CompleteActivityByID(ctx context.Context, domain string, workf } // CountWorkflow provides a mock function with given fields: ctx, request -func (_m *Client) CountWorkflow(ctx context.Context, request *shared.CountWorkflowExecutionsRequest) (*shared.CountWorkflowExecutionsResponse, error) { +func (_m *Client) CountWorkflow(ctx context.Context, request *apiv1.CountWorkflowExecutionsRequest) (*apiv1.CountWorkflowExecutionsResponse, error) { ret := _m.Called(ctx, request) - var r0 *shared.CountWorkflowExecutionsResponse - if rf, ok := ret.Get(0).(func(context.Context, *shared.CountWorkflowExecutionsRequest) *shared.CountWorkflowExecutionsResponse); ok { + var r0 *apiv1.CountWorkflowExecutionsResponse + if rf, ok := ret.Get(0).(func(context.Context, *apiv1.CountWorkflowExecutionsRequest) *apiv1.CountWorkflowExecutionsResponse); ok { r0 = rf(ctx, request) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*shared.CountWorkflowExecutionsResponse) + r0 = ret.Get(0).(*apiv1.CountWorkflowExecutionsResponse) } } var r1 error - if rf, ok := ret.Get(1).(func(context.Context, *shared.CountWorkflowExecutionsRequest) error); ok { + if rf, ok := ret.Get(1).(func(context.Context, *apiv1.CountWorkflowExecutionsRequest) error); ok { r1 = rf(ctx, request) } else { r1 = ret.Error(1) @@ -107,20 +106,20 @@ func (_m *Client) CountWorkflow(ctx context.Context, request *shared.CountWorkfl } // DescribeTaskList provides a mock function with given fields: ctx, tasklist, tasklistType -func (_m *Client) DescribeTaskList(ctx context.Context, tasklist string, tasklistType shared.TaskListType) (*shared.DescribeTaskListResponse, error) { +func (_m *Client) DescribeTaskList(ctx context.Context, tasklist string, tasklistType apiv1.TaskListType) (*apiv1.DescribeTaskListResponse, error) { ret := _m.Called(ctx, tasklist, tasklistType) - var r0 *shared.DescribeTaskListResponse - if rf, ok := ret.Get(0).(func(context.Context, string, shared.TaskListType) *shared.DescribeTaskListResponse); ok { + var r0 *apiv1.DescribeTaskListResponse + if rf, ok := ret.Get(0).(func(context.Context, string, apiv1.TaskListType) *apiv1.DescribeTaskListResponse); ok { r0 = rf(ctx, tasklist, tasklistType) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*shared.DescribeTaskListResponse) + r0 = ret.Get(0).(*apiv1.DescribeTaskListResponse) } } var r1 error - if rf, ok := ret.Get(1).(func(context.Context, string, shared.TaskListType) error); ok { + if rf, ok := ret.Get(1).(func(context.Context, string, apiv1.TaskListType) error); ok { r1 = rf(ctx, tasklist, tasklistType) } else { r1 = ret.Error(1) @@ -130,15 +129,15 @@ func (_m *Client) DescribeTaskList(ctx context.Context, tasklist string, tasklis } // DescribeWorkflowExecution provides a mock function with given fields: ctx, workflowID, runID -func (_m *Client) DescribeWorkflowExecution(ctx context.Context, workflowID string, runID string) (*shared.DescribeWorkflowExecutionResponse, error) { +func (_m *Client) DescribeWorkflowExecution(ctx context.Context, workflowID string, runID string) (*apiv1.DescribeWorkflowExecutionResponse, error) { ret := _m.Called(ctx, workflowID, runID) - var r0 *shared.DescribeWorkflowExecutionResponse - if rf, ok := ret.Get(0).(func(context.Context, string, string) *shared.DescribeWorkflowExecutionResponse); ok { + var r0 *apiv1.DescribeWorkflowExecutionResponse + if rf, ok := ret.Get(0).(func(context.Context, string, string) *apiv1.DescribeWorkflowExecutionResponse); ok { r0 = rf(ctx, workflowID, runID) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*shared.DescribeWorkflowExecutionResponse) + r0 = ret.Get(0).(*apiv1.DescribeWorkflowExecutionResponse) } } @@ -179,15 +178,15 @@ func (_m *Client) ExecuteWorkflow(ctx context.Context, options client.StartWorkf } // GetSearchAttributes provides a mock function with given fields: ctx -func (_m *Client) GetSearchAttributes(ctx context.Context) (*shared.GetSearchAttributesResponse, error) { +func (_m *Client) GetSearchAttributes(ctx context.Context) (*apiv1.GetSearchAttributesResponse, error) { ret := _m.Called(ctx) - var r0 *shared.GetSearchAttributesResponse - if rf, ok := ret.Get(0).(func(context.Context) *shared.GetSearchAttributesResponse); ok { + var r0 *apiv1.GetSearchAttributesResponse + if rf, ok := ret.Get(0).(func(context.Context) *apiv1.GetSearchAttributesResponse); ok { r0 = rf(ctx) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*shared.GetSearchAttributesResponse) + r0 = ret.Get(0).(*apiv1.GetSearchAttributesResponse) } } @@ -218,11 +217,11 @@ func (_m *Client) GetWorkflow(ctx context.Context, workflowID string, runID stri } // GetWorkflowHistory provides a mock function with given fields: ctx, workflowID, runID, isLongPoll, filterType -func (_m *Client) GetWorkflowHistory(ctx context.Context, workflowID string, runID string, isLongPoll bool, filterType shared.HistoryEventFilterType) client.HistoryEventIterator { +func (_m *Client) GetWorkflowHistory(ctx context.Context, workflowID string, runID string, isLongPoll bool, filterType apiv1.EventFilterType) client.HistoryEventIterator { ret := _m.Called(ctx, workflowID, runID, isLongPoll, filterType) var r0 internal.HistoryEventIterator - if rf, ok := ret.Get(0).(func(context.Context, string, string, bool, shared.HistoryEventFilterType) internal.HistoryEventIterator); ok { + if rf, ok := ret.Get(0).(func(context.Context, string, string, bool, apiv1.EventFilterType) internal.HistoryEventIterator); ok { r0 = rf(ctx, workflowID, runID, isLongPoll, filterType) } else { if ret.Get(0) != nil { @@ -234,20 +233,20 @@ func (_m *Client) GetWorkflowHistory(ctx context.Context, workflowID string, run } // ListClosedWorkflow provides a mock function with given fields: ctx, request -func (_m *Client) ListClosedWorkflow(ctx context.Context, request *shared.ListClosedWorkflowExecutionsRequest) (*shared.ListClosedWorkflowExecutionsResponse, error) { +func (_m *Client) ListClosedWorkflow(ctx context.Context, request *apiv1.ListClosedWorkflowExecutionsRequest) (*apiv1.ListClosedWorkflowExecutionsResponse, error) { ret := _m.Called(ctx, request) - var r0 *shared.ListClosedWorkflowExecutionsResponse - if rf, ok := ret.Get(0).(func(context.Context, *shared.ListClosedWorkflowExecutionsRequest) *shared.ListClosedWorkflowExecutionsResponse); ok { + var r0 *apiv1.ListClosedWorkflowExecutionsResponse + if rf, ok := ret.Get(0).(func(context.Context, *apiv1.ListClosedWorkflowExecutionsRequest) *apiv1.ListClosedWorkflowExecutionsResponse); ok { r0 = rf(ctx, request) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*shared.ListClosedWorkflowExecutionsResponse) + r0 = ret.Get(0).(*apiv1.ListClosedWorkflowExecutionsResponse) } } var r1 error - if rf, ok := ret.Get(1).(func(context.Context, *shared.ListClosedWorkflowExecutionsRequest) error); ok { + if rf, ok := ret.Get(1).(func(context.Context, *apiv1.ListClosedWorkflowExecutionsRequest) error); ok { r1 = rf(ctx, request) } else { r1 = ret.Error(1) @@ -257,20 +256,20 @@ func (_m *Client) ListClosedWorkflow(ctx context.Context, request *shared.ListCl } // ListOpenWorkflow provides a mock function with given fields: ctx, request -func (_m *Client) ListOpenWorkflow(ctx context.Context, request *shared.ListOpenWorkflowExecutionsRequest) (*shared.ListOpenWorkflowExecutionsResponse, error) { +func (_m *Client) ListOpenWorkflow(ctx context.Context, request *apiv1.ListOpenWorkflowExecutionsRequest) (*apiv1.ListOpenWorkflowExecutionsResponse, error) { ret := _m.Called(ctx, request) - var r0 *shared.ListOpenWorkflowExecutionsResponse - if rf, ok := ret.Get(0).(func(context.Context, *shared.ListOpenWorkflowExecutionsRequest) *shared.ListOpenWorkflowExecutionsResponse); ok { + var r0 *apiv1.ListOpenWorkflowExecutionsResponse + if rf, ok := ret.Get(0).(func(context.Context, *apiv1.ListOpenWorkflowExecutionsRequest) *apiv1.ListOpenWorkflowExecutionsResponse); ok { r0 = rf(ctx, request) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*shared.ListOpenWorkflowExecutionsResponse) + r0 = ret.Get(0).(*apiv1.ListOpenWorkflowExecutionsResponse) } } var r1 error - if rf, ok := ret.Get(1).(func(context.Context, *shared.ListOpenWorkflowExecutionsRequest) error); ok { + if rf, ok := ret.Get(1).(func(context.Context, *apiv1.ListOpenWorkflowExecutionsRequest) error); ok { r1 = rf(ctx, request) } else { r1 = ret.Error(1) @@ -280,20 +279,20 @@ func (_m *Client) ListOpenWorkflow(ctx context.Context, request *shared.ListOpen } // ListWorkflow provides a mock function with given fields: ctx, request -func (_m *Client) ListWorkflow(ctx context.Context, request *shared.ListWorkflowExecutionsRequest) (*shared.ListWorkflowExecutionsResponse, error) { +func (_m *Client) ListWorkflow(ctx context.Context, request *apiv1.ListWorkflowExecutionsRequest) (*apiv1.ListWorkflowExecutionsResponse, error) { ret := _m.Called(ctx, request) - var r0 *shared.ListWorkflowExecutionsResponse - if rf, ok := ret.Get(0).(func(context.Context, *shared.ListWorkflowExecutionsRequest) *shared.ListWorkflowExecutionsResponse); ok { + var r0 *apiv1.ListWorkflowExecutionsResponse + if rf, ok := ret.Get(0).(func(context.Context, *apiv1.ListWorkflowExecutionsRequest) *apiv1.ListWorkflowExecutionsResponse); ok { r0 = rf(ctx, request) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*shared.ListWorkflowExecutionsResponse) + r0 = ret.Get(0).(*apiv1.ListWorkflowExecutionsResponse) } } var r1 error - if rf, ok := ret.Get(1).(func(context.Context, *shared.ListWorkflowExecutionsRequest) error); ok { + if rf, ok := ret.Get(1).(func(context.Context, *apiv1.ListWorkflowExecutionsRequest) error); ok { r1 = rf(ctx, request) } else { r1 = ret.Error(1) @@ -303,20 +302,20 @@ func (_m *Client) ListWorkflow(ctx context.Context, request *shared.ListWorkflow } // ListArchivedWorkflow provides a mock function with given fields: ctx, request -func (_m *Client) ListArchivedWorkflow(ctx context.Context, request *shared.ListArchivedWorkflowExecutionsRequest) (*shared.ListArchivedWorkflowExecutionsResponse, error) { +func (_m *Client) ListArchivedWorkflow(ctx context.Context, request *apiv1.ListArchivedWorkflowExecutionsRequest) (*apiv1.ListArchivedWorkflowExecutionsResponse, error) { ret := _m.Called(ctx, request) - var r0 *shared.ListArchivedWorkflowExecutionsResponse - if rf, ok := ret.Get(0).(func(context.Context, *shared.ListArchivedWorkflowExecutionsRequest) *shared.ListArchivedWorkflowExecutionsResponse); ok { + var r0 *apiv1.ListArchivedWorkflowExecutionsResponse + if rf, ok := ret.Get(0).(func(context.Context, *apiv1.ListArchivedWorkflowExecutionsRequest) *apiv1.ListArchivedWorkflowExecutionsResponse); ok { r0 = rf(ctx, request) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*shared.ListArchivedWorkflowExecutionsResponse) + r0 = ret.Get(0).(*apiv1.ListArchivedWorkflowExecutionsResponse) } } var r1 error - if rf, ok := ret.Get(1).(func(context.Context, *shared.ListArchivedWorkflowExecutionsRequest) error); ok { + if rf, ok := ret.Get(1).(func(context.Context, *apiv1.ListArchivedWorkflowExecutionsRequest) error); ok { r1 = rf(ctx, request) } else { r1 = ret.Error(1) @@ -376,22 +375,22 @@ func (_m *Client) QueryWorkflowWithOptions(ctx context.Context, request *client. return r0, r1 } -func (_m *Client) ResetWorkflow(ctx context.Context, request *s.ResetWorkflowExecutionRequest) (*s.ResetWorkflowExecutionResponse, error){ +func (_m *Client) ResetWorkflow(ctx context.Context, request *apiv1.ResetWorkflowExecutionRequest) (*apiv1.ResetWorkflowExecutionResponse, error){ var _ca []interface{} _ca = append(_ca, ctx, request) ret := _m.Called(_ca...) - var r0 *s.ResetWorkflowExecutionResponse - if rf, ok := ret.Get(0).(func(context.Context, *s.ResetWorkflowExecutionRequest) *s.ResetWorkflowExecutionResponse); ok { + var r0 *apiv1.ResetWorkflowExecutionResponse + if rf, ok := ret.Get(0).(func(context.Context, *apiv1.ResetWorkflowExecutionRequest) *apiv1.ResetWorkflowExecutionResponse); ok { r0 = rf(ctx, request) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*s.ResetWorkflowExecutionResponse) + r0 = ret.Get(0).(*apiv1.ResetWorkflowExecutionResponse) } } var r1 error - if rf, ok := ret.Get(1).(func(context.Context, *s.ResetWorkflowExecutionRequest) error); ok { + if rf, ok := ret.Get(1).(func(context.Context, *apiv1.ResetWorkflowExecutionRequest) error); ok { r1 = rf(ctx, request) } else { r1 = ret.Error(1) @@ -435,20 +434,20 @@ func (_m *Client) RecordActivityHeartbeatByID(ctx context.Context, domain string } // ScanWorkflow provides a mock function with given fields: ctx, request -func (_m *Client) ScanWorkflow(ctx context.Context, request *shared.ListWorkflowExecutionsRequest) (*shared.ListWorkflowExecutionsResponse, error) { +func (_m *Client) ScanWorkflow(ctx context.Context, request *apiv1.ScanWorkflowExecutionsRequest) (*apiv1.ScanWorkflowExecutionsResponse, error) { ret := _m.Called(ctx, request) - var r0 *shared.ListWorkflowExecutionsResponse - if rf, ok := ret.Get(0).(func(context.Context, *shared.ListWorkflowExecutionsRequest) *shared.ListWorkflowExecutionsResponse); ok { + var r0 *apiv1.ScanWorkflowExecutionsResponse + if rf, ok := ret.Get(0).(func(context.Context, *apiv1.ScanWorkflowExecutionsRequest) *apiv1.ScanWorkflowExecutionsResponse); ok { r0 = rf(ctx, request) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*shared.ListWorkflowExecutionsResponse) + r0 = ret.Get(0).(*apiv1.ScanWorkflowExecutionsResponse) } } var r1 error - if rf, ok := ret.Get(1).(func(context.Context, *shared.ListWorkflowExecutionsRequest) error); ok { + if rf, ok := ret.Get(1).(func(context.Context, *apiv1.ScanWorkflowExecutionsRequest) error); ok { r1 = rf(ctx, request) } else { r1 = ret.Error(1) diff --git a/mocks/DomainClient.go b/mocks/DomainClient.go index 0ce3596ac..49efc33f4 100644 --- a/mocks/DomainClient.go +++ b/mocks/DomainClient.go @@ -23,7 +23,7 @@ package mocks import context "context" import mock "github.com/stretchr/testify/mock" -import shared "go.uber.org/cadence/v1/.gen/go/shared" +import apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" // DomainClient is an autogenerated mock type for the DomainClient type type DomainClient struct { @@ -31,15 +31,15 @@ type DomainClient struct { } // Describe provides a mock function with given fields: ctx, name -func (_m *DomainClient) Describe(ctx context.Context, name string) (*shared.DescribeDomainResponse, error) { +func (_m *DomainClient) Describe(ctx context.Context, name string) (*apiv1.DescribeDomainResponse, error) { ret := _m.Called(ctx, name) - var r0 *shared.DescribeDomainResponse - if rf, ok := ret.Get(0).(func(context.Context, string) *shared.DescribeDomainResponse); ok { + var r0 *apiv1.DescribeDomainResponse + if rf, ok := ret.Get(0).(func(context.Context, string) *apiv1.DescribeDomainResponse); ok { r0 = rf(ctx, name) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*shared.DescribeDomainResponse) + r0 = ret.Get(0).(*apiv1.DescribeDomainResponse) } } @@ -54,11 +54,11 @@ func (_m *DomainClient) Describe(ctx context.Context, name string) (*shared.Desc } // Register provides a mock function with given fields: ctx, request -func (_m *DomainClient) Register(ctx context.Context, request *shared.RegisterDomainRequest) error { +func (_m *DomainClient) Register(ctx context.Context, request *apiv1.RegisterDomainRequest) error { ret := _m.Called(ctx, request) var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *shared.RegisterDomainRequest) error); ok { + if rf, ok := ret.Get(0).(func(context.Context, *apiv1.RegisterDomainRequest) error); ok { r0 = rf(ctx, request) } else { r0 = ret.Error(0) @@ -68,11 +68,11 @@ func (_m *DomainClient) Register(ctx context.Context, request *shared.RegisterDo } // Update provides a mock function with given fields: ctx, request -func (_m *DomainClient) Update(ctx context.Context, request *shared.UpdateDomainRequest) error { +func (_m *DomainClient) Update(ctx context.Context, request *apiv1.UpdateDomainRequest) error { ret := _m.Called(ctx) var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *shared.UpdateDomainRequest) error); ok { + if rf, ok := ret.Get(0).(func(context.Context, *apiv1.UpdateDomainRequest) error); ok { r0 = rf(ctx, request) } else { r0 = ret.Error(0) diff --git a/mocks/HistoryEventIterator.go b/mocks/HistoryEventIterator.go index dbb746a23..82faa86b3 100644 --- a/mocks/HistoryEventIterator.go +++ b/mocks/HistoryEventIterator.go @@ -22,7 +22,7 @@ package mocks import mock "github.com/stretchr/testify/mock" -import shared "go.uber.org/cadence/v1/.gen/go/shared" +import apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" // HistoryEventIterator is an autogenerated mock type for the HistoryEventIterator type type HistoryEventIterator struct { @@ -44,15 +44,15 @@ func (_m *HistoryEventIterator) HasNext() bool { } // Next provides a mock function with given fields: -func (_m *HistoryEventIterator) Next() (*shared.HistoryEvent, error) { +func (_m *HistoryEventIterator) Next() (*apiv1.HistoryEvent, error) { ret := _m.Called() - var r0 *shared.HistoryEvent - if rf, ok := ret.Get(0).(func() *shared.HistoryEvent); ok { + var r0 *apiv1.HistoryEvent + if rf, ok := ret.Get(0).(func() *apiv1.HistoryEvent); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*shared.HistoryEvent) + r0 = ret.Get(0).(*apiv1.HistoryEvent) } } diff --git a/mocks/mock_test.go b/mocks/mock_test.go index 8b6b90bf5..1c865e4f6 100644 --- a/mocks/mock_test.go +++ b/mocks/mock_test.go @@ -22,13 +22,13 @@ package mocks import ( "context" - "go.uber.org/cadence/v1/.gen/go/shared" "testing" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" - "go.uber.org/cadence/v1/client" - "go.uber.org/cadence/v1/workflow" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/client" + "go.uber.org/cadence/v2/workflow" ) func Test_MockClient(t *testing.T) { @@ -84,10 +84,10 @@ func Test_MockClient(t *testing.T) { mockHistoryIter := &HistoryEventIterator{} mockHistoryIter.On("HasNext").Return(true).Once() - mockHistoryIter.On("Next").Return(&shared.HistoryEvent{}, nil).Once() + mockHistoryIter.On("Next").Return(&apiv1.HistoryEvent{}, nil).Once() mockClient.On("GetWorkflowHistory", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return(mockHistoryIter).Once() - historyIter := mockClient.GetWorkflowHistory(context.Background(), testWorkflowID, testRunID, true, shared.HistoryEventFilterTypeCloseEvent) + historyIter := mockClient.GetWorkflowHistory(context.Background(), testWorkflowID, testRunID, true, apiv1.EventFilterType_EVENT_FILTER_TYPE_CLOSE_EVENT) mockClient.AssertExpectations(t) require.NotNil(t, historyIter) require.Equal(t, true, historyIter.HasNext()) diff --git a/mocks/verify.go b/mocks/verify.go index 34c9857e3..4864438f5 100644 --- a/mocks/verify.go +++ b/mocks/verify.go @@ -21,7 +21,7 @@ package mocks import ( - "go.uber.org/cadence/v1/client" + "go.uber.org/cadence/v2/client" ) // make sure mocks are in sync with interfaces diff --git a/test/activity_test.go b/test/activity_test.go index d5e95b759..ef0467cf0 100644 --- a/test/activity_test.go +++ b/test/activity_test.go @@ -28,9 +28,9 @@ import ( "sync" "time" - "go.uber.org/cadence/v1" - "go.uber.org/cadence/v1/activity" - "go.uber.org/cadence/v1/worker" + "go.uber.org/cadence/v2" + "go.uber.org/cadence/v2/activity" + "go.uber.org/cadence/v2/worker" ) type Activities struct { diff --git a/test/fixtures/activity.cancel.sm.repro.json b/test/fixtures/activity.cancel.sm.repro.json index 0a977fc42..fa3f8ff47 100755 --- a/test/fixtures/activity.cancel.sm.repro.json +++ b/test/fixtures/activity.cancel.sm.repro.json @@ -6,7 +6,7 @@ "version": -24, "workflowExecutionStartedEventAttributes": { "workflowType": { - "name": "go.uber.org/cadence/v1/test.(*Workflows).ActivityCancelRepro-fm" + "name": "go.uber.org/cadence/v2/test.(*Workflows).ActivityCancelRepro-fm" }, "taskList": { "name": "tl-1" diff --git a/test/integration_test.go b/test/integration_test.go index 71c5c8287..e51b992db 100644 --- a/test/integration_test.go +++ b/test/integration_test.go @@ -33,12 +33,13 @@ import ( "github.com/pborman/uuid" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - "go.uber.org/cadence/v1" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/client" - "go.uber.org/cadence/v1/interceptors" - "go.uber.org/cadence/v1/worker" - "go.uber.org/cadence/v1/workflow" + "go.uber.org/cadence/v2" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/client" + "go.uber.org/cadence/v2/interceptors" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/worker" + "go.uber.org/cadence/v2/workflow" "go.uber.org/goleak" "go.uber.org/zap" ) @@ -123,7 +124,7 @@ func (ts *IntegrationTestSuite) TearDownSuite() { ts.FailNow("leaks timed out but no error, should be impossible") case <-time.After(time.Second): // https://github.com/uber-go/cadence-client/issues/739 - last = goleak.Find(goleak.IgnoreTopFunction("go.uber.org/cadence/v1/internal.(*coroutineState).initialYield")) + last = goleak.Find(goleak.IgnoreTopFunction("go.uber.org/cadence/v2/internal.(*coroutineState).initialYield")) if last == nil { // no leak, done waiting return @@ -166,7 +167,7 @@ func (ts *IntegrationTestSuite) TestBasic() { ts.NoError(err) ts.EqualValues(expected, ts.activities.invoked()) ts.Equal([]string{"ExecuteWorkflow begin", "ExecuteActivity", "ExecuteActivity", "ExecuteWorkflow end"}, - ts.tracer.GetTrace("go.uber.org/cadence/v1/test.(*Workflows).Basic")) + ts.tracer.GetTrace("go.uber.org/cadence/v2/test.(*Workflows).Basic")) } func (ts *IntegrationTestSuite) TestActivityRetryOnError() { @@ -195,7 +196,7 @@ func (ts *IntegrationTestSuite) TestActivityRetryOnStartToCloseTimeout() { "test-activity-retry-on-start2close-timeout", ts.workflows.ActivityRetryOnTimeout, &expected, - shared.TimeoutTypeStartToClose) + apiv1.TimeoutType_TIMEOUT_TYPE_START_TO_CLOSE) ts.NoError(err) ts.EqualValues(expected, ts.activities.invoked()) @@ -261,7 +262,7 @@ func (ts *IntegrationTestSuite) TestStackTraceQuery() { ts.NotNil(value) var trace string ts.Nil(value.Get(&trace)) - ts.True(strings.Contains(trace, "go.uber.org/cadence/v1/test.(*Workflows).Basic")) + ts.True(strings.Contains(trace, "go.uber.org/cadence/v2/test.(*Workflows).Basic")) } func (ts *IntegrationTestSuite) TestConsistentQuery() { @@ -286,7 +287,7 @@ func (ts *IntegrationTestSuite) TestConsistentQuery() { WorkflowID: "test-consistent-query", RunID: run.GetRunID(), QueryType: "consistent_query", - QueryConsistencyLevel: shared.QueryConsistencyLevelStrong.Ptr(), + QueryConsistencyLevel: apiv1.QueryConsistencyLevel_QUERY_CONSISTENCY_LEVEL_STRONG, }) ts.Nil(err) ts.NotNil(value) @@ -380,7 +381,7 @@ func (ts *IntegrationTestSuite) TestChildWFWithMemoAndSearchAttributes() { ts.EqualValues([]string{"getMemoAndSearchAttr"}, ts.activities.invoked()) ts.Equal("memoVal, searchAttrVal", result) ts.Equal([]string{"ExecuteWorkflow begin", "ExecuteChildWorkflow", "ExecuteWorkflow end"}, - ts.tracer.GetTrace("go.uber.org/cadence/v1/test.(*Workflows).ChildWorkflowSuccess")) + ts.tracer.GetTrace("go.uber.org/cadence/v2/test.(*Workflows).ChildWorkflowSuccess")) } func (ts *IntegrationTestSuite) TestChildWFWithParentClosePolicyTerminate() { @@ -389,7 +390,7 @@ func (ts *IntegrationTestSuite) TestChildWFWithParentClosePolicyTerminate() { ts.NoError(err) resp, err := ts.libClient.DescribeWorkflowExecution(context.Background(), childWorkflowID, "") ts.NoError(err) - ts.True(resp.WorkflowExecutionInfo.GetCloseTime() > 0) + ts.NotNil(resp.WorkflowExecutionInfo.CloseTime) } func (ts *IntegrationTestSuite) TestChildWFWithParentClosePolicyAbandon() { @@ -398,7 +399,7 @@ func (ts *IntegrationTestSuite) TestChildWFWithParentClosePolicyAbandon() { ts.NoError(err) resp, err := ts.libClient.DescribeWorkflowExecution(context.Background(), childWorkflowID, "") ts.NoError(err) - ts.True(resp.WorkflowExecutionInfo.GetCloseTime() == 0) + ts.Nil(resp.WorkflowExecutionInfo.CloseTime) } func (ts *IntegrationTestSuite) TestActivityCancelUsingReplay() { @@ -433,7 +434,7 @@ func (ts *IntegrationTestSuite) TestLargeQueryResultError() { value, err := ts.libClient.QueryWorkflow(ctx, "test-large-query-error", run.GetRunID(), "large_query") ts.Error(err) - queryErr, ok := err.(*shared.QueryFailedError) + queryErr, ok := err.(*api.QueryFailedError) ts.True(ok) ts.Equal("query result size (3000000) exceeds limit (2000000)", queryErr.Message) ts.Nil(value) @@ -455,12 +456,12 @@ func (ts *IntegrationTestSuite) registerDomain() { defer cancel() name := domainName retention := int32(1) - err := client.Register(ctx, &shared.RegisterDomainRequest{ - Name: &name, - WorkflowExecutionRetentionPeriodInDays: &retention, + err := client.Register(ctx, &apiv1.RegisterDomainRequest{ + Name: name, + WorkflowExecutionRetentionPeriod: api.DurationToProto(time.Duration(retention) * 24 * time.Hour), }) if err != nil { - if _, ok := err.(*shared.DomainAlreadyExistsError); ok { + if _, ok := err.(*api.DomainAlreadyExistsError); ok { return } } @@ -471,7 +472,7 @@ func (ts *IntegrationTestSuite) registerDomain() { err = ts.executeWorkflow("test-domain-exist", ts.workflows.SimplestWorkflow, &dummyReturn) numOfRetry := 20 for err != nil && numOfRetry >= 0 { - if _, ok := err.(*shared.EntityNotExistsError); ok { + if _, ok := err.(*api.EntityNotExistsError); ok { time.Sleep(domainCacheRefreshInterval) err = ts.executeWorkflow("test-domain-exist", ts.workflows.SimplestWorkflow, &dummyReturn) } else { @@ -498,7 +499,7 @@ func (ts *IntegrationTestSuite) executeWorkflowWithOption( } err = run.Get(ctx, retValPtr) if ts.config.Debug { - iter := ts.libClient.GetWorkflowHistory(ctx, options.ID, run.GetRunID(), false, shared.HistoryEventFilterTypeAllEvent) + iter := ts.libClient.GetWorkflowHistory(ctx, options.ID, run.GetRunID(), false, apiv1.EventFilterType_EVENT_FILTER_TYPE_ALL_EVENT) for iter.HasNext() { event, err1 := iter.Next() if err1 != nil { diff --git a/test/replaytests/basic.json b/test/replaytests/basic.json index 1a059a9a8..931a71174 100644 --- a/test/replaytests/basic.json +++ b/test/replaytests/basic.json @@ -7,7 +7,7 @@ "taskId":22037765, "workflowExecutionStartedEventAttributes":{ "workflowType":{ - "name":"go.uber.org/cadence/v1/test/replaytests.Workflow" + "name":"go.uber.org/cadence/v2/test/replaytests.Workflow" }, "taskList":{ "name":"helloWorldGroup" diff --git a/test/replaytests/basic_new.json b/test/replaytests/basic_new.json index ef2055fe7..3a502ab70 100644 --- a/test/replaytests/basic_new.json +++ b/test/replaytests/basic_new.json @@ -7,7 +7,7 @@ "taskId":22020168, "workflowExecutionStartedEventAttributes":{ "workflowType":{ - "name":"go.uber.org/cadence/v1/test/replaytests.Workflow" + "name":"go.uber.org/cadence/v2/test/replaytests.Workflow" }, "taskList":{ "name":"helloWorldGroup" diff --git a/test/replaytests/reply_test.go b/test/replaytests/reply_test.go index 88d627729..0fa721f28 100644 --- a/test/replaytests/reply_test.go +++ b/test/replaytests/reply_test.go @@ -25,7 +25,7 @@ import ( "testing" "github.com/stretchr/testify/require" - "go.uber.org/cadence/v1/worker" + "go.uber.org/cadence/v2/worker" "go.uber.org/zap/zaptest" ) diff --git a/test/replaytests/version.json b/test/replaytests/version.json index 000e17473..fb9b40616 100644 --- a/test/replaytests/version.json +++ b/test/replaytests/version.json @@ -7,7 +7,7 @@ "taskId":22020314, "workflowExecutionStartedEventAttributes":{ "workflowType":{ - "name":"go.uber.org/cadence/v1/test/replaytests.Workflow2" + "name":"go.uber.org/cadence/v2/test/replaytests.Workflow2" }, "taskList":{ "name":"helloWorldGroup" diff --git a/test/replaytests/version_new.json b/test/replaytests/version_new.json index 6f3b0c06a..a2944d29a 100644 --- a/test/replaytests/version_new.json +++ b/test/replaytests/version_new.json @@ -7,7 +7,7 @@ "taskId":23069221, "workflowExecutionStartedEventAttributes":{ "workflowType":{ - "name":"go.uber.org/cadence/v1/test/replaytests.Workflow2" + "name":"go.uber.org/cadence/v2/test/replaytests.Workflow2" }, "taskList":{ "name":"helloWorldGroup" diff --git a/test/replaytests/workflows.go b/test/replaytests/workflows.go index d5c3cb97e..4a5c7a70c 100644 --- a/test/replaytests/workflows.go +++ b/test/replaytests/workflows.go @@ -24,8 +24,8 @@ import ( "context" "time" - "go.uber.org/cadence/v1/activity" - "go.uber.org/cadence/v1/workflow" + "go.uber.org/cadence/v2/activity" + "go.uber.org/cadence/v2/workflow" "go.uber.org/zap" ) diff --git a/test/test_utils.go b/test/test_utils.go index 723a2dbe5..5b6a61291 100644 --- a/test/test_utils.go +++ b/test/test_utils.go @@ -27,11 +27,11 @@ import ( "os" "strings" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/workflow" "go.uber.org/yarpc" - "go.uber.org/yarpc/transport/tchannel" - - "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" - "go.uber.org/cadence/v1/workflow" + "go.uber.org/yarpc/transport/grpc" ) type ( @@ -50,7 +50,7 @@ type ( func newConfig() Config { cfg := Config{ ServiceName: "cadence-frontend", - ServiceAddr: "127.0.0.1:7933", + ServiceAddr: "127.0.0.1:7833", IsStickyOff: true, } if name := getEnvServiceName(); name != "" { @@ -84,8 +84,15 @@ func getDebug() string { return strings.ToLower(strings.TrimSpace(os.Getenv("DEBUG"))) } +type cadenceAPI struct { + apiv1.DomainAPIYARPCClient + apiv1.WorkflowAPIYARPCClient + apiv1.VisibilityAPIYARPCClient + apiv1.WorkerAPIYARPCClient +} + type rpcClient struct { - workflowserviceclient.Interface + api.Interface dispatcher *yarpc.Dispatcher } @@ -97,10 +104,7 @@ func (c *rpcClient) Close() { // make calls to the localhost cadence-server container func newRPCClient( serviceName string, serviceAddr string) (*rpcClient, error) { - transport, err := tchannel.NewTransport(tchannel.ServiceName("integration-test")) - if err != nil { - return nil, err - } + transport := grpc.NewTransport() outbound := transport.NewSingleOutbound(serviceAddr) dispatcher := yarpc.NewDispatcher(yarpc.Config{ Name: "integration-test", @@ -113,8 +117,14 @@ func newRPCClient( if err := dispatcher.Start(); err != nil { return nil, err } - client := workflowserviceclient.New(dispatcher.ClientConfig(serviceName)) - return &rpcClient{Interface: client, dispatcher: dispatcher}, nil + clientConfig := dispatcher.ClientConfig(serviceName) + service := cadenceAPI{ + DomainAPIYARPCClient: apiv1.NewDomainAPIYARPCClient(clientConfig), + VisibilityAPIYARPCClient: apiv1.NewVisibilityAPIYARPCClient(clientConfig), + WorkflowAPIYARPCClient: apiv1.NewWorkflowAPIYARPCClient(clientConfig), + WorkerAPIYARPCClient: apiv1.NewWorkerAPIYARPCClient(clientConfig), + } + return &rpcClient{Interface: service, dispatcher: dispatcher}, nil } // stringMapPropagator propagates the list of keys across a workflow, diff --git a/test/workflow_test.go b/test/workflow_test.go index a4d1dd721..fb4710ef3 100644 --- a/test/workflow_test.go +++ b/test/workflow_test.go @@ -27,12 +27,12 @@ import ( "math/rand" "time" - "go.uber.org/cadence/v1" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/client" - "go.uber.org/cadence/v1/internal" - "go.uber.org/cadence/v1/worker" - "go.uber.org/cadence/v1/workflow" + "go.uber.org/cadence/v2" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/client" + "go.uber.org/cadence/v2/internal" + "go.uber.org/cadence/v2/worker" + "go.uber.org/cadence/v2/workflow" ) const ( @@ -97,12 +97,12 @@ func (w *Workflows) ActivityRetryOptionsChange(ctx workflow.Context) ([]string, return []string{"fail", "fail"}, nil } -func (w *Workflows) ActivityRetryOnTimeout(ctx workflow.Context, timeoutType shared.TimeoutType) ([]string, error) { +func (w *Workflows) ActivityRetryOnTimeout(ctx workflow.Context, timeoutType apiv1.TimeoutType) ([]string, error) { opts := w.defaultActivityOptionsWithRetry() switch timeoutType { - case shared.TimeoutTypeScheduleToClose: + case apiv1.TimeoutType_TIMEOUT_TYPE_SCHEDULE_TO_CLOSE: opts.ScheduleToCloseTimeout = time.Second - case shared.TimeoutTypeStartToClose: + case apiv1.TimeoutType_TIMEOUT_TYPE_START_TO_CLOSE: opts.StartToCloseTimeout = time.Second } @@ -153,7 +153,7 @@ func (w *Workflows) ActivityRetryOnHBTimeout(ctx workflow.Context) ([]string, er return nil, fmt.Errorf("activity failed with unexpected error: %v", err) } - if terr.TimeoutType() != shared.TimeoutTypeHeartbeat { + if terr.TimeoutType() != apiv1.TimeoutType_TIMEOUT_TYPE_HEARTBEAT { return nil, fmt.Errorf("activity failed due to unexpected timeout %v", terr.TimeoutType()) } @@ -216,11 +216,11 @@ func (w *Workflows) ContinueAsNewWithOptions(ctx workflow.Context, count int, ta return "", errors.New("memo or search attributes are not carried over") } var memoVal, searchAttrVal string - err := client.NewValue(info.Memo.Fields["memoKey"]).Get(&memoVal) + err := client.NewValue(info.Memo.Fields["memoKey"].GetData()).Get(&memoVal) if err != nil { return "", errors.New("error when get memo value") } - err = client.NewValue(info.SearchAttributes.IndexedFields["CustomKeywordField"]).Get(&searchAttrVal) + err = client.NewValue(info.SearchAttributes.IndexedFields["CustomKeywordField"].GetData()).Get(&searchAttrVal) if err != nil { return "", errors.New("error when get search attributes value") } @@ -501,11 +501,11 @@ func (w *Workflows) child(ctx workflow.Context, arg string, mustFail bool) (stri func (w *Workflows) childForMemoAndSearchAttr(ctx workflow.Context) (result string, err error) { info := workflow.GetInfo(ctx) var memo, searchAttr string - err = client.NewValue(info.Memo.Fields["memoKey"]).Get(&memo) + err = client.NewValue(info.Memo.Fields["memoKey"].GetData()).Get(&memo) if err != nil { return } - err = client.NewValue(info.SearchAttributes.IndexedFields["CustomKeywordField"]).Get(&searchAttr) + err = client.NewValue(info.SearchAttributes.IndexedFields["CustomKeywordField"].GetData()).Get(&searchAttr) if err != nil { return } diff --git a/testsuite/testsuite.go b/testsuite/testsuite.go index 7a5b73e72..b97247889 100644 --- a/testsuite/testsuite.go +++ b/testsuite/testsuite.go @@ -22,7 +22,7 @@ package testsuite import ( - "go.uber.org/cadence/v1/internal" + "go.uber.org/cadence/v2/internal" ) type ( diff --git a/version.go b/version.go index e03d92298..8fb0428b6 100644 --- a/version.go +++ b/version.go @@ -20,7 +20,7 @@ package cadence -import "go.uber.org/cadence/v1/internal" +import "go.uber.org/cadence/v2/internal" // LibraryVersion is a semver string that represents // the version of this cadence client library diff --git a/worker/worker.go b/worker/worker.go index 29feffdf7..33c4d8108 100644 --- a/worker/worker.go +++ b/worker/worker.go @@ -25,11 +25,12 @@ package worker import ( "context" - "go.uber.org/cadence/v1/.gen/go/cadence/workflowserviceclient" - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/activity" - "go.uber.org/cadence/v1/internal" - "go.uber.org/cadence/v1/workflow" + "go.uber.org/cadence/v2" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/activity" + "go.uber.org/cadence/v2/internal" + "go.uber.org/cadence/v2/internal/api" + "go.uber.org/cadence/v2/workflow" "go.uber.org/zap" ) @@ -143,7 +144,7 @@ type ( // ReplayWorkflowHistory executes a single decision task for the given json history file. // Use for testing the backwards compatibility of code changes and troubleshooting workflows in a debugger. // The logger is an optional parameter. Defaults to the noop logger. - ReplayWorkflowHistory(logger *zap.Logger, history *shared.History) error + ReplayWorkflowHistory(logger *zap.Logger, history *apiv1.History) error // ReplayWorkflowHistoryFromJSONFile executes a single decision task for the json history file downloaded from the cli. // To download the history file: cadence workflow showid -of @@ -163,7 +164,7 @@ type ( // ReplayWorkflowExecution loads a workflow execution history from the Cadence service and executes a single decision task for it. // Use for testing the backwards compatibility of code changes and troubleshooting workflows in a debugger. // The logger is the only optional parameter. Defaults to the noop logger. - ReplayWorkflowExecution(ctx context.Context, service workflowserviceclient.Interface, logger *zap.Logger, domain string, execution workflow.Execution) error + ReplayWorkflowExecution(ctx context.Context, service api.Interface, logger *zap.Logger, domain string, execution workflow.Execution) error } // WorkflowShadower retrieves and replays workflow history from Cadence service to determine if there's any nondeterministic changes in the workflow definition @@ -223,14 +224,14 @@ const ( ) // New creates an instance of worker for managing workflow and activity executions. -// service - thrift connection to the cadence server +// service - API interface to the cadence server // domain - the name of the cadence domain // taskList - is the task list name you use to identify your client worker, also // identifies group of workflow and activity implementations that are // hosted by a single worker process // options - configure any worker specific options like logger, metrics, identity func New( - service workflowserviceclient.Interface, + service cadence.Interface, domain string, taskList string, options Options, @@ -253,7 +254,7 @@ func NewWorkflowReplayerWithOptions( // NewWorkflowShadower creates a WorkflowShadower instance. func NewWorkflowShadower( - service workflowserviceclient.Interface, + service api.Interface, domain string, shadowOptions ShadowOptions, replayOptions ReplayOptions, @@ -272,7 +273,7 @@ func EnableVerboseLogging(enable bool) { // ReplayWorkflowHistory executes a single decision task for the given json history file. // Use for testing the backwards compatibility of code changes and troubleshooting workflows in a debugger. // The logger is an optional parameter. Defaults to the noop logger. -func ReplayWorkflowHistory(logger *zap.Logger, history *shared.History) error { +func ReplayWorkflowHistory(logger *zap.Logger, history *apiv1.History) error { return internal.ReplayWorkflowHistory(logger, history) } @@ -298,7 +299,7 @@ func ReplayPartialWorkflowHistoryFromJSONFile(logger *zap.Logger, jsonfileName s // ReplayWorkflowExecution loads a workflow execution history from the Cadence service and executes a single decision task for it. // Use for testing the backwards compatibility of code changes and troubleshooting workflows in a debugger. // The logger is the only optional parameter. Defaults to the noop logger. -func ReplayWorkflowExecution(ctx context.Context, service workflowserviceclient.Interface, logger *zap.Logger, domain string, execution workflow.Execution) error { +func ReplayWorkflowExecution(ctx context.Context, service api.Interface, logger *zap.Logger, domain string, execution workflow.Execution) error { return internal.ReplayWorkflowExecution(ctx, service, logger, domain, execution) } diff --git a/workflow/activity_options.go b/workflow/activity_options.go index 99124dd96..e15b75695 100644 --- a/workflow/activity_options.go +++ b/workflow/activity_options.go @@ -23,7 +23,7 @@ package workflow import ( "time" - "go.uber.org/cadence/v1/internal" + "go.uber.org/cadence/v2/internal" ) // ActivityOptions stores all activity-specific invocation parameters that will be stored inside of a context. diff --git a/workflow/context.go b/workflow/context.go index 01f2acbd1..b82321c0f 100644 --- a/workflow/context.go +++ b/workflow/context.go @@ -21,7 +21,7 @@ package workflow import ( - "go.uber.org/cadence/v1/internal" + "go.uber.org/cadence/v2/internal" ) // Context is a clone of context.Context with Done() returning Channel instead diff --git a/workflow/context_propagator.go b/workflow/context_propagator.go index 970c44032..c5632378d 100644 --- a/workflow/context_propagator.go +++ b/workflow/context_propagator.go @@ -20,7 +20,7 @@ package workflow -import "go.uber.org/cadence/v1/internal" +import "go.uber.org/cadence/v2/internal" type ( // HeaderReader is an interface to read information from cadence headers diff --git a/workflow/deterministic_wrappers.go b/workflow/deterministic_wrappers.go index 566ae45ee..5d0fd5aa8 100644 --- a/workflow/deterministic_wrappers.go +++ b/workflow/deterministic_wrappers.go @@ -24,7 +24,7 @@ package workflow import ( "time" - "go.uber.org/cadence/v1/internal" + "go.uber.org/cadence/v2/internal" ) type ( diff --git a/workflow/doc.go b/workflow/doc.go index 2d2ebc043..f0eb86263 100644 --- a/workflow/doc.go +++ b/workflow/doc.go @@ -42,7 +42,7 @@ the sole parameter it receives as part of its initialization as a parameter to t import ( "time" - "go.uber.org/cadence/v1/workflow" + "go.uber.org/cadence/v2/workflow" ) func init() { @@ -487,7 +487,7 @@ The code below implements the unit tests for the SimpleWorkflow sample. "github.com/stretchr/testify/mock" "github.com/stretchr/testify/suite" - "go.uber.org/cadence/v1/testsuite" + "go.uber.org/cadence/v2/testsuite" ) type UnitTestSuite struct { diff --git a/workflow/error.go b/workflow/error.go index 5b420acd1..8a96548ee 100644 --- a/workflow/error.go +++ b/workflow/error.go @@ -21,8 +21,8 @@ package workflow import ( - "go.uber.org/cadence/v1/.gen/go/shared" - "go.uber.org/cadence/v1/internal" + apiv1 "go.uber.org/cadence/v2/.gen/proto/api/v1" + "go.uber.org/cadence/v2/internal" ) /* @@ -125,7 +125,7 @@ func NewContinueAsNewError(ctx Context, wfn interface{}, args ...interface{}) *C // Use NewHeartbeatTimeoutError to create heartbeat TimeoutError // WARNING: This function is public only to support unit testing of workflows. // It shouldn't be used by application level code. -func NewTimeoutError(timeoutType shared.TimeoutType, details ...interface{}) *TimeoutError { +func NewTimeoutError(timeoutType apiv1.TimeoutType, details ...interface{}) *TimeoutError { return internal.NewTimeoutError(timeoutType, details...) } diff --git a/workflow/session.go b/workflow/session.go index a0ec5df66..cd9c438a9 100644 --- a/workflow/session.go +++ b/workflow/session.go @@ -21,7 +21,7 @@ package workflow import ( - "go.uber.org/cadence/v1/internal" + "go.uber.org/cadence/v2/internal" ) type ( diff --git a/workflow/workflow.go b/workflow/workflow.go index e082f88b7..510b82de8 100644 --- a/workflow/workflow.go +++ b/workflow/workflow.go @@ -22,8 +22,8 @@ package workflow import ( "github.com/uber-go/tally" - "go.uber.org/cadence/v1/encoded" - "go.uber.org/cadence/v1/internal" + "go.uber.org/cadence/v2/encoded" + "go.uber.org/cadence/v2/internal" "go.uber.org/zap" ) diff --git a/workflow/workflow_options.go b/workflow/workflow_options.go index da0d0edaf..d66a1ddac 100644 --- a/workflow/workflow_options.go +++ b/workflow/workflow_options.go @@ -23,8 +23,8 @@ package workflow import ( "time" - "go.uber.org/cadence/v1/encoded" - "go.uber.org/cadence/v1/internal" + "go.uber.org/cadence/v2/encoded" + "go.uber.org/cadence/v2/internal" ) // WithChildOptions adds all workflow options to the context.