Browse Source

feat: add component event handler

Thomas Zhang 4 months ago
parent
commit
55acfa3f51
1 changed files with 67 additions and 0 deletions
  1. 67 0
      internal/controller/helper.go

+ 67 - 0
internal/controller/helper.go

@@ -0,0 +1,67 @@
+/*
+Copyright 2026 LocoStack.
+
+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.
+*/
+
+package controller
+
+import (
+	"context"
+
+	"github.com/LocoStack/loco-operator/api/v1alpha1"
+	corev1 "k8s.io/api/core/v1"
+	"k8s.io/apimachinery/pkg/runtime/schema"
+	"k8s.io/apimachinery/pkg/types"
+	"sigs.k8s.io/controller-runtime/pkg/client"
+	"sigs.k8s.io/controller-runtime/pkg/handler"
+	"sigs.k8s.io/controller-runtime/pkg/reconcile"
+)
+
+func ComponentEventHandler(kind string) handler.EventHandler {
+	mapFunc := func(ctx context.Context, obj client.Object) []reconcile.Request {
+		comp, ok := obj.(*v1alpha1.Component)
+		if !ok {
+			return nil
+		}
+		var reqs []reconcile.Request
+		for _, dep := range comp.Spec.Dependencies {
+			if !dependencyRefMatches(dep, kind) {
+				continue
+			}
+			namespace := dep.Namespace
+			if namespace == "" {
+				namespace = comp.GetNamespace()
+			}
+			reqs = append(reqs, reconcile.Request{
+				NamespacedName: types.NamespacedName{
+					Name:      dep.Name,
+					Namespace: namespace,
+				},
+			})
+		}
+		return reqs
+	}
+	return handler.EnqueueRequestsFromMapFunc(mapFunc)
+}
+
+func dependencyRefMatches(ref corev1.ObjectReference, kind string) bool {
+	if ref.Kind != kind {
+		return false
+	}
+	if ref.APIVersion == "" {
+		return true
+	}
+	gv, err := schema.ParseGroupVersion(ref.APIVersion)
+	return err == nil && gv.Group == v1alpha1.GroupVersion.Group
+}