Skip to main content

engenho_controllers/
served_capability.rs

1//! ADVERTISED-BUT-INERT KINDS — making a no-op say so.
2//!
3//! ★ THE GAP THIS CLOSES. Three kinds are in the catalog and therefore in
4//! discovery, and nothing implements their behaviour: `APIService` (no
5//! aggregation proxy), `FlowSchema` and `PriorityLevelConfiguration` (no
6//! priority-and-fairness queueing). A client can discover them, create one,
7//! get a `201`, and receive no semantics whatsoever.
8//!
9//! That is the one pattern this codebase otherwise refuses everywhere else.
10//! `kotae` says an answer must name WHICH of four things happened; a
11//! silently-inert kind answers `found` when the truth is `refused`.
12//!
13//! ★ WHY NOT SIMPLY STOP ADVERTISING THEM. Because the contract is the
14//! product. Removing `APIService` from discovery makes engenho visibly not
15//! a Kubernetes API server — every client that enumerates api groups sees a
16//! hole — and the whole programme is to present the real surface first and
17//! decide about the technology behind it afterwards. The honest move is to
18//! keep the surface and make the ABSENCE queryable.
19//!
20//! ★ WHY `Available=False` ON `APIService` IS THE LOAD-BEARING HALF.
21//! `Available` is not decoration: it is the field a client reads to decide
22//! whether to ROUTE to an aggregated service. metrics-server registers an
23//! `APIService` and expects the apiserver to proxy `metrics.k8s.io` to it.
24//! Left with no status, its registration looks successful and every query
25//! to that group silently goes nowhere — a broken feature that reports
26//! itself healthy. `Available=False` turns that into `kubectl get
27//! apiservices` showing exactly which group is not served, and why.
28//!
29//! ★ THE OTHER TWO GET AN ENGENHO-SCOPED CONDITION, NOT AN UPSTREAM ONE.
30//! `FlowSchema` has an upstream `Dangling` condition meaning something
31//! specific (it references a `PriorityLevelConfiguration` that does not
32//! exist). Reusing it to mean "engenho has no APF" would be a lie in
33//! upstream's own vocabulary — a client acting on `Dangling` would go fix a
34//! reference that is perfectly correct. A condition type we own cannot be
35//! misread as a claim we are not making.
36
37use std::sync::Arc;
38
39use async_trait::async_trait;
40use serde_json::{Value, json};
41
42use engenho_store::StoreMesh;
43use engenho_store::command::{Reason, ResourceCommand};
44
45use crate::controller::{Controller, ReconcileOutcome, ReconcileReport};
46use crate::effect::Effect;
47use crate::error::ControllerError;
48use crate::reads::{DeclaresReads, Reads, gvk};
49
50/// The condition type engenho uses to declare that a kind's behaviour is
51/// not implemented on this server.
52///
53/// Deliberately NOT an upstream condition type: see the module header.
54pub const SERVED_CONDITION: &str = "engenho.io/Served";
55
56/// Upstream's `APIService` availability condition. Real, and read by real
57/// clients to decide routing — which is why it is set here and why the
58/// value is `False`.
59pub const AVAILABLE_CONDITION: &str = "Available";
60
61/// A kind engenho advertises but does not implement.
62///
63/// A CLOSED enum: adding a fourth inert kind is a compile error at every
64/// match, which is the only way this list stays honest as the catalog
65/// grows. An open `&str` here would let a kind go inert silently — exactly
66/// the failure this module exists to end.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum InertKind {
69    /// Aggregation layer: no proxy to an aggregated apiserver.
70    ApiService,
71    /// Priority and fairness: no request queueing.
72    FlowSchema,
73    /// Priority and fairness: no concurrency shares.
74    PriorityLevelConfiguration,
75}
76
77impl InertKind {
78    /// Classify a kind name.
79    ///
80    /// Returns `None` for every kind engenho DOES implement — a served kind
81    /// must never be stamped inert, which would be a worse lie than the
82    /// silence this replaces.
83    #[must_use]
84    pub fn classify(kind: &str) -> Option<Self> {
85        match kind {
86            "APIService" => Some(Self::ApiService),
87            "FlowSchema" => Some(Self::FlowSchema),
88            "PriorityLevelConfiguration" => Some(Self::PriorityLevelConfiguration),
89            _ => None,
90        }
91    }
92
93    /// The kind's name, as it appears in the catalog.
94    #[must_use]
95    pub fn kind_name(self) -> &'static str {
96        match self {
97            Self::ApiService => "APIService",
98            Self::FlowSchema => "FlowSchema",
99            Self::PriorityLevelConfiguration => "PriorityLevelConfiguration",
100        }
101    }
102
103    /// A machine-readable reason, in upstream's CamelCase convention.
104    #[must_use]
105    pub fn reason(self) -> &'static str {
106        match self {
107            Self::ApiService => "AggregationNotImplemented",
108            Self::FlowSchema | Self::PriorityLevelConfiguration => {
109                "PriorityAndFairnessNotImplemented"
110            }
111        }
112    }
113
114    /// A message naming what is missing and what follows from it, because
115    /// the operator reading this needs to know the CONSEQUENCE, not just
116    /// that a box is unchecked.
117    #[must_use]
118    pub fn message(self) -> &'static str {
119        match self {
120            Self::ApiService => {
121                "engenho does not implement the aggregation layer: this \
122                 APIService is stored and returned, but no request to its \
123                 group is proxied to the backing service"
124            }
125            Self::FlowSchema => {
126                "engenho does not implement priority and fairness: this \
127                 FlowSchema is stored and returned, but no request is \
128                 classified or queued by it"
129            }
130            Self::PriorityLevelConfiguration => {
131                "engenho does not implement priority and fairness: this \
132                 PriorityLevelConfiguration is stored and returned, but no \
133                 concurrency share is enforced from it"
134            }
135        }
136    }
137
138    /// Whether this kind ALSO carries upstream's own condition.
139    ///
140    /// Only `APIService` does, and only because `Available` is the field a
141    /// client reads to decide routing. Inventing upstream conditions for
142    /// the other two would put false claims in upstream's vocabulary.
143    #[must_use]
144    pub fn upstream_condition(self) -> Option<&'static str> {
145        match self {
146            Self::ApiService => Some(AVAILABLE_CONDITION),
147            Self::FlowSchema | Self::PriorityLevelConfiguration => None,
148        }
149    }
150
151    /// The conditions to publish on this object's `status`.
152    #[must_use]
153    pub fn conditions(self, now: &str) -> Vec<Value> {
154        let mut out = vec![json!({
155            "type": SERVED_CONDITION,
156            "status": "False",
157            "reason": self.reason(),
158            "message": self.message(),
159            "lastTransitionTime": now,
160        })];
161        if let Some(upstream) = self.upstream_condition() {
162            out.push(json!({
163                "type": upstream,
164                "status": "False",
165                "reason": self.reason(),
166                "message": self.message(),
167                "lastTransitionTime": now,
168            }));
169        }
170        out
171    }
172}
173
174/// Whether an object already carries the truthful conditions.
175///
176/// Used to keep the stamping idempotent: re-writing an unchanged status on
177/// every tick advances the store revision forever, which is the hot-loop
178/// class this codebase guards against elsewhere and would reintroduce here.
179#[must_use]
180pub fn already_stamped(object: &Value, kind: InertKind) -> bool {
181    let Some(conds) = object
182        .get("status")
183        .and_then(|s| s.get("conditions"))
184        .and_then(Value::as_array)
185    else {
186        return false;
187    };
188    let has = |ty: &str| {
189        conds.iter().any(|c| {
190            c.get("type").and_then(Value::as_str) == Some(ty)
191                && c.get("status").and_then(Value::as_str) == Some("False")
192                && c.get("reason").and_then(Value::as_str) == Some(kind.reason())
193        })
194    };
195    has(SERVED_CONDITION) && kind.upstream_condition().is_none_or(has)
196}
197
198/// The object with truthful conditions applied.
199#[must_use]
200pub fn stamped(object: &Value, kind: InertKind, now: &str) -> Value {
201    let mut out = object.clone();
202    out["status"] = json!({ "conditions": kind.conditions(now) });
203    out
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209
210    const NOW: &str = "2026-08-30T00:00:00Z";
211
212    #[test]
213    fn only_the_three_inert_kinds_classify() {
214        for k in ["APIService", "FlowSchema", "PriorityLevelConfiguration"] {
215            assert!(InertKind::classify(k).is_some(), "{k}");
216        }
217        // A served kind stamped inert would be a worse lie than the silence
218        // this module replaces.
219        for k in [
220            "Pod",
221            "Service",
222            "Deployment",
223            "Node",
224            "CustomResourceDefinition",
225        ] {
226            assert!(InertKind::classify(k).is_none(), "{k} is served");
227        }
228    }
229
230    #[test]
231    fn classify_round_trips_the_kind_name() {
232        for k in ["APIService", "FlowSchema", "PriorityLevelConfiguration"] {
233            assert_eq!(InertKind::classify(k).unwrap().kind_name(), k);
234        }
235    }
236
237    #[test]
238    fn apiservice_carries_upstreams_available_and_the_others_do_not() {
239        // The load-bearing asymmetry. `Available` is what a client reads to
240        // decide whether to route to an aggregated service, so a
241        // registration that is silently unreachable must say so THERE.
242        let api = InertKind::ApiService.conditions(NOW);
243        assert_eq!(api.len(), 2);
244        assert!(api.iter().any(|c| c["type"] == AVAILABLE_CONDITION));
245        assert!(api.iter().all(|c| c["status"] == "False"));
246
247        // Reusing upstream's `Dangling` to mean "no APF" would send a
248        // client to fix a reference that is perfectly correct.
249        for k in [InertKind::FlowSchema, InertKind::PriorityLevelConfiguration] {
250            let c = k.conditions(NOW);
251            assert_eq!(c.len(), 1, "{k:?}");
252            assert_eq!(c[0]["type"], SERVED_CONDITION);
253            assert_ne!(c[0]["type"], "Dangling");
254        }
255    }
256
257    #[test]
258    fn every_message_names_the_consequence_not_just_the_absence() {
259        // An operator needs to know what STOPS WORKING, not that a box is
260        // unchecked. Each message says what is stored and what is not done.
261        for k in [
262            InertKind::ApiService,
263            InertKind::FlowSchema,
264            InertKind::PriorityLevelConfiguration,
265        ] {
266            let m = k.message();
267            assert!(m.contains("stored and returned"), "{k:?}: {m}");
268            assert!(m.contains("engenho does not implement"), "{k:?}: {m}");
269        }
270    }
271
272    #[test]
273    fn stamping_is_idempotent() {
274        // Re-writing an unchanged status every tick advances the revision
275        // forever — the same hot-loop class the node lease hit.
276        for k in [
277            InertKind::ApiService,
278            InertKind::FlowSchema,
279            InertKind::PriorityLevelConfiguration,
280        ] {
281            let obj = json!({ "kind": k.kind_name(), "metadata": { "name": "x" } });
282            assert!(!already_stamped(&obj, k), "{k:?} starts unstamped");
283            let once = stamped(&obj, k, NOW);
284            assert!(already_stamped(&once, k), "{k:?} is stamped after one pass");
285        }
286    }
287
288    #[test]
289    fn a_partial_stamp_is_not_accepted_as_complete() {
290        // An APIService carrying only the engenho condition is still
291        // silently unroutable to a client reading `Available`.
292        let partial = json!({
293            "status": { "conditions": [{
294                "type": SERVED_CONDITION,
295                "status": "False",
296                "reason": InertKind::ApiService.reason(),
297            }]}
298        });
299        assert!(
300            !already_stamped(&partial, InertKind::ApiService),
301            "the Available half is missing"
302        );
303    }
304
305    #[test]
306    fn a_true_condition_does_not_count_as_stamped() {
307        // Guards the direction that matters: something claiming the kind IS
308        // served must never satisfy the check.
309        let lying = json!({
310            "status": { "conditions": [{
311                "type": SERVED_CONDITION,
312                "status": "True",
313                "reason": InertKind::FlowSchema.reason(),
314            }]}
315        });
316        assert!(!already_stamped(&lying, InertKind::FlowSchema));
317    }
318}
319
320// =====================================================================
321// THE PRODUCER
322// =====================================================================
323
324/// The API group each inert kind lives in. Kept beside the enum rather
325/// than looked up, because the whole list is three entries and a lookup
326/// that can miss would silently skip a kind — the failure this module
327/// exists to end.
328impl InertKind {
329    /// `(group, version)` for this kind.
330    #[must_use]
331    pub fn group_version(self) -> (&'static str, &'static str) {
332        match self {
333            Self::ApiService => ("apiregistration.k8s.io", "v1"),
334            Self::FlowSchema | Self::PriorityLevelConfiguration => {
335                ("flowcontrol.apiserver.k8s.io", "v1")
336            }
337        }
338    }
339
340    /// Every inert kind. An array rather than an iterator over strings so
341    /// the compiler checks the arity against the closed enum.
342    #[must_use]
343    pub const fn all() -> [Self; 3] {
344        [
345            Self::ApiService,
346            Self::FlowSchema,
347            Self::PriorityLevelConfiguration,
348        ]
349    }
350}
351
352/// Stamps truthful status conditions onto every advertised-but-inert
353/// object, so a no-op is queryable instead of silent.
354///
355/// ★ THIS CONTROLLER IS THE PRODUCER. Without it the module above is a
356/// well-tested vocabulary nobody emits — the exact shape that has now been
357/// the root of six separate gaps in this codebase.
358pub struct ServedCapabilityController {
359    store: Arc<StoreMesh>,
360}
361
362impl ServedCapabilityController {
363    /// New controller over `store`.
364    #[must_use]
365    pub fn new(store: Arc<StoreMesh>) -> Self {
366        Self { store }
367    }
368}
369
370/// Every inert kind, from the same [`InertKind::all`] its tick walks.
371impl DeclaresReads for ServedCapabilityController {
372    fn reads(&self) -> Reads {
373        InertKind::all()
374            .into_iter()
375            .map(|kind| {
376                let (group, version) = kind.group_version();
377                gvk(group, version, kind.kind_name())
378            })
379            .collect()
380    }
381}
382
383#[async_trait]
384impl Controller for ServedCapabilityController {
385    fn name(&self) -> &'static str {
386        "served-capability"
387    }
388
389    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
390        let mut report = ReconcileReport::default();
391        let now = engenho_types::time::now_rfc3339_utc();
392
393        for kind in InertKind::all() {
394            let (group, version) = kind.group_version();
395            let objects = self
396                .store
397                .list(group, version, kind.kind_name(), None)
398                .await;
399            report.objects_examined += objects.len();
400
401            for (key, object) in objects {
402                // Idempotent: an unchanged status rewritten every tick
403                // advances the revision forever, which is the hot-loop
404                // class guarded against elsewhere in this crate.
405                if already_stamped(&object, kind) {
406                    report.objects_skipped += 1;
407                    continue;
408                }
409                let desired = stamped(&object, kind, &now);
410                match self
411                    .store
412                    .propose(ResourceCommand::Put {
413                        key,
414                        value: desired,
415                        expected: None,
416                        reason: Reason::Controller,
417                    })
418                    .await
419                {
420                    Ok(applied) => report.record(Effect::of(applied.op)),
421                    // Never fatal: failing to annotate an inert object must
422                    // not stop the rest of the control plane. The next tick
423                    // retries, and the object is no worse off than the
424                    // silence this replaces.
425                    Err(_) => report.objects_skipped += 1,
426                }
427            }
428        }
429
430        Ok(ReconcileOutcome::from(report))
431    }
432}
433
434#[cfg(test)]
435mod producer_tests {
436    use super::*;
437    use engenho_store::{InProcessRouter, ResourceKey, default_config};
438    use std::time::Duration;
439
440    async fn boot(name: &str) -> Arc<StoreMesh> {
441        let router = InProcessRouter::new();
442        let cfg = default_config(name).unwrap();
443        let store = Arc::new(
444            StoreMesh::start(1, "in-process://1".into(), router, cfg)
445                .await
446                .unwrap(),
447        );
448        store.initialize_singleton().await.unwrap();
449        assert!(store.wait_for_leadership(Duration::from_secs(3)).await);
450        store
451    }
452
453    #[tokio::test]
454    async fn an_apiservice_is_marked_unavailable_so_a_client_stops_routing() {
455        let store = boot("served-cap").await;
456        let key = ResourceKey::cluster_scoped(
457            "apiregistration.k8s.io",
458            "v1",
459            "APIService",
460            "v1beta1.metrics.k8s.io",
461        );
462        store
463            .propose(ResourceCommand::Put {
464                key: key.clone(),
465                value: json!({
466                    "apiVersion": "apiregistration.k8s.io/v1",
467                    "kind": "APIService",
468                    "metadata": { "name": "v1beta1.metrics.k8s.io" },
469                    "spec": { "group": "metrics.k8s.io", "version": "v1beta1" }
470                }),
471                expected: None,
472                reason: Reason::Operator,
473            })
474            .await
475            .unwrap();
476
477        let c = ServedCapabilityController::new(store.clone());
478        c.tick().await.unwrap();
479
480        let got = store.get(&key).await.expect("apiservice");
481        let conds = got["status"]["conditions"].as_array().expect("conditions");
482        // The load-bearing one: this is what metrics-server's registration
483        // is judged by, and without it an unreachable service reports
484        // itself healthy.
485        let avail = conds
486            .iter()
487            .find(|c| c["type"] == AVAILABLE_CONDITION)
488            .expect("Available condition");
489        assert_eq!(avail["status"], "False");
490        assert_eq!(avail["reason"], "AggregationNotImplemented");
491
492        // And a second tick changes nothing.
493        let before = store.current_revision().await;
494        c.tick().await.unwrap();
495        assert_eq!(
496            store.current_revision().await,
497            before,
498            "stamping is idempotent — a rewrite every tick is a hot loop"
499        );
500
501        // The controller holds a store clone; it must go first.
502        drop(c);
503        Arc::try_unwrap(store)
504            .ok()
505            .unwrap()
506            .terminate()
507            .await
508            .unwrap();
509    }
510}