From 0347ee0a3a82f2fa89a886b05eea14b9cdd01bb8 Mon Sep 17 00:00:00 2001 From: Marco Bebway Date: Thu, 14 Mar 2024 11:47:46 +0100 Subject: [PATCH] feat: remove v1alpha1 subscription (#517) * feat: remove subscription v1alpha1 * update crd * update docs * codegen * fix tests * Add tests for exact type matching * fix tests * Undo doc changes --- .golangci.yaml | 2 - api/eventing/v1alpha1/condition.go | 259 ---------- api/eventing/v1alpha1/condition_unit_test.go | 486 ------------------ api/eventing/v1alpha1/fixtures_test.go | 186 ------- api/eventing/v1alpha1/groupversion_info.go | 22 - .../v1alpha1/subscription_conversion.go | 323 ------------ .../subscription_conversion_unit_test.go | 409 --------------- api/eventing/v1alpha1/subscription_types.go | 279 ---------- .../v1alpha1/subscription_types_unit_test.go | 150 ------ api/eventing/v1alpha1/subscription_webhook.go | 11 - .../v1alpha1/zz_generated.deepcopy.go | 318 ------------ .../v1alpha1/zz_generated.deepcopy.go | 2 +- cmd/main.go | 8 - ...venting.kyma-project.io_subscriptions.yaml | 257 --------- config/samples/subscription_v1alpha1_js.yaml | 27 - .../common/eventing/testsubscriptioninfo.go | 11 +- hack/e2e/common/eventing/utils.go | 20 +- hack/e2e/common/fixtures/fixtures.go | 55 +- .../testenvironment/test_environment.go | 15 +- hack/e2e/eventing/delivery/delivery_test.go | 17 +- internal/connection/nats/mocks/connection.go | 18 +- pkg/eventing/manager.go | 12 - pkg/eventing/manager_test.go | 42 -- pkg/eventing/mocks/manager.go | 32 +- .../eventmesh/eventmesh.go | 9 - .../jetstream/jetstream.go | 9 - .../mocks/manager_factory.go | 18 +- testing/test_helpers.go | 161 ------ 28 files changed, 117 insertions(+), 3041 deletions(-) delete mode 100644 api/eventing/v1alpha1/condition.go delete mode 100644 api/eventing/v1alpha1/condition_unit_test.go delete mode 100644 api/eventing/v1alpha1/fixtures_test.go delete mode 100644 api/eventing/v1alpha1/groupversion_info.go delete mode 100644 api/eventing/v1alpha1/subscription_conversion.go delete mode 100644 api/eventing/v1alpha1/subscription_conversion_unit_test.go delete mode 100644 api/eventing/v1alpha1/subscription_types.go delete mode 100644 api/eventing/v1alpha1/subscription_types_unit_test.go delete mode 100644 api/eventing/v1alpha1/subscription_webhook.go delete mode 100644 api/eventing/v1alpha1/zz_generated.deepcopy.go delete mode 100644 config/samples/subscription_v1alpha1_js.yaml diff --git a/.golangci.yaml b/.golangci.yaml index 0afa5c2d1..30403d666 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -84,8 +84,6 @@ linters-settings: alias: kunstructured - pkg: k8s.io/apimachinery/pkg/apis/meta/v1 alias: kmetav1 - - pkg: github.com/kyma-project/eventing-manager/api/eventing/v1alpha1 - alias: eventingv1alpha1 - pkg: github.com/kyma-project/eventing-manager/api/eventing/v1alpha2 alias: eventingv1alpha2 - pkg: github.com/kyma-project/eventing-manager/api/operator/v1alpha1 diff --git a/api/eventing/v1alpha1/condition.go b/api/eventing/v1alpha1/condition.go deleted file mode 100644 index 9b8e52191..000000000 --- a/api/eventing/v1alpha1/condition.go +++ /dev/null @@ -1,259 +0,0 @@ -package v1alpha1 - -import ( - "fmt" - - kcorev1 "k8s.io/api/core/v1" - kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -type ConditionType string - -const ( - ConditionSubscribed ConditionType = "Subscribed" - ConditionSubscriptionActive ConditionType = "Subscription active" - ConditionAPIRuleStatus ConditionType = "APIRule status" - ConditionWebhookCallStatus ConditionType = "Webhook call status" - - ConditionPublisherProxyReady ConditionType = "Publisher Proxy Ready" - ConditionControllerReady ConditionType = "Subscription Controller Ready" -) - -type Condition struct { - // Short description of the condition. - Type ConditionType `json:"type,omitempty"` - // Status of the condition. The value is either `True`, `False`, or `Unknown`. - Status kcorev1.ConditionStatus `json:"status"` - // Defines the date of the last condition status change. - LastTransitionTime kmetav1.Time `json:"lastTransitionTime,omitempty"` - // Defines the reason for the condition status change. - Reason ConditionReason `json:"reason,omitempty"` - // Provides more details about the condition status change. - Message string `json:"message,omitempty"` -} - -type ConditionReason string - -const ( - // BEB Conditions. - ConditionReasonSubscriptionActive ConditionReason = "BEB Subscription active" - ConditionReasonSubscriptionNotActive ConditionReason = "BEB Subscription not active" - ConditionReasonSubscriptionDeleted ConditionReason = "BEB Subscription deleted" - ConditionReasonAPIRuleStatusReady ConditionReason = "APIRule status ready" - ConditionReasonAPIRuleStatusNotReady ConditionReason = "APIRule status not ready" - - // Common backend Conditions. - ConditionReasonSubscriptionControllerReady ConditionReason = "Subscription controller started" - ConditionReasonSubscriptionControllerNotReady ConditionReason = "Subscription controller not ready" - ConditionReasonPublisherDeploymentReady ConditionReason = "Publisher proxy deployment ready" - ConditionReasonPublisherDeploymentNotReady ConditionReason = "Publisher proxy deployment not ready" -) - -// initializeConditions sets unset conditions to Unknown. -func initializeConditions(initialConditions, currentConditions []Condition) []Condition { - givenConditions := make(map[ConditionType]Condition) - - // create map of Condition per ConditionType - for _, condition := range currentConditions { - givenConditions[condition.Type] = condition - } - - finalConditions := currentConditions - // check if every Condition is present in the current Conditions - for _, expectedCondition := range initialConditions { - if _, ok := givenConditions[expectedCondition.Type]; !ok { - // and add it if it is missing - finalConditions = append(finalConditions, expectedCondition) - } - } - return finalConditions -} - -// InitializeConditions sets unset Subscription conditions to Unknown. -func (s *SubscriptionStatus) InitializeConditions() { - initialConditions := MakeSubscriptionConditions() - s.Conditions = initializeConditions(initialConditions, s.Conditions) -} - -func (s SubscriptionStatus) IsReady() bool { - if !ContainSameConditionTypes(MakeSubscriptionConditions(), s.Conditions) { - return false - } - - // the subscription is ready if all its conditions are evaluated to true - for _, c := range s.Conditions { - if c.Status != kcorev1.ConditionTrue { - return false - } - } - return true -} - -func (s SubscriptionStatus) FindCondition(conditionType ConditionType) *Condition { - for _, condition := range s.Conditions { - if conditionType == condition.Type { - return &condition - } - } - return nil -} - -// ShouldUpdateReadyStatus checks if there is a mismatch between the -// subscription Ready Status and the Ready status of all the conditions. -func (s SubscriptionStatus) ShouldUpdateReadyStatus() bool { - if !s.Ready && s.IsReady() || s.Ready && !s.IsReady() { - return true - } - return false -} - -// MakeSubscriptionConditions creates a map of all conditions which the Subscription should have. -func MakeSubscriptionConditions() []Condition { - conditions := []Condition{ - { - Type: ConditionAPIRuleStatus, - LastTransitionTime: kmetav1.Now(), - Status: kcorev1.ConditionUnknown, - }, - { - Type: ConditionSubscribed, - LastTransitionTime: kmetav1.Now(), - Status: kcorev1.ConditionUnknown, - }, - { - Type: ConditionSubscriptionActive, - LastTransitionTime: kmetav1.Now(), - Status: kcorev1.ConditionUnknown, - }, - { - Type: ConditionWebhookCallStatus, - LastTransitionTime: kmetav1.Now(), - Status: kcorev1.ConditionUnknown, - }, - } - return conditions -} - -func ContainSameConditionTypes(conditions1, conditions2 []Condition) bool { - if len(conditions1) != len(conditions2) { - return false - } - - for _, condition := range conditions1 { - if !containConditionType(conditions2, condition.Type) { - return false - } - } - - return true -} - -func containConditionType(conditions []Condition, conditionType ConditionType) bool { - for _, condition := range conditions { - if condition.Type == conditionType { - return true - } - } - - return false -} - -func MakeCondition(conditionType ConditionType, reason ConditionReason, - status kcorev1.ConditionStatus, message string, -) Condition { - return Condition{ - Type: conditionType, - Status: status, - LastTransitionTime: kmetav1.Now(), - Reason: reason, - Message: message, - } -} - -func (s *SubscriptionStatus) IsConditionSubscribed() bool { - for _, condition := range s.Conditions { - if condition.Type == ConditionSubscribed && condition.Status == kcorev1.ConditionTrue { - return true - } - } - return false -} - -func (s *SubscriptionStatus) IsConditionWebhookCall() bool { - for _, condition := range s.Conditions { - if condition.Type == ConditionWebhookCallStatus && - (condition.Status == kcorev1.ConditionTrue || condition.Status == kcorev1.ConditionUnknown) { - return true - } - } - return false -} - -func (s *SubscriptionStatus) GetConditionAPIRuleStatus() kcorev1.ConditionStatus { - for _, condition := range s.Conditions { - if condition.Type == ConditionAPIRuleStatus { - return condition.Status - } - } - return kcorev1.ConditionUnknown -} - -func (s *SubscriptionStatus) SetConditionAPIRuleStatus(err error) { - reason := ConditionReasonAPIRuleStatusReady - status := kcorev1.ConditionTrue - message := "" - if err != nil { - reason = ConditionReasonAPIRuleStatusNotReady - status = kcorev1.ConditionFalse - message = err.Error() - } - - newConditions := []Condition{MakeCondition(ConditionAPIRuleStatus, reason, status, message)} - for _, condition := range s.Conditions { - if condition.Type == ConditionAPIRuleStatus { - continue - } - newConditions = append(newConditions, condition) - } - s.Conditions = newConditions -} - -func CreateMessageForConditionReasonSubscriptionCreated(bebName string) string { - return fmt.Sprintf("BEB-subscription-name=%s", bebName) -} - -// ConditionsEquals checks if two list of conditions are equal. -func ConditionsEquals(existing, expected []Condition) bool { - // not equal if length is different - if len(existing) != len(expected) { - return false - } - - // compile map of Conditions per ConditionType - existingMap := make(map[ConditionType]Condition, len(existing)) - for _, value := range existing { - existingMap[value.Type] = value - } - - for _, value := range expected { - if !ConditionEquals(existingMap[value.Type], value) { - return false - } - } - - return true -} - -// ConditionEquals checks if two conditions are equal. -func ConditionEquals(existing, expected Condition) bool { - isTypeEqual := existing.Type == expected.Type - isStatusEqual := existing.Status == expected.Status - isReasonEqual := existing.Reason == expected.Reason - isMessageEqual := existing.Message == expected.Message - - if !isStatusEqual || !isReasonEqual || !isMessageEqual || !isTypeEqual { - return false - } - - return true -} diff --git a/api/eventing/v1alpha1/condition_unit_test.go b/api/eventing/v1alpha1/condition_unit_test.go deleted file mode 100644 index a6cb34c0d..000000000 --- a/api/eventing/v1alpha1/condition_unit_test.go +++ /dev/null @@ -1,486 +0,0 @@ -package v1alpha1_test - -import ( - "reflect" - "testing" - "time" - - kcorev1 "k8s.io/api/core/v1" - kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" - - . "github.com/onsi/gomega" -) - -func Test_InitializeSubscriptionConditions(t *testing.T) { - t.Parallel() - tests := []struct { - name string - givenConditions []v1alpha1.Condition - }{ - { - name: "Conditions empty", - givenConditions: v1alpha1.MakeSubscriptionConditions(), - }, - { - name: "Conditions partially initialized", - givenConditions: []v1alpha1.Condition{ - { - Type: v1alpha1.ConditionSubscribed, - LastTransitionTime: kmetav1.Now(), - Status: kcorev1.ConditionUnknown, - }, - }, - }, - } - - for _, tt := range tests { - testcase := tt - t.Run(testcase.name, func(t *testing.T) { - t.Parallel() - // given - g := NewGomegaWithT(t) - subStatus := v1alpha1.SubscriptionStatus{} - subStatus.Conditions = testcase.givenConditions - wantConditionTypes := []v1alpha1.ConditionType{ - v1alpha1.ConditionSubscribed, - v1alpha1.ConditionSubscriptionActive, - v1alpha1.ConditionAPIRuleStatus, - v1alpha1.ConditionWebhookCallStatus, - } - - // when - subStatus.InitializeConditions() - - // then - g.Expect(subStatus.Conditions).To(HaveLen(len(wantConditionTypes))) - foundConditionTypes := make([]v1alpha1.ConditionType, 0) - for _, condition := range subStatus.Conditions { - g.Expect(condition.Status).To(BeEquivalentTo(kcorev1.ConditionUnknown)) - foundConditionTypes = append(foundConditionTypes, condition.Type) - } - g.Expect(wantConditionTypes).To(ConsistOf(foundConditionTypes)) - }) - } -} - -func Test_IsReady(t *testing.T) { - t.Parallel() - testCases := []struct { - name string - givenConditions []v1alpha1.Condition - wantReadyStatus bool - }{ - { - name: "should not be ready if conditions are nil", - givenConditions: nil, - wantReadyStatus: false, - }, - { - name: "should not be ready if conditions are empty", - givenConditions: []v1alpha1.Condition{{}}, - wantReadyStatus: false, - }, - { - name: "should not be ready if only ConditionSubscribed is available and true", - givenConditions: []v1alpha1.Condition{{Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionTrue}}, - wantReadyStatus: false, - }, - { - name: "should not be ready if only ConditionSubscriptionActive is available and true", - givenConditions: []v1alpha1.Condition{{ - Type: v1alpha1.ConditionSubscriptionActive, - Status: kcorev1.ConditionTrue, - }}, - wantReadyStatus: false, - }, - { - name: "should not be ready if only ConditionAPIRuleStatus is available and true", - givenConditions: []v1alpha1.Condition{{ - Type: v1alpha1.ConditionAPIRuleStatus, - Status: kcorev1.ConditionTrue, - }}, - wantReadyStatus: false, - }, - { - name: "should not be ready if all conditions are unknown", - givenConditions: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionUnknown}, - {Type: v1alpha1.ConditionSubscriptionActive, Status: kcorev1.ConditionUnknown}, - {Type: v1alpha1.ConditionAPIRuleStatus, Status: kcorev1.ConditionUnknown}, - }, - wantReadyStatus: false, - }, - { - name: "should not be ready if all conditions are false", - givenConditions: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionFalse}, - {Type: v1alpha1.ConditionSubscriptionActive, Status: kcorev1.ConditionFalse}, - {Type: v1alpha1.ConditionAPIRuleStatus, Status: kcorev1.ConditionFalse}, - }, - wantReadyStatus: false, - }, - { - name: "should be ready if all conditions are true", - givenConditions: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionTrue}, - {Type: v1alpha1.ConditionSubscriptionActive, Status: kcorev1.ConditionTrue}, - {Type: v1alpha1.ConditionAPIRuleStatus, Status: kcorev1.ConditionTrue}, - {Type: v1alpha1.ConditionWebhookCallStatus, Status: kcorev1.ConditionTrue}, - }, - wantReadyStatus: true, - }, - } - - status := v1alpha1.SubscriptionStatus{} - for _, tc := range testCases { - testcase := tc - t.Run(testcase.name, func(t *testing.T) { - t.Parallel() - status.Conditions = testcase.givenConditions - if gotReadyStatus := status.IsReady(); testcase.wantReadyStatus != gotReadyStatus { - t.Errorf("Subscription status is not valid, want: %v but got: %v", testcase.wantReadyStatus, gotReadyStatus) - } - }) - } -} - -func Test_FindCondition(t *testing.T) { - t.Parallel() - currentTime := kmetav1.NewTime(time.Now()) - - testCases := []struct { - name string - givenConditions []v1alpha1.Condition - findConditionType v1alpha1.ConditionType - wantCondition *v1alpha1.Condition - }{ - { - name: "should be able to find the present condition", - givenConditions: []v1alpha1.Condition{ - { - Type: v1alpha1.ConditionSubscribed, - Status: kcorev1.ConditionTrue, - LastTransitionTime: currentTime, - }, { - Type: v1alpha1.ConditionSubscriptionActive, - Status: kcorev1.ConditionTrue, - LastTransitionTime: currentTime, - }, { - Type: v1alpha1.ConditionAPIRuleStatus, - Status: kcorev1.ConditionTrue, - LastTransitionTime: currentTime, - }, { - Type: v1alpha1.ConditionWebhookCallStatus, - Status: kcorev1.ConditionTrue, - LastTransitionTime: currentTime, - }, - }, - findConditionType: v1alpha1.ConditionSubscriptionActive, - wantCondition: &v1alpha1.Condition{ - Type: v1alpha1.ConditionSubscriptionActive, - Status: kcorev1.ConditionTrue, - LastTransitionTime: currentTime, - }, - }, - { - name: "should not be able to find the non-present condition", - givenConditions: []v1alpha1.Condition{{ - Type: v1alpha1.ConditionSubscribed, - Status: kcorev1.ConditionTrue, - LastTransitionTime: currentTime, - }, { - Type: v1alpha1.ConditionAPIRuleStatus, - Status: kcorev1.ConditionTrue, - LastTransitionTime: currentTime, - }, { - Type: v1alpha1.ConditionWebhookCallStatus, - Status: kcorev1.ConditionTrue, - LastTransitionTime: currentTime, - }}, - findConditionType: v1alpha1.ConditionSubscriptionActive, - wantCondition: nil, - }, - } - - status := v1alpha1.SubscriptionStatus{} - for _, tc := range testCases { - testcase := tc - t.Run(testcase.name, func(t *testing.T) { - t.Parallel() - status.Conditions = testcase.givenConditions - gotCondition := status.FindCondition(testcase.findConditionType) - - if !reflect.DeepEqual(testcase.wantCondition, gotCondition) { - t.Errorf("Subscription FindCondition failed, want: %v but got: %v", testcase.wantCondition, gotCondition) - } - }) - } -} - -func Test_ShouldUpdateReadyStatus(t *testing.T) { - t.Parallel() - testCases := []struct { - name string - subscriptionReady bool - subscriptionConditions []v1alpha1.Condition - wantStatus bool - }{ - { - name: "should not update if the subscription is ready and the conditions are ready", - subscriptionReady: true, - subscriptionConditions: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionTrue}, - {Type: v1alpha1.ConditionSubscriptionActive, Status: kcorev1.ConditionTrue}, - {Type: v1alpha1.ConditionAPIRuleStatus, Status: kcorev1.ConditionTrue}, - {Type: v1alpha1.ConditionWebhookCallStatus, Status: kcorev1.ConditionTrue}, - }, - wantStatus: false, - }, - { - name: "should not update if the subscription is not ready and the conditions are not ready", - subscriptionReady: false, - subscriptionConditions: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionFalse}, - {Type: v1alpha1.ConditionSubscriptionActive, Status: kcorev1.ConditionFalse}, - {Type: v1alpha1.ConditionAPIRuleStatus, Status: kcorev1.ConditionFalse}, - {Type: v1alpha1.ConditionWebhookCallStatus, Status: kcorev1.ConditionFalse}, - }, - wantStatus: false, - }, - { - name: "should update if the subscription is not ready and the conditions are ready", - subscriptionReady: false, - subscriptionConditions: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionTrue}, - {Type: v1alpha1.ConditionSubscriptionActive, Status: kcorev1.ConditionTrue}, - {Type: v1alpha1.ConditionAPIRuleStatus, Status: kcorev1.ConditionTrue}, - {Type: v1alpha1.ConditionWebhookCallStatus, Status: kcorev1.ConditionTrue}, - }, - wantStatus: true, - }, - { - name: "should update if the subscription is ready and the conditions are not ready", - subscriptionReady: true, - subscriptionConditions: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionFalse}, - {Type: v1alpha1.ConditionSubscriptionActive, Status: kcorev1.ConditionFalse}, - {Type: v1alpha1.ConditionAPIRuleStatus, Status: kcorev1.ConditionFalse}, - {Type: v1alpha1.ConditionWebhookCallStatus, Status: kcorev1.ConditionFalse}, - }, - wantStatus: true, - }, - { - name: "should update if the subscription is ready and some of the conditions are missing", - subscriptionReady: true, - subscriptionConditions: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionUnknown}, - }, - wantStatus: true, - }, - { - name: "should not update if the subscription is not ready and some of the conditions are missing", - subscriptionReady: false, - subscriptionConditions: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionUnknown}, - }, - wantStatus: false, - }, - { - name: "should update if the subscription is ready and the status of the conditions are unknown", - subscriptionReady: true, - subscriptionConditions: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionUnknown}, - {Type: v1alpha1.ConditionSubscriptionActive, Status: kcorev1.ConditionUnknown}, - {Type: v1alpha1.ConditionAPIRuleStatus, Status: kcorev1.ConditionUnknown}, - {Type: v1alpha1.ConditionWebhookCallStatus, Status: kcorev1.ConditionUnknown}, - }, - wantStatus: true, - }, - } - - status := v1alpha1.SubscriptionStatus{} - for _, tc := range testCases { - testcase := tc - t.Run(testcase.name, func(t *testing.T) { - t.Parallel() - status.Conditions = testcase.subscriptionConditions - status.Ready = testcase.subscriptionReady - if gotStatus := status.ShouldUpdateReadyStatus(); testcase.wantStatus != gotStatus { - t.Errorf("ShouldUpdateReadyStatus is not valid, want: %v but got: %v", testcase.wantStatus, gotStatus) - } - }) - } -} - -func Test_conditionsEquals(t *testing.T) { - t.Parallel() - testCases := []struct { - name string - conditionsSet1 []v1alpha1.Condition - conditionsSet2 []v1alpha1.Condition - wantEqualStatus bool - }{ - { - name: "should not be equal if the number of conditions are not equal", - conditionsSet1: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionTrue}, - }, - conditionsSet2: []v1alpha1.Condition{}, - wantEqualStatus: false, - }, - { - name: "should be equal if the conditions are the same", - conditionsSet1: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionTrue}, - {Type: v1alpha1.ConditionAPIRuleStatus, Status: kcorev1.ConditionTrue}, - }, - conditionsSet2: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionTrue}, - {Type: v1alpha1.ConditionAPIRuleStatus, Status: kcorev1.ConditionTrue}, - }, - wantEqualStatus: true, - }, - { - name: "should not be equal if the condition types are different", - conditionsSet1: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionTrue}, - {Type: v1alpha1.ConditionAPIRuleStatus, Status: kcorev1.ConditionTrue}, - }, - conditionsSet2: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionWebhookCallStatus, Status: kcorev1.ConditionTrue}, - {Type: v1alpha1.ConditionSubscriptionActive, Status: kcorev1.ConditionTrue}, - }, - wantEqualStatus: false, - }, - { - name: "should not be equal if the condition types are the same but the status is different", - conditionsSet1: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionTrue}, - }, - conditionsSet2: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionFalse}, - }, - wantEqualStatus: false, - }, - { - name: "should not be equal if the condition types are different but the status is the same", - conditionsSet1: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionTrue}, - {Type: v1alpha1.ConditionAPIRuleStatus, Status: kcorev1.ConditionFalse}, - }, - conditionsSet2: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionTrue}, - {Type: v1alpha1.ConditionAPIRuleStatus, Status: kcorev1.ConditionTrue}, - }, - wantEqualStatus: false, - }, - { - name: "should not be equal if the condition types are different and an empty key is referenced", - conditionsSet1: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionTrue}, - {Type: v1alpha1.ConditionAPIRuleStatus, Status: kcorev1.ConditionTrue}, - }, - conditionsSet2: []v1alpha1.Condition{ - {Type: v1alpha1.ConditionAPIRuleStatus, Status: kcorev1.ConditionTrue}, - {Type: v1alpha1.ConditionControllerReady, Status: kcorev1.ConditionTrue}, - }, - wantEqualStatus: false, - }, - } - for _, tc := range testCases { - testcase := tc - t.Run(testcase.name, func(t *testing.T) { - t.Parallel() - want := testcase.wantEqualStatus - actual := v1alpha1.ConditionsEquals(testcase.conditionsSet1, testcase.conditionsSet2) - if actual != want { - t.Errorf("The list of conditions are not equal, want: %v but got: %v", want, actual) - } - }) - } -} - -func Test_conditionEquals(t *testing.T) { - testCases := []struct { - name string - condition1 v1alpha1.Condition - condition2 v1alpha1.Condition - wantEqualStatus bool - }{ - { - name: "should not be equal if the types are the same but the status is different", - condition1: v1alpha1.Condition{ - Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionTrue, - }, - - condition2: v1alpha1.Condition{ - Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionUnknown, - }, - wantEqualStatus: false, - }, - { - name: "should not be equal if the types are different but the status is the same", - condition1: v1alpha1.Condition{ - Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionTrue, - }, - - condition2: v1alpha1.Condition{ - Type: v1alpha1.ConditionAPIRuleStatus, Status: kcorev1.ConditionTrue, - }, - wantEqualStatus: false, - }, - { - name: "should not be equal if the message fields are different", - condition1: v1alpha1.Condition{ - Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionTrue, Message: "", - }, - - condition2: v1alpha1.Condition{ - Type: v1alpha1.ConditionSubscribed, Status: kcorev1.ConditionTrue, Message: "some message", - }, - wantEqualStatus: false, - }, - { - name: "should not be equal if the reason fields are different", - condition1: v1alpha1.Condition{ - Type: v1alpha1.ConditionSubscribed, - Status: kcorev1.ConditionTrue, - Reason: v1alpha1.ConditionReasonSubscriptionDeleted, - }, - - condition2: v1alpha1.Condition{ - Type: v1alpha1.ConditionSubscribed, - Status: kcorev1.ConditionTrue, - Reason: v1alpha1.ConditionReasonSubscriptionActive, - }, - wantEqualStatus: false, - }, - { - name: "should be equal if all the fields are the same", - condition1: v1alpha1.Condition{ - Type: v1alpha1.ConditionAPIRuleStatus, - Status: kcorev1.ConditionFalse, - Reason: v1alpha1.ConditionReasonAPIRuleStatusNotReady, - Message: "API Rule is not ready", - }, - condition2: v1alpha1.Condition{ - Type: v1alpha1.ConditionAPIRuleStatus, - Status: kcorev1.ConditionFalse, - Reason: v1alpha1.ConditionReasonAPIRuleStatusNotReady, - Message: "API Rule is not ready", - }, - wantEqualStatus: true, - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - want := tc.wantEqualStatus - actual := v1alpha1.ConditionEquals(tc.condition1, tc.condition2) - if want != actual { - t.Errorf("The conditions are not equal, want: %v but got: %v", want, actual) - } - }) - } -} diff --git a/api/eventing/v1alpha1/fixtures_test.go b/api/eventing/v1alpha1/fixtures_test.go deleted file mode 100644 index 07fdc3b4f..000000000 --- a/api/eventing/v1alpha1/fixtures_test.go +++ /dev/null @@ -1,186 +0,0 @@ -package v1alpha1_test - -import ( - "strconv" - - kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" - "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - "github.com/kyma-project/eventing-manager/pkg/utils" - eventingtesting "github.com/kyma-project/eventing-manager/testing" -) - -const ( - eventSource = "source" - orderCreatedEventType = "prefix.noapp.order.created.v1" - orderUpdatedEventType = "prefix.app.order.updated.v1" - orderDeletedEventType = "prefix.noapp.order.deleted.v1" - orderDeletedEventTypeNonClean = "prefix.noapp.order.deleted_&.v1" - orderProcessedEventType = "prefix.noapp.order.processed.v1" -) - -const ( - defaultName = "test" - defaultNamespace = "test-namespace" - defaultSink = "https://svc2.test.local" - defaultID = "id" - defaultMaxInFlight = 10 - defaultStatusReady = true -) - -var v2DefaultConditions = []v1alpha2.Condition{ - { - Type: v1alpha2.ConditionSubscriptionActive, - Status: "true", - }, - { - Type: v1alpha2.ConditionSubscribed, - Status: "false", - }, -} - -func newDefaultSubscription(opts ...eventingtesting.SubscriptionV1alpha1Opt) *v1alpha1.Subscription { - var defaultConditions []v1alpha1.Condition - for _, condition := range v2DefaultConditions { - defaultConditions = append(defaultConditions, v1alpha1.ConditionV2ToV1(condition)) - } - newSub := &v1alpha1.Subscription{ - TypeMeta: kmetav1.TypeMeta{ - Kind: "Subscription", - APIVersion: "eventing.kyma-project.io/v1alpha1", - }, - ObjectMeta: kmetav1.ObjectMeta{ - Name: defaultName, - Namespace: defaultNamespace, - }, - Spec: v1alpha1.SubscriptionSpec{ - Sink: defaultSink, - ID: defaultID, - Config: &v1alpha1.SubscriptionConfig{MaxInFlightMessages: defaultMaxInFlight}, - }, - Status: v1alpha1.SubscriptionStatus{ - Conditions: defaultConditions, - Ready: defaultStatusReady, - Config: &v1alpha1.SubscriptionConfig{MaxInFlightMessages: defaultMaxInFlight}, - }, - } - for _, o := range opts { - o(newSub) - } - - // remove nats specific field in eventmesh case - if newSub.Status.EmsSubscriptionStatus != nil { - newSub.Spec.Config = nil - newSub.Status.Config = nil - } - - return newSub -} - -// extend the v1 Subscription helpers with Status fields - -func v1WithWebhookAuthForBEB() eventingtesting.SubscriptionV1alpha1Opt { - return func(s *v1alpha1.Subscription) { - s.Spec.Protocol = "BEB" - s.Spec.ProtocolSettings = &v1alpha1.ProtocolSettings{ - ContentMode: func() *string { - contentMode := v1alpha1.ProtocolSettingsContentModeBinary - return &contentMode - }(), - Qos: func() *string { - qos := "AT_LEAST_ONCE" - return &qos - }(), - ExemptHandshake: utils.BoolPtr(true), - WebhookAuth: &v1alpha1.WebhookAuth{ - Type: "oauth2", - GrantType: "client_credentials", - ClientID: "xxx", - ClientSecret: "xxx", - TokenURL: "https://oauth2.xxx.com/oauth2/token", - Scope: []string{"guid-identifier", "root"}, - }, - } - } -} - -func v1WithBEBStatusFields() eventingtesting.SubscriptionV1alpha1Opt { - return func(s *v1alpha1.Subscription) { - s.Status.Ev2hash = 123 - s.Status.ExternalSink = "testlink.com" - s.Status.FailedActivation = "123156464672" - s.Status.APIRuleName = "APIRule" - s.Status.EmsSubscriptionStatus = &v1alpha1.EmsSubscriptionStatus{ - SubscriptionStatus: "not active", - SubscriptionStatusReason: "reason", - LastSuccessfulDelivery: "", - LastFailedDelivery: "1345613234", - LastFailedDeliveryReason: "failed", - } - } -} - -func newV2DefaultSubscription(opts ...eventingtesting.SubscriptionOpt) *v1alpha2.Subscription { - newSub := &v1alpha2.Subscription{ - TypeMeta: kmetav1.TypeMeta{ - Kind: "Subscription", - APIVersion: "eventing.kyma-project.io/v1alpha2", - }, - ObjectMeta: kmetav1.ObjectMeta{ - Name: defaultName, - Namespace: defaultNamespace, - }, - Spec: v1alpha2.SubscriptionSpec{ - TypeMatching: v1alpha2.TypeMatchingExact, - Sink: defaultSink, - ID: defaultID, - Config: map[string]string{ - v1alpha2.MaxInFlightMessages: strconv.Itoa(defaultMaxInFlight), - }, - }, - Status: v1alpha2.SubscriptionStatus{ - Ready: defaultStatusReady, - Conditions: v2DefaultConditions, - }, - } - for _, o := range opts { - o(newSub) - } - - return newSub -} - -// extend the v2 Subscription helpers with Status fields - -func v2WithBEBStatusFields() eventingtesting.SubscriptionOpt { - return func(s *v1alpha2.Subscription) { - s.Status.Backend.Ev2hash = 123 - s.Status.Backend.ExternalSink = "testlink.com" - s.Status.Backend.FailedActivation = "123156464672" - s.Status.Backend.APIRuleName = "APIRule" - s.Status.Backend.EventMeshSubscriptionStatus = &v1alpha2.EventMeshSubscriptionStatus{ - Status: "not active", - StatusReason: "reason", - LastSuccessfulDelivery: "", - LastFailedDelivery: "1345613234", - LastFailedDeliveryReason: "failed", - } - } -} - -func v2WithStatusTypes(statusTypes []v1alpha2.EventType) eventingtesting.SubscriptionOpt { - return func(sub *v1alpha2.Subscription) { - if statusTypes == nil { - sub.Status.InitializeEventTypes() - return - } - sub.Status.Types = statusTypes - } -} - -func v2WithStatusJetStreamTypes(types []v1alpha2.JetStreamTypes) eventingtesting.SubscriptionOpt { - return func(sub *v1alpha2.Subscription) { - sub.Status.Backend.Types = types - } -} diff --git a/api/eventing/v1alpha1/groupversion_info.go b/api/eventing/v1alpha1/groupversion_info.go deleted file mode 100644 index 7b7f8d502..000000000 --- a/api/eventing/v1alpha1/groupversion_info.go +++ /dev/null @@ -1,22 +0,0 @@ -// Package v1alpha1 contains API Schema definitions for the eventing v1alpha1 API group -// +kubebuilder:object:generate=true -// +groupName=eventing.kyma-project.io -// -//nolint:gochecknoglobals // required for utilizing the API -package v1alpha1 - -import ( - "k8s.io/apimachinery/pkg/runtime/schema" - "sigs.k8s.io/controller-runtime/pkg/scheme" -) - -var ( - // GroupVersion is group version used to register these objects. - GroupVersion = schema.GroupVersion{Group: "eventing.kyma-project.io", Version: "v1alpha1"} - - // SchemeBuilder is used to add go types to the GroupVersionKind scheme. - SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} - - // AddToScheme adds the types in this group-version to the given scheme. - AddToScheme = SchemeBuilder.AddToScheme -) diff --git a/api/eventing/v1alpha1/subscription_conversion.go b/api/eventing/v1alpha1/subscription_conversion.go deleted file mode 100644 index ebb170cc4..000000000 --- a/api/eventing/v1alpha1/subscription_conversion.go +++ /dev/null @@ -1,323 +0,0 @@ -package v1alpha1 - -import ( - "fmt" - "strconv" - "strings" - - "github.com/pkg/errors" - "sigs.k8s.io/controller-runtime/pkg/conversion" - - "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - "github.com/kyma-project/eventing-manager/pkg/backend/eventtype" -) - -const ( - ErrorHubVersionMsg = "hub version is not the expected v1alpha2 version" - ErrorMultipleSourceMsg = "subscription contains more than 1 eventSource" -) - -var v1alpha1TypeCleaner eventtype.Cleaner //nolint:gochecknoglobals // using global var because there is no runtime -// object to hold this instance. - -func InitializeEventTypeCleaner(cleaner eventtype.Cleaner) { - v1alpha1TypeCleaner = cleaner -} - -// ConvertTo converts this Subscription in version v1 to the Hub version v2. -func (s *Subscription) ConvertTo(dstRaw conversion.Hub) error { - dst, ok := dstRaw.(*v1alpha2.Subscription) - if !ok { - return errors.Errorf(ErrorHubVersionMsg) - } - return V1ToV2(s, dst) -} - -// V1ToV2 copies the v1alpha1-type field values into v1alpha2-type field values. -func V1ToV2(src *Subscription, dst *v1alpha2.Subscription) error { - // ObjectMeta - dst.ObjectMeta = src.ObjectMeta - - // SPEC fields - - dst.Spec.ID = src.Spec.ID - dst.Spec.Sink = src.Spec.Sink - dst.Spec.Source = "" - - src.setV2TypeMatching(dst) - - // protocol fields - src.setV2ProtocolFields(dst) - - // Types - if err := src.setV2SpecTypes(dst); err != nil { - return err - } - - // Config - src.natsSpecConfigToV2(dst) - - return nil -} - -// ConvertFrom converts this Subscription from the Hub version (v2) to v1. -func (s *Subscription) ConvertFrom(srcRaw conversion.Hub) error { - src, ok := srcRaw.(*v1alpha2.Subscription) - if !ok { - return errors.Errorf(ErrorHubVersionMsg) - } - return V2ToV1(s, src) -} - -// V2ToV1 copies the v1alpha2-type field values into v1alpha1-type field values. -func V2ToV1(dst *Subscription, src *v1alpha2.Subscription) error { - // ObjectMeta - dst.ObjectMeta = src.ObjectMeta - - dst.Spec.ID = src.Spec.ID - dst.Spec.Sink = src.Spec.Sink - - dst.setV1ProtocolFields(src) - - dst.Spec.Filter = &BEBFilters{ - Filters: []*EventMeshFilter{}, - } - - for _, eventType := range src.Spec.Types { - filter := &EventMeshFilter{ - EventSource: &Filter{ - Property: "source", - Type: fmt.Sprint(v1alpha2.TypeMatchingExact), - Value: src.Spec.Source, - }, - EventType: &Filter{ - Type: fmt.Sprint(v1alpha2.TypeMatchingExact), - Property: "type", - Value: eventType, - }, - } - dst.Spec.Filter.Filters = append(dst.Spec.Filter.Filters, filter) - } - - if src.Spec.Config != nil { - if err := dst.natsSpecConfigToV1(src); err != nil { - return err - } - } - - // Conditions - for _, condition := range src.Status.Conditions { - dst.Status.Conditions = append(dst.Status.Conditions, ConditionV2ToV1(condition)) - } - - dst.Status.Ready = src.Status.Ready - - dst.setV1CleanEvenTypes(src) - dst.bebBackendStatusToV1(src) - dst.natsBackendStatusToV1(src) - - return nil -} - -// setV2TypeMatching sets the default typeMatching on the v1alpha2 Subscription version. -func (s *Subscription) setV2TypeMatching(dst *v1alpha2.Subscription) { - dst.Spec.TypeMatching = v1alpha2.TypeMatchingExact -} - -// setV2ProtocolFields converts the protocol-related fields from v1alpha1 to v1alpha2 Subscription version. -func (s *Subscription) setV2ProtocolFields(dst *v1alpha2.Subscription) { - dst.Spec.Config = map[string]string{} - if s.Spec.Protocol != "" { - dst.Spec.Config[v1alpha2.Protocol] = s.Spec.Protocol - } - // protocol settings - if s.Spec.ProtocolSettings != nil { - s.setProtocolSettings(dst) - } -} - -func (s *Subscription) setProtocolSettings(dst *v1alpha2.Subscription) { - if s.Spec.ProtocolSettings.ContentMode != nil { - dst.Spec.Config[v1alpha2.ProtocolSettingsContentMode] = *s.Spec.ProtocolSettings.ContentMode - } - if s.Spec.ProtocolSettings.ExemptHandshake != nil { - dst.Spec.Config[v1alpha2.ProtocolSettingsExemptHandshake] = strconv.FormatBool(*s.Spec.ProtocolSettings.ExemptHandshake) - } - if s.Spec.ProtocolSettings.Qos != nil { - dst.Spec.Config[v1alpha2.ProtocolSettingsQos] = *s.Spec.ProtocolSettings.Qos - } - // webhookAuth fields - if s.Spec.ProtocolSettings.WebhookAuth != nil { - if s.Spec.ProtocolSettings.WebhookAuth.Type != "" { - dst.Spec.Config[v1alpha2.WebhookAuthType] = s.Spec.ProtocolSettings.WebhookAuth.Type - } - dst.Spec.Config[v1alpha2.WebhookAuthGrantType] = s.Spec.ProtocolSettings.WebhookAuth.GrantType - dst.Spec.Config[v1alpha2.WebhookAuthClientID] = s.Spec.ProtocolSettings.WebhookAuth.ClientID - dst.Spec.Config[v1alpha2.WebhookAuthClientSecret] = s.Spec.ProtocolSettings.WebhookAuth.ClientSecret - dst.Spec.Config[v1alpha2.WebhookAuthTokenURL] = s.Spec.ProtocolSettings.WebhookAuth.TokenURL - if s.Spec.ProtocolSettings.WebhookAuth.Scope != nil { - dst.Spec.Config[v1alpha2.WebhookAuthScope] = strings.Join(s.Spec.ProtocolSettings.WebhookAuth.Scope, ",") - } - } -} - -func (s *Subscription) initializeProtocolSettingsIfNil() { - if s.Spec.ProtocolSettings == nil { - s.Spec.ProtocolSettings = &ProtocolSettings{} - } -} - -func (s *Subscription) initializeWebhookAuthIfNil() { - s.initializeProtocolSettingsIfNil() - if s.Spec.ProtocolSettings.WebhookAuth == nil { - s.Spec.ProtocolSettings.WebhookAuth = &WebhookAuth{} - } -} - -// setV1ProtocolFields converts the protocol-related fields from v1alpha1 to v1alpha2 Subscription version. -func (s *Subscription) setV1ProtocolFields(dst *v1alpha2.Subscription) { - if protocol, ok := dst.Spec.Config[v1alpha2.Protocol]; ok { - s.Spec.Protocol = protocol - } - - if currentMode, ok := dst.Spec.Config[v1alpha2.ProtocolSettingsContentMode]; ok { - s.initializeProtocolSettingsIfNil() - s.Spec.ProtocolSettings.ContentMode = ¤tMode - } - if qos, ok := dst.Spec.Config[v1alpha2.ProtocolSettingsQos]; ok { - s.initializeProtocolSettingsIfNil() - s.Spec.ProtocolSettings.Qos = &qos - } - if exemptHandshake, ok := dst.Spec.Config[v1alpha2.ProtocolSettingsExemptHandshake]; ok { - handshake, err := strconv.ParseBool(exemptHandshake) - if err != nil { - handshake = true - } - s.initializeProtocolSettingsIfNil() - s.Spec.ProtocolSettings.ExemptHandshake = &handshake - } - - if authType, ok := dst.Spec.Config[v1alpha2.WebhookAuthType]; ok { - s.initializeWebhookAuthIfNil() - s.Spec.ProtocolSettings.WebhookAuth.Type = authType - } - if grantType, ok := dst.Spec.Config[v1alpha2.WebhookAuthGrantType]; ok { - s.initializeWebhookAuthIfNil() - s.Spec.ProtocolSettings.WebhookAuth.GrantType = grantType - } - if clientID, ok := dst.Spec.Config[v1alpha2.WebhookAuthClientID]; ok { - s.initializeWebhookAuthIfNil() - s.Spec.ProtocolSettings.WebhookAuth.ClientID = clientID - } - if secret, ok := dst.Spec.Config[v1alpha2.WebhookAuthClientSecret]; ok { - s.initializeWebhookAuthIfNil() - s.Spec.ProtocolSettings.WebhookAuth.ClientSecret = secret - } - if token, ok := dst.Spec.Config[v1alpha2.WebhookAuthTokenURL]; ok { - s.initializeWebhookAuthIfNil() - s.Spec.ProtocolSettings.WebhookAuth.TokenURL = token - } - if scope, ok := dst.Spec.Config[v1alpha2.WebhookAuthScope]; ok { - s.initializeWebhookAuthIfNil() - s.Spec.ProtocolSettings.WebhookAuth.Scope = strings.Split(scope, ",") - } -} - -// setV2SpecTypes sets event types in the Subscription Spec in the v1alpha2 way. -func (s *Subscription) setV2SpecTypes(dst *v1alpha2.Subscription) error { - if v1alpha1TypeCleaner == nil { - return errors.New("event type cleaner is not initialized") - } - - if s.Spec.Filter != nil { - for _, filter := range s.Spec.Filter.Filters { - if dst.Spec.Source == "" { - dst.Spec.Source = filter.EventSource.Value - } - if dst.Spec.Source != "" && filter.EventSource.Value != dst.Spec.Source { - return errors.New(ErrorMultipleSourceMsg) - } - // clean the type and merge segments if needed - cleanedType, err := v1alpha1TypeCleaner.Clean(filter.EventType.Value) - if err != nil { - return err - } - - // add the type to spec - dst.Spec.Types = append(dst.Spec.Types, cleanedType) - } - } - return nil -} - -// natsSpecConfigToV2 converts the v1alpha2 Spec config to v1alpha1. -func (s *Subscription) natsSpecConfigToV1(dst *v1alpha2.Subscription) error { - if maxInFlightMessages, ok := dst.Spec.Config[v1alpha2.MaxInFlightMessages]; ok { - intVal, err := strconv.Atoi(maxInFlightMessages) - if err != nil { - return err - } - s.Spec.Config = &SubscriptionConfig{ - MaxInFlightMessages: intVal, - } - } - return nil -} - -// natsSpecConfigToV2 converts the hardcoded v1alpha1 Spec config to v1alpha2 generic config version. -func (s *Subscription) natsSpecConfigToV2(dst *v1alpha2.Subscription) { - if s.Spec.Config != nil { - if dst.Spec.Config == nil { - dst.Spec.Config = map[string]string{} - } - dst.Spec.Config[v1alpha2.MaxInFlightMessages] = strconv.Itoa(s.Spec.Config.MaxInFlightMessages) - } -} - -// setBEBBackendStatus moves the BEB-related to Backend fields of the Status in the v1alpha2. -func (s *Subscription) bebBackendStatusToV1(dst *v1alpha2.Subscription) { - s.Status.Ev2hash = dst.Status.Backend.Ev2hash - s.Status.Emshash = dst.Status.Backend.EventMeshHash - s.Status.ExternalSink = dst.Status.Backend.ExternalSink - s.Status.FailedActivation = dst.Status.Backend.FailedActivation - s.Status.APIRuleName = dst.Status.Backend.APIRuleName - if dst.Status.Backend.EventMeshSubscriptionStatus != nil { - s.Status.EmsSubscriptionStatus = &EmsSubscriptionStatus{ - SubscriptionStatus: dst.Status.Backend.EventMeshSubscriptionStatus.Status, - SubscriptionStatusReason: dst.Status.Backend.EventMeshSubscriptionStatus.StatusReason, - LastSuccessfulDelivery: dst.Status.Backend.EventMeshSubscriptionStatus.LastSuccessfulDelivery, - LastFailedDelivery: dst.Status.Backend.EventMeshSubscriptionStatus.LastFailedDelivery, - LastFailedDeliveryReason: dst.Status.Backend.EventMeshSubscriptionStatus.LastFailedDeliveryReason, - } - } -} - -// natsBackendStatusToV1 moves the NATS-related to Backend fields of the Status in the v1alpha2. -func (s *Subscription) natsBackendStatusToV1(dst *v1alpha2.Subscription) { - if maxInFlightMessages, ok := dst.Spec.Config[v1alpha2.MaxInFlightMessages]; ok { - intVal, err := strconv.Atoi(maxInFlightMessages) - if err == nil { - s.Status.Config = &SubscriptionConfig{} - s.Status.Config.MaxInFlightMessages = intVal - } - } -} - -// setV1CleanEvenTypes sets the clean event types to v1alpha1 Subscription Status. -func (s *Subscription) setV1CleanEvenTypes(dst *v1alpha2.Subscription) { - s.Status.InitializeCleanEventTypes() - for _, eventType := range dst.Status.Types { - s.Status.CleanEventTypes = append(s.Status.CleanEventTypes, eventType.CleanType) - } -} - -// ConditionV2ToV1 converts the v1alpha2 Condition to v1alpha1 version. -func ConditionV2ToV1(condition v1alpha2.Condition) Condition { - return Condition{ - Type: ConditionType(condition.Type), - Status: condition.Status, - LastTransitionTime: condition.LastTransitionTime, - Reason: ConditionReason(condition.Reason), - Message: condition.Message, - } -} diff --git a/api/eventing/v1alpha1/subscription_conversion_unit_test.go b/api/eventing/v1alpha1/subscription_conversion_unit_test.go deleted file mode 100644 index 32f5a8d05..000000000 --- a/api/eventing/v1alpha1/subscription_conversion_unit_test.go +++ /dev/null @@ -1,409 +0,0 @@ -package v1alpha1_test - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" - "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" - "github.com/kyma-project/eventing-manager/pkg/backend/eventtype" - "github.com/kyma-project/eventing-manager/pkg/ems/api/events/types" - "github.com/kyma-project/eventing-manager/pkg/logger" - eventingtesting "github.com/kyma-project/eventing-manager/testing" -) - -func Test_Conversion(t *testing.T) { - type TestCase struct { - name string - alpha1Sub *v1alpha1.Subscription - alpha2Sub *v1alpha2.Subscription - wantErrMsgV1toV2 string - wantErrMsgV2toV1 string - } - - testCases := []TestCase{ - { - name: "Converting NATS Subscription with empty Status", - alpha1Sub: newDefaultSubscription( - eventingtesting.WithV1alpha1EmptyFilter(), - eventingtesting.WithV1alpha1EmptyConfig(), - eventingtesting.WithV1alpha1EmptyStatus(), - ), - alpha2Sub: newV2DefaultSubscription( - eventingtesting.WithEmptyStatus(), - eventingtesting.WithEmptyConfig(), - ), - }, - { - name: "Converting NATS Subscription with empty Filters", - alpha1Sub: newDefaultSubscription( - eventingtesting.WithV1alpha1EmptyFilter(), - eventingtesting.WithStatusCleanEventTypes(nil), - ), - alpha2Sub: newV2DefaultSubscription(), - }, - { - name: "Converting NATS Subscription with multiple source which should result in a conversion error", - alpha1Sub: newDefaultSubscription( - eventingtesting.WithV1alpha1Filter("app", orderUpdatedEventType), - eventingtesting.WithV1alpha1Filter("", orderDeletedEventTypeNonClean), - ), - alpha2Sub: newV2DefaultSubscription(), - wantErrMsgV1toV2: v1alpha1.ErrorMultipleSourceMsg, - }, - { - name: "Converting NATS Subscription with non-convertable maxInFlight in the config which should result in a conversion error", - alpha1Sub: newDefaultSubscription( - eventingtesting.WithV1alpha1Filter("", orderUpdatedEventType), - ), - alpha2Sub: newV2DefaultSubscription( - eventingtesting.WithMaxInFlightMessages("nonint"), - ), - wantErrMsgV2toV1: "strconv.Atoi: parsing \"nonint\": invalid syntax", - }, - { - name: "Converting NATS Subscription with Filters", - alpha1Sub: newDefaultSubscription( - eventingtesting.WithV1alpha1Filter(eventSource, orderCreatedEventType), - eventingtesting.WithV1alpha1Filter(eventSource, orderUpdatedEventType), - eventingtesting.WithV1alpha1Filter(eventSource, orderDeletedEventTypeNonClean), - eventingtesting.WithStatusCleanEventTypes([]string{ - orderCreatedEventType, - orderUpdatedEventType, - orderDeletedEventType, - }), - ), - alpha2Sub: newV2DefaultSubscription( - eventingtesting.WithEventSource(eventSource), - eventingtesting.WithTypes([]string{ - orderCreatedEventType, - orderUpdatedEventType, - orderDeletedEventTypeNonClean, - }), - v2WithStatusTypes([]v1alpha2.EventType{ - { - OriginalType: orderCreatedEventType, - CleanType: orderCreatedEventType, - }, - { - OriginalType: orderUpdatedEventType, - CleanType: orderUpdatedEventType, - }, - { - OriginalType: orderDeletedEventTypeNonClean, - CleanType: orderDeletedEventType, - }, - }), - v2WithStatusJetStreamTypes([]v1alpha2.JetStreamTypes{ - { - OriginalType: orderCreatedEventType, - ConsumerName: "", - }, - { - OriginalType: orderUpdatedEventType, - ConsumerName: "", - }, - { - OriginalType: orderDeletedEventTypeNonClean, - ConsumerName: "", - }, - }), - ), - }, - { - name: "Converting BEB Subscription", - alpha1Sub: newDefaultSubscription( - eventingtesting.WithV1alpha1ProtocolEventMesh(), - v1WithWebhookAuthForBEB(), - eventingtesting.WithV1alpha1Filter(eventSource, orderCreatedEventType), - eventingtesting.WithV1alpha1Filter(eventSource, orderUpdatedEventType), - eventingtesting.WithV1alpha1Filter(eventSource, orderDeletedEventTypeNonClean), - eventingtesting.WithStatusCleanEventTypes([]string{ - orderCreatedEventType, - orderUpdatedEventType, - orderDeletedEventType, - }), - v1WithBEBStatusFields(), - ), - alpha2Sub: newV2DefaultSubscription( - eventingtesting.WithEventSource(eventSource), - eventingtesting.WithTypes([]string{ - orderCreatedEventType, - orderUpdatedEventType, - orderDeletedEventTypeNonClean, - }), - eventingtesting.WithProtocolEventMesh(), - eventingtesting.WithWebhookAuthForEventMesh(), - v2WithStatusTypes([]v1alpha2.EventType{ - { - OriginalType: orderCreatedEventType, - CleanType: orderCreatedEventType, - }, - { - OriginalType: orderUpdatedEventType, - CleanType: orderUpdatedEventType, - }, - { - OriginalType: orderDeletedEventTypeNonClean, - CleanType: orderDeletedEventType, - }, - }), - v2WithBEBStatusFields(), - ), - }, - { - name: "Converting Subscription with Protocol, ProtocolSettings and WebhookAuth", - alpha1Sub: newDefaultSubscription( - eventingtesting.WithV1alpha1ProtocolEventMesh(), - eventingtesting.WithV1alpha1ProtocolSettings( - eventingtesting.NewProtocolSettings( - eventingtesting.WithAtLeastOnceQOS(), - eventingtesting.WithRequiredWebhookAuth())), - eventingtesting.WithV1alpha1Filter(eventSource, orderCreatedEventType), - eventingtesting.WithStatusCleanEventTypes([]string{ - orderCreatedEventType, - }), - ), - alpha2Sub: newV2DefaultSubscription( - eventingtesting.WithEventSource(eventSource), - eventingtesting.WithTypes([]string{ - orderCreatedEventType, - }), - eventingtesting.WithProtocolEventMesh(), - eventingtesting.WithConfigValue(v1alpha2.ProtocolSettingsQos, - string(types.QosAtLeastOnce)), - eventingtesting.WithConfigValue(v1alpha2.WebhookAuthGrantType, - "client_credentials"), - eventingtesting.WithConfigValue(v1alpha2.WebhookAuthClientID, - "xxx"), - eventingtesting.WithConfigValue(v1alpha2.WebhookAuthClientSecret, - "xxx"), - eventingtesting.WithConfigValue(v1alpha2.WebhookAuthTokenURL, - "https://oauth2.xxx.com/oauth2/token"), - v2WithStatusTypes([]v1alpha2.EventType{ - { - OriginalType: orderCreatedEventType, - CleanType: orderCreatedEventType, - }, - }), - ), - }, - } - - for _, testCase := range testCases { - t.Run(testCase.name, func(t *testing.T) { - // WHEN - t.Run("Test v1 to v2 conversion", func(t *testing.T) { - // skip the conversion if the backwards conversion cannot succeed - if testCase.wantErrMsgV2toV1 != "" { - return - } - - // initialize dummy cleaner - cleaner := eventtype.CleanerFunc(func(et string) (string, error) { return et, nil }) - v1alpha1.InitializeEventTypeCleaner(cleaner) - - convertedV1Alpha2 := &v1alpha2.Subscription{} - err := v1alpha1.V1ToV2(testCase.alpha1Sub, convertedV1Alpha2) - if err != nil && testCase.wantErrMsgV1toV2 != "" { - require.Equal(t, testCase.wantErrMsgV1toV2, err.Error()) - } else { - require.NoError(t, err) - v1ToV2Assertions(t, testCase.alpha2Sub, convertedV1Alpha2) - } - }) - - // test ConvertFrom - t.Run("Test v2 to v1 conversion", func(t *testing.T) { - // skip the backwards conversion if the initial one cannot succeed - if testCase.wantErrMsgV1toV2 != "" { - return - } - convertedV1Alpha1 := &v1alpha1.Subscription{} - err := v1alpha1.V2ToV1(convertedV1Alpha1, testCase.alpha2Sub) - if err != nil && testCase.wantErrMsgV2toV1 != "" { - require.Equal(t, testCase.wantErrMsgV2toV1, err.Error()) - } else { - require.NoError(t, err) - v2ToV1Assertions(t, testCase.alpha1Sub, convertedV1Alpha1) - } - }) - }) - } -} - -// Test_CleanupInV1ToV2Conversion test the cleaning from non-alphanumeric characters -// and also merging of segments in event types if they exceed the limit. -// -//nolint:goconst // the event types used here in tests do not get more readable by extracting them to constants -func Test_CleanupInV1ToV2Conversion(t *testing.T) { - type TestCase struct { - name string - givenAlpha1Sub *v1alpha1.Subscription - givenPrefix string - wantTypes []string - wantError bool - } - - testCases := []TestCase{ - { - name: "success if prefix is empty", - givenAlpha1Sub: newDefaultSubscription( - eventingtesting.WithV1alpha1Filter(eventSource, "testapp.Segment1-Part1-Part2-Ä.Segment2-Part1-Part2-Ä.v1"), - ), - givenPrefix: "", - wantTypes: []string{ - "testapp.Segment1Part1Part2.Segment2Part1Part2.v1", - }, - }, - { - name: "success if the given event has more than two segments", - givenPrefix: "prefix", - givenAlpha1Sub: newDefaultSubscription( - eventingtesting.WithV1alpha1Filter(eventSource, "prefix.testapp.Segment1.Segment2.Segment3."+ - "Segment4-Part1-Part2-Ä.Segment5-Part1-Part2-Ä.v1"), - ), - wantTypes: []string{ - "prefix.testapp.Segment1Segment2Segment3Segment4Part1Part2.Segment5Part1Part2.v1", - }, - wantError: false, - }, - { - name: "success if the application name needs to be cleaned", - givenPrefix: "prefix", - givenAlpha1Sub: newDefaultSubscription( - eventingtesting.WithV1alpha1Filter(eventSource, "prefix.te--s__t!!a@@p##p%%.Segment1-Part1-Part2-Ä."+ - "Segment2-Part1-Part2-Ä.v1"), - ), - wantTypes: []string{ - "prefix.testapp.Segment1Part1Part2.Segment2Part1Part2.v1", - }, - wantError: false, - }, - { - name: "success if the application name needs to be cleaned and event has more than two segments", - givenPrefix: "prefix", - givenAlpha1Sub: newDefaultSubscription( - eventingtesting.WithV1alpha1Filter(eventSource, "prefix.te--s__t!!a@@p##p%%.Segment1.Segment2.Segment3."+ - "Segment4-Part1-Part2-Ä.Segment5-Part1-Part2-Ä.v1"), - ), - wantTypes: []string{ - "prefix.testapp.Segment1Segment2Segment3Segment4Part1Part2.Segment5Part1Part2.v1", - }, - wantError: false, - }, - { - name: "success if there are multiple filters", - givenPrefix: "prefix", - givenAlpha1Sub: newDefaultSubscription( - eventingtesting.WithV1alpha1Filter(eventSource, "prefix.test-app.Segme@@nt1.Segment2.Segment3."+ - "Segment4-Part1-Part2-Ä.Segment5-Part1-Part2-Ä.v1"), - eventingtesting.WithV1alpha1Filter(eventSource, "prefix.testapp.Segment1.Segment2.Segment3."+ - "Segment4-Part1-Part2-Ä.Segment5-Part1-Part2-Ä.v1"), - ), - wantTypes: []string{ - "prefix.testapp.Segment1Segment2Segment3Segment4Part1Part2.Segment5Part1Part2.v1", - "prefix.testapp.Segment1Segment2Segment3Segment4Part1Part2.Segment5Part1Part2.v1", - }, - wantError: false, - }, - // invalid even-types - { - name: "fail if the prefix is invalid", - givenPrefix: "prefix", - givenAlpha1Sub: newDefaultSubscription( - eventingtesting.WithV1alpha1Filter(eventSource, "invalid.test-app.Segme@@nt1.Segment2.Segment3."+ - "Segment4-Part1-Part2-Ä.Segment5-Part1-Part2-Ä.v1"), - ), - wantError: true, - }, - { - name: "fail if the prefix is missing", - givenPrefix: "prefix", - givenAlpha1Sub: newDefaultSubscription( - eventingtesting.WithV1alpha1Filter(eventSource, "test-app.Segme@@nt1.Segment2.Segment3."+ - "Segment4-Part1-Part2-Ä.Segment5-Part1-Part2-Ä.v1"), - ), - wantError: true, - }, - { - name: "fail if the event-type is incomplete", - givenPrefix: "prefix", - givenAlpha1Sub: newDefaultSubscription( - eventingtesting.WithV1alpha1Filter(eventSource, "prefix.testapp.Segment1-Part1-Part2-Ä.v1"), - ), - wantError: true, - }, - } - - for _, tc := range testCases { - testcase := tc - t.Run(testcase.name, func(t *testing.T) { - // given - testLogger, err := logger.New("json", "info") - require.NoError(t, err) - - // initialize dummy cleaner - cleaner := eventtype.NewSimpleCleaner(testcase.givenPrefix, testLogger) - v1alpha1.InitializeEventTypeCleaner(cleaner) - - // initialize v1alpha2 Subscription instance - convertedV1Alpha2 := &v1alpha2.Subscription{} - - // when - err = v1alpha1.V1ToV2(testcase.givenAlpha1Sub, convertedV1Alpha2) - - // then - if testcase.wantError { - require.Error(t, err) - } else { - require.NoError(t, err) - require.Equal(t, testcase.wantTypes, convertedV1Alpha2.Spec.Types) - } - }) - } -} - -func v1ToV2Assertions(t *testing.T, wantSub, convertedSub *v1alpha2.Subscription) { - t.Helper() - assert.Equal(t, wantSub.ObjectMeta, convertedSub.ObjectMeta) - - // Spec - assert.Equal(t, wantSub.Spec.ID, convertedSub.Spec.ID) - assert.Equal(t, wantSub.Spec.Sink, convertedSub.Spec.Sink) - assert.Equal(t, wantSub.Spec.TypeMatching, convertedSub.Spec.TypeMatching) - assert.Equal(t, wantSub.Spec.Source, convertedSub.Spec.Source) - assert.Equal(t, wantSub.Spec.Types, convertedSub.Spec.Types) - assert.Equal(t, wantSub.Spec.Config, convertedSub.Spec.Config) -} - -func v2ToV1Assertions(t *testing.T, wantSub, convertedSub *v1alpha1.Subscription) { - t.Helper() - assert.Equal(t, wantSub.ObjectMeta, convertedSub.ObjectMeta) - - // Spec - assert.Equal(t, wantSub.Spec.ID, convertedSub.Spec.ID) - assert.Equal(t, wantSub.Spec.Sink, convertedSub.Spec.Sink) - assert.Equal(t, wantSub.Spec.Protocol, convertedSub.Spec.Protocol) - assert.Equal(t, wantSub.Spec.ProtocolSettings, convertedSub.Spec.ProtocolSettings) - - assert.Equal(t, wantSub.Spec.Filter, convertedSub.Spec.Filter) - assert.Equal(t, wantSub.Spec.Config, convertedSub.Spec.Config) - - // Status - assert.Equal(t, wantSub.Status.Ready, convertedSub.Status.Ready) - assert.Equal(t, wantSub.Status.Conditions, convertedSub.Status.Conditions) - assert.Equal(t, wantSub.Status.CleanEventTypes, convertedSub.Status.CleanEventTypes) - - // BEB fields - assert.Equal(t, wantSub.Status.Ev2hash, convertedSub.Status.Ev2hash) - assert.Equal(t, wantSub.Status.Emshash, convertedSub.Status.Emshash) - assert.Equal(t, wantSub.Status.ExternalSink, convertedSub.Status.ExternalSink) - assert.Equal(t, wantSub.Status.FailedActivation, convertedSub.Status.FailedActivation) - assert.Equal(t, wantSub.Status.APIRuleName, convertedSub.Status.APIRuleName) - assert.Equal(t, wantSub.Status.EmsSubscriptionStatus, convertedSub.Status.EmsSubscriptionStatus) - - assert.Equal(t, wantSub.Status.Config, convertedSub.Status.Config) -} diff --git a/api/eventing/v1alpha1/subscription_types.go b/api/eventing/v1alpha1/subscription_types.go deleted file mode 100644 index 6ec561d66..000000000 --- a/api/eventing/v1alpha1/subscription_types.go +++ /dev/null @@ -1,279 +0,0 @@ -//nolint:godox // this package will be removed soon -package v1alpha1 - -import ( - "encoding/json" - - "github.com/mitchellh/hashstructure/v2" - kmetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/kyma-project/eventing-manager/pkg/env" -) - -type BackendType string - -const ( - BEBBackendType BackendType = "BEB" - NatsBackendType BackendType = "NATS" -) - -// WebhookAuth defines the Webhook called by an active subscription in BEB. -// TODO: Remove it when depreciating code of v1alpha1. -type WebhookAuth struct { - // Defines the authentication type. - // +optional - Type string `json:"type,omitempty"` - - // Defines the grant type for OAuth2. - GrantType string `json:"grantType"` - - // Defines the clientID for OAuth2. - ClientID string `json:"clientId"` - - // Defines the Client Secret for OAuth2. - ClientSecret string `json:"clientSecret"` - - // Defines the token URL for OAuth2. - TokenURL string `json:"tokenUrl"` - - // Defines the scope for OAuth2. - Scope []string `json:"scope,omitempty"` -} - -// ProtocolSettings defines the CE protocol setting specification implementation. -// TODO: Remove it when depreciating code of v1alpha1. -type ProtocolSettings struct { - // Defines the content mode for eventing based on BEB. - // The value is either `BINARY`, or `STRUCTURED`. - // +optional - ContentMode *string `json:"contentMode,omitempty"` - - // Defines if the exempt handshake for eventing is based on BEB. - // +optional - ExemptHandshake *bool `json:"exemptHandshake,omitempty"` - - // Defines the quality of service for eventing based on BEB. - // +optional - Qos *string `json:"qos,omitempty"` - - // Defines the Webhook called by an active subscription on BEB. - // +optional - WebhookAuth *WebhookAuth `json:"webhookAuth,omitempty"` -} - -// TODO: Remove it when depreciating code of v1alpha1. -const ( - ProtocolSettingsContentModeBinary string = "BINARY" - ProtocolSettingsContentModeStructured string = "STRUCTURED" -) - -// Filter defines the CE filter element. -type Filter struct { - // Defines the type of the filter. - // +optional - Type string `json:"type,omitempty"` - - // Defines the property of the filter. - Property string `json:"property"` - - // Defines the value of the filter. - Value string `json:"value"` -} - -// Defines the BEB filter element as a combination of two CE filter elements. -type EventMeshFilter struct { - // Defines the source of the CE filter. - EventSource *Filter `json:"eventSource"` - - // Defines the type of the CE filter. - EventType *Filter `json:"eventType"` -} - -func (bf *EventMeshFilter) hash() (uint64, error) { - return hashstructure.Hash(bf, hashstructure.FormatV2, nil) -} - -// BEBFilters defines the list of BEB filters. -type BEBFilters struct { - // Contains a `URI-reference` to the CloudEvent filter dialect. See - // [here](https://github.com/cloudevents/spec/blob/main/subscriptions/spec.md#3241-filter-dialects) for more details. - // +optional - Dialect string `json:"dialect,omitempty"` - - Filters []*EventMeshFilter `json:"filters"` -} - -// Deduplicate returns a deduplicated copy of BEBFilters. -func (bf *BEBFilters) Deduplicate() (*BEBFilters, error) { - seen := map[uint64]struct{}{} - result := &BEBFilters{ - Dialect: bf.Dialect, - } - for _, filter := range bf.Filters { - hash, err := filter.hash() - if err != nil { - return nil, err - } - if _, exists := seen[hash]; !exists { - result.Filters = append(result.Filters, filter) - seen[hash] = struct{}{} - } - } - return result, nil -} - -type SubscriptionConfig struct { - // Defines how many not-ACKed messages can be in flight simultaneously. - // +optional - // +kubebuilder:validation:Minimum=1 - MaxInFlightMessages int `json:"maxInFlightMessages,omitempty"` -} - -// MergeSubsConfigs returns a valid subscription config object based on the provided config, -// complemented with default values, if necessary. -func MergeSubsConfigs(config *SubscriptionConfig, defaults *env.DefaultSubscriptionConfig) *SubscriptionConfig { - merged := &SubscriptionConfig{ - MaxInFlightMessages: defaults.MaxInFlightMessages, - } - if config == nil { - return merged - } - if config.MaxInFlightMessages >= 1 { - merged.MaxInFlightMessages = config.MaxInFlightMessages - } - return merged -} - -// SubscriptionSpec defines the desired state of Subscription. -type SubscriptionSpec struct { - // Unique identifier of the Subscription, read-only. - // +optional - ID string `json:"id,omitempty"` - - // Defines the CE protocol specification implementation. - // +optional - Protocol string `json:"protocol,omitempty"` - - // Defines the CE protocol settings specification implementation. - // +optional - ProtocolSettings *ProtocolSettings `json:"protocolsettings,omitempty"` - - // Kubernetes Service that should be used as a target for the events that match the Subscription. - // Must exist in the same Namespace as the Subscription. - Sink string `json:"sink"` - - // Defines which events will be sent to the sink. - Filter *BEBFilters `json:"filter"` - - // Defines additional configuration for the active backend. - // +optional - Config *SubscriptionConfig `json:"config,omitempty"` -} - -type EmsSubscriptionStatus struct { - // Status of the Subscription as reported by EventMesh. - // +optional - SubscriptionStatus string `json:"subscriptionStatus,omitempty"` - - // Reason for the current status. - // +optional - SubscriptionStatusReason string `json:"subscriptionStatusReason,omitempty"` - - // Timestamp of the last successful delivery. - // +optional - LastSuccessfulDelivery string `json:"lastSuccessfulDelivery,omitempty"` - - // Timestamp of the last failed delivery. - // +optional - LastFailedDelivery string `json:"lastFailedDelivery,omitempty"` - - // Reason for the last failed delivery. - // +optional - LastFailedDeliveryReason string `json:"lastFailedDeliveryReason,omitempty"` -} - -// SubscriptionStatus defines the observed state of the Subscription. -type SubscriptionStatus struct { - // Current state of the Subscription. - // +optional - Conditions []Condition `json:"conditions,omitempty"` - - // Overall readiness of the Subscription. - Ready bool `json:"ready"` - - // CleanEventTypes defines the filter's event types after cleanup to use it with the configured backend. - CleanEventTypes []string `json:"cleanEventTypes"` - - // Defines the checksum for the Subscription custom resource. - // +optional - Ev2hash int64 `json:"ev2hash,omitempty"` - - // Defines the checksum for the Subscription in EventMesh. - // +optional - Emshash int64 `json:"emshash,omitempty"` - - // Defines the webhook URL which is used by EventMesh to trigger subscribers. - // +optional - ExternalSink string `json:"externalSink,omitempty"` - - // Defines the reason if a Subscription failed activation in EventMesh. - // +optional - FailedActivation string `json:"failedActivation,omitempty"` - - // Defines the name of the APIRule which is used by the Subscription. - // +optional - APIRuleName string `json:"apiRuleName,omitempty"` - - // Defines the status of the Subscription in EventMesh. - // +optional - EmsSubscriptionStatus *EmsSubscriptionStatus `json:"emsSubscriptionStatus,omitempty"` - - // Defines the configurations that have been applied to the eventing backend when creating this Subscription. - // +optional - Config *SubscriptionConfig `json:"config,omitempty"` -} - -// Subscription is the Schema for the subscriptions API. -// +kubebuilder:object:root=true -// +kubebuilder:subresource:status -// +kubebuilder:deprecatedversion:warning=The v1alpha1 API version is deprecated as of Kyma 2.14.X. -// +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=".status.ready" -// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp" -// +kubebuilder:printcolumn:name="Clean Event Types",type="string",JSONPath=".status.cleanEventTypes" -type Subscription struct { - kmetav1.TypeMeta `json:",inline"` - kmetav1.ObjectMeta `json:"metadata,omitempty"` - - Spec SubscriptionSpec `json:"spec,omitempty"` - Status SubscriptionStatus `json:"status,omitempty"` -} - -// MarshalJSON implements the json.Marshaler interface. -// If the SubscriptionStatus.CleanEventTypes is nil, it will be initialized to an empty slice of stings. -// It is needed because the Kubernetes APIServer will reject requests containing null in the JSON payload. -func (s Subscription) MarshalJSON() ([]byte, error) { - // Use type alias to copy the subscription without causing an infinite recursion when calling json.Marshal. - type Alias Subscription - a := Alias(s) - if a.Status.CleanEventTypes == nil { - a.Status.InitializeCleanEventTypes() - } - return json.Marshal(a) -} - -// SubscriptionList contains a list of Subscription. -// +kubebuilder:object:root=true -type SubscriptionList struct { - kmetav1.TypeMeta `json:",inline"` - kmetav1.ListMeta `json:"metadata,omitempty"` - Items []Subscription `json:"items"` -} - -// InitializeCleanEventTypes initializes the SubscriptionStatus.CleanEventTypes with an empty slice of strings. -func (s *SubscriptionStatus) InitializeCleanEventTypes() { - s.CleanEventTypes = []string{} -} - -func init() { //nolint:gochecknoinits - SchemeBuilder.Register(&Subscription{}, &SubscriptionList{}) -} diff --git a/api/eventing/v1alpha1/subscription_types_unit_test.go b/api/eventing/v1alpha1/subscription_types_unit_test.go deleted file mode 100644 index bad376926..000000000 --- a/api/eventing/v1alpha1/subscription_types_unit_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package v1alpha1_test - -import ( - "reflect" - "testing" - - "github.com/stretchr/testify/require" - - "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" - "github.com/kyma-project/eventing-manager/pkg/env" -) - -func TestBEBFilters_Deduplicate(t *testing.T) { - filter1 := &v1alpha1.EventMeshFilter{ - EventSource: &v1alpha1.Filter{ - Type: "exact", - Property: "source", - Value: "", - }, - EventType: &v1alpha1.Filter{ - Type: "exact", - Property: "type", - Value: orderCreatedEventType, - }, - } - filter2 := &v1alpha1.EventMeshFilter{ - EventSource: &v1alpha1.Filter{ - Type: "exact", - Property: "source", - Value: "", - }, - EventType: &v1alpha1.Filter{ - Type: "exact", - Property: "type", - Value: orderProcessedEventType, - }, - } - filter3 := &v1alpha1.EventMeshFilter{ - EventSource: &v1alpha1.Filter{ - Type: "exact", - Property: "source", - Value: "/external/system/id", - }, - EventType: &v1alpha1.Filter{ - Type: "exact", - Property: "type", - Value: orderCreatedEventType, - }, - } - testCases := []struct { - caseName string - input *v1alpha1.BEBFilters - expected *v1alpha1.BEBFilters - expectErr bool - }{ - { - caseName: "Only one filter", - input: &v1alpha1.BEBFilters{ - Dialect: "beb", - Filters: []*v1alpha1.EventMeshFilter{filter1}, - }, - expected: &v1alpha1.BEBFilters{ - Dialect: "beb", - Filters: []*v1alpha1.EventMeshFilter{filter1}, - }, - expectErr: false, - }, - { - caseName: "Filters with duplicate", - input: &v1alpha1.BEBFilters{ - Dialect: "nats", - Filters: []*v1alpha1.EventMeshFilter{filter1, filter1}, - }, - expected: &v1alpha1.BEBFilters{ - Dialect: "nats", - Filters: []*v1alpha1.EventMeshFilter{filter1}, - }, - expectErr: false, - }, - { - caseName: "Filters without duplicate", - input: &v1alpha1.BEBFilters{ - Filters: []*v1alpha1.EventMeshFilter{filter1, filter2, filter3}, - }, - expected: &v1alpha1.BEBFilters{ - Filters: []*v1alpha1.EventMeshFilter{filter1, filter2, filter3}, - }, - expectErr: false, - }, - } - for _, tc := range testCases { - testcase := tc - t.Run(testcase.caseName, func(t *testing.T) { - got, err := testcase.input.Deduplicate() - if (err != nil) != testcase.expectErr { - t.Errorf("Deduplicate() error = %v, expectErr %v", err, testcase.expected) - return - } - if !reflect.DeepEqual(got, testcase.expected) { - t.Errorf("Deduplicate() got = %v, want %v", got, testcase.expected) - } - }) - } -} - -func TestMergeSubsConfigs(t *testing.T) { - defaultConf := &env.DefaultSubscriptionConfig{MaxInFlightMessages: 4} - tests := []struct { - caseName string - inputConf *v1alpha1.SubscriptionConfig - inputDefaults *env.DefaultSubscriptionConfig - expectedOutput *v1alpha1.SubscriptionConfig - }{ - { - caseName: "nil input config", - inputConf: nil, - inputDefaults: defaultConf, - expectedOutput: &v1alpha1.SubscriptionConfig{MaxInFlightMessages: 4}, - }, - { - caseName: "default is overridden", - inputConf: &v1alpha1.SubscriptionConfig{MaxInFlightMessages: 10}, - inputDefaults: defaultConf, - expectedOutput: &v1alpha1.SubscriptionConfig{MaxInFlightMessages: 10}, - }, - { - caseName: "provided input is invalid", - inputConf: &v1alpha1.SubscriptionConfig{MaxInFlightMessages: 0}, - inputDefaults: defaultConf, - expectedOutput: &v1alpha1.SubscriptionConfig{MaxInFlightMessages: 4}, - }, - } - - for _, tt := range tests { - t.Run(tt.caseName, func(t *testing.T) { - got := v1alpha1.MergeSubsConfigs(tt.inputConf, tt.inputDefaults) - if !reflect.DeepEqual(got, tt.expectedOutput) { - t.Errorf("MergeSubsConfigs() got = %v, want = %v", got, tt.expectedOutput) - } - }) - } -} - -func TestInitializeCleanEventTypes(t *testing.T) { - s := v1alpha1.Subscription{} - require.Nil(t, s.Status.CleanEventTypes) - - s.Status.InitializeCleanEventTypes() - require.NotNil(t, s.Status.CleanEventTypes) -} diff --git a/api/eventing/v1alpha1/subscription_webhook.go b/api/eventing/v1alpha1/subscription_webhook.go deleted file mode 100644 index 22e69e6f8..000000000 --- a/api/eventing/v1alpha1/subscription_webhook.go +++ /dev/null @@ -1,11 +0,0 @@ -package v1alpha1 - -import ( - kctrl "sigs.k8s.io/controller-runtime" -) - -func (s *Subscription) SetupWebhookWithManager(mgr kctrl.Manager) error { - return kctrl.NewWebhookManagedBy(mgr). - For(s). - Complete() -} diff --git a/api/eventing/v1alpha1/zz_generated.deepcopy.go b/api/eventing/v1alpha1/zz_generated.deepcopy.go deleted file mode 100644 index 15f4a2a23..000000000 --- a/api/eventing/v1alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,318 +0,0 @@ -//go:build !ignore_autogenerated - -/* -Copyright 2023. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Code generated by controller-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *BEBFilters) DeepCopyInto(out *BEBFilters) { - *out = *in - if in.Filters != nil { - in, out := &in.Filters, &out.Filters - *out = make([]*EventMeshFilter, len(*in)) - for i := range *in { - if (*in)[i] != nil { - in, out := &(*in)[i], &(*out)[i] - *out = new(EventMeshFilter) - (*in).DeepCopyInto(*out) - } - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BEBFilters. -func (in *BEBFilters) DeepCopy() *BEBFilters { - if in == nil { - return nil - } - out := new(BEBFilters) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Condition) DeepCopyInto(out *Condition) { - *out = *in - in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Condition. -func (in *Condition) DeepCopy() *Condition { - if in == nil { - return nil - } - out := new(Condition) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *EmsSubscriptionStatus) DeepCopyInto(out *EmsSubscriptionStatus) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EmsSubscriptionStatus. -func (in *EmsSubscriptionStatus) DeepCopy() *EmsSubscriptionStatus { - if in == nil { - return nil - } - out := new(EmsSubscriptionStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *EventMeshFilter) DeepCopyInto(out *EventMeshFilter) { - *out = *in - if in.EventSource != nil { - in, out := &in.EventSource, &out.EventSource - *out = new(Filter) - **out = **in - } - if in.EventType != nil { - in, out := &in.EventType, &out.EventType - *out = new(Filter) - **out = **in - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EventMeshFilter. -func (in *EventMeshFilter) DeepCopy() *EventMeshFilter { - if in == nil { - return nil - } - out := new(EventMeshFilter) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Filter) DeepCopyInto(out *Filter) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Filter. -func (in *Filter) DeepCopy() *Filter { - if in == nil { - return nil - } - out := new(Filter) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ProtocolSettings) DeepCopyInto(out *ProtocolSettings) { - *out = *in - if in.ContentMode != nil { - in, out := &in.ContentMode, &out.ContentMode - *out = new(string) - **out = **in - } - if in.ExemptHandshake != nil { - in, out := &in.ExemptHandshake, &out.ExemptHandshake - *out = new(bool) - **out = **in - } - if in.Qos != nil { - in, out := &in.Qos, &out.Qos - *out = new(string) - **out = **in - } - if in.WebhookAuth != nil { - in, out := &in.WebhookAuth, &out.WebhookAuth - *out = new(WebhookAuth) - (*in).DeepCopyInto(*out) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProtocolSettings. -func (in *ProtocolSettings) DeepCopy() *ProtocolSettings { - if in == nil { - return nil - } - out := new(ProtocolSettings) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Subscription) DeepCopyInto(out *Subscription) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Subscription. -func (in *Subscription) DeepCopy() *Subscription { - if in == nil { - return nil - } - out := new(Subscription) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *Subscription) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SubscriptionConfig) DeepCopyInto(out *SubscriptionConfig) { - *out = *in -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SubscriptionConfig. -func (in *SubscriptionConfig) DeepCopy() *SubscriptionConfig { - if in == nil { - return nil - } - out := new(SubscriptionConfig) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SubscriptionList) DeepCopyInto(out *SubscriptionList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]Subscription, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SubscriptionList. -func (in *SubscriptionList) DeepCopy() *SubscriptionList { - if in == nil { - return nil - } - out := new(SubscriptionList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *SubscriptionList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SubscriptionSpec) DeepCopyInto(out *SubscriptionSpec) { - *out = *in - if in.ProtocolSettings != nil { - in, out := &in.ProtocolSettings, &out.ProtocolSettings - *out = new(ProtocolSettings) - (*in).DeepCopyInto(*out) - } - if in.Filter != nil { - in, out := &in.Filter, &out.Filter - *out = new(BEBFilters) - (*in).DeepCopyInto(*out) - } - if in.Config != nil { - in, out := &in.Config, &out.Config - *out = new(SubscriptionConfig) - **out = **in - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SubscriptionSpec. -func (in *SubscriptionSpec) DeepCopy() *SubscriptionSpec { - if in == nil { - return nil - } - out := new(SubscriptionSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SubscriptionStatus) DeepCopyInto(out *SubscriptionStatus) { - *out = *in - if in.Conditions != nil { - in, out := &in.Conditions, &out.Conditions - *out = make([]Condition, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.CleanEventTypes != nil { - in, out := &in.CleanEventTypes, &out.CleanEventTypes - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.EmsSubscriptionStatus != nil { - in, out := &in.EmsSubscriptionStatus, &out.EmsSubscriptionStatus - *out = new(EmsSubscriptionStatus) - **out = **in - } - if in.Config != nil { - in, out := &in.Config, &out.Config - *out = new(SubscriptionConfig) - **out = **in - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SubscriptionStatus. -func (in *SubscriptionStatus) DeepCopy() *SubscriptionStatus { - if in == nil { - return nil - } - out := new(SubscriptionStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *WebhookAuth) DeepCopyInto(out *WebhookAuth) { - *out = *in - if in.Scope != nil { - in, out := &in.Scope, &out.Scope - *out = make([]string, len(*in)) - copy(*out, *in) - } -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WebhookAuth. -func (in *WebhookAuth) DeepCopy() *WebhookAuth { - if in == nil { - return nil - } - out := new(WebhookAuth) - in.DeepCopyInto(out) - return out -} diff --git a/api/operator/v1alpha1/zz_generated.deepcopy.go b/api/operator/v1alpha1/zz_generated.deepcopy.go index c227b3446..25bcddd82 100644 --- a/api/operator/v1alpha1/zz_generated.deepcopy.go +++ b/api/operator/v1alpha1/zz_generated.deepcopy.go @@ -21,7 +21,7 @@ limitations under the License. package v1alpha1 import ( - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) diff --git a/cmd/main.go b/cmd/main.go index d25a54207..b28138479 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -39,7 +39,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/metrics/server" "sigs.k8s.io/controller-runtime/pkg/webhook" - eventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" operatorv1alpha1 "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" natsconnection "github.com/kyma-project/eventing-manager/internal/connection/nats" @@ -64,7 +63,6 @@ func registerSchemas(scheme *runtime.Scheme) { kutilruntime.Must(kapiextensionsv1.AddToScheme(scheme)) kutilruntime.Must(jetstream.AddToScheme(scheme)) kutilruntime.Must(jetstream.AddV1Alpha2ToScheme(scheme)) - kutilruntime.Must(eventingv1alpha1.AddToScheme(scheme)) kutilruntime.Must(eventingv1alpha2.AddToScheme(scheme)) //+kubebuilder:scaffold:scheme } @@ -203,12 +201,6 @@ func main() { //nolint:funlen // main function needs to initialize many object //+kubebuilder:scaffold:builder // Setup webhooks. - if err = (&eventingv1alpha1.Subscription{}).SetupWebhookWithManager(mgr); err != nil { - setupLog.Error(err, "Failed to create webhook") - syncLogger(ctrLogger) - os.Exit(1) - } - if err = (&eventingv1alpha2.Subscription{}).SetupWebhookWithManager(mgr); err != nil { setupLog.Error(err, "Failed to create webhook") syncLogger(ctrLogger) diff --git a/config/crd/bases/eventing.kyma-project.io_subscriptions.yaml b/config/crd/bases/eventing.kyma-project.io_subscriptions.yaml index 87fcd300d..e69d77c82 100644 --- a/config/crd/bases/eventing.kyma-project.io_subscriptions.yaml +++ b/config/crd/bases/eventing.kyma-project.io_subscriptions.yaml @@ -14,263 +14,6 @@ spec: singular: subscription scope: Namespaced versions: - - additionalPrinterColumns: - - jsonPath: .status.ready - name: Ready - type: string - - jsonPath: .metadata.creationTimestamp - name: Age - type: date - - jsonPath: .status.cleanEventTypes - name: Clean Event Types - type: string - deprecated: true - deprecationWarning: The v1alpha1 API version is deprecated as of Kyma 2.14.X. - name: v1alpha1 - schema: - openAPIV3Schema: - description: Subscription is the Schema for the subscriptions API. - properties: - apiVersion: - description: |- - APIVersion defines the versioned schema of this representation of an object. - Servers should convert recognized schemas to the latest internal value, and - may reject unrecognized values. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources - type: string - kind: - description: |- - Kind is a string value representing the REST resource this object represents. - Servers may infer this from the endpoint the client submits requests to. - Cannot be updated. - In CamelCase. - More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - type: string - metadata: - type: object - spec: - description: SubscriptionSpec defines the desired state of Subscription. - properties: - config: - description: Defines additional configuration for the active backend. - properties: - maxInFlightMessages: - description: Defines how many not-ACKed messages can be in flight - simultaneously. - minimum: 1 - type: integer - type: object - filter: - description: Defines which events will be sent to the sink. - properties: - dialect: - description: |- - Contains a `URI-reference` to the CloudEvent filter dialect. See - [here](https://github.com/cloudevents/spec/blob/main/subscriptions/spec.md#3241-filter-dialects) for more details. - type: string - filters: - items: - description: Defines the BEB filter element as a combination - of two CE filter elements. - properties: - eventSource: - description: Defines the source of the CE filter. - properties: - property: - description: Defines the property of the filter. - type: string - type: - description: Defines the type of the filter. - type: string - value: - description: Defines the value of the filter. - type: string - required: - - property - - value - type: object - eventType: - description: Defines the type of the CE filter. - properties: - property: - description: Defines the property of the filter. - type: string - type: - description: Defines the type of the filter. - type: string - value: - description: Defines the value of the filter. - type: string - required: - - property - - value - type: object - required: - - eventSource - - eventType - type: object - type: array - required: - - filters - type: object - id: - description: Unique identifier of the Subscription, read-only. - type: string - protocol: - description: Defines the CE protocol specification implementation. - type: string - protocolsettings: - description: Defines the CE protocol settings specification implementation. - properties: - contentMode: - description: |- - Defines the content mode for eventing based on BEB. - The value is either `BINARY`, or `STRUCTURED`. - type: string - exemptHandshake: - description: Defines if the exempt handshake for eventing is based - on BEB. - type: boolean - qos: - description: Defines the quality of service for eventing based - on BEB. - type: string - webhookAuth: - description: Defines the Webhook called by an active subscription - on BEB. - properties: - clientId: - description: Defines the clientID for OAuth2. - type: string - clientSecret: - description: Defines the Client Secret for OAuth2. - type: string - grantType: - description: Defines the grant type for OAuth2. - type: string - scope: - description: Defines the scope for OAuth2. - items: - type: string - type: array - tokenUrl: - description: Defines the token URL for OAuth2. - type: string - type: - description: Defines the authentication type. - type: string - required: - - clientId - - clientSecret - - grantType - - tokenUrl - type: object - type: object - sink: - description: |- - Kubernetes Service that should be used as a target for the events that match the Subscription. - Must exist in the same Namespace as the Subscription. - type: string - required: - - filter - - sink - type: object - status: - description: SubscriptionStatus defines the observed state of the Subscription. - properties: - apiRuleName: - description: Defines the name of the APIRule which is used by the - Subscription. - type: string - cleanEventTypes: - description: CleanEventTypes defines the filter's event types after - cleanup to use it with the configured backend. - items: - type: string - type: array - conditions: - description: Current state of the Subscription. - items: - properties: - lastTransitionTime: - description: Defines the date of the last condition status change. - format: date-time - type: string - message: - description: Provides more details about the condition status - change. - type: string - reason: - description: Defines the reason for the condition status change. - type: string - status: - description: Status of the condition. The value is either `True`, - `False`, or `Unknown`. - type: string - type: - description: Short description of the condition. - type: string - required: - - status - type: object - type: array - config: - description: Defines the configurations that have been applied to - the eventing backend when creating this Subscription. - properties: - maxInFlightMessages: - description: Defines how many not-ACKed messages can be in flight - simultaneously. - minimum: 1 - type: integer - type: object - emsSubscriptionStatus: - description: Defines the status of the Subscription in EventMesh. - properties: - lastFailedDelivery: - description: Timestamp of the last failed delivery. - type: string - lastFailedDeliveryReason: - description: Reason for the last failed delivery. - type: string - lastSuccessfulDelivery: - description: Timestamp of the last successful delivery. - type: string - subscriptionStatus: - description: Status of the Subscription as reported by EventMesh. - type: string - subscriptionStatusReason: - description: Reason for the current status. - type: string - type: object - emshash: - description: Defines the checksum for the Subscription in EventMesh. - format: int64 - type: integer - ev2hash: - description: Defines the checksum for the Subscription custom resource. - format: int64 - type: integer - externalSink: - description: Defines the webhook URL which is used by EventMesh to - trigger subscribers. - type: string - failedActivation: - description: Defines the reason if a Subscription failed activation - in EventMesh. - type: string - ready: - description: Overall readiness of the Subscription. - type: boolean - required: - - cleanEventTypes - - ready - type: object - type: object - served: true - storage: false - subresources: - status: {} - additionalPrinterColumns: - jsonPath: .status.ready name: Ready diff --git a/config/samples/subscription_v1alpha1_js.yaml b/config/samples/subscription_v1alpha1_js.yaml deleted file mode 100644 index 86840626c..000000000 --- a/config/samples/subscription_v1alpha1_js.yaml +++ /dev/null @@ -1,27 +0,0 @@ -apiVersion: eventing.kyma-project.io/v1alpha1 -kind: Subscription -metadata: - name: test-noapp1 - namespace: tunas-testing -spec: - filter: - filters: - - eventSource: - property: source - type: exact - value: "noapp" - eventType: - property: type - type: exact - value: sap.kyma.custom.noapp.order.created.v1 - - eventSource: - property: source - type: exact - value: "noapp" - eventType: - property: type - type: exact - value: sap.kyma.custom.noapp.order.created.v2 - protocol: "" - protocolsettings: {} - sink: http://test.tunas-testing.svc.cluster.local \ No newline at end of file diff --git a/hack/e2e/common/eventing/testsubscriptioninfo.go b/hack/e2e/common/eventing/testsubscriptioninfo.go index 52d19b1b5..290d2b6a4 100644 --- a/hack/e2e/common/eventing/testsubscriptioninfo.go +++ b/hack/e2e/common/eventing/testsubscriptioninfo.go @@ -7,10 +7,11 @@ import ( ) type TestSubscriptionInfo struct { - Name string - Description string - Source string - Types []string + Name string + Description string + TypeMatching eventingv1alpha2.TypeMatching + Source string + Types []string } func (s TestSubscriptionInfo) ToSubscriptionV1Alpha2(sink, namespace string) *eventingv1alpha2.Subscription { @@ -21,7 +22,7 @@ func (s TestSubscriptionInfo) ToSubscriptionV1Alpha2(sink, namespace string) *ev }, Spec: eventingv1alpha2.SubscriptionSpec{ Sink: sink, - TypeMatching: eventingv1alpha2.TypeMatchingStandard, + TypeMatching: s.TypeMatching, Source: s.Source, Types: s.Types, }, diff --git a/hack/e2e/common/eventing/utils.go b/hack/e2e/common/eventing/utils.go index 675ca249f..797699a5e 100644 --- a/hack/e2e/common/eventing/utils.go +++ b/hack/e2e/common/eventing/utils.go @@ -8,6 +8,8 @@ import ( cloudevents "github.com/cloudevents/sdk-go/v2" "github.com/cloudevents/sdk-go/v2/binding" "github.com/google/uuid" + + eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" ) const ( @@ -36,8 +38,18 @@ func CloudEventData(source, eventType string, encoding binding.Encoding) map[str return map[string]interface{}{keyApp: source, keyMode: CloudEventMode(encoding), keyType: eventType} } -func ExtractLegacyTypeFromSubscriptionV1Alpha2Type(eventVersion, eventType string) string { - return strings.TrimSuffix(eventType, fmt.Sprintf(".%s", eventVersion)) +func ExtractLegacyTypeFromSubscriptionV1Alpha2Type(eventVersion, eventType string, typeMatching eventingv1alpha2.TypeMatching) string { + if typeMatching == eventingv1alpha2.TypeMatchingStandard { + return strings.TrimSuffix(eventType, fmt.Sprintf(".%s", eventVersion)) + } + + // Assumption: The event type consists of at least 3 parts separated by the "." character. + parts := strings.Split(eventType, ".") + if len(parts) < 3 { + return "" + } + parts = parts[len(parts)-3 : len(parts)-1] + return strings.Join(parts, ".") } func ExtractVersionFromEventType(eventType string) string { @@ -45,14 +57,14 @@ func ExtractVersionFromEventType(eventType string) string { return segments[len(segments)-1] } -func NewLegacyEvent(eventSource, eventType string) (string, string, string, string) { +func NewLegacyEvent(eventSource, eventType string, typeMatching eventingv1alpha2.TypeMatching) (string, string, string, string) { // If the eventType is order.created.v1 and source is noapp, then for legacy event: // eventSource should be: noapp // eventType should be: order.created // eventVersion should be: v1 eventID := uuid.New().String() eventVersion := ExtractVersionFromEventType(eventType) - legacyEventType := ExtractLegacyTypeFromSubscriptionV1Alpha2Type(eventVersion, eventType) + legacyEventType := ExtractLegacyTypeFromSubscriptionV1Alpha2Type(eventVersion, eventType, typeMatching) eventData := LegacyEventData(eventSource, legacyEventType) payload := LegacyEventPayload(eventID, eventVersion, legacyEventType, eventData) diff --git a/hack/e2e/common/fixtures/fixtures.go b/hack/e2e/common/fixtures/fixtures.go index 4c0bf549f..d305d955b 100644 --- a/hack/e2e/common/fixtures/fixtures.go +++ b/hack/e2e/common/fixtures/fixtures.go @@ -13,6 +13,7 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/intstr" + eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" operatorv1alpha1 "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" "github.com/kyma-project/eventing-manager/hack/e2e/common/eventing" ) @@ -120,31 +121,57 @@ func PublisherSpec() operatorv1alpha1.Publisher { func V1Alpha2SubscriptionsToTest() []eventing.TestSubscriptionInfo { return []eventing.TestSubscriptionInfo{ + // type matching exact { - Name: "test-sub-1-v1alpha2", - Description: "event type and source without any alpha-numeric characters", - Source: "noapp", - Types: []string{"order.modified.v1"}, + Name: "test-v1alpha2-exact1", + Description: "single event type", + TypeMatching: eventingv1alpha2.TypeMatchingExact, + Source: "commerce", + Types: []string{ + "sap.kyma.custom.commerce.order.created.v1", + }, + }, + { + Name: "test-v1alpha2-exact2-with-multiple-types", + Description: "multiple event types", + TypeMatching: eventingv1alpha2.TypeMatchingExact, + Source: "app", + Types: []string{ + "sap.kyma.custom.app.event.created.v1", + "sap.kyma.custom.app.event.updated.v1", + "sap.kyma.custom.app.event.deleted.v1", + }, + }, + // type matching standard + { + Name: "test-v1alpha2-standard1", + Description: "event type and source without any alpha-numeric characters", + TypeMatching: eventingv1alpha2.TypeMatchingStandard, + Source: "noapp", + Types: []string{"order.modified.v1"}, }, { - Name: "test-sub-2-v1alpha2", - Description: "event type and source with alpha-numeric characters", - Source: "test-app", - Types: []string{"Order-$.third.R-e-c-e-i-v-e-d.v1"}, + Name: "test-v1alpha2-standard2", + Description: "event type and source with alpha-numeric characters", + TypeMatching: eventingv1alpha2.TypeMatchingStandard, + Source: "test-app", + Types: []string{"Order-$.third.R-e-c-e-i-v-e-d.v1"}, }, { - Name: "test-sub-3-with-multiple-types-v1alpha2", - Description: "multiple types in same subscription", - Source: "test-evnt", + Name: "test-v1alpha2-standard3-with-multiple-types", + Description: "multiple types in same subscription", + TypeMatching: eventingv1alpha2.TypeMatchingStandard, + Source: "test-evnt", Types: []string{ "or-der.crea-ted.one.two.three.four.v4", "order.testing.v1", }, }, { - Name: "test-sub-4-with-multiple-types-v1alpha2", - Description: "multiple types in same subscription", - Source: "test-evnt", + Name: "test-v1alpha2-standard4-with-multiple-types", + Description: "multiple types in same subscription", + TypeMatching: eventingv1alpha2.TypeMatchingStandard, + Source: "test-evnt", Types: []string{ "New.Some-Other.Order-äöüÄÖÜβ.Final.C-r-e-a-t-e-d.v1", "DocuSing_BO.Account_DocuSign.Updated.v1", diff --git a/hack/e2e/common/testenvironment/test_environment.go b/hack/e2e/common/testenvironment/test_environment.go index 7497f5869..90146615a 100644 --- a/hack/e2e/common/testenvironment/test_environment.go +++ b/hack/e2e/common/testenvironment/test_environment.go @@ -160,6 +160,10 @@ func (te *TestEnvironment) CreateV1Alpha2Subscriptions(ctx context.Context, subL for _, subInfo := range subList { err := common.Retry(FewAttempts, SmallInterval, func() error { newSub := subInfo.ToSubscriptionV1Alpha2(te.TestConfigs.SubscriptionSinkURL, te.TestConfigs.TestNamespace) + // create subscription with an empty source in case of exact type matching + if subInfo.TypeMatching == eventingv1alpha2.TypeMatchingExact { + newSub.Spec.Source = "" + } return client.IgnoreAlreadyExists(te.K8sClient.Create(ctx, newSub)) }) // return error if all retries are exhausted. @@ -346,9 +350,9 @@ func (te *TestEnvironment) DeleteSubscriptionFromK8s(name, namespace string) err }) } -func (te *TestEnvironment) TestDeliveryOfLegacyEvent(eventSource, eventType string, subCRVersion fixtures.SubscriptionCRVersion) error { +func (te *TestEnvironment) TestDeliveryOfLegacyEvent(eventSource, eventType string, typeMatching eventingv1alpha2.TypeMatching) error { // define the event - evntID, legacyEventSource, legacyEventType, payload := eventing.NewLegacyEvent(eventSource, eventType) + evntID, legacyEventSource, legacyEventType, payload := eventing.NewLegacyEvent(eventSource, eventType, typeMatching) // publish the event if err := te.EventPublisher.SendLegacyEventWithRetries(legacyEventSource, legacyEventType, payload, FewAttempts, Interval); err != nil { @@ -361,7 +365,12 @@ func (te *TestEnvironment) TestDeliveryOfLegacyEvent(eventSource, eventType stri return te.VerifyLegacyEventReceivedBySink(evntID, eventType, eventSource, payload) } -func (te *TestEnvironment) TestDeliveryOfCloudEvent(eventSource, eventType string, encoding binding.Encoding) error { +func (te *TestEnvironment) TestDeliveryOfCloudEvent(eventSource, eventType string, encoding binding.Encoding, typeMatching eventingv1alpha2.TypeMatching) error { + // use the configured source in case of the exact type matching + if typeMatching == eventingv1alpha2.TypeMatchingExact { + eventSource = te.TestConfigs.EventMeshNamespace + } + // define the event ceEvent, err := eventing.NewCloudEvent(eventSource, eventType, encoding) if err != nil { diff --git a/hack/e2e/eventing/delivery/delivery_test.go b/hack/e2e/eventing/delivery/delivery_test.go index 23b28ee8e..a31d8fb48 100644 --- a/hack/e2e/eventing/delivery/delivery_test.go +++ b/hack/e2e/eventing/delivery/delivery_test.go @@ -8,14 +8,12 @@ import ( "os" "testing" - "github.com/kyma-project/eventing-manager/hack/e2e/common/eventing" - "github.com/cloudevents/sdk-go/v2/binding" "github.com/stretchr/testify/require" "github.com/kyma-project/eventing-manager/hack/e2e/common" + "github.com/kyma-project/eventing-manager/hack/e2e/common/eventing" "github.com/kyma-project/eventing-manager/hack/e2e/common/fixtures" - "github.com/kyma-project/eventing-manager/hack/e2e/common/testenvironment" ) @@ -59,17 +57,17 @@ func TestMain(m *testing.M) { func Test_LegacyEvents(t *testing.T) { t.Parallel() // binding.EncodingUnknown means legacy event. - testEventDelivery(t, LegacyEventCase, fixtures.V1Alpha2SubscriptionsToTest(), binding.EncodingUnknown, fixtures.V1Alpha2SubscriptionCRVersion) + testEventDelivery(t, LegacyEventCase, fixtures.V1Alpha2SubscriptionsToTest(), binding.EncodingUnknown) } func Test_StructuredCloudEvents(t *testing.T) { t.Parallel() - testEventDelivery(t, StructuredCloudEventCase, fixtures.V1Alpha2SubscriptionsToTest(), binding.EncodingStructured, fixtures.V1Alpha2SubscriptionCRVersion) + testEventDelivery(t, StructuredCloudEventCase, fixtures.V1Alpha2SubscriptionsToTest(), binding.EncodingStructured) } func Test_BinaryCloudEvents(t *testing.T) { t.Parallel() - testEventDelivery(t, BinaryCloudEventCase, fixtures.V1Alpha2SubscriptionsToTest(), binding.EncodingBinary, fixtures.V1Alpha2SubscriptionCRVersion) + testEventDelivery(t, BinaryCloudEventCase, fixtures.V1Alpha2SubscriptionsToTest(), binding.EncodingBinary) } // ++ Helper functions @@ -77,8 +75,7 @@ func Test_BinaryCloudEvents(t *testing.T) { func testEventDelivery(t *testing.T, testCase EventTestCase, subsToTest []eventing.TestSubscriptionInfo, - encoding binding.Encoding, - subCRVersion fixtures.SubscriptionCRVersion) { + encoding binding.Encoding) { // In each subscription, we need to run the tests for each event type. // loop over each subscription. for _, subToTest := range subsToTest { @@ -99,9 +96,9 @@ func testEventDelivery(t *testing.T, err := common.Retry(testenvironment.ThreeAttempts, testenvironment.Interval, func() error { if encoding == binding.EncodingUnknown { // binding.EncodingUnknown means legacy event. - return testEnvironment.TestDeliveryOfLegacyEvent(eventSourceToUse, eventTypeToTest, subCRVersion) + return testEnvironment.TestDeliveryOfLegacyEvent(eventSourceToUse, eventTypeToTest, subToTest.TypeMatching) } - return testEnvironment.TestDeliveryOfCloudEvent(eventSourceToUse, eventTypeToTest, encoding) + return testEnvironment.TestDeliveryOfCloudEvent(eventSourceToUse, eventTypeToTest, encoding, subToTest.TypeMatching) }) // then diff --git a/internal/connection/nats/mocks/connection.go b/internal/connection/nats/mocks/connection.go index 26bfb76eb..b09eee073 100644 --- a/internal/connection/nats/mocks/connection.go +++ b/internal/connection/nats/mocks/connection.go @@ -20,9 +20,9 @@ func (_m *Connection) EXPECT() *Connection_Expecter { return &Connection_Expecter{mock: &_m.Mock} } -// Connect provides a mock function with given fields: _a0, _a1 -func (_m *Connection) Connect(_a0 nats.ConnHandler, _a1 nats.ConnErrHandler) error { - ret := _m.Called(_a0, _a1) +// Connect provides a mock function with given fields: handler, errorHandler +func (_m *Connection) Connect(handler nats.ConnHandler, errorHandler nats.ConnErrHandler) error { + ret := _m.Called(handler, errorHandler) if len(ret) == 0 { panic("no return value specified for Connect") @@ -30,7 +30,7 @@ func (_m *Connection) Connect(_a0 nats.ConnHandler, _a1 nats.ConnErrHandler) err var r0 error if rf, ok := ret.Get(0).(func(nats.ConnHandler, nats.ConnErrHandler) error); ok { - r0 = rf(_a0, _a1) + r0 = rf(handler, errorHandler) } else { r0 = ret.Error(0) } @@ -44,13 +44,13 @@ type Connection_Connect_Call struct { } // Connect is a helper method to define mock.On call -// - _a0 nats.ConnHandler -// - _a1 nats.ConnErrHandler -func (_e *Connection_Expecter) Connect(_a0 interface{}, _a1 interface{}) *Connection_Connect_Call { - return &Connection_Connect_Call{Call: _e.mock.On("Connect", _a0, _a1)} +// - handler nats.ConnHandler +// - errorHandler nats.ConnErrHandler +func (_e *Connection_Expecter) Connect(handler interface{}, errorHandler interface{}) *Connection_Connect_Call { + return &Connection_Connect_Call{Call: _e.mock.On("Connect", handler, errorHandler)} } -func (_c *Connection_Connect_Call) Run(run func(_a0 nats.ConnHandler, _a1 nats.ConnErrHandler)) *Connection_Connect_Call { +func (_c *Connection_Connect_Call) Run(run func(handler nats.ConnHandler, errorHandler nats.ConnErrHandler)) *Connection_Connect_Call { _c.Call.Run(func(args mock.Arguments) { run(args[0].(nats.ConnHandler), args[1].(nats.ConnErrHandler)) }) diff --git a/pkg/eventing/manager.go b/pkg/eventing/manager.go index 03d5493ed..af275f8ae 100644 --- a/pkg/eventing/manager.go +++ b/pkg/eventing/manager.go @@ -11,7 +11,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" - eventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" "github.com/kyma-project/eventing-manager/pkg/env" "github.com/kyma-project/eventing-manager/pkg/k8s" @@ -284,14 +283,3 @@ func (em *EventingManager) SubscriptionExists(ctx context.Context) (bool, error) } return false, nil } - -func convertECBackendType(backendType v1alpha1.BackendType) (eventingv1alpha1.BackendType, error) { - switch backendType { - case v1alpha1.EventMeshBackendType: - return eventingv1alpha1.BEBBackendType, nil - case v1alpha1.NatsBackendType: - return eventingv1alpha1.NatsBackendType, nil - default: - return "", fmt.Errorf("%w: %s", ErrUnknownBackendType, backendType) - } -} diff --git a/pkg/eventing/manager_test.go b/pkg/eventing/manager_test.go index b3ef820b6..934d36ca3 100644 --- a/pkg/eventing/manager_test.go +++ b/pkg/eventing/manager_test.go @@ -16,7 +16,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" - eventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/api/operator/v1alpha1" "github.com/kyma-project/eventing-manager/pkg/env" @@ -318,47 +317,6 @@ func Test_IsNATSAvailable(t *testing.T) { } } -func Test_ConvertECBackendType(t *testing.T) { - // Define a list of test cases - testCases := []struct { - name string - backendType v1alpha1.BackendType - expectedResult eventingv1alpha1.BackendType - expectedError error - }{ - { - name: "Convert EventMeshBackendType", - backendType: v1alpha1.EventMeshBackendType, - expectedResult: eventingv1alpha1.BEBBackendType, - expectedError: nil, - }, - { - name: "Convert NatsBackendType", - backendType: v1alpha1.NatsBackendType, - expectedResult: eventingv1alpha1.NatsBackendType, - expectedError: nil, - }, - { - name: "Unknown backend type", - backendType: "unknown", - expectedResult: "", - expectedError: ErrUnknownBackendType, - }, - } - - // Iterate over the test cases and run sub-tests - for _, tc := range testCases { - testcase := tc - t.Run(testcase.name, func(t *testing.T) { - // when - result, err := convertECBackendType(testcase.backendType) - // then - require.ErrorIs(t, err, testcase.expectedError) - require.Equal(t, testcase.expectedResult, result) - }) - } -} - func Test_DeployPublisherProxyResources(t *testing.T) { t.Parallel() diff --git a/pkg/eventing/mocks/manager.go b/pkg/eventing/mocks/manager.go index 9ee6c7d45..28b63adb1 100644 --- a/pkg/eventing/mocks/manager.go +++ b/pkg/eventing/mocks/manager.go @@ -135,9 +135,9 @@ func (_c *Manager_DeployPublisherProxy_Call) RunAndReturn(run func(context.Conte return _c } -// DeployPublisherProxyResources provides a mock function with given fields: _a0, _a1, _a2 -func (_m *Manager) DeployPublisherProxyResources(_a0 context.Context, _a1 *v1alpha1.Eventing, _a2 *v1.Deployment) error { - ret := _m.Called(_a0, _a1, _a2) +// DeployPublisherProxyResources provides a mock function with given fields: ctx, _a1, deploy +func (_m *Manager) DeployPublisherProxyResources(ctx context.Context, _a1 *v1alpha1.Eventing, deploy *v1.Deployment) error { + ret := _m.Called(ctx, _a1, deploy) if len(ret) == 0 { panic("no return value specified for DeployPublisherProxyResources") @@ -145,7 +145,7 @@ func (_m *Manager) DeployPublisherProxyResources(_a0 context.Context, _a1 *v1alp var r0 error if rf, ok := ret.Get(0).(func(context.Context, *v1alpha1.Eventing, *v1.Deployment) error); ok { - r0 = rf(_a0, _a1, _a2) + r0 = rf(ctx, _a1, deploy) } else { r0 = ret.Error(0) } @@ -159,14 +159,14 @@ type Manager_DeployPublisherProxyResources_Call struct { } // DeployPublisherProxyResources is a helper method to define mock.On call -// - _a0 context.Context +// - ctx context.Context // - _a1 *v1alpha1.Eventing -// - _a2 *v1.Deployment -func (_e *Manager_Expecter) DeployPublisherProxyResources(_a0 interface{}, _a1 interface{}, _a2 interface{}) *Manager_DeployPublisherProxyResources_Call { - return &Manager_DeployPublisherProxyResources_Call{Call: _e.mock.On("DeployPublisherProxyResources", _a0, _a1, _a2)} +// - deploy *v1.Deployment +func (_e *Manager_Expecter) DeployPublisherProxyResources(ctx interface{}, _a1 interface{}, deploy interface{}) *Manager_DeployPublisherProxyResources_Call { + return &Manager_DeployPublisherProxyResources_Call{Call: _e.mock.On("DeployPublisherProxyResources", ctx, _a1, deploy)} } -func (_c *Manager_DeployPublisherProxyResources_Call) Run(run func(_a0 context.Context, _a1 *v1alpha1.Eventing, _a2 *v1.Deployment)) *Manager_DeployPublisherProxyResources_Call { +func (_c *Manager_DeployPublisherProxyResources_Call) Run(run func(ctx context.Context, _a1 *v1alpha1.Eventing, deploy *v1.Deployment)) *Manager_DeployPublisherProxyResources_Call { _c.Call.Run(func(args mock.Arguments) { run(args[0].(context.Context), args[1].(*v1alpha1.Eventing), args[2].(*v1.Deployment)) }) @@ -287,9 +287,9 @@ func (_c *Manager_IsNATSAvailable_Call) RunAndReturn(run func(context.Context, s return _c } -// SetBackendConfig provides a mock function with given fields: _a0 -func (_m *Manager) SetBackendConfig(_a0 env.BackendConfig) { - _m.Called(_a0) +// SetBackendConfig provides a mock function with given fields: config +func (_m *Manager) SetBackendConfig(config env.BackendConfig) { + _m.Called(config) } // Manager_SetBackendConfig_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SetBackendConfig' @@ -298,12 +298,12 @@ type Manager_SetBackendConfig_Call struct { } // SetBackendConfig is a helper method to define mock.On call -// - _a0 env.BackendConfig -func (_e *Manager_Expecter) SetBackendConfig(_a0 interface{}) *Manager_SetBackendConfig_Call { - return &Manager_SetBackendConfig_Call{Call: _e.mock.On("SetBackendConfig", _a0)} +// - config env.BackendConfig +func (_e *Manager_Expecter) SetBackendConfig(config interface{}) *Manager_SetBackendConfig_Call { + return &Manager_SetBackendConfig_Call{Call: _e.mock.On("SetBackendConfig", config)} } -func (_c *Manager_SetBackendConfig_Call) Run(run func(_a0 env.BackendConfig)) *Manager_SetBackendConfig_Call { +func (_c *Manager_SetBackendConfig_Call) Run(run func(config env.BackendConfig)) *Manager_SetBackendConfig_Call { _c.Call.Run(func(args mock.Arguments) { run(args[0].(env.BackendConfig)) }) diff --git a/pkg/subscriptionmanager/eventmesh/eventmesh.go b/pkg/subscriptionmanager/eventmesh/eventmesh.go index f3e7bd201..0065e5799 100644 --- a/pkg/subscriptionmanager/eventmesh/eventmesh.go +++ b/pkg/subscriptionmanager/eventmesh/eventmesh.go @@ -18,12 +18,10 @@ import ( kctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/manager" - eventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/internal/controller/eventing/subscription/eventmesh" "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" backendeventmesh "github.com/kyma-project/eventing-manager/pkg/backend/eventmesh" - "github.com/kyma-project/eventing-manager/pkg/backend/eventtype" "github.com/kyma-project/eventing-manager/pkg/backend/metrics" "github.com/kyma-project/eventing-manager/pkg/backend/sink" backendutils "github.com/kyma-project/eventing-manager/pkg/backend/utils" @@ -46,9 +44,6 @@ func AddToScheme(scheme *runtime.Scheme) error { if err := kkubernetesscheme.AddToScheme(scheme); err != nil { return err } - if err := eventingv1alpha1.AddToScheme(scheme); err != nil { - return err - } if err := apigatewayv1beta1.AddToScheme(scheme); err != nil { return err } @@ -121,10 +116,6 @@ func (c *SubscriptionManager) Start(_ env.DefaultSubscriptionConfig, params subm client := c.mgr.GetClient() recorder := c.mgr.GetEventRecorderFor("eventing-controller-beb") - // Initialize v1alpha1 event type cleaner for conversion webhook - simpleCleaner := eventtype.NewSimpleCleaner(c.envCfg.EventTypePrefix, c.logger) - eventingv1alpha1.InitializeEventTypeCleaner(simpleCleaner) - // Initialize v1alpha2 handler for EventMesh eventMeshHandler := backendeventmesh.NewEventMesh(oauth2credential, nameMapper, c.logger) eventMeshcleaner := cleaner.NewEventMeshCleaner(c.logger) diff --git a/pkg/subscriptionmanager/jetstream/jetstream.go b/pkg/subscriptionmanager/jetstream/jetstream.go index b15a471d7..68795b972 100644 --- a/pkg/subscriptionmanager/jetstream/jetstream.go +++ b/pkg/subscriptionmanager/jetstream/jetstream.go @@ -16,11 +16,9 @@ import ( "k8s.io/client-go/rest" "sigs.k8s.io/controller-runtime/pkg/manager" - eventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" subscriptioncontrollerjetstream "github.com/kyma-project/eventing-manager/internal/controller/eventing/subscription/jetstream" "github.com/kyma-project/eventing-manager/pkg/backend/cleaner" - "github.com/kyma-project/eventing-manager/pkg/backend/eventtype" backendjetstream "github.com/kyma-project/eventing-manager/pkg/backend/jetstream" backendmetrics "github.com/kyma-project/eventing-manager/pkg/backend/metrics" "github.com/kyma-project/eventing-manager/pkg/backend/sink" @@ -39,9 +37,6 @@ func AddToScheme(scheme *runtime.Scheme) error { if err := kkubernetesscheme.AddToScheme(scheme); err != nil { return err } - if err := eventingv1alpha1.AddToScheme(scheme); err != nil { - return err - } return nil } @@ -96,10 +91,6 @@ func (sm *SubscriptionManager) Start(defaultSubsConfig env.DefaultSubscriptionCo client := sm.mgr.GetClient() recorder := sm.mgr.GetEventRecorderFor("eventing-controller-jetstream") - // Initialize v1alpha1 event type cleaner for conversion webhook - simpleCleaner := eventtype.NewSimpleCleaner(sm.envCfg.EventTypePrefix, sm.logger) - eventingv1alpha1.InitializeEventTypeCleaner(simpleCleaner) - // Initialize v1alpha2 event type cleaner jsCleaner := cleaner.NewJetStreamCleaner(sm.logger) jetStreamHandler := backendjetstream.NewJetStream(sm.envCfg, diff --git a/pkg/subscriptionmanager/mocks/manager_factory.go b/pkg/subscriptionmanager/mocks/manager_factory.go index a3b18a724..e0fc82d84 100644 --- a/pkg/subscriptionmanager/mocks/manager_factory.go +++ b/pkg/subscriptionmanager/mocks/manager_factory.go @@ -81,9 +81,9 @@ func (_c *ManagerFactory_NewEventMeshManager_Call) RunAndReturn(run func(string) return _c } -// NewJetStreamManager provides a mock function with given fields: _a0, _a1 -func (_m *ManagerFactory) NewJetStreamManager(_a0 v1alpha1.Eventing, _a1 env.NATSConfig) manager.Manager { - ret := _m.Called(_a0, _a1) +// NewJetStreamManager provides a mock function with given fields: eventing, config +func (_m *ManagerFactory) NewJetStreamManager(eventing v1alpha1.Eventing, config env.NATSConfig) manager.Manager { + ret := _m.Called(eventing, config) if len(ret) == 0 { panic("no return value specified for NewJetStreamManager") @@ -91,7 +91,7 @@ func (_m *ManagerFactory) NewJetStreamManager(_a0 v1alpha1.Eventing, _a1 env.NAT var r0 manager.Manager if rf, ok := ret.Get(0).(func(v1alpha1.Eventing, env.NATSConfig) manager.Manager); ok { - r0 = rf(_a0, _a1) + r0 = rf(eventing, config) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(manager.Manager) @@ -107,13 +107,13 @@ type ManagerFactory_NewJetStreamManager_Call struct { } // NewJetStreamManager is a helper method to define mock.On call -// - _a0 v1alpha1.Eventing -// - _a1 env.NATSConfig -func (_e *ManagerFactory_Expecter) NewJetStreamManager(_a0 interface{}, _a1 interface{}) *ManagerFactory_NewJetStreamManager_Call { - return &ManagerFactory_NewJetStreamManager_Call{Call: _e.mock.On("NewJetStreamManager", _a0, _a1)} +// - eventing v1alpha1.Eventing +// - config env.NATSConfig +func (_e *ManagerFactory_Expecter) NewJetStreamManager(eventing interface{}, config interface{}) *ManagerFactory_NewJetStreamManager_Call { + return &ManagerFactory_NewJetStreamManager_Call{Call: _e.mock.On("NewJetStreamManager", eventing, config)} } -func (_c *ManagerFactory_NewJetStreamManager_Call) Run(run func(_a0 v1alpha1.Eventing, _a1 env.NATSConfig)) *ManagerFactory_NewJetStreamManager_Call { +func (_c *ManagerFactory_NewJetStreamManager_Call) Run(run func(eventing v1alpha1.Eventing, config env.NATSConfig)) *ManagerFactory_NewJetStreamManager_Call { _c.Call.Run(func(args mock.Arguments) { run(args[0].(v1alpha1.Eventing), args[1].(env.NATSConfig)) }) diff --git a/testing/test_helpers.go b/testing/test_helpers.go index 1008c1bc6..1f527eddb 100644 --- a/testing/test_helpers.go +++ b/testing/test_helpers.go @@ -16,11 +16,9 @@ import ( "k8s.io/client-go/dynamic" kdynamicfake "k8s.io/client-go/dynamic/fake" - eventingv1alpha1 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha1" eventingv1alpha2 "github.com/kyma-project/eventing-manager/api/eventing/v1alpha2" "github.com/kyma-project/eventing-manager/pkg/ems/api/events/types" "github.com/kyma-project/eventing-manager/pkg/object" - "github.com/kyma-project/eventing-manager/pkg/utils" ) const ( @@ -90,113 +88,6 @@ func GetFreePort() (int, error) { return port, err } -type ProtoOpt func(p *eventingv1alpha1.ProtocolSettings) - -func NewProtocolSettings(opts ...ProtoOpt) *eventingv1alpha1.ProtocolSettings { - protoSettings := &eventingv1alpha1.ProtocolSettings{} - for _, o := range opts { - o(protoSettings) - } - return protoSettings -} - -func WithAtLeastOnceQOS() ProtoOpt { - return func(p *eventingv1alpha1.ProtocolSettings) { - p.Qos = utils.StringPtr(string(types.QosAtLeastOnce)) - } -} - -func WithRequiredWebhookAuth() ProtoOpt { - return func(p *eventingv1alpha1.ProtocolSettings) { - p.WebhookAuth = &eventingv1alpha1.WebhookAuth{ - GrantType: "client_credentials", - ClientID: "xxx", - ClientSecret: "xxx", - TokenURL: "https://oauth2.xxx.com/oauth2/token", - } - } -} - -type SubscriptionV1alpha1Opt func(subscription *eventingv1alpha1.Subscription) - -func WithStatusCleanEventTypes(cleanEventTypes []string) SubscriptionV1alpha1Opt { - return func(sub *eventingv1alpha1.Subscription) { - if cleanEventTypes == nil { - sub.Status.InitializeCleanEventTypes() - } else { - sub.Status.CleanEventTypes = cleanEventTypes - } - } -} - -func WithV1alpha1ProtocolEventMesh() SubscriptionV1alpha1Opt { - return func(s *eventingv1alpha1.Subscription) { - s.Spec.Protocol = EventMeshProtocol - } -} - -func WithV1alpha1ProtocolSettings(p *eventingv1alpha1.ProtocolSettings) SubscriptionV1alpha1Opt { - return func(s *eventingv1alpha1.Subscription) { - s.Spec.ProtocolSettings = p - } -} - -// AddV1alpha1Filter creates a new Filter from eventSource and eventType and adds it to the subscription. -func AddV1alpha1Filter(eventSource, eventType string, subscription *eventingv1alpha1.Subscription) { - if subscription.Spec.Filter == nil { - subscription.Spec.Filter = &eventingv1alpha1.BEBFilters{ - Filters: []*eventingv1alpha1.EventMeshFilter{}, - } - } - - filter := &eventingv1alpha1.EventMeshFilter{ - EventSource: &eventingv1alpha1.Filter{ - Type: "exact", - Property: "source", - Value: eventSource, - }, - EventType: &eventingv1alpha1.Filter{ - Type: "exact", - Property: "type", - Value: eventType, - }, - } - - subscription.Spec.Filter.Filters = append(subscription.Spec.Filter.Filters, filter) -} - -// WithV1alpha1Filter is a SubscriptionOpt for creating a Subscription with a specific event type filter, -// that itself gets created from the passed eventSource and eventType. -func WithV1alpha1Filter(eventSource, eventType string) SubscriptionV1alpha1Opt { - return func(subscription *eventingv1alpha1.Subscription) { - AddV1alpha1Filter(eventSource, eventType, subscription) - } -} - -// WithV1alpha1EmptyFilter is a SubscriptionOpt for creating a subscription with an empty event type filter. -// Note that this is different from setting Filter to nil. -func WithV1alpha1EmptyFilter() SubscriptionV1alpha1Opt { - return func(subscription *eventingv1alpha1.Subscription) { - subscription.Spec.Filter = &eventingv1alpha1.BEBFilters{ - Filters: []*eventingv1alpha1.EventMeshFilter{}, - } - } -} - -func WithV1alpha1EmptyStatus() SubscriptionV1alpha1Opt { - return func(subscription *eventingv1alpha1.Subscription) { - subscription.Status = eventingv1alpha1.SubscriptionStatus{ - CleanEventTypes: []string{}, - } - } -} - -func WithV1alpha1EmptyConfig() SubscriptionV1alpha1Opt { - return func(subscription *eventingv1alpha1.Subscription) { - subscription.Spec.Config = nil - } -} - func NewBEBMessagingSecret(name, namespace string) *kcorev1.Secret { messagingValue := ` [{ @@ -271,58 +162,6 @@ func GetBinaryMessageHeaders() http.Header { return headers } -func PublisherProxyDefaultReadyCondition() eventingv1alpha1.Condition { - return eventingv1alpha1.MakeCondition(eventingv1alpha1.ConditionPublisherProxyReady, - eventingv1alpha1.ConditionReasonPublisherDeploymentReady, - kcorev1.ConditionTrue, "") -} - -func PublisherProxyDefaultNotReadyCondition() eventingv1alpha1.Condition { - return eventingv1alpha1.MakeCondition(eventingv1alpha1.ConditionPublisherProxyReady, - eventingv1alpha1.ConditionReasonPublisherDeploymentNotReady, - kcorev1.ConditionFalse, "") -} - -func SubscriptionControllerDefaultReadyCondition() eventingv1alpha1.Condition { - return eventingv1alpha1.MakeCondition(eventingv1alpha1.ConditionControllerReady, - eventingv1alpha1.ConditionReasonSubscriptionControllerReady, - kcorev1.ConditionTrue, "") -} - -func SubscriptionControllerReadyConditionWith(ready kcorev1.ConditionStatus, - reason eventingv1alpha1.ConditionReason, -) eventingv1alpha1.Condition { - return eventingv1alpha1.MakeCondition(eventingv1alpha1.ConditionControllerReady, reason, ready, "") -} - -func SubscriptionControllerReadyEvent() kcorev1.Event { - return kcorev1.Event{ - Reason: string(eventingv1alpha1.ConditionReasonSubscriptionControllerReady), - Type: kcorev1.EventTypeNormal, - } -} - -func SubscriptionControllerNotReadyEvent() kcorev1.Event { - return kcorev1.Event{ - Reason: string(eventingv1alpha1.ConditionReasonSubscriptionControllerNotReady), - Type: kcorev1.EventTypeWarning, - } -} - -func PublisherDeploymentReadyEvent() kcorev1.Event { - return kcorev1.Event{ - Reason: string(eventingv1alpha1.ConditionReasonPublisherDeploymentReady), - Type: kcorev1.EventTypeNormal, - } -} - -func PublisherDeploymentNotReadyEvent() kcorev1.Event { - return kcorev1.Event{ - Reason: string(eventingv1alpha1.ConditionReasonPublisherDeploymentNotReady), - Type: kcorev1.EventTypeWarning, - } -} - // NewAPIRule returns a valid APIRule. func NewAPIRule(subscription *eventingv1alpha2.Subscription, opts ...APIRuleOption) *apigatewayv1beta1.APIRule { apiRule := &apigatewayv1beta1.APIRule{