Skip to main content

engenho_controllers/
namespace.rs

1//! `NamespaceController` — namespace-cascade (Background) deletion.
2//!
3//! The Viggy/controllers-not-runbooks realization of Kubernetes'
4//! namespace teardown: deleting a Namespace does NOT synchronously remove
5//! its contents in-request. Instead the namespace goes `Terminating` (the
6//! finalizer gate in `engenho-store::state::apply_delete` stamps a
7//! `deletionTimestamp` because the namespace carries the `kubernetes`
8//! finalizer) and THIS controller drives the background sweep:
9//!
10//!   1. list every namespaced object in the Terminating namespace
11//!      (across the typed served namespaced kinds — [`RESOURCE_CATALOG`]
12//!      rows with `namespaced == true`) and DELETE each;
13//!   2. set `status.phase = "Terminating"` so kubectl shows the phase;
14//!   3. once the namespace is EMPTY of namespaced objects, clear the
15//!      `kubernetes` finalizer via a typed `Patch` — which (per the
16//!      store's finalizer-release rule) empties `metadata.finalizers` on a
17//!      deletionTimestamp-bearing object and so the namespace itself is
18//!      GC-removed.
19//!
20//! ## Why a raw [`Controller`] (not [`OwnedChildrenReconciler`](crate::owned_children::OwnedChildrenReconciler))
21//!
22//! Like [`crate::gc::GcController`], the cascade has NO single parent kind
23//! and does a CROSS-KIND sweep — it is "out of family" for the
24//! single-parent owned-children reconciler. It implements the raw
25//! `Controller` trait directly, modeled on `GcController`.
26//!
27//! ## Finalizer-awareness all the way down
28//!
29//! Each child delete is a normal `ResourceCommand::Delete`. If a CHILD
30//! object itself bears finalizers, the store's gate gives IT the
31//! Terminating treatment (deletionTimestamp set, kept until its
32//! finalizers clear) — so the cascade is finalizer-aware end to end. A
33//! child already Terminating is not deleted again (I3): it waits on its
34//! finalizers, and a second delete is the store's `NoOp`. The controller
35//! re-ticks (`WatchDriver` fallback) until the namespace is actually empty.
36//!
37//! ## Scope
38//!
39//! Cascade covers every namespaced kind served right now: the built-in
40//! [`RESOURCE_CATALOG`] rows plus every served version of every stored
41//! `CustomResourceDefinition` ([`ServedKinds`], the garbage collector's
42//! `RESTMapper`), rebuilt each tick.
43//!
44//! ## Where the `kubernetes` finalizer lives
45//!
46//! The apiserver births a Namespace with `kubernetes` in `spec.finalizers`,
47//! as upstream does, and the store holds a deleted Namespace Terminating on
48//! that list ([`engenho_store::ApplySemantics::V2`]). A Namespace stored
49//! before then may carry it in `metadata.finalizers`; both are honoured and
50//! both are cleared.
51
52use std::sync::Arc;
53
54use async_trait::async_trait;
55use engenho_store::{
56    StoreMesh,
57    command::{Reason, ResourceCommand},
58    resource::ResourceKey,
59};
60use engenho_types::generated_v1_34::{RESOURCE_CATALOG, ResourceDescriptor};
61use engenho_types::kind::Scope;
62use serde_json::Value;
63use tracing::{debug, info};
64
65use crate::controller::{Controller, ReconcileOutcome, ReconcileReport};
66use crate::effect::Effect;
67use crate::error::ControllerError;
68use crate::gc::{ServedKind, ServedKinds};
69use crate::meta::ObjectMeta;
70use crate::reads::{DeclaresReads, Reads};
71use crate::status::write_status_cas;
72
73/// The Kubernetes namespace finalizer — gates a Namespace's removal until
74/// its contents are gone. Stamped at create (apiserver) + cleared here.
75const KUBERNETES_FINALIZER: &str = "kubernetes";
76
77/// The typed catalog-reflection surface: every served NAMESPACED kind,
78/// from [`RESOURCE_CATALOG`] where `namespaced == true`. The cascade
79/// iterates this mechanically — adding a namespaced kind to the catalog
80/// extends the cascade with no controller edit.
81#[must_use]
82pub fn namespaced_kinds() -> impl Iterator<Item = &'static ResourceDescriptor> {
83    RESOURCE_CATALOG.iter().filter(|d| d.namespaced)
84}
85
86pub struct NamespaceController {
87    store: Arc<StoreMesh>,
88    /// Namespace scope filter (empty/None = all). Mirrors the other
89    /// controllers' `namespace` knob; the cascade itself is per-namespace
90    /// (it sweeps the Terminating namespace's own contents).
91    #[allow(dead_code)]
92    namespace: Option<String>,
93}
94
95impl NamespaceController {
96    #[must_use]
97    pub fn new(store: Arc<StoreMesh>, namespace: Option<String>) -> Self {
98        Self { store, namespace }
99    }
100
101    /// The finalizer list at `section.finalizers` (`spec` or `metadata`)
102    /// of a Namespace object.
103    fn finalizers_at(ns: &Value, section: &str) -> Vec<String> {
104        ns.get(section)
105            .and_then(|m| m.get("finalizers"))
106            .and_then(Value::as_array)
107            .map(|a| {
108                a.iter()
109                    .filter_map(|v| v.as_str().map(str::to_string))
110                    .collect()
111            })
112            .unwrap_or_default()
113    }
114
115    /// Whether the namespace still holds the `kubernetes` finalizer, in
116    /// `spec.finalizers` or `metadata.finalizers`.
117    fn holds_kubernetes_finalizer(ns: &Value) -> bool {
118        ["spec", "metadata"].iter().any(|section| {
119            Self::finalizers_at(ns, section)
120                .iter()
121                .any(|f| f == KUBERNETES_FINALIZER)
122        })
123    }
124
125    /// Every namespaced kind served right now, each group/version/kind
126    /// once: the catalog plus every stored CRD's served versions.
127    async fn served_namespaced(&self) -> Vec<ServedKind> {
128        let crds = self
129            .store
130            .list(
131                "apiextensions.k8s.io",
132                "v1",
133                "CustomResourceDefinition",
134                None,
135            )
136            .await;
137        let served = ServedKinds::builtin().with_crds(crds.iter().map(|(_, crd)| crd));
138        let mut kinds: Vec<ServedKind> = Vec::new();
139        for k in served.iter().filter(|k| k.scope == Scope::Namespaced) {
140            if !kinds
141                .iter()
142                .any(|s| s.group == k.group && s.version == k.version && s.kind == k.kind)
143            {
144                kinds.push(k.clone());
145            }
146        }
147        kinds
148    }
149
150    /// Sweep one Terminating namespace: delete every namespaced object in
151    /// it, set `status.phase = Terminating`, and — when empty — clear the
152    /// `kubernetes` finalizer (which removes the namespace via the store's
153    /// finalizer-release rule). Every write is recorded on `report` by what
154    /// the store did with it.
155    async fn sweep(
156        &self,
157        ns_name: &str,
158        ns_obj: &Value,
159        report: &mut ReconcileReport,
160    ) -> Result<(), ControllerError> {
161        // Freeze ONE boundary clock read for THIS sweep — threaded into
162        // every child delete so a finalizer-bearing child gets a Terminating
163        // deletionTimestamp (the store's finalizer gate stamps it from this
164        // REPLICATED scalar, never its own clock). A controller is the right
165        // place to read the clock (it's the boundary, not the deterministic
166        // store-apply path). Without this, a child with its OWN finalizer
167        // would hit the gate's "finalizer + no timestamp ⇒ NoOp" branch and
168        // the cascade would never drain it.
169        let deletion_ts = engenho_types::time::now_rfc3339_utc();
170
171        // 1. status.phase = Terminating (idempotent via write_status_cas).
172        let ns_key = ResourceKey::cluster_scoped("", "v1", "Namespace", ns_name);
173        let desired_status = serde_json::json!({ "phase": "Terminating" });
174        let status = write_status_cas(&self.store, &ns_key, ns_obj, &desired_status).await?;
175        report.record(status.effect());
176
177        // 2. Delete every namespaced object in this namespace across all
178        //    served namespaced kinds, CRD-served kinds included.
179        let mut remaining = 0usize;
180        for d in self.served_namespaced().await {
181            let objs = self
182                .store
183                .list(&d.group, &d.version, &d.kind, Some(ns_name))
184                .await;
185            for (key, value) in objs {
186                remaining += 1;
187                // Already Terminating: its delete was accepted and its own
188                // finalizers hold it. Deleting it again is the store's
189                // NoOp, one Raft entry per tick for as long as the finalizer
190                // holds, so it is left alone. It still counts as remaining:
191                // the namespace waits for it to go.
192                if value.is_terminating() {
193                    continue;
194                }
195                debug!(
196                    namespace = ns_name,
197                    child = %key.label(),
198                    "cascade-deleting namespaced object"
199                );
200                // GC-reason delete carrying the frozen sweep timestamp. If
201                // the child bears its OWN finalizers, the store gate stamps
202                // its deletionTimestamp (Terminating) from this replicated
203                // scalar and keeps it until its finalizers clear; the next
204                // tick re-counts it as still-remaining (cascade is
205                // finalizer-aware all the way down). A no-finalizer child is
206                // removed immediately.
207                let out = self
208                    .store
209                    .propose(ResourceCommand::delete_at(
210                        key,
211                        None,
212                        Reason::GarbageCollector,
213                        Some(deletion_ts.clone()),
214                    ))
215                    .await?;
216                // Only a real removal / Terminating stamp counts as a change.
217                report.record(Effect::of(out.op));
218            }
219        }
220
221        // 3. If the namespace is now EMPTY of namespaced objects, clear the
222        //    kubernetes finalizer so the namespace itself is removed. We use
223        //    the LIVE listed-this-tick `remaining` count; a non-zero count
224        //    means we re-tick (WatchDriver fallback) until drained.
225        if remaining == 0 {
226            if Self::holds_kubernetes_finalizer(ns_obj) {
227                let mut patch = serde_json::Map::new();
228                for section in ["spec", "metadata"] {
229                    let current = Self::finalizers_at(ns_obj, section);
230                    if current.iter().any(|f| f == KUBERNETES_FINALIZER) {
231                        let next: Vec<String> = current
232                            .into_iter()
233                            .filter(|f| f != KUBERNETES_FINALIZER)
234                            .collect();
235                        patch.insert(
236                            section.to_string(),
237                            serde_json::json!({ "finalizers": next }),
238                        );
239                    }
240                }
241                let patch = Value::Object(patch);
242                info!(
243                    namespace = ns_name,
244                    "namespace empty; clearing kubernetes finalizer (removal follows)"
245                );
246                let out = self
247                    .store
248                    .propose(ResourceCommand::patch(
249                        ns_key,
250                        patch,
251                        Reason::GarbageCollector,
252                    ))
253                    .await?;
254                report.record(Effect::of(out.op));
255            }
256        } else {
257            debug!(
258                namespace = ns_name,
259                remaining, "namespace still has objects; will re-tick"
260            );
261        }
262
263        Ok(())
264    }
265}
266
267/// The cascade lists every served namespaced kind, CRD-served kinds it
268/// cannot name ahead of time included, so every event wakes it (as
269/// [`crate::gc::GcController`]). A child's deletion then wakes it, so a
270/// namespace finishes draining when its last object goes rather than a
271/// fallback interval later.
272impl DeclaresReads for NamespaceController {
273    fn reads(&self) -> Reads {
274        Reads::every()
275    }
276}
277
278#[async_trait]
279impl Controller for NamespaceController {
280    fn name(&self) -> &'static str {
281        "namespace"
282    }
283
284    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
285        let mut report = ReconcileReport::default();
286
287        // Enumerate Namespaces (cluster-scoped).
288        let namespaces = self.store.list("", "v1", "Namespace", None).await;
289        report.objects_examined = namespaces.len();
290
291        for (key, ns_obj) in namespaces {
292            // Only act on Terminating namespaces that still hold the
293            // kubernetes finalizer (the ones we own the teardown of).
294            if !ns_obj.is_terminating() || !Self::holds_kubernetes_finalizer(&ns_obj) {
295                continue;
296            }
297            let ns_name = &key.name;
298            self.sweep(ns_name, &ns_obj, &mut report).await?;
299        }
300
301        // Done — the WatchDriver fallback tick re-runs until each
302        // Terminating namespace drains (mirrors gc.rs).
303        Ok(report.into())
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310    use engenho_store::{InProcessRouter, default_config};
311    use serde_json::json;
312    use std::time::Duration;
313
314    /// Build a single-node in-memory `StoreMesh` (the controller-test rig the
315    /// other reconciler tests use — see `tests/r9_replicaset_controller.rs`).
316    async fn test_store() -> Arc<StoreMesh> {
317        let router = InProcessRouter::new();
318        let cfg = default_config("controllers-namespace").unwrap();
319        let store = Arc::new(
320            StoreMesh::start(1, "in-process://1".into(), router, cfg)
321                .await
322                .unwrap(),
323        );
324        store.initialize_singleton().await.unwrap();
325        assert!(store.wait_for_leadership(Duration::from_secs(3)).await);
326        store
327    }
328
329    async fn put(store: &StoreMesh, key: ResourceKey, value: Value) {
330        store
331            .propose(ResourceCommand::put(key, value, Reason::Operator))
332            .await
333            .expect("put");
334    }
335
336    #[test]
337    fn namespaced_kinds_filters_to_namespaced_only() {
338        // The catalog-reflection surface enumerates ONLY namespaced rows.
339        let kinds: Vec<&str> = namespaced_kinds().map(|d| d.kind).collect();
340        assert!(kinds.contains(&"ConfigMap"));
341        assert!(kinds.contains(&"Deployment"));
342        assert!(kinds.contains(&"Pod"));
343        // Cluster-scoped kinds are excluded.
344        assert!(!kinds.contains(&"Namespace"));
345        assert!(!kinds.contains(&"Node"));
346        assert!(!kinds.contains(&"ClusterRole"));
347        // Every enumerated descriptor is genuinely namespaced.
348        assert!(namespaced_kinds().all(|d| d.namespaced));
349    }
350
351    #[tokio::test]
352    async fn cascade_deletes_children_then_clears_finalizer() {
353        let store = test_store().await;
354        let c = NamespaceController::new(store.clone(), None);
355
356        // Seed a Terminating namespace WITH the kubernetes finalizer.
357        let ns_key = ResourceKey::cluster_scoped("", "v1", "Namespace", "demo");
358        put(
359            &store,
360            ns_key.clone(),
361            json!({
362                "kind": "Namespace",
363                "apiVersion": "v1",
364                "metadata": {
365                    "name": "demo",
366                    "finalizers": [KUBERNETES_FINALIZER],
367                    "deletionTimestamp": "2026-06-08T00:00:00Z"
368                },
369                "status": { "phase": "Active" }
370            }),
371        )
372        .await;
373        // + 1 ConfigMap and 1 Deployment in it.
374        put(
375            &store,
376            ResourceKey::namespaced("", "v1", "ConfigMap", "demo", "a"),
377            json!({"kind": "ConfigMap", "metadata": {"name": "a", "namespace": "demo"}, "data": {"x": "y"}}),
378        )
379        .await;
380        put(
381            &store,
382            ResourceKey::namespaced("apps", "v1", "Deployment", "demo", "d"),
383            json!({"kind": "Deployment", "metadata": {"name": "d", "namespace": "demo"}, "spec": {"replicas": 1}}),
384        )
385        .await;
386
387        // First tick: status.phase=Terminating (1) + 2 child deletes = 3
388        // changes; the namespace is NOT yet empty THIS tick (children were
389        // listed as present), so the finalizer is not cleared.
390        let out = c.tick().await.unwrap();
391        assert!(out.objects_changed >= 2, "both children deleted");
392        // Children are gone.
393        assert!(
394            store
395                .get(&ResourceKey::namespaced("", "v1", "ConfigMap", "demo", "a"))
396                .await
397                .is_none(),
398            "configmap cascade-deleted"
399        );
400        assert!(
401            store
402                .get(&ResourceKey::namespaced(
403                    "apps",
404                    "v1",
405                    "Deployment",
406                    "demo",
407                    "d"
408                ))
409                .await
410                .is_none(),
411            "deployment cascade-deleted"
412        );
413
414        // Second tick: namespace now empty → clear the kubernetes
415        // finalizer, which removes the namespace itself.
416        let out2 = c.tick().await.unwrap();
417        assert!(out2.objects_changed >= 1, "finalizer cleared");
418        assert!(
419            store.get(&ns_key).await.is_none(),
420            "namespace removed once finalizer cleared"
421        );
422    }
423
424    #[tokio::test]
425    async fn cascade_is_finalizer_aware_for_children() {
426        // A child bearing its OWN finalizer gets the Terminating treatment
427        // (deletionTimestamp stamped, kept) on the first sweep — the cascade
428        // threads a frozen timestamp so the store gate stamps it. The
429        // namespace is NOT removed while the child is still present. Once the
430        // child's finalizer clears, the next sweep drains it + removes the ns.
431        let store = test_store().await;
432        let c = NamespaceController::new(store.clone(), None);
433        let ns_key = ResourceKey::cluster_scoped("", "v1", "Namespace", "fin");
434        put(
435            &store,
436            ns_key.clone(),
437            json!({
438                "kind": "Namespace",
439                "metadata": {
440                    "name": "fin",
441                    "finalizers": [KUBERNETES_FINALIZER],
442                    "deletionTimestamp": "2026-06-08T00:00:00Z"
443                }
444            }),
445        )
446        .await;
447        let child_key = ResourceKey::namespaced("", "v1", "ConfigMap", "fin", "held");
448        put(
449            &store,
450            child_key.clone(),
451            json!({
452                "kind": "ConfigMap",
453                "metadata": {"name": "held", "namespace": "fin", "finalizers": ["example.com/hold"]},
454                "data": {"x": "y"}
455            }),
456        )
457        .await;
458
459        // First sweep: the child is given a deletionTimestamp (Terminating),
460        // NOT removed; the namespace stays (child still present).
461        c.tick().await.unwrap();
462        let child = store
463            .get(&child_key)
464            .await
465            .expect("child still present (Terminating)");
466        assert!(
467            child
468                .get("metadata")
469                .and_then(|m| m.get("deletionTimestamp"))
470                .and_then(|d| d.as_str())
471                .is_some(),
472            "finalizer-bearing child got a deletionTimestamp (Terminating)"
473        );
474        assert!(
475            store.get(&ns_key).await.is_some(),
476            "ns held while child present"
477        );
478
479        // Clear the child's finalizer → it is removed by the store rule.
480        store
481            .propose(ResourceCommand::patch(
482                child_key.clone(),
483                json!({"metadata": {"finalizers": []}}),
484                Reason::Operator,
485            ))
486            .await
487            .unwrap();
488        assert!(
489            store.get(&child_key).await.is_none(),
490            "child removed after finalizer clear"
491        );
492
493        // Next sweep: namespace now empty → finalizer cleared → removed.
494        c.tick().await.unwrap();
495        assert!(store.get(&ns_key).await.is_none(), "ns removed once empty");
496    }
497
498    #[tokio::test]
499    async fn non_terminating_namespace_untouched() {
500        let store = test_store().await;
501        let c = NamespaceController::new(store.clone(), None);
502        let ns_key = ResourceKey::cluster_scoped("", "v1", "Namespace", "live");
503        put(
504            &store,
505            ns_key.clone(),
506            json!({
507                "kind": "Namespace",
508                "metadata": { "name": "live", "finalizers": [KUBERNETES_FINALIZER] },
509                "status": { "phase": "Active" }
510            }),
511        )
512        .await;
513        let out = c.tick().await.unwrap();
514        assert_eq!(out.objects_changed, 0, "active namespace untouched");
515        assert!(store.get(&ns_key).await.is_some(), "still present");
516    }
517}