-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathworker_versioning.go
More file actions
1276 lines (1150 loc) · 51.5 KB
/
Copy pathworker_versioning.go
File metadata and controls
1276 lines (1150 loc) · 51.5 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 worker_versioning
import (
"context"
"errors"
"fmt"
"math"
"math/rand"
"sort"
"strings"
"time"
"github.com/dgryski/go-farm"
"github.com/temporalio/sqlparser"
commonpb "go.temporal.io/api/common/v1"
deploymentpb "go.temporal.io/api/deployment/v1"
enumspb "go.temporal.io/api/enums/v1"
"go.temporal.io/api/serviceerror"
workflowpb "go.temporal.io/api/workflow/v1"
deploymentspb "go.temporal.io/server/api/deployment/v1"
"go.temporal.io/server/api/matchingservice/v1"
persistencespb "go.temporal.io/server/api/persistence/v1"
taskqueuespb "go.temporal.io/server/api/taskqueue/v1"
"go.temporal.io/server/common/namespace"
"go.temporal.io/server/common/persistence/visibility/manager"
"go.temporal.io/server/common/resource"
"go.temporal.io/server/common/searchattribute/sadefs"
serviceerrors "go.temporal.io/server/common/serviceerror"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/emptypb"
)
const (
BuildIdSearchAttributePrefixPinned = "pinned"
buildIdSearchAttributePrefixAssigned = "assigned"
buildIdSearchAttributePrefixVersioned = "versioned"
buildIdSearchAttributePrefixUnversioned = "unversioned"
BuildIdSearchAttributeDelimiter = ":"
BuildIdSearchAttributeEscape = "|"
// UnversionedSearchAttribute is the sentinel value used to mark all unversioned workflows
UnversionedSearchAttribute = buildIdSearchAttributePrefixUnversioned
UnversionedVersionId = "__unversioned__"
// ErrPinnedVersionNotInTaskQueueSubstring is the key substring used to identify
// when a pinned version is not present in a task queue. This is used for error
// classification in batch operations.
ErrPinnedVersionNotInTaskQueueSubstring = "is not present in task queue"
// WorkerDeploymentVersionIdDelimiterV31 will be deleted once we stop supporting v31 version string fields
// in external and internal APIs. Until then, both delimiters are banned in deployment name. All
// deprecated version string fields in APIs keep using the old delimiter. Workflow SA uses new delimiter.
WorkerDeploymentVersionIDDelimiterV31 = "."
WorkerDeploymentVersionDelimiter = ":"
WorkerDeploymentVersionWorkflowIDEscape = "|"
// Prefixes, Delimeters and Keys that are used in the internal entity workflows backing worker-versioning
WorkerDeploymentWorkflowIDPrefix = "temporal-sys-worker-deployment"
WorkerDeploymentVersionWorkflowIDPrefix = "temporal-sys-worker-deployment-version"
WorkerDeploymentVersionWorkflowIDInitialSize = len(WorkerDeploymentVersionWorkflowIDPrefix) + len(WorkerDeploymentVersionDelimiter) // 39
WorkerDeploymentNameFieldName = "WorkerDeploymentName"
WorkerDeploymentBuildIDFieldName = "BuildID"
)
// FormatPinnedVersionNotInTaskQueueError formats the error message when a pinned version
// is not present in a task queue.
func FormatPinnedVersionNotInTaskQueueError(deploymentName, buildID, taskQueue string, taskQueueType enumspb.TaskQueueType) string {
var tqType string
switch taskQueueType {
case enumspb.TASK_QUEUE_TYPE_WORKFLOW:
tqType = "Workflow"
case enumspb.TASK_QUEUE_TYPE_ACTIVITY:
tqType = "Activity"
case enumspb.TASK_QUEUE_TYPE_NEXUS:
tqType = "Nexus"
default:
tqType = "Unknown"
}
return fmt.Sprintf("Pinned version '%s:%s' %s '%s' of type '%s'",
deploymentName, buildID, ErrPinnedVersionNotInTaskQueueSubstring, taskQueue, tqType)
}
// PinnedBuildIdSearchAttribute creates the pinned search attribute for the BuildIds list, used as a visibility optimization.
// For pinned workflows using WorkerDeployment APIs (ms.GetEffectiveVersioningBehavior() == PINNED &&
// ms.executionInfo.VersioningInfo.Version != ""), this will be `pinned:<version>`. The version used
// will be the override version if set, or the versioningInfo.Version.
//
// If deprecated Deployment-based APIs are in use and the workflow is pinned, `pinned:<deployment_series_name>:<deployment_build_id>`
// will. The values used will be the override deployment_series and build_id if set, or versioningInfo.Deployment.
//
// If the workflow becomes unpinned or unversioned, this entry will be removed from that list.
func PinnedBuildIdSearchAttribute(version string) string {
return fmt.Sprintf("%s%s%s",
BuildIdSearchAttributePrefixPinned,
BuildIdSearchAttributeDelimiter,
version,
)
}
// AssignedBuildIdSearchAttribute returns the search attribute value for the currently assigned build ID
func AssignedBuildIdSearchAttribute(buildId string) string {
return buildIdSearchAttributePrefixAssigned + BuildIdSearchAttributeDelimiter + buildId
}
// IsUnversionedOrAssignedBuildIdSearchAttribute returns the value is "unversioned" or "assigned:<bld>"
func IsUnversionedOrAssignedBuildIdSearchAttribute(buildId string) bool {
return buildId == UnversionedSearchAttribute ||
strings.HasPrefix(buildId, buildIdSearchAttributePrefixAssigned+BuildIdSearchAttributeDelimiter)
}
// VersionedBuildIdSearchAttribute returns the search attribute value for a versioned build ID
func VersionedBuildIdSearchAttribute(buildId string) string {
return buildIdSearchAttributePrefixVersioned + BuildIdSearchAttributeDelimiter + buildId
}
// UnversionedBuildIdSearchAttribute returns the search attribute value for an unversioned build ID
func UnversionedBuildIdSearchAttribute(buildId string) string {
return buildIdSearchAttributePrefixUnversioned + BuildIdSearchAttributeDelimiter + buildId
}
// VersionStampToBuildIdSearchAttribute returns the search attribute value for a version stamp
func VersionStampToBuildIdSearchAttribute(stamp *commonpb.WorkerVersionStamp) string {
if stamp.GetBuildId() == "" {
return UnversionedSearchAttribute
}
if stamp.UseVersioning {
return VersionedBuildIdSearchAttribute(stamp.BuildId)
}
return UnversionedBuildIdSearchAttribute(stamp.BuildId)
}
// FindBuildId finds a build ID in the version data's sets, returning (set index, index within that set).
// Returns -1, -1 if not found.
func FindBuildId(versioningData *persistencespb.VersioningData, buildId string) (setIndex, indexInSet int) {
versionSets := versioningData.GetVersionSets()
for sidx, set := range versionSets {
for bidx, id := range set.GetBuildIds() {
if buildId == id.Id {
return sidx, bidx
}
}
}
return -1, -1
}
func WorkflowsExistForBuildId(ctx context.Context, visibilityManager manager.VisibilityManager, ns *namespace.Namespace, taskQueue, buildId string) (bool, error) {
escapedTaskQueue := sqlparser.String(sqlparser.NewStrVal([]byte(taskQueue)))
escapedBuildId := sqlparser.String(sqlparser.NewStrVal([]byte(VersionedBuildIdSearchAttribute(buildId))))
query := fmt.Sprintf("%s = %s AND %s = %s", sadefs.TaskQueue, escapedTaskQueue, sadefs.BuildIds, escapedBuildId)
response, err := visibilityManager.CountWorkflowExecutions(ctx, &manager.CountWorkflowExecutionsRequest{
NamespaceID: ns.ID(),
Namespace: ns.Name(),
Query: query,
})
if err != nil {
return false, err
}
return response.Count > 0, nil
}
// StampIfUsingVersioning returns the given WorkerVersionStamp if it is using versioning,
// otherwise returns nil.
func StampIfUsingVersioning(stamp *commonpb.WorkerVersionStamp) *commonpb.WorkerVersionStamp {
if stamp.GetUseVersioning() {
return stamp
}
return nil
}
// BuildIdIfUsingVersioning returns the given WorkerVersionStamp if it is using versioning,
// otherwise returns nil.
func BuildIdIfUsingVersioning(stamp *commonpb.WorkerVersionStamp) string {
if stamp.GetUseVersioning() {
return stamp.GetBuildId()
}
return ""
}
// DeploymentFromCapabilities returns the deployment if it is using versioning V3, otherwise nil.
// It returns the deployment from the `options` if present, otherwise, from `capabilities`,
func DeploymentFromCapabilities(capabilities *commonpb.WorkerVersionCapabilities, options *deploymentpb.WorkerDeploymentOptions) (*deploymentpb.Deployment, error) {
if options.GetWorkerVersioningMode() == enumspb.WORKER_VERSIONING_MODE_VERSIONED {
d := options.GetDeploymentName()
b := options.GetBuildId()
if d == "" {
return nil, serviceerror.NewInvalidArgumentf("versioned worker must have deployment name")
}
if b == "" {
return nil, serviceerror.NewInvalidArgumentf("versioned worker must have build id")
}
if strings.Contains(d, WorkerDeploymentVersionDelimiter) || strings.Contains(d, WorkerDeploymentVersionIDDelimiterV31) {
// TODO: allow '.' once we get rid of v31 stuff
return nil, serviceerror.NewInvalidArgumentf("deployment name cannot contain '%s' or '%s'", WorkerDeploymentVersionDelimiter, WorkerDeploymentVersionIDDelimiterV31)
}
return &deploymentpb.Deployment{
SeriesName: d,
BuildId: b,
}, nil
}
if capabilities.GetUseVersioning() && capabilities.GetDeploymentSeriesName() != "" && capabilities.GetBuildId() != "" {
return &deploymentpb.Deployment{
SeriesName: capabilities.GetDeploymentSeriesName(),
BuildId: capabilities.GetBuildId(),
}, nil
}
return nil, nil
}
func DeploymentNameFromCapabilities(capabilities *commonpb.WorkerVersionCapabilities, options *deploymentpb.WorkerDeploymentOptions) string {
if d := options.GetDeploymentName(); d != "" {
return d
}
return capabilities.GetDeploymentSeriesName()
}
func BuildIdFromCapabilities(capabilities *commonpb.WorkerVersionCapabilities, options *deploymentpb.WorkerDeploymentOptions) string {
if d := options.GetBuildId(); d != "" {
return d
}
return capabilities.GetBuildId()
}
func DeploymentVersionFromOptions(options *deploymentpb.WorkerDeploymentOptions) *deploymentspb.WorkerDeploymentVersion {
if options.GetWorkerVersioningMode() == enumspb.WORKER_VERSIONING_MODE_VERSIONED {
return &deploymentspb.WorkerDeploymentVersion{
DeploymentName: options.GetDeploymentName(),
BuildId: options.GetBuildId(),
}
}
return nil
}
// DeploymentOrVersion Temporary helper function to return a Deployment based on passed Deployment
// or WorkerDeploymentVersion objects, if `v` is not nil, it'll take precedence.
func DeploymentOrVersion(d *deploymentpb.Deployment, v *deploymentspb.WorkerDeploymentVersion) *deploymentpb.Deployment {
if v != nil {
return DeploymentIfValid(DeploymentFromDeploymentVersion(v))
}
return DeploymentIfValid(d)
}
// DeploymentIfValid returns the deployment back if is both of its fields have value.
func DeploymentIfValid(d *deploymentpb.Deployment) *deploymentpb.Deployment {
if d.GetSeriesName() != "" && d.GetBuildId() != "" {
return d
}
return nil
}
// MakeDirectiveForWorkflowTask returns a versioning directive based on the following parameters:
// - inheritedBuildId: build ID inherited from a past/previous wf execution (for Child WF or CaN)
// - assignedBuildId: the build ID to which the WF is currently assigned (i.e. mutable state's AssginedBuildId)
// - stamp: the latest versioning stamp of the execution (only needed for old versioning)
// - hasCompletedWorkflowTask: if the wf has completed any WFT
// - behavior: workflow's effective behavior
// - deployment: workflow's effective deployment
func MakeDirectiveForWorkflowTask(
inheritedBuildId string,
assignedBuildId string,
stamp *commonpb.WorkerVersionStamp,
hasCompletedWorkflowTask bool,
behavior enumspb.VersioningBehavior,
deployment *deploymentpb.Deployment,
revisionNumber int64,
useRampingVersion bool,
) *taskqueuespb.TaskVersionDirective {
if behavior != enumspb.VERSIONING_BEHAVIOR_UNSPECIFIED {
return &taskqueuespb.TaskVersionDirective{
Behavior: behavior,
DeploymentVersion: DeploymentVersionFromDeployment(deployment),
RevisionNumber: revisionNumber,
UseRampingVersion: useRampingVersion,
}
}
if id := BuildIdIfUsingVersioning(stamp); id != "" && assignedBuildId == "" {
// TODO: old versioning only [cleanup-old-wv]
return MakeBuildIdDirective(id)
} else if !hasCompletedWorkflowTask && inheritedBuildId == "" {
// first workflow task (or a retry of) and build ID not inherited. if this is retry we reassign build ID
// if WF has an inherited build ID, we do not allow usage of assignment rules
return MakeUseAssignmentRulesDirective()
} else if assignedBuildId != "" {
return MakeBuildIdDirective(assignedBuildId)
}
// else: unversioned queue
return nil
}
type IsWFTaskQueueInVersionDetector = func(ctx context.Context, namespaceID, tq string, version *deploymentpb.WorkerDeploymentVersion) (bool, error)
func GetIsWFTaskQueueInVersionDetector(matchingClient resource.MatchingClient, versionCache VersionMembershipAndReactivationStatusCache) IsWFTaskQueueInVersionDetector {
return func(ctx context.Context,
namespaceID, tq string,
version *deploymentpb.WorkerDeploymentVersion) (bool, error) {
// Check cache first.
if isMember, _, _, ok := versionCache.Get(
namespaceID, tq, enumspb.TASK_QUEUE_TYPE_WORKFLOW,
version.GetDeploymentName(), version.GetBuildId(),
); ok {
return isMember, nil
}
// Cache miss — resolve via matching RPC.
isMember, shouldSkipReactivation, revisionNumber, err := checkVersionMembershipAndReactivationEligibility(ctx, matchingClient, namespaceID, tq, enumspb.TASK_QUEUE_TYPE_WORKFLOW, version)
if err != nil {
return false, err
}
// Add result to cache
versionCache.Put(
namespaceID, tq, enumspb.TASK_QUEUE_TYPE_WORKFLOW,
version.GetDeploymentName(), version.GetBuildId(),
isMember, shouldSkipReactivation, revisionNumber,
)
return isMember, nil
}
}
// checkVersionMembershipAndReactivationEligibility calls matching to check if a task queue belongs to a version
// and whether the version is currently active-or-draining (see ShouldSkipReactivation for the
// exact status set). Falls back to fetching the full user data if the CheckTaskQueueVersionMembership
// RPC is not implemented (this can happen during rolling upgrades where history is on a higher
// version than matching).
func checkVersionMembershipAndReactivationEligibility(
ctx context.Context,
matchingClient resource.MatchingClient,
namespaceID, tq string,
tqType enumspb.TaskQueueType,
version *deploymentpb.WorkerDeploymentVersion,
) (isMember bool, shouldSkipReactivation bool, revisionNumber int64, err error) {
resp, err := matchingClient.CheckTaskQueueVersionMembership(ctx, &matchingservice.CheckTaskQueueVersionMembershipRequest{
NamespaceId: namespaceID,
TaskQueue: tq,
TaskQueueType: tqType,
Version: DeploymentVersionFromDeployment(DeploymentFromExternalDeploymentVersion(version)),
})
if err != nil {
// If matching is on an older version that doesn't have this RPC,
// fall back to fetching full user data and checking version membership based on the received information.
var unimplErr *serviceerror.Unimplemented
if errors.As(err, &unimplErr) {
return checkVersionMembershipViaUserData(ctx, matchingClient, namespaceID, tq, tqType, version)
}
return false, false, 0, err
}
return resp.GetIsMember(), resp.GetShouldSkipReactivation(), resp.GetRevisionNumber(), nil
}
// checkVersionMembershipViaUserData is the fallback for when matching doesn't support
// CheckTaskQueueVersionMembership (e.g. during rolling deployments). It fetches the full
// Task Queue User Data and checks version membership based on the receieved information.
func checkVersionMembershipViaUserData(
ctx context.Context,
matchingClient resource.MatchingClient,
namespaceID string,
tq string,
tqType enumspb.TaskQueueType,
version *deploymentpb.WorkerDeploymentVersion,
) (isMember bool, shouldSkipReactivation bool, revisionNumber int64, err error) {
resp, err := matchingClient.GetTaskQueueUserData(ctx,
&matchingservice.GetTaskQueueUserDataRequest{
NamespaceId: namespaceID,
TaskQueue: tq,
TaskQueueType: tqType,
})
if err != nil {
return false, false, 0, err
}
tqData, ok := resp.GetUserData().GetData().GetPerType()[int32(tqType)]
if !ok {
return false, false, 0, nil
}
deploymentData := tqData.GetDeploymentData()
isMember = HasDeploymentVersion(deploymentData, DeploymentVersionFromDeployment(DeploymentFromExternalDeploymentVersion(version)))
shouldSkipReactivation, revisionNumber = ShouldSkipReactivation(deploymentData, version.GetDeploymentName(), version.GetBuildId())
return isMember, shouldSkipReactivation, revisionNumber, nil
}
func FindOldDeploymentVersion(deployments *persistencespb.DeploymentData, v *deploymentspb.WorkerDeploymentVersion) int {
for i, vd := range deployments.GetVersions() {
if proto.Equal(v, vd.GetVersion()) {
return i
}
}
return -1
}
//nolint:staticcheck
func HasDeploymentVersion(deployments *persistencespb.DeploymentData, v *deploymentspb.WorkerDeploymentVersion) bool {
// Represents unversioned workers.
if v == nil {
return false
}
for _, vd := range deployments.GetVersions() {
if proto.Equal(v, vd.GetVersion()) {
return true
}
}
// Check for the presence of the version in the new DeploymentData format.
if deploymentData, ok := deployments.GetDeploymentsData()[v.GetDeploymentName()]; ok {
vd := deploymentData.GetVersions()[v.GetBuildId()]
return vd != nil && !vd.GetDeleted()
}
return false
}
// ShouldSkipReactivation reports whether a reactivation signal to the given version would
// be redundant. Returns true when the version's status is CURRENT, RAMPING, or DRAINING.
// Returns false for DRAINED and INACTIVE (the two statuses the reactivation handler in
// version_workflow.go acts on) and when the version is not present in the deployment data.
// (UNSPECIFIED also yields false; in practice the deployment workflow sets a status at
// construction so this branch should not trigger.)
//
// The returned revisionNumber is the version's revision as tracked in the new deployment
// data format (WorkerDeploymentVersionData.revision_number). It is 0 for the legacy
// DeploymentVersionData format (which does not carry a revision number) and when the
// version is not found at all.
//
//nolint:staticcheck
func ShouldSkipReactivation(
deployments *persistencespb.DeploymentData,
deploymentName string,
buildID string,
) (bool, int64) {
// Check old format first (deprecated versions list).
for _, vd := range deployments.GetVersions() {
if vd.GetVersion().GetDeploymentName() == deploymentName && vd.GetVersion().GetBuildId() == buildID {
return isStatusSkippableFromReactivation(vd.GetStatus()), 0
}
}
// Check new format (deployments_data map).
deploymentData := deployments.GetDeploymentsData()[deploymentName]
versionData := deploymentData.GetVersions()[buildID]
if versionData == nil || versionData.GetDeleted() {
return false, 0
}
return isStatusSkippableFromReactivation(versionData.GetStatus()), versionData.GetRevisionNumber()
}
func isStatusSkippableFromReactivation(s enumspb.WorkerDeploymentVersionStatus) bool {
return s == enumspb.WORKER_DEPLOYMENT_VERSION_STATUS_CURRENT ||
s == enumspb.WORKER_DEPLOYMENT_VERSION_STATUS_RAMPING ||
s == enumspb.WORKER_DEPLOYMENT_VERSION_STATUS_DRAINING
}
func CountDeploymentVersions(deployments *persistencespb.DeploymentData) int {
//nolint:staticcheck // SA1019
res := len(deployments.GetVersions())
// Check for the presence of the version in the new DeploymentData format.
for _, d := range deployments.GetDeploymentsData() {
for _, vd := range d.GetVersions() {
if vd != nil && !vd.GetDeleted() {
res++
}
}
}
return res
}
// DeploymentVersionFromDeployment Temporary helper function to convert Deployment to
// WorkerDeploymentVersion proto until we update code to use the new proto in all places.
func DeploymentVersionFromDeployment(deployment *deploymentpb.Deployment) *deploymentspb.WorkerDeploymentVersion {
if deployment == nil {
return nil
}
return &deploymentspb.WorkerDeploymentVersion{
BuildId: deployment.GetBuildId(),
DeploymentName: deployment.GetSeriesName(),
}
}
// ExternalWorkerDeploymentVersionFromDeployment Temporary helper function to convert Deployment to
// WorkerDeploymentVersion proto until we update code to use the new proto in all places.
func ExternalWorkerDeploymentVersionFromDeployment(deployment *deploymentpb.Deployment) *deploymentpb.WorkerDeploymentVersion {
if deployment == nil {
return nil
}
return &deploymentpb.WorkerDeploymentVersion{
BuildId: deployment.GetBuildId(),
DeploymentName: deployment.GetSeriesName(),
}
}
// ExternalWorkerDeploymentVersionFromVersion Temporary helper function to convert internal Worker Deployment to
// WorkerDeploymentVersion proto until we update code to use the new proto in all places.
func ExternalWorkerDeploymentVersionFromVersion(version *deploymentspb.WorkerDeploymentVersion) *deploymentpb.WorkerDeploymentVersion {
if version == nil {
return nil
}
return &deploymentpb.WorkerDeploymentVersion{
BuildId: version.GetBuildId(),
DeploymentName: version.GetDeploymentName(),
}
}
// DeploymentFromExternalDeploymentVersion Temporary helper function to convert WorkerDeploymentVersion to
// Deployment proto until we update code to use the new proto in all places.
func DeploymentFromExternalDeploymentVersion(dv *deploymentpb.WorkerDeploymentVersion) *deploymentpb.Deployment {
if dv == nil {
return nil
}
return &deploymentpb.Deployment{
BuildId: dv.GetBuildId(),
SeriesName: dv.GetDeploymentName(),
}
}
// DeploymentFromDeploymentVersion Temporary helper function to convert WorkerDeploymentVersion to
// Deployment proto until we update code to use the new proto in all places.
func DeploymentFromDeploymentVersion(dv *deploymentspb.WorkerDeploymentVersion) *deploymentpb.Deployment {
if dv == nil {
return nil
}
return &deploymentpb.Deployment{
BuildId: dv.GetBuildId(),
SeriesName: dv.GetDeploymentName(),
}
}
func MakeUseAssignmentRulesDirective() *taskqueuespb.TaskVersionDirective {
return &taskqueuespb.TaskVersionDirective{BuildId: &taskqueuespb.TaskVersionDirective_UseAssignmentRules{UseAssignmentRules: &emptypb.Empty{}}}
}
func MakeBuildIdDirective(buildId string) *taskqueuespb.TaskVersionDirective {
return &taskqueuespb.TaskVersionDirective{BuildId: &taskqueuespb.TaskVersionDirective_AssignedBuildId{AssignedBuildId: buildId}}
}
func StampFromCapabilities(capabilities *commonpb.WorkerVersionCapabilities, options *deploymentpb.WorkerDeploymentOptions) *commonpb.WorkerVersionStamp {
if options.GetWorkerVersioningMode() == enumspb.WORKER_VERSIONING_MODE_VERSIONED && options.GetDeploymentName() != "" {
// Versioning 3, do not return stamp.
return nil
}
if capabilities.GetUseVersioning() && capabilities.GetDeploymentSeriesName() != "" {
// Versioning 3, do not return stamp.
return nil
}
// TODO: remove `capabilities.BuildId != ""` condition after old versioning cleanup. this condition is used to differentiate
// between old and new versioning in Record*TaskStart calls. [cleanup-old-wv]
// we don't want to add stamp for task started events in old versioning
if capabilities.GetBuildId() != "" {
return &commonpb.WorkerVersionStamp{UseVersioning: capabilities.UseVersioning, BuildId: capabilities.BuildId}
}
return nil
}
func StampFromBuildId(buildId string) *commonpb.WorkerVersionStamp {
return &commonpb.WorkerVersionStamp{UseVersioning: true, BuildId: buildId}
}
// ValidateDeployment returns error if the deployment is nil or it has empty build ID or deployment
// name.
func ValidateDeployment(deployment *deploymentpb.Deployment) error {
if deployment == nil {
return serviceerror.NewInvalidArgument("deployment cannot be nil")
}
if deployment.GetSeriesName() == "" {
return serviceerror.NewInvalidArgument("deployment name cannot be empty")
}
// TODO: remove '.' restriction once the v31 version strings are completely cleaned from external and internal API
if strings.Contains(deployment.GetSeriesName(), WorkerDeploymentVersionIDDelimiterV31) ||
strings.Contains(deployment.GetSeriesName(), WorkerDeploymentVersionDelimiter) {
return serviceerror.NewInvalidArgumentf("deployment name cannot contain '%s' or '%s'", WorkerDeploymentVersionIDDelimiterV31, WorkerDeploymentVersionDelimiter)
}
if deployment.GetBuildId() == "" {
return serviceerror.NewInvalidArgument("deployment build ID cannot be empty")
}
return nil
}
// ValidateDeploymentVersion returns error if the deployment version is not a valid entity.
func ValidateDeploymentVersion(version *deploymentspb.WorkerDeploymentVersion, maxIDLengthLimit int) error {
if version == nil {
return serviceerror.NewInvalidArgument("deployment version cannot be nil")
}
// Validate deployment name
err := ValidateDeploymentVersionFields(WorkerDeploymentNameFieldName, version.GetDeploymentName(), maxIDLengthLimit)
if err != nil {
return err
}
// Validate build ID
err = ValidateDeploymentVersionFields(WorkerDeploymentBuildIDFieldName, version.GetBuildId(), maxIDLengthLimit)
if err != nil {
return err
}
return nil
}
// ValidateDeploymentVersionFields is a helper that verifies if the fields within a
// Worker Deployment Version are valid
func ValidateDeploymentVersionFields(fieldName string, field string, maxIDLengthLimit int) error {
// Length checks
if field == "" {
return serviceerror.NewInvalidArgumentf("%v cannot be empty", fieldName)
}
// Length of each field should be: (MaxIDLengthLimit - (prefix + delimeter length)) / 2
// Note: Using the same initial size for both the fields since they are used together to generate the version workflow's ID
if len(field) > (maxIDLengthLimit-WorkerDeploymentVersionWorkflowIDInitialSize)/2 {
return serviceerror.NewInvalidArgumentf("size of %v larger than the maximum allowed", fieldName)
}
// deploymentName cannot have "."
// TODO: remove this restriction once the old version strings are completely cleaned from external and internal API
if fieldName == WorkerDeploymentNameFieldName && strings.Contains(field, WorkerDeploymentVersionIDDelimiterV31) {
return serviceerror.NewInvalidArgumentf("worker deployment name cannot contain '%s'", WorkerDeploymentVersionIDDelimiterV31)
}
// deploymentName cannot have ":"
if fieldName == WorkerDeploymentNameFieldName && strings.Contains(field, WorkerDeploymentVersionDelimiter) {
return serviceerror.NewInvalidArgumentf("worker deployment name cannot contain '%s'", WorkerDeploymentVersionDelimiter)
}
// buildID or deployment name cannot start with "__"
if strings.HasPrefix(field, "__") {
return serviceerror.NewInvalidArgumentf("%v cannot start with '__'", fieldName)
}
return nil
}
// ValidateDeploymentVersionStringV31 returns error if the deployment version is nil or it has empty version
// or deployment name.
func ValidateDeploymentVersionStringV31(version string) (*deploymentspb.WorkerDeploymentVersion, error) {
if version == "" {
return nil, serviceerror.NewInvalidArgument("version is required")
}
v, err := WorkerDeploymentVersionFromStringV31(version)
if err != nil {
return nil, serviceerror.NewInvalidArgumentf("invalid version string %q, expected format is \"<deployment_name>.<build_id>\"", version)
}
return v, nil
}
func OverrideIsPinned(override *workflowpb.VersioningOverride) bool {
//nolint:staticcheck // SA1019: worker versioning v0.31 and v0.30
return override.GetBehavior() == enumspb.VERSIONING_BEHAVIOR_PINNED ||
override.GetPinned().GetBehavior() == workflowpb.VersioningOverride_PINNED_OVERRIDE_BEHAVIOR_PINNED
}
func GetOverridePinnedVersion(override *workflowpb.VersioningOverride) *deploymentpb.WorkerDeploymentVersion {
if OverrideIsPinned(override) {
if v := override.GetPinned().GetVersion(); v != nil {
return v
} else if v := override.GetPinnedVersion(); v != "" { //nolint:staticcheck // SA1019: worker versioning v0.31
return ExternalWorkerDeploymentVersionFromStringV31(v)
}
return ExternalWorkerDeploymentVersionFromDeployment(override.GetDeployment()) //nolint:staticcheck // SA1019: worker versioning v0.30
}
return nil
}
func GetOverrideOneTimeTargetVersion(override *workflowpb.VersioningOverride) *deploymentpb.WorkerDeploymentVersion {
return override.GetOneTime().GetTargetDeploymentVersion()
}
func GetOverrideTargetDeploymentVersion(override *workflowpb.VersioningOverride) *deploymentpb.WorkerDeploymentVersion {
if OverrideIsPinned(override) {
return GetOverridePinnedVersion(override)
}
return GetOverrideOneTimeTargetVersion(override)
}
func ExtractVersioningBehaviorFromOverride(override *workflowpb.VersioningOverride) enumspb.VersioningBehavior {
if override.GetAutoUpgrade() {
return enumspb.VERSIONING_BEHAVIOR_AUTO_UPGRADE
} else if override.GetPinned() != nil || override.GetOneTime() != nil {
return enumspb.VERSIONING_BEHAVIOR_PINNED
}
//nolint:staticcheck // SA1019: worker versioning v0.31
return override.GetBehavior()
}
func validateVersionAndGetReactivationEligibility(ctx context.Context,
pinnedVersion *deploymentpb.WorkerDeploymentVersion,
matchingClient resource.MatchingClient,
versionCache VersionMembershipAndReactivationStatusCache,
tq string,
tqType enumspb.TaskQueueType,
namespaceID string) (shouldSkipReactivation bool, revisionNumber int64, err error) {
// Check if we have recently queried matching to validate if this version exists in the task queue.
if isMember, cachedActiveOrDraining, cachedRevision, ok := versionCache.Get(
namespaceID,
tq,
tqType,
pinnedVersion.DeploymentName,
pinnedVersion.BuildId,
); ok {
if isMember {
return cachedActiveOrDraining, cachedRevision, nil
}
return false, 0, serviceerror.NewFailedPrecondition(
FormatPinnedVersionNotInTaskQueueError(pinnedVersion.GetDeploymentName(), pinnedVersion.GetBuildId(), tq, tqType),
)
}
isMember, shouldSkipReactivation, revisionNumber, err := checkVersionMembershipAndReactivationEligibility(ctx, matchingClient, namespaceID, tq, tqType, pinnedVersion)
if err != nil {
return false, 0, err
}
// Add result to cache
versionCache.Put(
namespaceID,
tq,
tqType,
pinnedVersion.DeploymentName,
pinnedVersion.BuildId,
isMember,
shouldSkipReactivation,
revisionNumber,
)
if !isMember {
return false, 0, serviceerror.NewFailedPrecondition(
FormatPinnedVersionNotInTaskQueueError(pinnedVersion.GetDeploymentName(), pinnedVersion.GetBuildId(), tq, tqType),
)
}
return shouldSkipReactivation, revisionNumber, nil
}
func ValidateVersioningOverrideAndGetReactivationEligibility(ctx context.Context,
override *workflowpb.VersioningOverride,
matchingClient resource.MatchingClient,
versionCache VersionMembershipAndReactivationStatusCache,
tq string,
tqType enumspb.TaskQueueType,
namespaceID string) (shouldSkipReactivation bool, revisionNumber int64, err error) {
if override == nil {
return false, 0, nil
}
if override.GetAutoUpgrade() { // v0.32
return false, 0, nil
} else if p := override.GetPinned(); p != nil {
if p.GetVersion() == nil {
return false, 0, serviceerror.NewInvalidArgument("must provide version if override is pinned.")
}
if p.GetBehavior() == workflowpb.VersioningOverride_PINNED_OVERRIDE_BEHAVIOR_UNSPECIFIED {
return false, 0, serviceerror.NewInvalidArgument("must specify pinned override behavior if override is pinned.")
}
return validateVersionAndGetReactivationEligibility(ctx, p.GetVersion(), matchingClient, versionCache, tq, tqType, namespaceID)
} else if oneTime := override.GetOneTime(); oneTime != nil {
if oneTime.GetTargetDeploymentVersion() == nil {
return false, 0, serviceerror.NewInvalidArgument("must provide target deployment version if override is one-time.")
}
return validateVersionAndGetReactivationEligibility(ctx, oneTime.GetTargetDeploymentVersion(), matchingClient, versionCache, tq, tqType, namespaceID)
}
//nolint:staticcheck // SA1019: worker versioning v0.31
switch override.GetBehavior() {
case enumspb.VERSIONING_BEHAVIOR_PINNED:
if override.GetDeployment() != nil {
return false, 0, ValidateDeployment(override.GetDeployment())
} else if override.GetPinnedVersion() != "" {
_, err := ValidateDeploymentVersionStringV31(override.GetPinnedVersion())
if err != nil {
return false, 0, err
}
return validateVersionAndGetReactivationEligibility(ctx, ExternalWorkerDeploymentVersionFromStringV31(override.GetPinnedVersion()), matchingClient, versionCache, tq, tqType, namespaceID)
} else {
return false, 0, serviceerror.NewInvalidArgument("must provide deployment (deprecated) or pinned version if behavior is 'PINNED'")
}
case enumspb.VERSIONING_BEHAVIOR_AUTO_UPGRADE:
if override.GetDeployment() != nil {
return false, 0, serviceerror.NewInvalidArgument("only provide deployment if behavior is 'PINNED'")
}
if override.GetPinnedVersion() != "" {
return false, 0, serviceerror.NewInvalidArgument("only provide pinned version if behavior is 'PINNED'")
}
case enumspb.VERSIONING_BEHAVIOR_UNSPECIFIED:
return false, 0, serviceerror.NewInvalidArgument("override behavior is required")
default:
//nolint:staticcheck // SA1019 deprecated stamp will clean up later
return false, 0, serviceerror.NewInvalidArgumentf("override behavior %s not recognized", override.GetBehavior())
}
return false, 0, nil
}
// FindTargetDeploymentVersionAndRevisionNumberForWorkflowID returns the deployment version and revision number (if applicable) for
// the particular workflow ID based on the versioning info of the task queue. Nil means unversioned.
func FindTargetDeploymentVersionAndRevisionNumberForWorkflowID(
current *deploymentspb.WorkerDeploymentVersion,
currentRevisionNumber int64,
ramping *deploymentspb.WorkerDeploymentVersion,
rampingPercentage float32,
rampingRevisionNumber int64,
workflowId string,
useRampingVersion bool,
) (*deploymentspb.WorkerDeploymentVersion, int64) {
if useRampingVersion && ramping != nil {
return ramping, rampingRevisionNumber
}
// Apply ramp logic using final values
if rampingPercentage <= 0 {
// No ramp
return current, currentRevisionNumber
} else if rampingPercentage == 100 {
return ramping, rampingRevisionNumber
}
// Partial ramp. Decide based on workflow ID
wfRampThreshold := calcRampThreshold(workflowId)
if wfRampThreshold <= float64(rampingPercentage) {
return ramping, rampingRevisionNumber
}
return current, currentRevisionNumber
}
// PickFinalCurrentAndRamping determines the effective "current" and "ramping" deployment versions
// by comparing timestamps from the legacy deployment data (old format) and the RoutingConfig (new format).
// It returns:
// - final current deployment version and its revision number (0 for old format)
// - final ramping deployment version, its revision number (0 for old format), and ramp percentage
//
//revive:disable-next-line:function-result-limit
func PickFinalCurrentAndRamping(
current *deploymentspb.DeploymentVersionData,
ramping *deploymentspb.DeploymentVersionData,
currentVersionRoutingConfig *deploymentpb.RoutingConfig,
rampingVersionRoutingConfig *deploymentpb.RoutingConfig,
) (
finalCurrent *deploymentspb.WorkerDeploymentVersion,
finalCurrentRev int64,
finalCurrentUpdateTime time.Time,
finalRamping *deploymentspb.WorkerDeploymentVersion,
isRamping bool,
finalRampPercentage float32,
finalRampingRev int64,
finalRampingUpdateTime time.Time,
) {
// current: choose newer of old vs new format
oldCurrentTime := current.GetRoutingUpdateTime().AsTime()
newCurrentTime := currentVersionRoutingConfig.GetCurrentVersionChangedTime().AsTime()
// Break ties by choosing the newer format
if newCurrentTime.After(oldCurrentTime) || newCurrentTime.Equal(oldCurrentTime) {
finalCurrent = DeploymentVersionFromDeployment(DeploymentFromExternalDeploymentVersion(currentVersionRoutingConfig.GetCurrentDeploymentVersion()))
finalCurrentRev = currentVersionRoutingConfig.GetRevisionNumber()
finalCurrentUpdateTime = newCurrentTime
} else {
finalCurrent = current.GetVersion()
finalCurrentRev = 0
finalCurrentUpdateTime = oldCurrentTime
}
// ramping: choose newer of old vs new format; new format can change either version or percentage
oldRampingTime := ramping.GetRoutingUpdateTime().AsTime()
newRampingTime := rampingVersionRoutingConfig.GetRampingVersionPercentageChangedTime().AsTime()
// Break ties by choosing the newer format
if newRampingTime.After(oldRampingTime) || newRampingTime.Equal(oldRampingTime) {
finalRamping = DeploymentVersionFromDeployment(DeploymentFromExternalDeploymentVersion(rampingVersionRoutingConfig.GetRampingDeploymentVersion()))
finalRampingRev = rampingVersionRoutingConfig.GetRevisionNumber()
finalRampPercentage = rampingVersionRoutingConfig.GetRampingVersionPercentage()
finalRampingUpdateTime = newRampingTime
// When using the new deployment format, we do not have access to GetRampingSinceTime. Thus, we need to understand if a version is truly ramping or not.
// When using the new deployment format, a version is *not ramping* if it has nil ramping version with ramping version percentage set to 0.
if finalRamping == nil && finalRampPercentage == 0 {
isRamping = false
} else {
isRamping = true
}
} else {
finalRamping = ramping.GetVersion()
finalRampingRev = 0
finalRampPercentage = ramping.GetRampPercentage()
finalRampingUpdateTime = oldRampingTime
// A version can only be ramping if it has a rampingSinceTime.
if ramping.GetRampingSinceTime() == nil {
isRamping = false
} else {
isRamping = true
}
}
return finalCurrent, finalCurrentRev, finalCurrentUpdateTime, finalRamping, isRamping, finalRampPercentage, finalRampingRev, finalRampingUpdateTime
}
// calcRampThreshold returns a number in [0, 100) that is deterministically calculated based on the
// passed id. If id is empty, a random threshold is returned.
func calcRampThreshold(id string) float64 {
if id == "" {
return rand.Float64()
}
h := farm.Fingerprint32([]byte(id))
return 100 * (float64(h) / (float64(math.MaxUint32) + 1))
}
// CalculateTaskQueueVersioningInfo calculates the current and ramping versioning info for a task queue.
//
//revive:disable-next-line:cognitive-complexity,confusing-results,function-result-limit,cyclomatic
func CalculateTaskQueueVersioningInfo(deployments *persistencespb.DeploymentData) (
*deploymentspb.WorkerDeploymentVersion, // current version
int64, // current revision number
time.Time, // current update time
*deploymentspb.WorkerDeploymentVersion, // ramping version
bool, // is ramping (ramping_since_time != nil)
float32, // ramp percentage
int64, // ramping revision number
time.Time, // ramping update time
) {
if deployments == nil {
return nil, 0, time.Time{}, nil, false, 0, 0, time.Time{}
}
var current *deploymentspb.DeploymentVersionData
ramping := deployments.GetUnversionedRampData() // nil if there is no unversioned ramp
// Find current and ramping
// [cleanup-pp-wv]
for _, v := range deployments.GetVersions() {
if v.RoutingUpdateTime != nil && v.GetCurrentSinceTime() != nil {
if t := v.RoutingUpdateTime.AsTime(); t.After(current.GetRoutingUpdateTime().AsTime()) {
current = v
}
}
if v.RoutingUpdateTime != nil && v.GetRampingSinceTime() != nil {
if t := v.RoutingUpdateTime.AsTime(); t.After(ramping.GetRoutingUpdateTime().AsTime()) {
ramping = v
}
}
}
// Find new current and ramping and pass information in DeploymentVersionData when returning to the caller to
// preserve backwards compatibility.
var routingConfigLatestCurrentVersion *deploymentpb.RoutingConfig
var routingConfigLatestRampingVersion *deploymentpb.RoutingConfig
// Track the latest "versioned and TQ is a member" and "unversioned" routing configs
// separately so a versioned current/ramping always wins over an unversioned-but-newer
// entry in another deployment bucket, independent of map iteration order.
//
// Only chose those RoutingConfigs which pass the HasDeploymentVersion check due to the following example case:
// t0: TQ "foo" is in current version A with other TQ's
// t1: All other TQ's are moved to new version B except for "foo".
// t2: New version B is set as the current version.
//
// When this happens, we sync to "foo" that A is no longer the current version by passing in the new routing config. However,
// version B should not be considered as the current version for "foo" because the task-queue is not part of version B.
var latestVersionedCurrent, latestUnversionedCurrent *deploymentpb.RoutingConfig
var latestVersionedRamping, latestUnversionedRamping *deploymentpb.RoutingConfig
for _, deploymentInfo := range deployments.GetDeploymentsData() {
rc := deploymentInfo.GetRoutingConfig()
tCurrent := rc.GetCurrentVersionChangedTime().AsTime()
if HasDeploymentVersion(deployments, DeploymentVersionFromDeployment(DeploymentFromExternalDeploymentVersion(rc.GetCurrentDeploymentVersion()))) {
if tCurrent.After(latestVersionedCurrent.GetCurrentVersionChangedTime().AsTime()) {
latestVersionedCurrent = rc
}
} else if rc.GetCurrentDeploymentVersion() == nil {
if tCurrent.After(latestUnversionedCurrent.GetCurrentVersionChangedTime().AsTime()) {
latestUnversionedCurrent = rc
}
}
tRamping := rc.GetRampingVersionPercentageChangedTime().AsTime()
if HasDeploymentVersion(deployments, DeploymentVersionFromDeployment(DeploymentFromExternalDeploymentVersion(rc.GetRampingDeploymentVersion()))) {
if tRamping.After(latestVersionedRamping.GetRampingVersionPercentageChangedTime().AsTime()) {
latestVersionedRamping = rc
}
} else if rc.GetRampingDeploymentVersion() == nil {
if tRamping.After(latestUnversionedRamping.GetRampingVersionPercentageChangedTime().AsTime()) {
latestUnversionedRamping = rc
}
}
}
if latestVersionedCurrent != nil {
routingConfigLatestCurrentVersion = latestVersionedCurrent
} else {
routingConfigLatestCurrentVersion = latestUnversionedCurrent
}
if latestVersionedRamping != nil {
routingConfigLatestRampingVersion = latestVersionedRamping
} else {
routingConfigLatestRampingVersion = latestUnversionedRamping
}
if routingConfigLatestCurrentVersion.GetCurrentDeploymentVersion() == nil && current.GetVersion() != nil {
// The new current version is not unversioned but belongs to a versioned deployment which synced to the task-queue using the old deployment data format.