Skip to main content

engenho_controllers/
crd.rs

1//! R21 — CRD (`CustomResourceDefinition`) serving.
2//!
3//! Lets operators register new typed kinds at runtime without recompiling.
4//! A CRD declares:
5//!   * `spec.group`
6//!   * `spec.versions[]` — each `{name, served, storage, schema.openAPIV3Schema}`
7//!   * `spec.scope` (`Namespaced` | `Cluster`)
8//!   * `spec.names` — `{plural, singular, kind, listKind, shortNames[]}`
9//!
10//! ## How it gets served (REUSE, not fork)
11//!
12//! A CRD object is stored opaquely via the SAME `StoreBackedHandler` as any
13//! other kind (the `apiextensions.k8s.io/v1.CustomResourceDefinition`
14//! catalog row builds it automatically). The [`CrdController`] then reacts
15//! to CRD writes by registering a `StoreBackedHandler` PER SERVED VERSION
16//! into the apiserver's live `RouterState` (via the [`DynamicHandlerSink`]
17//! trait the apiserver implements) — so every CR instance verb (CRUD / list
18//! / watch) flows through the existing catch-all + `do_*` bodies, and the
19//! group + resource auto-appear in discovery (both fold the same live
20//! handler snapshot). There is NO parallel CR codepath.
21//!
22//! ## Reconcile rule (`CrdController`)
23//!
24//! For each `CustomResourceDefinition` in the store:
25//!   1. Parse `spec` through the typed [`CrdSpec`] serde border.
26//!   2. For EACH served version, `sink.register_crd(...)` under
27//!      `(group, version, plural)` + scope + names + shortNames.
28//!   3. Patch CRD `status` to `Established=True` / `NamesAccepted=True`.
29//!
30//! Removal of a CRD object → `sink.unregister_crd(...)` for every version
31//! the controller had registered (precise GC via the private
32//! [`CrdEntry`]-keyed bookkeeping set). Orphaned CR objects remain in the
33//! store unreachable (no cascade-delete — finalizers are a future brick).
34
35use std::collections::BTreeMap;
36use std::sync::Arc;
37
38use async_trait::async_trait;
39use engenho_store::{
40    StoreMesh,
41    command::{Reason, ResourceCommand},
42};
43use serde::{Deserialize, Serialize};
44use serde_json::{Value, json};
45use thiserror::Error;
46
47use crate::controller::{Controller, ReconcileOutcome, ReconcileReport};
48use crate::effect::Effect;
49use crate::error::ControllerError;
50use crate::reads::{DeclaresReads, Reads, gvk};
51
52/// Resource scope.
53#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(rename_all = "PascalCase")]
55pub enum CrdScope {
56    /// Namespaced — must specify `metadata.namespace`.
57    Namespaced,
58    /// Cluster-scoped — no namespace allowed.
59    Cluster,
60}
61
62impl CrdScope {
63    /// `true` for `Namespaced`. The router/handler scope flag is
64    /// `namespaced: bool`, so this is the bridge.
65    #[must_use]
66    pub fn is_namespaced(self) -> bool {
67        matches!(self, CrdScope::Namespaced)
68    }
69}
70
71// ── typed serde border for the CRD spec (TYPED EMISSION) ────────────────
72//
73// The CRD OBJECT is stored opaquely (StoreBackedHandler is opaque-JSON);
74// this typed border is purely how the controller PARSES the few `spec.*`
75// paths it acts on — through types, not ad-hoc `.get()` chains. Unknown
76// fields are tolerated (CRDs carry far more than we read) so we never
77// reject a valid upstream CRD.
78
79/// `spec.names` — how kubectl names the custom resource.
80#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
81pub struct CrdNames {
82    /// Plural URL segment (`widgets`).
83    pub plural: String,
84    /// Singular name (`widget`) — discovery `singularName`. Defaults to the
85    /// lowercased kind when absent.
86    #[serde(default)]
87    pub singular: String,
88    /// Kind (`Widget`).
89    pub kind: String,
90    /// List kind (`WidgetList`) — defaults to `{kind}List` when absent.
91    #[serde(rename = "listKind", default)]
92    pub list_kind: String,
93    /// kubectl short-name aliases (`["wd"]`) — discovery `shortNames`.
94    #[serde(rename = "shortNames", default)]
95    pub short_names: Vec<String>,
96    /// kubectl categories (`["all"]`).
97    #[serde(default)]
98    pub categories: Vec<String>,
99}
100
101/// `spec.versions[].subresources` — which subresources a CRD version serves.
102///
103/// kube declares an enabled subresource as an EMPTY OBJECT
104/// (`subresources: {status: {}}`), so presence is the signal and there is no
105/// boolean to read. `Option<serde_json::Value>` therefore models it exactly:
106/// `Some` ⇒ served, `None` ⇒ not.
107#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
108pub struct CrdSubresources {
109    /// Present ⇒ this version serves `/status`.
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub status: Option<serde_json::Value>,
112    /// Present ⇒ this version serves `/scale`. Captured so it round-trips;
113    /// engenho does not serve it for CRDs yet.
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub scale: Option<serde_json::Value>,
116}
117
118/// One entry in `spec.versions[]`.
119#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
120pub struct CrdVersion {
121    /// Version name (`v1`, `v1beta1`).
122    pub name: String,
123    /// Whether this version is served at the API surface. Only served
124    /// versions get a registered handler.
125    #[serde(default)]
126    pub served: bool,
127    /// Whether this version is the storage version. Recorded but not
128    /// load-bearing until conversion lands (each served version reads/writes
129    /// the same stored object at its own GVK).
130    #[serde(default)]
131    pub storage: bool,
132    /// `subresources` as the CRD declares them.
133    ///
134    /// Only the PRESENCE of `status` is read: kube's schema models it as
135    /// `subresources.status: {}` — an empty object whose existence is the
136    /// whole signal. Captured opaque so `scale` (unsupported here) round-trips
137    /// without being silently dropped.
138    #[serde(default)]
139    pub subresources: Option<CrdSubresources>,
140    /// The `OpenAPI` v3 schema (`schema.openAPIV3Schema`) — captured opaque;
141    /// structural validation against it is DEFERRED (CR creates are accepted
142    /// as-is via `--validate=false`).
143    #[serde(default)]
144    pub schema: Value,
145    #[serde(default, rename = "additionalPrinterColumns")]
146    pub additional_printer_columns: Vec<Value>,
147}
148
149/// The typed `spec` of a `CustomResourceDefinition` — the parse border the
150/// controller drives. Unknown fields tolerated (no `deny_unknown_fields`).
151#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
152pub struct CrdSpec {
153    /// API group (`example.com`).
154    #[serde(default)]
155    pub group: String,
156    /// Resource scope. Defaults to Namespaced (kube-apiserver default).
157    #[serde(default = "default_scope")]
158    pub scope: CrdScope,
159    /// Names block.
160    pub names: CrdNames,
161    /// All declared versions. The controller registers a handler PER served
162    /// version (widened beyond the old `versions.first()`).
163    #[serde(default)]
164    pub versions: Vec<CrdVersion>,
165}
166
167fn default_scope() -> CrdScope {
168    CrdScope::Namespaced
169}
170
171/// One registered CRD-version handler descriptor — the controller's PRIVATE
172/// bookkeeping of "what I registered" (keyed by `(group, version, plural)`)
173/// so unregister-on-delete is precise. This REPLACES the old `CrdRegistry`
174/// routing surface; routing now lives in the apiserver's `RouterState` via
175/// the [`DynamicHandlerSink`].
176#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
177pub struct CrdEntry {
178    /// `example.com` (empty for core, never for a real CRD).
179    pub group: String,
180    /// The served version (`v1`).
181    pub version: String,
182    /// `Widget`.
183    pub kind: String,
184    /// Plural list-kind (`WidgetList`).
185    pub list_kind: String,
186    /// Plural URL segment (`widgets`).
187    pub plural: String,
188    /// Singular (`widget`).
189    pub singular: String,
190    /// kubectl short-name aliases (`["wd"]`).
191    pub short_names: Vec<String>,
192    /// kubectl categories (`["all"]`).
193    pub categories: Vec<String>,
194    /// Namespace scope.
195    pub scope: CrdScope,
196    /// Does THIS version serve `/status`? Read from the CRD's own
197    /// `subresources.status`, never assumed — a CRD that declares no
198    /// status subresource must keep 404-ing, exactly as kube does.
199    pub serves_status: bool,
200    /// The opaque openAPIV3Schema for this version (validation DEFERRED).
201    pub schema: Value,
202    #[serde(default)]
203    pub printer_columns: Vec<Value>,
204}
205
206impl CrdEntry {
207    /// Canonical routing key `(group, version, plural)` — the SAME triple
208    /// the `RouterState` handler map is keyed on.
209    #[must_use]
210    pub fn route_key(&self) -> (String, String, String) {
211        (
212            self.group.clone(),
213            self.version.clone(),
214            self.plural.clone(),
215        )
216    }
217}
218
219/// Registry errors.
220#[derive(Debug, Clone, Error)]
221pub enum CrdError {
222    /// Conflict — a different CRD already exists under this key.
223    #[error("conflict on {0}")]
224    Conflict(String),
225    /// Schema invalid (apiserver couldn't compile / validate).
226    #[error("invalid schema for {key}: {reason}")]
227    InvalidSchema {
228        /// CRD key.
229        key: String,
230        /// Reason from the schema compiler.
231        reason: String,
232    },
233}
234
235engenho_substrate::impl_error_kind! {
236    CrdError {
237        (Conflict(_)) => "conflict",
238        { InvalidSchema { .. } } => "invalid_schema",
239    }
240}
241
242// =================================================================
243// DynamicHandlerSink — the apiserver-provided registration surface
244// =================================================================
245
246/// Typed sink the apiserver implements so the controller (which must NOT
247/// depend on engenho-apiserver — that would be a dependency cycle, since
248/// apiserver already depends on controllers for admission) can mutate the
249/// live `RouterState` handler table.
250///
251/// The apiserver impl builds a `StoreBackedHandler::new(store, g, v, kind,
252/// plural, namespaced).with_registration_metadata(short_names, singular,
253/// categories).with_admission(chain)` and calls `RouterState::register` /
254/// `::unregister`. Threading `short_names` + `singular` from `spec.names`
255/// into `with_registration_metadata` is the ONE load-bearing wiring detail
256/// that makes `kubectl get wd` + `kubectl api-resources` resolve the CR.
257pub trait DynamicHandlerSink: Send + Sync {
258    /// Register a CR-instance handler under `(group, version, plural)` with
259    /// the given scope + discovery metadata. Idempotent (a re-register is a
260    /// harmless overwrite of the same GVK).
261    fn register_crd(&self, spec: CrdHandlerSpec);
262
263    /// Unregister the CR-instance handler keyed by `(group, version,
264    /// plural)`. Returns `true` iff one was present + removed.
265    fn unregister_crd(&self, group: &str, version: &str, plural: &str) -> bool;
266}
267
268/// The typed argument bundle for [`DynamicHandlerSink::register_crd`] — one
269/// served CRD version's full handler shape, carried as owned `String`s
270/// (the controller derives them from the typed `CrdSpec`).
271#[derive(Clone, Debug, PartialEq, Eq)]
272pub struct CrdHandlerSpec {
273    /// API group (`example.com`).
274    pub group: String,
275    /// Served version (`v1`).
276    pub version: String,
277    /// Kind (`Widget`).
278    pub kind: String,
279    /// Plural (`widgets`).
280    pub plural: String,
281    /// Singular (`widget`).
282    pub singular: String,
283    /// Short-name aliases (`["wd"]`).
284    pub short_names: Vec<String>,
285    /// Categories (`["all"]`).
286    pub categories: Vec<String>,
287    /// `true` ⇒ namespaced.
288    pub namespaced: bool,
289    /// `true` ⇒ register the `/status` subresource for this version.
290    pub serves_status: bool,
291    /// This version's `openAPIV3Schema` — the INNER schema, already unwrapped
292    /// from [`CrdEntry::schema`]'s `{ "openAPIV3Schema": … }` envelope, so the
293    /// consumer validates against a real schema rather than against a
294    /// one-key wrapper that declares no `type` and silently matches
295    /// everything. That exact off-by-one-level made the first cut of this
296    /// enforcement a no-op.
297    pub schema: Value,
298    pub printer_columns: Vec<Value>,
299}
300
301impl From<&CrdEntry> for CrdHandlerSpec {
302    fn from(e: &CrdEntry) -> Self {
303        Self {
304            group: e.group.clone(),
305            version: e.version.clone(),
306            kind: e.kind.clone(),
307            plural: e.plural.clone(),
308            singular: e.singular.clone(),
309            short_names: e.short_names.clone(),
310            categories: e.categories.clone(),
311            namespaced: e.scope.is_namespaced(),
312            serves_status: e.serves_status,
313            // Unwrap the envelope HERE, where the shape is known, rather than
314            // making every consumer remember to.
315            schema: e
316                .schema
317                .get("openAPIV3Schema")
318                .cloned()
319                .unwrap_or(Value::Null),
320            printer_columns: e.printer_columns.clone(),
321        }
322    }
323}
324
325// =================================================================
326// CrdController — reconciles CRDs from the store into the router table
327// =================================================================
328
329/// Controller that syncs `apiextensions.k8s.io/v1.CustomResourceDefinition`
330/// objects from the store into the apiserver's live handler table via a
331/// [`DynamicHandlerSink`]. Driven by a `WatchDriver` filtered to
332/// `["CustomResourceDefinition"]`.
333pub struct CrdController {
334    store: Arc<StoreMesh>,
335    sink: Arc<dyn DynamicHandlerSink>,
336    /// What this controller has registered, keyed by `(group, version,
337    /// plural)` → entry. PRIVATE bookkeeping (the old `CrdRegistry` collapses
338    /// into this), so unregister-on-delete is precise. Behind a `Mutex`
339    /// because `tick()` takes `&self` (the `Controller` trait), but the set
340    /// is mutated across ticks.
341    registered: std::sync::Mutex<BTreeMap<(String, String, String), CrdEntry>>,
342}
343
344impl CrdController {
345    /// New controller. `sink` is the apiserver-provided handle that mutates
346    /// the live `RouterState`.
347    #[must_use]
348    pub fn new(store: Arc<StoreMesh>, sink: Arc<dyn DynamicHandlerSink>) -> Self {
349        Self {
350            store,
351            sink,
352            registered: std::sync::Mutex::new(BTreeMap::new()),
353        }
354    }
355
356    /// Parse a CRD manifest into the typed [`CrdSpec`]. `None` if `spec` is
357    /// missing or unparseable (a malformed CRD is skipped, never panics).
358    #[must_use]
359    pub fn parse_spec(crd: &Value) -> Option<CrdSpec> {
360        let spec = crd.get("spec")?;
361        serde_json::from_value::<CrdSpec>(spec.clone()).ok()
362    }
363
364    /// Extract one [`CrdEntry`] PER SERVED version from a CRD manifest. This
365    /// WIDENS the old `extract_entry` (which only read `versions.first()`):
366    /// a multi-served-version CRD now yields one entry per served version,
367    /// each registered under its own GVK. Returns an empty vec for a CRD
368    /// with no served versions (or an unparseable spec).
369    ///
370    /// `plural` / `singular` / `kind` / `shortNames` / `scope` / `listKind`
371    /// all flow from the typed `spec.names` + `spec.scope`.
372    #[must_use]
373    pub fn extract_entries(crd: &Value) -> Vec<CrdEntry> {
374        let Some(spec) = Self::parse_spec(crd) else {
375            return Vec::new();
376        };
377        let kind = &spec.names.kind;
378        let singular = if spec.names.singular.is_empty() {
379            kind.to_lowercase()
380        } else {
381            spec.names.singular.clone()
382        };
383        let list_kind = if spec.names.list_kind.is_empty() {
384            let mut lk = kind.clone();
385            lk.push_str("List");
386            lk
387        } else {
388            spec.names.list_kind.clone()
389        };
390        spec.versions
391            .iter()
392            .filter(|v| v.served)
393            .map(|v| CrdEntry {
394                group: spec.group.clone(),
395                version: v.name.clone(),
396                kind: kind.clone(),
397                list_kind: list_kind.clone(),
398                plural: spec.names.plural.clone(),
399                singular: singular.clone(),
400                short_names: spec.names.short_names.clone(),
401                categories: spec.names.categories.clone(),
402                scope: spec.scope,
403                serves_status: v
404                    .subresources
405                    .as_ref()
406                    .is_some_and(|sr| sr.status.is_some()),
407                schema: v.schema.clone(),
408                printer_columns: v.additional_printer_columns.clone(),
409            })
410            .collect()
411    }
412
413    /// Snapshot of the controller's currently-registered entries (test +
414    /// introspection). Order is by `(group, version, plural)`.
415    #[must_use]
416    pub fn registered_entries(&self) -> Vec<CrdEntry> {
417        self.registered
418            .lock()
419            .expect("registered mutex not poisoned")
420            .values()
421            .cloned()
422            .collect()
423    }
424}
425
426/// Register every served version of every CRD in `store` into `sink`, and
427/// return how many were registered.
428///
429/// The boot calls this before the apiserver binds, so a restarted daemon
430/// serves its stored CRDs on its first request instead of answering
431/// `unknown kind` until the [`CrdController`]'s first tick (measured on plo
432/// 2026-11-15: seconds to minutes, and an informer that started in that
433/// window made no progress for about 40 minutes). The controller's first tick
434/// registers the same entries again, an overwrite of the same handler.
435pub async fn serve_stored_crds(store: &StoreMesh, sink: &dyn DynamicHandlerSink) -> usize {
436    let crds = store
437        .list(
438            "apiextensions.k8s.io",
439            "v1",
440            "CustomResourceDefinition",
441            None,
442        )
443        .await;
444    let mut registered = 0;
445    for entry in crds
446        .iter()
447        .flat_map(|(_, crd)| CrdController::extract_entries(crd))
448    {
449        sink.register_crd(CrdHandlerSpec::from(&entry));
450        registered += 1;
451    }
452    registered
453}
454
455/// The CRDs whose served versions it registers handlers for.
456impl DeclaresReads for CrdController {
457    fn reads(&self) -> Reads {
458        Reads::of(&[gvk(
459            "apiextensions.k8s.io",
460            "v1",
461            "CustomResourceDefinition",
462        )])
463    }
464}
465
466#[async_trait]
467impl Controller for CrdController {
468    fn name(&self) -> &'static str {
469        "crd"
470    }
471
472    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
473        let crds = self
474            .store
475            .list(
476                "apiextensions.k8s.io",
477                "v1",
478                "CustomResourceDefinition",
479                None,
480            )
481            .await;
482        let mut report = ReconcileReport::default();
483        report.objects_examined = crds.len();
484
485        // Build the desired set: for every CRD, one entry per served
486        // version keyed by (group, version, plural).
487        let mut desired: BTreeMap<(String, String, String), CrdEntry> = BTreeMap::new();
488        // Track which CRD object (by store ResourceKey) owns each route key,
489        // so we patch status on the right object exactly once per CRD when
490        // first established.
491        let mut crd_for_key: BTreeMap<(String, String, String), engenho_store::ResourceKey> =
492            BTreeMap::new();
493
494        for (crd_key, crd_value) in &crds {
495            let entries = Self::extract_entries(crd_value);
496            if entries.is_empty() {
497                report.objects_skipped += 1;
498                continue;
499            }
500            for entry in entries {
501                let key = entry.route_key();
502                crd_for_key
503                    .entry(key.clone())
504                    .or_insert_with(|| crd_key.clone());
505                desired.insert(key, entry);
506            }
507        }
508
509        // Register any newly-desired (or changed) route key. Idempotent
510        // re-registration is a harmless overwrite of the same GVK.
511        let mut crds_to_establish: std::collections::BTreeSet<engenho_store::ResourceKey> =
512            std::collections::BTreeSet::new();
513        {
514            let mut reg = self
515                .registered
516                .lock()
517                .expect("registered mutex not poisoned");
518            for (key, entry) in &desired {
519                let needs_register = reg.get(key) != Some(entry);
520                if needs_register {
521                    // An in-process handler-table insert that cannot fail
522                    // and returns nothing to read. Not a store write: the
523                    // controller's own record of what it registered answers
524                    // whether the table changed.
525                    self.sink.register_crd(CrdHandlerSpec::from(entry));
526                    let previous = reg.insert(key.clone(), entry.clone());
527                    report.record(Effect::answered(previous.as_ref() != Some(entry)));
528                    if let Some(crd_key) = crd_for_key.get(key) {
529                        crds_to_establish.insert(crd_key.clone());
530                    }
531                }
532            }
533
534            // GC: any previously-registered route key not in the desired set
535            // (its CRD object was deleted, or that version stopped being
536            // served) → unregister the handler so subsequent CR access is a
537            // typed NotFound.
538            let stale: Vec<(String, String, String)> = reg
539                .keys()
540                .filter(|k| !desired.contains_key(*k))
541                .cloned()
542                .collect();
543            // The sink says whether a handler was actually there to remove;
544            // that answer is the change, not the attempt.
545            for key in stale {
546                let removed = self.sink.unregister_crd(&key.0, &key.1, &key.2);
547                reg.remove(&key);
548                report.record(Effect::answered(removed));
549            }
550        }
551
552        // Patch status Established=True / NamesAccepted=True on each CRD
553        // that gained a fresh registration this tick. Done OUTSIDE the
554        // registered-set lock (no .await while holding a std Mutex).
555        for crd_key in crds_to_establish {
556            self.store
557                .propose(ResourceCommand::patch(
558                    crd_key,
559                    json!({
560                        "status": {
561                            "conditions": [
562                                {
563                                    "type": "Established",
564                                    "status": "True",
565                                    "reason": "InitialNamesAccepted",
566                                    "message": "the initial names have been accepted"
567                                },
568                                {
569                                    "type": "NamesAccepted",
570                                    "status": "True",
571                                    "reason": "NoConflicts",
572                                    "message": "no conflicts found"
573                                }
574                            ]
575                        }
576                    }),
577                    Reason::Controller,
578                ))
579                .await?;
580        }
581
582        Ok(report.into())
583    }
584}
585
586#[cfg(test)]
587mod tests {
588    use super::*;
589    use std::sync::Mutex;
590
591    // ── recording mock sink ──────────────────────────────────────
592
593    #[derive(Default)]
594    struct RecordingSink {
595        registered: Mutex<Vec<CrdHandlerSpec>>,
596        unregistered: Mutex<Vec<(String, String, String)>>,
597        /// The handler table lost the entry on its own (a restart, a
598        /// sibling's unregister): `unregister_crd` finds nothing to remove.
599        already_gone: bool,
600    }
601
602    impl DynamicHandlerSink for RecordingSink {
603        fn register_crd(&self, spec: CrdHandlerSpec) {
604            self.registered.lock().unwrap().push(spec);
605        }
606        fn unregister_crd(&self, group: &str, version: &str, plural: &str) -> bool {
607            self.unregistered.lock().unwrap().push((
608                group.to_string(),
609                version.to_string(),
610                plural.to_string(),
611            ));
612            !self.already_gone
613        }
614    }
615
616    fn single_version_crd() -> Value {
617        json!({
618            "spec": {
619                "group": "example.com",
620                "scope": "Namespaced",
621                "names": {
622                    "plural": "widgets",
623                    "singular": "widget",
624                    "kind": "Widget",
625                    "listKind": "WidgetList",
626                    "shortNames": ["wd"]
627                },
628                "versions": [{
629                    "name": "v1",
630                    "served": true,
631                    "storage": true,
632                    "schema": {"openAPIV3Schema": {"type": "object"}}
633                }]
634            }
635        })
636    }
637
638    fn multi_version_crd() -> Value {
639        json!({
640            "spec": {
641                "group": "example.com",
642                "scope": "Cluster",
643                "names": {
644                    "plural": "gizmos",
645                    "kind": "Gizmo",
646                    "shortNames": ["gz"]
647                },
648                "versions": [
649                    {"name": "v1", "served": true, "storage": true},
650                    {"name": "v2", "served": true, "storage": false},
651                    {"name": "v1alpha1", "served": false, "storage": false}
652                ]
653            }
654        })
655    }
656
657    // ── parse_spec / extract_entries ─────────────────────────────
658
659    #[test]
660    fn extract_entries_single_served_version() {
661        let entries = CrdController::extract_entries(&single_version_crd());
662        assert_eq!(entries.len(), 1);
663        let e = &entries[0];
664        assert_eq!(e.group, "example.com");
665        assert_eq!(e.version, "v1");
666        assert_eq!(e.kind, "Widget");
667        assert_eq!(e.plural, "widgets");
668        assert_eq!(e.singular, "widget");
669        assert_eq!(e.short_names, vec!["wd".to_string()]);
670        assert_eq!(e.scope, CrdScope::Namespaced);
671        assert_eq!(
672            e.schema
673                .get("openAPIV3Schema")
674                .unwrap()
675                .get("type")
676                .unwrap(),
677            "object"
678        );
679    }
680
681    #[test]
682    fn extract_entries_iterates_all_served_versions_only() {
683        // The widened behavior: a 3-version CRD with 2 served versions
684        // yields exactly 2 entries (the served=false one is skipped); the
685        // old `versions.first()` would have yielded 1.
686        let entries = CrdController::extract_entries(&multi_version_crd());
687        assert_eq!(entries.len(), 2, "one entry per SERVED version");
688        let versions: Vec<&str> = entries.iter().map(|e| e.version.as_str()).collect();
689        assert!(versions.contains(&"v1"));
690        assert!(versions.contains(&"v2"));
691        assert!(!versions.contains(&"v1alpha1"), "unserved version skipped");
692        // Names/scope flow from spec.names + spec.scope onto every entry.
693        for e in &entries {
694            assert_eq!(e.kind, "Gizmo");
695            assert_eq!(e.plural, "gizmos");
696            assert_eq!(e.singular, "gizmo", "singular defaults to lowercased kind");
697            assert_eq!(
698                e.list_kind, "GizmoList",
699                "listKind defaults to {{kind}}List"
700            );
701            assert_eq!(e.short_names, vec!["gz".to_string()]);
702            assert_eq!(e.scope, CrdScope::Cluster);
703        }
704    }
705
706    #[test]
707    fn extract_entries_empty_for_missing_names() {
708        // No spec.names → unparseable → empty (skipped, never panics).
709        let crd = json!({"spec": {"group": "x", "versions": [{"name": "v1", "served": true}]}});
710        assert!(CrdController::extract_entries(&crd).is_empty());
711    }
712
713    #[test]
714    fn extract_entries_empty_for_no_served_versions() {
715        let crd = json!({
716            "spec": {
717                "group": "x.io",
718                "names": {"plural": "xs", "kind": "X"},
719                "versions": [{"name": "v1", "served": false}]
720            }
721        });
722        assert!(CrdController::extract_entries(&crd).is_empty());
723    }
724
725    #[test]
726    fn crd_handler_spec_from_entry_threads_metadata() {
727        let entries = CrdController::extract_entries(&single_version_crd());
728        let spec = CrdHandlerSpec::from(&entries[0]);
729        assert_eq!(spec.plural, "widgets");
730        assert_eq!(spec.singular, "widget");
731        assert_eq!(spec.short_names, vec!["wd".to_string()]);
732        assert!(spec.namespaced, "Namespaced scope → namespaced=true");
733    }
734
735    #[test]
736    fn scope_serializes_pascal_case() {
737        assert_eq!(
738            serde_json::to_string(&CrdScope::Cluster).unwrap(),
739            "\"Cluster\""
740        );
741    }
742
743    #[test]
744    fn error_kinds_are_stable() {
745        assert_eq!(CrdError::Conflict("x".into()).kind(), "conflict");
746        assert_eq!(
747            CrdError::InvalidSchema {
748                key: "x".into(),
749                reason: "y".into()
750            }
751            .kind(),
752            "invalid_schema"
753        );
754    }
755
756    #[test]
757    fn controller_name_is_stable() {
758        struct F;
759        #[async_trait]
760        impl Controller for F {
761            fn name(&self) -> &'static str {
762                "crd"
763            }
764            async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
765                Ok(ReconcileReport::default().into())
766            }
767        }
768        assert_eq!(F.name(), "crd");
769    }
770
771    // ── tick() with a recording sink + ephemeral store ───────────
772
773    async fn ephemeral_store() -> Arc<StoreMesh> {
774        use engenho_store::{InProcessRouter, default_config};
775        use std::time::Duration;
776        let router = InProcessRouter::new();
777        let cfg = default_config("crd-ctrl-test").unwrap();
778        let store = Arc::new(
779            StoreMesh::start(1, "in-process://1".into(), router, cfg)
780                .await
781                .unwrap(),
782        );
783        store.initialize_singleton().await.unwrap();
784        assert!(store.wait_for_leadership(Duration::from_secs(3)).await);
785        store
786    }
787
788    #[tokio::test]
789    async fn tick_registers_one_handler_per_served_version() {
790        use engenho_store::{ResourceKey, command::ResourceCommand};
791        let store = ephemeral_store().await;
792        let sink = Arc::new(RecordingSink::default());
793        let ctrl = CrdController::new(store.clone(), sink.clone());
794
795        // Install a multi-served-version CRD object.
796        store
797            .propose(ResourceCommand::Put {
798                key: ResourceKey::cluster_scoped(
799                    "apiextensions.k8s.io",
800                    "v1",
801                    "CustomResourceDefinition",
802                    "gizmos.example.com",
803                ),
804                value: multi_version_crd(),
805                expected: None,
806                reason: Reason::Operator,
807            })
808            .await
809            .unwrap();
810
811        ctrl.tick().await.unwrap();
812
813        // Two register_crd calls (v1 + v2), neither for the unserved
814        // v1alpha1; both cluster-scoped with the gz short name.
815        let regs = sink.registered.lock().unwrap();
816        assert_eq!(regs.len(), 2);
817        for r in regs.iter() {
818            assert_eq!(r.plural, "gizmos");
819            assert_eq!(r.short_names, vec!["gz".to_string()]);
820            assert!(!r.namespaced, "Cluster scope → namespaced=false");
821        }
822        let versions: Vec<&str> = regs.iter().map(|r| r.version.as_str()).collect();
823        assert!(versions.contains(&"v1") && versions.contains(&"v2"));
824
825        // The controller's bookkeeping mirrors the two registrations.
826        assert_eq!(ctrl.registered_entries().len(), 2);
827    }
828
829    #[tokio::test]
830    async fn tick_is_idempotent_no_duplicate_registers() {
831        use engenho_store::{ResourceKey, command::ResourceCommand};
832        let store = ephemeral_store().await;
833        let sink = Arc::new(RecordingSink::default());
834        let ctrl = CrdController::new(store.clone(), sink.clone());
835        store
836            .propose(ResourceCommand::Put {
837                key: ResourceKey::cluster_scoped(
838                    "apiextensions.k8s.io",
839                    "v1",
840                    "CustomResourceDefinition",
841                    "widgets.example.com",
842                ),
843                value: single_version_crd(),
844                expected: None,
845                reason: Reason::Operator,
846            })
847            .await
848            .unwrap();
849
850        let first = ctrl.tick().await.unwrap();
851        let second = ctrl.tick().await.unwrap(); // nothing new.
852        assert_eq!(
853            sink.registered.lock().unwrap().len(),
854            1,
855            "re-tick does not re-register the unchanged CRD"
856        );
857        assert_eq!(first.objects_changed, 1, "the new handler is a change");
858        assert_eq!(second.objects_changed, 0, "a re-tick changes nothing");
859    }
860
861    /// The count after deleting a registered CRD, against a sink that
862    /// either still holds the handler or has already lost it.
863    async fn changed_by_unregister(sink: Arc<RecordingSink>) -> usize {
864        use engenho_store::{ResourceKey, command::ResourceCommand};
865        let store = ephemeral_store().await;
866        let ctrl = CrdController::new(store.clone(), sink.clone());
867        let crd_key = ResourceKey::cluster_scoped(
868            "apiextensions.k8s.io",
869            "v1",
870            "CustomResourceDefinition",
871            "widgets.example.com",
872        );
873        store
874            .propose(ResourceCommand::Put {
875                key: crd_key.clone(),
876                value: single_version_crd(),
877                expected: None,
878                reason: Reason::Operator,
879            })
880            .await
881            .unwrap();
882        ctrl.tick().await.unwrap();
883        store
884            .propose(ResourceCommand::delete(crd_key, Reason::Operator))
885            .await
886            .unwrap();
887        let outcome = ctrl.tick().await.unwrap();
888        assert_eq!(
889            sink.unregistered.lock().unwrap().len(),
890            1,
891            "unregister was called"
892        );
893        assert!(ctrl.registered_entries().is_empty(), "bookkeeping cleared");
894        outcome.objects_changed
895    }
896
897    /// An unregister is counted by the sink's answer, not by the call: a
898    /// handler that was already gone is not a change.
899    #[tokio::test]
900    async fn an_unregister_that_found_nothing_is_not_a_change() {
901        let present = Arc::new(RecordingSink::default());
902        assert_eq!(
903            changed_by_unregister(present).await,
904            1,
905            "positive control: removing a live handler is a change"
906        );
907        let gone = Arc::new(RecordingSink {
908            already_gone: true,
909            ..RecordingSink::default()
910        });
911        assert_eq!(
912            changed_by_unregister(gone).await,
913            0,
914            "the sink removed nothing, so nothing changed"
915        );
916    }
917
918    #[tokio::test]
919    async fn tick_unregisters_on_crd_delete() {
920        use engenho_store::{ResourceKey, command::ResourceCommand};
921        let store = ephemeral_store().await;
922        let sink = Arc::new(RecordingSink::default());
923        let ctrl = CrdController::new(store.clone(), sink.clone());
924        let crd_key = ResourceKey::cluster_scoped(
925            "apiextensions.k8s.io",
926            "v1",
927            "CustomResourceDefinition",
928            "widgets.example.com",
929        );
930        store
931            .propose(ResourceCommand::Put {
932                key: crd_key.clone(),
933                value: single_version_crd(),
934                expected: None,
935                reason: Reason::Operator,
936            })
937            .await
938            .unwrap();
939        ctrl.tick().await.unwrap();
940        assert_eq!(ctrl.registered_entries().len(), 1);
941
942        // Delete the CRD object, then tick → the handler is unregistered.
943        store
944            .propose(ResourceCommand::delete(crd_key, Reason::Operator))
945            .await
946            .unwrap();
947        ctrl.tick().await.unwrap();
948
949        let unregs = sink.unregistered.lock().unwrap();
950        assert_eq!(unregs.len(), 1);
951        assert_eq!(
952            unregs[0],
953            (
954                "example.com".to_string(),
955                "v1".to_string(),
956                "widgets".to_string()
957            )
958        );
959        assert!(
960            ctrl.registered_entries().is_empty(),
961            "bookkeeping cleared on GC"
962        );
963    }
964}