1use 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
50pub const SERVED_CONDITION: &str = "engenho.io/Served";
55
56pub const AVAILABLE_CONDITION: &str = "Available";
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum InertKind {
69 ApiService,
71 FlowSchema,
73 PriorityLevelConfiguration,
75}
76
77impl InertKind {
78 #[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 #[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 #[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 #[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 #[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 #[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#[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#[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 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 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 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 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 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 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 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
320impl InertKind {
329 #[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 #[must_use]
343 pub const fn all() -> [Self; 3] {
344 [
345 Self::ApiService,
346 Self::FlowSchema,
347 Self::PriorityLevelConfiguration,
348 ]
349 }
350}
351
352pub struct ServedCapabilityController {
359 store: Arc<StoreMesh>,
360}
361
362impl ServedCapabilityController {
363 #[must_use]
365 pub fn new(store: Arc<StoreMesh>) -> Self {
366 Self { store }
367 }
368}
369
370impl 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 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 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 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 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 drop(c);
503 Arc::try_unwrap(store)
504 .ok()
505 .unwrap()
506 .terminate()
507 .await
508 .unwrap();
509 }
510}