/* Copyright 2025 The kcp Authors. 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 clustercachedresources import ( "context" "slices" cachev1alpha1 "github.com/kcp-dev/sdk/apis/cache/v1alpha1" conditionsv1alpha1 "github.com/kcp-dev/sdk/apis/third_party/conditions/apis/conditions/v1alpha1" "github.com/kcp-dev/sdk/apis/third_party/conditions/util/conditions" ) // finalizer is a reconciler that ensures the finalizer is present on the published resource and object is marked as deleting // If is done deleting - it removes the finalizer. type finalizer struct{} func (r *finalizer) reconcile(ctx context.Context, clusterCachedResource *cachev1alpha1.ClusterCachedResource) (reconcileStatus, error) { switch { case !clusterCachedResource.DeletionTimestamp.IsZero() && clusterCachedResource.Status.Phase == cachev1alpha1.ClusterCachedResourcePhaseDeleted: // case 1: Resource is in Deleted phase, remove finalizer if slices.Contains(clusterCachedResource.Finalizers, cachev1alpha1.ClusterCachedResourceFinalizer) { clusterCachedResource.Finalizers = slices.DeleteFunc(clusterCachedResource.Finalizers, func(f string) bool { return f == cachev1alpha1.ClusterCachedResourceFinalizer }) // Requeue once to let the commit land; the object will then be GC'd by the API server. return reconcileStatusStopAndRequeue, nil } // Finalizer already gone — stop without requeueing. The controller will be triggered again // by the Delete watch event once the API server removes the object. return reconcileStatusStop, nil case !clusterCachedResource.DeletionTimestamp.IsZero() && clusterCachedResource.Status.Phase != cachev1alpha1.ClusterCachedResourcePhaseDeleting: // case 2: Resource is being deleted - mark as deleting // Case 1: Resource is being deleted conditions.MarkFalse(clusterCachedResource, cachev1alpha1.ClusterCachedResourceValid, cachev1alpha1.ClusterCachedResourceValidDeleting, conditionsv1alpha1.ConditionSeverityError, "Published resource deleting") clusterCachedResource.Status.Phase = cachev1alpha1.ClusterCachedResourcePhaseDeleting return reconcileStatusStopAndRequeue, nil default: // case 3: Resource is not deleted, ensure finalizer is present if !slices.Contains(clusterCachedResource.Finalizers, cachev1alpha1.ClusterCachedResourceFinalizer) { clusterCachedResource.Finalizers = append(clusterCachedResource.Finalizers, cachev1alpha1.ClusterCachedResourceFinalizer) return reconcileStatusStopAndRequeue, nil } } return reconcileStatusContinue, nil }