-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathworkflow_handler.go
More file actions
7319 lines (6328 loc) · 253 KB
/
Copy pathworkflow_handler.go
File metadata and controls
7319 lines (6328 loc) · 253 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package frontend
import (
"cmp"
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/google/uuid"
"github.com/temporalio/sqlparser"
batchpb "go.temporal.io/api/batch/v1"
commonpb "go.temporal.io/api/common/v1"
deploymentpb "go.temporal.io/api/deployment/v1"
enumspb "go.temporal.io/api/enums/v1"
filterpb "go.temporal.io/api/filter/v1"
historypb "go.temporal.io/api/history/v1"
querypb "go.temporal.io/api/query/v1"
schedulepb "go.temporal.io/api/schedule/v1"
"go.temporal.io/api/serviceerror"
taskqueuepb "go.temporal.io/api/taskqueue/v1"
updatepb "go.temporal.io/api/update/v1"
workerpb "go.temporal.io/api/worker/v1"
workflowpb "go.temporal.io/api/workflow/v1"
"go.temporal.io/api/workflowservice/v1"
batchspb "go.temporal.io/server/api/batch/v1"
deploymentspb "go.temporal.io/server/api/deployment/v1"
"go.temporal.io/server/api/historyservice/v1"
"go.temporal.io/server/api/matchingservice/v1"
schedulespb "go.temporal.io/server/api/schedule/v1"
taskqueuespb "go.temporal.io/server/api/taskqueue/v1"
"go.temporal.io/server/chasm"
"go.temporal.io/server/chasm/lib/activity"
"go.temporal.io/server/chasm/lib/callback"
chasmnexus "go.temporal.io/server/chasm/lib/nexusoperation"
chasmscheduler "go.temporal.io/server/chasm/lib/scheduler"
schedulerpb "go.temporal.io/server/chasm/lib/scheduler/gen/schedulerpb/v1"
"go.temporal.io/server/chasm/lib/workflow"
"go.temporal.io/server/client/frontend"
matchingclient "go.temporal.io/server/client/matching"
"go.temporal.io/server/common"
"go.temporal.io/server/common/archiver"
"go.temporal.io/server/common/archiver/provider"
"go.temporal.io/server/common/backoff"
"go.temporal.io/server/common/clock"
"go.temporal.io/server/common/cluster"
"go.temporal.io/server/common/collection"
"go.temporal.io/server/common/contextutil"
"go.temporal.io/server/common/dynamicconfig"
"go.temporal.io/server/common/enums"
"go.temporal.io/server/common/failure"
"go.temporal.io/server/common/headers"
commonlinks "go.temporal.io/server/common/links"
"go.temporal.io/server/common/log"
"go.temporal.io/server/common/log/tag"
"go.temporal.io/server/common/membership"
"go.temporal.io/server/common/metrics"
"go.temporal.io/server/common/namespace"
"go.temporal.io/server/common/namespace/nsreplication"
"go.temporal.io/server/common/payload"
"go.temporal.io/server/common/payloads"
"go.temporal.io/server/common/persistence"
"go.temporal.io/server/common/persistence/serialization"
"go.temporal.io/server/common/persistence/visibility/manager"
"go.temporal.io/server/common/primitives"
"go.temporal.io/server/common/primitives/timestamp"
"go.temporal.io/server/common/priorities"
"go.temporal.io/server/common/quotas"
"go.temporal.io/server/common/retrypolicy"
"go.temporal.io/server/common/rpc"
"go.temporal.io/server/common/rpc/interceptor"
"go.temporal.io/server/common/sdk"
"go.temporal.io/server/common/searchattribute"
"go.temporal.io/server/common/searchattribute/sadefs"
"go.temporal.io/server/common/tasktoken"
"go.temporal.io/server/common/tqid"
"go.temporal.io/server/common/util"
"go.temporal.io/server/common/worker_versioning"
"go.temporal.io/server/service/history/api"
"go.temporal.io/server/service/worker/batcher"
"go.temporal.io/server/service/worker/dummy"
"go.temporal.io/server/service/worker/scheduler"
"go.temporal.io/server/service/worker/workerdeployment"
"google.golang.org/grpc/health"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/protobuf/encoding/protowire"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/fieldmaskpb"
"google.golang.org/protobuf/types/known/timestamppb"
)
var _ Handler = (*WorkflowHandler)(nil)
var (
minTime = time.Unix(0, 0).UTC()
maxTime = time.Date(2100, 1, 1, 1, 0, 0, 0, time.UTC)
// Tail room for context deadline to bail out from retry for long poll.
longPollTailRoom = time.Second
errWaitForRefresh = serviceerror.NewDeadlineExceeded("waiting for schedule to refresh status of completed workflows")
)
const (
maxReasonLength = 1000 // Maximum length for the reason field in RateLimitUpdate configurations.
defaultUserTerminateReason = "terminated by user via frontend"
defaultUserTerminateIdentity = "frontend-service"
)
type (
// ActivityHandler is the activity frontend handler, aliased to avoid embedding name collision.
ActivityHandler = activity.FrontendHandler
// NexusOperationHandler is the nexus operation frontend handler, aliased to avoid embedding name collision.
NexusOperationHandler = chasmnexus.FrontendHandler
// WorkflowHandler - gRPC handler interface for workflowservice
WorkflowHandler struct {
workflowservice.UnsafeWorkflowServiceServer
ActivityHandler
NexusOperationHandler
validator *workflow.RequestValidator
status int32
callbackValidator callback.Validator
tokenSerializer *tasktoken.Serializer
config *Config
versionChecker headers.VersionChecker
namespaceHandler *namespaceHandler
getDefaultWorkflowRetrySettings dynamicconfig.TypedPropertyFnWithNamespaceFilter[retrypolicy.DefaultRetrySettings]
visibilityMgr manager.VisibilityManager
logger log.Logger
throttledLogger log.Logger
persistenceExecutionName string
clusterMetadataManager persistence.ClusterMetadataManager
clusterMetadata cluster.Metadata
historyClient historyservice.HistoryServiceClient
matchingClient matchingservice.MatchingServiceClient
workerDeploymentClient workerdeployment.Client
schedulerClient schedulerpb.SchedulerServiceClient
archiverProvider provider.ArchiverProvider
payloadSerializer serialization.Serializer
namespaceRegistry namespace.Registry
saMapperProvider searchattribute.MapperProvider
saProvider searchattribute.Provider
saValidator *searchattribute.Validator
archivalMetadata archiver.ArchivalMetadata
healthServer *health.Server
overrides *Overrides
membershipMonitor membership.Monitor
healthInterceptor *interceptor.HealthInterceptor
scheduleSpecBuilder *scheduler.SpecBuilder
outstandingPollers collection.SyncMap[string, collection.SyncMap[string, context.CancelFunc]]
httpEnabled bool
registry *chasm.Registry
workerDeploymentReadRateLimiter quotas.RequestRateLimiter
}
)
func (wh *WorkflowHandler) CreateWorkerDeploymentVersion(
ctx context.Context,
request *workflowservice.CreateWorkerDeploymentVersionRequest,
) (_ *workflowservice.CreateWorkerDeploymentVersionResponse, retError error) {
defer log.CapturePanic(wh.logger, &retError)
if request == nil {
return nil, errRequestNotSet
}
if len(request.Namespace) == 0 {
return nil, errNamespaceNotSet
}
if request.GetDeploymentVersion().GetDeploymentName() == "" {
return nil, serviceerror.NewInvalidArgument("deployment name cannot be empty")
}
if request.GetDeploymentVersion().GetBuildId() == "" {
return nil, serviceerror.NewInvalidArgument("build ID cannot be empty")
}
if !wh.config.EnableDeploymentVersions(request.Namespace) {
return nil, errDeploymentVersionsNotAllowed
}
namespaceEntry, err := wh.namespaceRegistry.GetNamespace(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
requestID := request.RequestId
if requestID == "" {
requestID = uuid.NewString()
}
err = wh.workerDeploymentClient.CreateWorkerDeploymentVersion(
ctx,
namespaceEntry,
request.GetDeploymentVersion().GetDeploymentName(),
request.GetDeploymentVersion().GetBuildId(),
request.Identity,
requestID,
request.GetComputeConfig(),
)
if err != nil {
return nil, err
}
return &workflowservice.CreateWorkerDeploymentVersionResponse{}, nil
}
func (wh *WorkflowHandler) UpdateWorkerDeploymentVersionComputeConfig(
ctx context.Context,
request *workflowservice.UpdateWorkerDeploymentVersionComputeConfigRequest,
) (_ *workflowservice.UpdateWorkerDeploymentVersionComputeConfigResponse, retError error) {
defer log.CapturePanic(wh.logger, &retError)
if request == nil {
return nil, errRequestNotSet
}
if len(request.Namespace) == 0 {
return nil, errNamespaceNotSet
}
if request.GetDeploymentVersion().GetDeploymentName() == "" {
return nil, serviceerror.NewInvalidArgument("deployment name cannot be empty")
}
if request.GetDeploymentVersion().GetBuildId() == "" {
return nil, serviceerror.NewInvalidArgument("build ID cannot be empty")
}
if !wh.config.EnableDeploymentVersions(request.Namespace) {
return nil, errDeploymentVersionsNotAllowed
}
namespaceEntry, err := wh.namespaceRegistry.GetNamespace(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
requestID := request.RequestId
if requestID == "" {
requestID = uuid.NewString()
}
err = wh.workerDeploymentClient.UpdateVersionComputeConfig(
ctx,
namespaceEntry,
request.GetDeploymentVersion(),
request.GetComputeConfigScalingGroups(),
request.GetRemoveComputeConfigScalingGroups(),
request.Identity,
requestID,
)
if err != nil {
return nil, err
}
return &workflowservice.UpdateWorkerDeploymentVersionComputeConfigResponse{}, nil
}
func (wh *WorkflowHandler) ValidateWorkerDeploymentVersionComputeConfig(
ctx context.Context,
request *workflowservice.ValidateWorkerDeploymentVersionComputeConfigRequest,
) (_ *workflowservice.ValidateWorkerDeploymentVersionComputeConfigResponse, retError error) {
defer log.CapturePanic(wh.logger, &retError)
if request == nil {
return nil, errRequestNotSet
}
if len(request.Namespace) == 0 {
return nil, errNamespaceNotSet
}
if !wh.config.EnableDeploymentVersions(request.Namespace) {
return nil, errDeploymentVersionsNotAllowed
}
namespaceEntry, err := wh.namespaceRegistry.GetNamespace(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
err = wh.workerDeploymentClient.ValidateComputeConfig(
ctx,
namespaceEntry,
request.GetDeploymentVersion(),
request.GetComputeConfigScalingGroups(),
request.GetRemoveComputeConfigScalingGroups(),
request.Identity,
)
if err != nil {
return nil, err
}
return &workflowservice.ValidateWorkerDeploymentVersionComputeConfigResponse{}, nil
}
// NewWorkflowHandler creates a gRPC handler for workflowservice
func NewWorkflowHandler(
callbackValidator callback.Validator,
config *Config,
namespaceReplicationQueue persistence.NamespaceReplicationQueue,
visibilityMgr manager.VisibilityManager,
logger log.Logger,
throttledLogger log.Logger,
persistenceExecutionName string,
clusterMetadataManager persistence.ClusterMetadataManager,
persistenceMetadataManager persistence.MetadataManager,
historyClient historyservice.HistoryServiceClient,
matchingClient matchingservice.MatchingServiceClient,
workerDeploymentClient workerdeployment.Client,
schedulerClient schedulerpb.SchedulerServiceClient,
archiverProvider provider.ArchiverProvider,
payloadSerializer serialization.Serializer,
namespaceRegistry namespace.Registry,
saMapperProvider searchattribute.MapperProvider,
saProvider searchattribute.Provider,
saValidator *searchattribute.Validator,
clusterMetadata cluster.Metadata,
archivalMetadata archiver.ArchivalMetadata,
healthServer *health.Server,
timeSource clock.TimeSource,
membershipMonitor membership.Monitor,
healthInterceptor *interceptor.HealthInterceptor,
scheduleSpecBuilder *scheduler.SpecBuilder,
httpEnabled bool,
activityHandler activity.FrontendHandler,
nexusOperationHandler chasmnexus.FrontendHandler,
registry *chasm.Registry,
workerDeploymentReadRateLimiter quotas.RequestRateLimiter,
validator *workflow.RequestValidator,
) *WorkflowHandler {
handler := &WorkflowHandler{
ActivityHandler: activityHandler,
NexusOperationHandler: nexusOperationHandler,
status: common.DaemonStatusInitialized,
callbackValidator: callbackValidator,
config: config,
tokenSerializer: tasktoken.NewSerializer(),
versionChecker: headers.NewDefaultVersionChecker(),
namespaceHandler: newNamespaceHandler(
logger,
persistenceMetadataManager,
namespaceRegistry,
clusterMetadata,
nsreplication.NewReplicator(namespaceReplicationQueue, logger),
archivalMetadata,
archiverProvider,
timeSource,
config,
),
getDefaultWorkflowRetrySettings: config.DefaultWorkflowRetryPolicy,
visibilityMgr: visibilityMgr,
logger: logger,
throttledLogger: throttledLogger,
persistenceExecutionName: persistenceExecutionName,
clusterMetadataManager: clusterMetadataManager,
clusterMetadata: clusterMetadata,
historyClient: historyClient,
matchingClient: matchingClient,
workerDeploymentClient: workerDeploymentClient,
schedulerClient: schedulerClient,
archiverProvider: archiverProvider,
payloadSerializer: payloadSerializer,
namespaceRegistry: namespaceRegistry,
saProvider: saProvider,
saMapperProvider: saMapperProvider,
saValidator: saValidator,
archivalMetadata: archivalMetadata,
healthServer: healthServer,
overrides: NewOverrides(),
membershipMonitor: membershipMonitor,
healthInterceptor: healthInterceptor,
scheduleSpecBuilder: scheduleSpecBuilder,
outstandingPollers: collection.NewSyncMap[string, collection.SyncMap[string, context.CancelFunc]](),
httpEnabled: httpEnabled,
registry: registry,
workerDeploymentReadRateLimiter: workerDeploymentReadRateLimiter,
validator: validator,
}
return handler
}
// Start starts the handler
func (wh *WorkflowHandler) Start() {
if atomic.CompareAndSwapInt32(
&wh.status,
common.DaemonStatusInitialized,
common.DaemonStatusStarted,
) {
// Start in NOT_SERVING state and switch to SERVING after membership is ready
wh.healthServer.SetServingStatus(WorkflowServiceName, healthpb.HealthCheckResponse_NOT_SERVING)
go func() {
_ = wh.membershipMonitor.WaitUntilInitialized(context.Background())
wh.healthServer.SetServingStatus(WorkflowServiceName, healthpb.HealthCheckResponse_SERVING)
wh.healthInterceptor.SetHealthy(true)
wh.logger.Info("Frontend is now healthy")
}()
wh.namespaceRegistry.RegisterStateChangeCallback(wh, func(ns *namespace.Namespace, deletedFromDb bool) {
if deletedFromDb {
return
}
if ns.IsGlobalNamespace() &&
ns.ReplicationPolicy() == namespace.ReplicationPolicyMultiCluster &&
//nolint:forbidigo // namespace state-change callback; cancels all pollers on ns deactivation
!ns.ActiveInCluster(wh.clusterMetadata.GetCurrentClusterName()) {
pollers, ok := wh.outstandingPollers.Get(ns.ID().String())
if ok {
for _, cancelFn := range pollers.PopAll() {
cancelFn()
}
}
}
})
}
}
// Stop stops the handler
func (wh *WorkflowHandler) Stop() {
if atomic.CompareAndSwapInt32(
&wh.status,
common.DaemonStatusStarted,
common.DaemonStatusStopped,
) {
wh.namespaceRegistry.UnregisterStateChangeCallback(wh)
wh.healthServer.SetServingStatus(WorkflowServiceName, healthpb.HealthCheckResponse_NOT_SERVING)
wh.healthInterceptor.SetHealthy(false)
}
}
// GetConfig return config
func (wh *WorkflowHandler) GetConfig() *Config {
return wh.config
}
// RegisterNamespace creates a new namespace which can be used as a container for all resources. Namespace is a top level
// entity within Temporal, used as a container for all resources like workflow executions, task queues, etc. Namespace
// acts as a sandbox and provides isolation for all resources within the namespace. All resources belong to exactly one
// namespace.
func (wh *WorkflowHandler) RegisterNamespace(ctx context.Context, request *workflowservice.RegisterNamespaceRequest) (_ *workflowservice.RegisterNamespaceResponse, retError error) {
defer log.CapturePanic(wh.logger, &retError)
if request == nil {
return nil, errRequestNotSet
}
if err := wh.validateNamespace(request.GetNamespace()); err != nil {
return nil, err
}
resp, err := wh.namespaceHandler.RegisterNamespace(ctx, request)
if err != nil {
return nil, err
}
return resp, nil
}
// DescribeNamespace returns the information and configuration for a registered namespace.
func (wh *WorkflowHandler) DescribeNamespace(ctx context.Context, request *workflowservice.DescribeNamespaceRequest) (_ *workflowservice.DescribeNamespaceResponse, retError error) {
defer log.CapturePanic(wh.logger, &retError)
if request == nil {
return nil, errRequestNotSet
}
resp, err := wh.namespaceHandler.DescribeNamespace(ctx, request)
if err != nil {
return resp, err
}
return resp, err
}
// ListNamespaces returns the information and configuration for all namespaces.
func (wh *WorkflowHandler) ListNamespaces(ctx context.Context, request *workflowservice.ListNamespacesRequest) (_ *workflowservice.ListNamespacesResponse, retError error) {
defer log.CapturePanic(wh.logger, &retError)
if request == nil {
return nil, errRequestNotSet
}
resp, err := wh.namespaceHandler.ListNamespaces(ctx, request)
if err != nil {
return resp, err
}
return resp, err
}
// UpdateNamespace is used to update the information and configuration for a registered namespace.
func (wh *WorkflowHandler) UpdateNamespace(ctx context.Context, request *workflowservice.UpdateNamespaceRequest) (_ *workflowservice.UpdateNamespaceResponse, retError error) {
defer log.CapturePanic(wh.logger, &retError)
if request == nil {
return nil, errRequestNotSet
}
resp, err := wh.namespaceHandler.UpdateNamespace(ctx, request)
if err != nil {
return resp, err
}
return resp, err
}
// DeprecateNamespace us used to update status of a registered namespace to DEPRECATED. Once the namespace is deprecated
// it cannot be used to start new workflow executions. Existing workflow executions will continue to run on
// deprecated namespaces.
// Deprecated.
func (wh *WorkflowHandler) DeprecateNamespace(ctx context.Context, request *workflowservice.DeprecateNamespaceRequest) (_ *workflowservice.DeprecateNamespaceResponse, retError error) {
defer log.CapturePanic(wh.logger, &retError)
if request == nil {
return nil, errRequestNotSet
}
resp, err := wh.namespaceHandler.DeprecateNamespace(ctx, request)
if err != nil {
return nil, err
}
return resp, err
}
// StartWorkflowExecution starts a new workflow instance (a "workflow execution"). It will create the instance with
// 'WorkflowExecutionStarted' event in history and also schedule the first WorkflowTask for the worker to make the
// first workflow task for this instance. It will return 'WorkflowExecutionAlreadyStartedError', if an instance already
// exists with same workflowId.
func (wh *WorkflowHandler) StartWorkflowExecution(
ctx context.Context,
request *workflowservice.StartWorkflowExecutionRequest,
) (_ *workflowservice.StartWorkflowExecutionResponse, retError error) {
defer log.CapturePanic(wh.logger, &retError)
var err error
if request, err = wh.prepareStartWorkflowRequest(ctx, request); err != nil {
return nil, err
}
wh.logger.Debug("Received StartWorkflowExecution.", tag.WorkflowID(request.GetWorkflowId()), tag.WorkflowType(request.GetWorkflowType().GetName()))
namespaceName := namespace.Name(request.GetNamespace())
wh.logger.Debug("Start workflow execution request namespace.", tag.WorkflowNamespace(namespaceName.String()))
namespaceID, err := wh.namespaceRegistry.GetNamespaceID(namespaceName)
if err != nil {
return nil, err
}
wh.logger.Debug("Start workflow execution request namespaceID.", tag.WorkflowNamespaceID(namespaceID.String()))
resp, err := wh.historyClient.StartWorkflowExecution(
ctx,
common.CreateHistoryStartWorkflowRequest(
namespaceID.String(),
request,
nil,
nil,
time.Now().UTC(),
),
)
if err != nil {
return nil, err
}
return wh.convertToStartWorkflowExecutionResponse(resp, namespaceName)
}
func (wh *WorkflowHandler) convertToStartWorkflowExecutionResponse(
resp *historyservice.StartWorkflowExecutionResponse,
namespaceName namespace.Name,
) (*workflowservice.StartWorkflowExecutionResponse, error) {
if resp.GetEagerWorkflowTask() != nil {
if err := api.ProcessOutgoingSearchAttributes(
wh.saProvider,
wh.saMapperProvider,
resp.GetEagerWorkflowTask().GetHistory().GetEvents(),
namespaceName,
wh.visibilityMgr,
); err != nil {
return nil, err
}
}
return &workflowservice.StartWorkflowExecutionResponse{
RunId: resp.GetRunId(),
Started: resp.Started,
EagerWorkflowTask: resp.GetEagerWorkflowTask(),
Link: resp.GetLink(),
Status: resp.GetStatus(),
}, nil
}
// Validates the request and sets default values where they are missing.
func (wh *WorkflowHandler) prepareStartWorkflowRequest(
ctx context.Context,
request *workflowservice.StartWorkflowExecutionRequest,
) (*workflowservice.StartWorkflowExecutionRequest, error) {
if request == nil {
return nil, errRequestNotSet
}
// Apply defaults before validation; must be first for idempotency on internal retries.
enums.SetDefaultWorkflowIDPolicies(
&request.WorkflowIdReusePolicy,
&request.WorkflowIdConflictPolicy,
enumspb.WORKFLOW_ID_CONFLICT_POLICY_FAIL,
)
if err := wh.validator.ValidateWorkflowID(request.GetWorkflowId()); err != nil {
return nil, err
}
namespaceName := namespace.Name(request.GetNamespace())
if err := wh.validator.ValidateRetryPolicy(request.GetNamespace(), request.RetryPolicy); err != nil {
return nil, err
}
if err := wh.validator.ValidateWorkflowStartDelay(request.GetCronSchedule(), request.WorkflowStartDelay); err != nil {
return nil, err
}
if err := backoff.ValidateSchedule(request.GetCronSchedule()); err != nil {
return nil, err
}
if request.WorkflowType == nil || request.WorkflowType.GetName() == "" {
return nil, errWorkflowTypeNotSet
}
if len(request.WorkflowType.GetName()) > wh.config.MaxIDLengthLimit() {
return nil, errWorkflowTypeTooLong
}
if err := tqid.NormalizeAndValidateUserDefined(request.TaskQueue, "", "", wh.config.MaxIDLengthLimit()); err != nil {
return nil, err
}
if err := wh.validator.ValidateWorkflowTimeouts(request); err != nil {
return nil, err
}
if err := validateRequestId(&request.RequestId, wh.config.MaxIDLengthLimit()); err != nil {
return nil, err
}
if err := wh.validator.ValidateWorkflowIDReusePolicy(
request.WorkflowIdReusePolicy,
request.WorkflowIdConflictPolicy); err != nil {
return nil, err
}
if err := wh.validateOnConflictOptions(request.OnConflictOptions); err != nil {
return nil, err
}
sa, err := wh.validator.UnaliasedSearchAttributesFrom(request.GetSearchAttributes(), request.GetNamespace())
if err != nil {
return nil, err
}
if sa != request.SearchAttributes {
// Since unaliasedSearchAttributesFrom is not idempotent, we need to clone the request so that
// in case of retries, the field is set to the original value.
request = common.CloneProto(request)
request.SearchAttributes = sa
}
if err := priorities.Validate(request.Priority); err != nil {
return nil, err
}
if cbs := request.GetCompletionCallbacks(); len(cbs) > 0 {
if err := wh.callbackValidator.Validate(ctx, namespaceName.String(), cbs); err != nil {
return nil, err
}
}
request.Links = dedupLinksFromCallbacks(request.GetLinks(), request.GetCompletionCallbacks())
allLinks := make([]*commonpb.Link, 0, len(request.GetLinks())+len(request.GetCompletionCallbacks()))
allLinks = append(allLinks, request.GetLinks()...)
for _, cb := range request.GetCompletionCallbacks() {
allLinks = append(allLinks, cb.GetLinks()...)
}
if err := commonlinks.Validate(allLinks, wh.config.MaxLinksPerRequest(namespaceName.String()), wh.config.LinkMaxSize(namespaceName.String())); err != nil {
return nil, err
}
if err := wh.validateTimeSkippingConfig(request.GetTimeSkippingConfig(), namespaceName); err != nil {
return nil, err
}
return request, nil
}
func (wh *WorkflowHandler) validateTimeSkippingConfig(
tsc *commonpb.TimeSkippingConfig,
ns namespace.Name,
) error {
if tsc == nil {
return nil
}
// if this feature is not enabled, we don't allow setting any related config
if !wh.config.TimeSkippingEnabled(ns.String()) {
return serviceerror.NewUnimplementedf(
"The Time-Skipping feature is not enabled for namespace %s",
ns.String(),
)
}
if !tsc.GetEnabled() {
if tsc.GetFastForward() != nil {
return serviceerror.NewInvalidArgument("time_skipping_config: cannot set fast_forward when enabled is false")
}
return nil
}
if ff := tsc.GetFastForward(); ff != nil && ff.AsDuration() < 0 {
return serviceerror.NewInvalidArgument("time_skipping_config: fast_forward must be positive")
}
return nil
}
func (wh *WorkflowHandler) unaliasedSearchAttributesFrom(
attributes *commonpb.SearchAttributes,
namespaceName namespace.Name,
) (*commonpb.SearchAttributes, error) {
sa, err := searchattribute.UnaliasFields(wh.saMapperProvider, attributes, namespaceName.String())
if err != nil {
return nil, err
}
if err = wh.validator.ValidateSearchAttributes(sa, namespaceName.String()); err != nil {
return nil, err
}
return sa, nil
}
func (wh *WorkflowHandler) ExecuteMultiOperation(
ctx context.Context,
request *workflowservice.ExecuteMultiOperationRequest,
) (_ *workflowservice.ExecuteMultiOperationResponse, retError error) {
defer log.CapturePanic(wh.logger, &retError)
if request == nil {
return nil, errRequestNotSet
}
namespaceName := namespace.Name(request.Namespace)
namespaceID, err := wh.namespaceRegistry.GetNamespaceID(namespaceName)
if err != nil {
return nil, err
}
// as a temporary limitation, the only allowed list of operations is exactly [Start, Update]
if len(request.Operations) != 2 {
return nil, errMultiOpNotStartAndUpdate
}
if request.Operations[0].GetStartWorkflow() == nil {
return nil, errMultiOpNotStartAndUpdate
}
if request.Operations[1].GetUpdateWorkflow() == nil {
return nil, errMultiOpNotStartAndUpdate
}
metrics.EventBlobSize.With(wh.metricsScope(ctx).WithTags(metrics.CommandTypeTag(enumspb.COMMAND_TYPE_UNSPECIFIED.String()))).Record(int64(request.Operations[1].GetUpdateWorkflow().GetRequest().GetInput().GetArgs().Size()), metrics.OperationTag("UpdateWorkflowExecution"))
historyReq, err := wh.convertToHistoryMultiOperationRequest(ctx, namespaceID, request)
if err != nil {
return nil, err
}
historyResp, err := wh.historyClient.ExecuteMultiOperation(ctx, historyReq)
if err != nil {
var multiErr *serviceerror.MultiOperationExecution
if errors.As(err, &multiErr) {
// Tweak error message for end-users to match the feature name.
// The per-operation errors are embedded inside the error and unpacked by the SDK.
multiErr.Message = "Update-with-Start could not be executed."
}
return nil, err
}
response, err := wh.convertToMultiOperationResponse(historyResp, namespaceName)
if err != nil {
return nil, err
}
return response, nil
}
func (wh *WorkflowHandler) convertToHistoryMultiOperationRequest(
ctx context.Context,
namespaceID namespace.ID,
request *workflowservice.ExecuteMultiOperationRequest,
) (*historyservice.ExecuteMultiOperationRequest, error) {
var lastWorkflowID string
ops := make([]*historyservice.ExecuteMultiOperationRequest_Operation, len(request.Operations))
var hasError bool
errs := make([]error, len(request.Operations))
for i, op := range request.Operations {
convertedOp, opWorkflowID, err := wh.convertToHistoryMultiOperationItem(ctx, namespaceID, namespace.Name(request.Namespace), op)
if err != nil {
hasError = true
} else {
// set to default in case the whole MultOp request
err = errMultiOpAborted
switch {
case lastWorkflowID == "":
lastWorkflowID = opWorkflowID
case lastWorkflowID != opWorkflowID:
err = errMultiOpWorkflowIdInconsistent
hasError = true
}
}
errs[i] = err
ops[i] = convertedOp
}
if hasError {
return nil, serviceerror.NewMultiOperationExecution("Update-with-Start could not be executed.", errs)
}
return &historyservice.ExecuteMultiOperationRequest{
NamespaceId: namespaceID.String(),
WorkflowId: lastWorkflowID,
Operations: ops,
}, nil
}
func (wh *WorkflowHandler) convertToHistoryMultiOperationItem(
ctx context.Context,
namespaceID namespace.ID,
namespaceName namespace.Name,
op *workflowservice.ExecuteMultiOperationRequest_Operation,
) (*historyservice.ExecuteMultiOperationRequest_Operation, string, error) {
var workflowId string
var opReq *historyservice.ExecuteMultiOperationRequest_Operation
if startReq := op.GetStartWorkflow(); startReq != nil {
if startReq.Namespace != "" && startReq.Namespace != namespaceName.String() {
return nil, "", errMultiOpNamespaceMismatch
}
var err error
if startReq, err = wh.prepareStartWorkflowRequest(ctx, startReq); err != nil {
return nil, "", err
}
if len(startReq.CronSchedule) > 0 {
return nil, "", errMultiOpStartCronSchedule
}
if startReq.RequestEagerExecution {
return nil, "", errMultiOpEagerWorkflow
}
if timestamp.DurationValue(startReq.WorkflowStartDelay) > 0 {
return nil, "", errMultiOpStartDelay
}
workflowId = startReq.WorkflowId
opReq = &historyservice.ExecuteMultiOperationRequest_Operation{
Operation: &historyservice.ExecuteMultiOperationRequest_Operation_StartWorkflow{
StartWorkflow: common.CreateHistoryStartWorkflowRequest(
namespaceID.String(),
startReq,
nil,
nil,
time.Now().UTC(),
),
},
}
} else if updateReq := op.GetUpdateWorkflow(); updateReq != nil {
if updateReq.Namespace != "" && updateReq.Namespace != namespaceName.String() {
return nil, "", errMultiOpNamespaceMismatch
}
if err := wh.prepareUpdateWorkflowRequest(updateReq); err != nil {
return nil, "", err
}
if updateReq.FirstExecutionRunId != "" {
return nil, "", errMultiOpUpdateFirstExecutionRunId
}
if updateReq.WorkflowExecution.RunId != "" {
return nil, "", errMultiOpUpdateExecutionRunId
}
workflowId = updateReq.WorkflowExecution.WorkflowId
opReq = &historyservice.ExecuteMultiOperationRequest_Operation{
Operation: &historyservice.ExecuteMultiOperationRequest_Operation_UpdateWorkflow{
UpdateWorkflow: &historyservice.UpdateWorkflowExecutionRequest{
NamespaceId: namespaceID.String(),
Request: updateReq,
},
},
}
} else {
return nil, "", serviceerror.NewInternalf("unsupported operation: %T", op.Operation)
}
return opReq, workflowId, nil
}
func (wh *WorkflowHandler) convertToMultiOperationResponse(
historyResp *historyservice.ExecuteMultiOperationResponse,
namespaceName namespace.Name,
) (*workflowservice.ExecuteMultiOperationResponse, error) {
resp := &workflowservice.ExecuteMultiOperationResponse{
Responses: make([]*workflowservice.ExecuteMultiOperationResponse_Response, len(historyResp.Responses)),
}
for i, op := range historyResp.Responses {
var opResp *workflowservice.ExecuteMultiOperationResponse_Response
if historyStartResp := op.GetStartWorkflow(); historyStartResp != nil {
startResp, err := wh.convertToStartWorkflowExecutionResponse(historyStartResp, namespaceName)
if err != nil {
return nil, err
}
opResp = &workflowservice.ExecuteMultiOperationResponse_Response{
Response: &workflowservice.ExecuteMultiOperationResponse_Response_StartWorkflow{
StartWorkflow: startResp,
},
}
} else if histUpdateResp := op.GetUpdateWorkflow(); histUpdateResp != nil {
opResp = &workflowservice.ExecuteMultiOperationResponse_Response{
Response: &workflowservice.ExecuteMultiOperationResponse_Response_UpdateWorkflow{
UpdateWorkflow: histUpdateResp.GetResponse(),
},
}
} else {
return nil, serviceerror.NewInternalf("unexpected operation result: %T", op.Response)
}
resp.Responses[i] = opResp
}
return resp, nil
}
// GetWorkflowExecutionHistory returns the history of specified workflow execution. It fails with 'EntityNotExistError' if specified workflow
// execution in unknown to the service.
func (wh *WorkflowHandler) GetWorkflowExecutionHistory(ctx context.Context, request *workflowservice.GetWorkflowExecutionHistoryRequest) (_ *workflowservice.GetWorkflowExecutionHistoryResponse, retError error) {
defer log.CapturePanic(wh.logger, &retError)
if request == nil {
return nil, errRequestNotSet
}
if err := validateExecution(request.Execution); err != nil {
return nil, err
}
if request.GetMaximumPageSize() <= 0 {
request.MaximumPageSize = int32(wh.config.HistoryMaxPageSize(request.GetNamespace()))
}
enums.SetDefaultHistoryEventFilterType(&request.HistoryEventFilterType)
namespaceID, err := wh.namespaceRegistry.GetNamespaceID(namespace.Name(request.GetNamespace()))
if err != nil {
return nil, err
}
// force limit page size if exceed
if request.GetMaximumPageSize() > primitives.GetHistoryMaxPageSize {
wh.throttledLogger.Warn("GetHistory page size is larger than threshold",
tag.WorkflowID(request.Execution.GetWorkflowId()),
tag.WorkflowRunID(request.Execution.GetRunId()),
tag.WorkflowNamespaceID(namespaceID.String()), tag.WorkflowSize(int64(request.GetMaximumPageSize())))
request.MaximumPageSize = primitives.GetHistoryMaxPageSize
}
if !request.GetSkipArchival() {
enableArchivalRead := wh.archivalMetadata.GetHistoryConfig().ReadEnabled()
historyArchived := wh.historyArchived(ctx, request, namespaceID)
if enableArchivalRead && historyArchived {
return wh.getArchivedHistory(ctx, request, namespaceID)
}
}
response, err := wh.historyClient.GetWorkflowExecutionHistory(ctx,
&historyservice.GetWorkflowExecutionHistoryRequest{
NamespaceId: namespaceID.String(),
Request: request,
})
if err != nil {
return nil, err
}
isCloseEventOnly := request.HistoryEventFilterType == enumspb.HISTORY_EVENT_FILTER_TYPE_CLOSE_EVENT
err = api.ProcessInternalRawHistory(
ctx,
wh.saProvider,
wh.saMapperProvider,
response,
wh.visibilityMgr,
wh.versionChecker,
namespace.Name(request.GetNamespace()),
isCloseEventOnly,