diff --git a/pkg/workload/util.go b/pkg/workload/util.go index f19d1d7..c81c769 100644 --- a/pkg/workload/util.go +++ b/pkg/workload/util.go @@ -65,6 +65,19 @@ func CalculateExpectedPartition(total *int32, expectedUpdatedReplicas, partition return max(totalReplicas-expectedUpdatedReplicas, 0) } +// CalculateProgressingPartition calculates the progressing partition based on the total replicas, expected replicas, and the partition in the spec. +// In this function, partition means how many replicas need to be updated. +func CalculateProgressingPartition(total *int32, expectedUpdatedReplicas, partitionInSpec int32) int32 { + totalReplicas := ptr.Deref(total, 0) + + if partitionInSpec >= expectedUpdatedReplicas { + // already updated if the current updated partition is greater than or equal to the expected updated partition + return partitionInSpec + } + + return min(expectedUpdatedReplicas, totalReplicas) +} + // PatchMetadata patches metadata with the given patch func PatchMetadata(meta *metav1.ObjectMeta, patch rolloutv1alpha1.MetadataPatch) { if len(patch.Labels) > 0 { diff --git a/pkg/workload/util_test.go b/pkg/workload/util_test.go index 91ae3a7..b675427 100644 --- a/pkg/workload/util_test.go +++ b/pkg/workload/util_test.go @@ -86,3 +86,64 @@ func TestCalculateExpectedPartition(t *testing.T) { }) } } + +func TestCalculatexProgressingPartition(t *testing.T) { + tests := []struct { + name string + total int32 + expectedReplicas int32 + partitionInSpec int32 + want int32 + wantErr bool + }{ + { + name: "total 10, current partition 0, want to update 1", + total: 10, + expectedReplicas: 1, + partitionInSpec: 0, + want: 1, + wantErr: false, + }, + { + name: "total 10, current partition 5, want to update 1", + total: 10, + expectedReplicas: 1, + partitionInSpec: 5, + want: 5, + wantErr: false, + }, + { + name: "total 10, current partition 10, want to update 1", + total: 10, + expectedReplicas: 1, + partitionInSpec: 10, + want: 10, + wantErr: false, + }, + { + name: "total 10, current partition 15, want to update 0", + total: 10, + expectedReplicas: 0, + partitionInSpec: 15, + want: 15, + wantErr: false, + }, + { + name: "total 10, current partition 0, want to update 15", + total: 10, + expectedReplicas: 15, + partitionInSpec: 0, + want: 10, + wantErr: false, + }, + } + for i := range tests { + tt := tests[i] + t.Run(tt.name, func(t *testing.T) { + got := CalculateProgressingPartition(&tt.total, tt.expectedReplicas, tt.partitionInSpec) + if got != tt.want { + t.Errorf("CalculateExpectedPartition() = %v, want %v", got, tt.want) + } + }) + } +}