Skip to main content

engenho_controllers/
controller.rs

1//! The `Controller` trait — second-site extraction of the
2//! reconcile-loop pattern. First site: `engenho-scheduler::Scheduler`.
3//!
4//! A controller observes resources of a particular kind + (re)
5//! drives the world toward the declared spec. Pure I/O at the
6//! boundary; pure decision logic inside.
7//!
8//! ## The unified loop outcome
9//!
10//! Pre-unification engenho carried TWO competing loop traits: the live
11//! `Controller` (sweep-based, counter-only) and a dead generic
12//! `Reconciler<R>` in `engenho-types` that owned a typed
13//! requeue-bearing [`ReconcileResult`] but was never driven by anything.
14//! Per the Prime Directive (two traits modelling one concept is the
15//! duplication-bug), the dead trait is gone and its requeue vocabulary
16//! lives HERE, folded into the live loop: `tick` now returns a
17//! [`ReconcileOutcome`] carrying BOTH the [`ReconcileReport`] AND a
18//! [`ReconcileResult`]. The default `ReconcileResult::Done` preserves
19//! today's behavior for every controller that doesn't opt into a
20//! requeue — the drivers act on the result only when it's non-`Done`.
21
22use std::fmt;
23use std::ops::Deref;
24use std::time::Duration;
25
26use async_trait::async_trait;
27
28use crate::effect::Effect;
29use crate::error::ControllerError;
30use crate::sweep::SweepReport;
31
32/// One controller — implements the standard reconcile-loop shape.
33#[async_trait]
34pub trait Controller: Send + Sync {
35    /// Stable name for telemetry + runtime registration.
36    fn name(&self) -> &'static str;
37
38    /// One reconcile tick. Returns a typed [`ReconcileOutcome`] so the
39    /// runtime can log the [`ReconcileReport`] AND act on the
40    /// [`ReconcileResult`] (requeue decision). A controller that does
41    /// not opt into requeue returns `ReconcileResult::Done` (the
42    /// default), which the drivers treat exactly as the pre-unification
43    /// counter-only behavior.
44    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError>;
45
46    /// The type that does this controller's reconciling (T5.11).
47    ///
48    /// The default names `Self`. An adapter that only forwards to another
49    /// controller — `Arc<C>` here, the runtime's `DeclaredHere` — forwards
50    /// this too, so what the runtime records for a driver is the type it
51    /// really runs, not the wrapper around it. Through a `dyn Controller`
52    /// it is the concrete type behind the object.
53    fn controller_type(&self) -> ControllerType {
54        ControllerType::of::<Self>()
55    }
56}
57
58/// A type that implements [`Controller`], named by the compiler (T5.11).
59///
60/// The only constructor is [`ControllerType::of`], which takes the type
61/// itself: a catalog row built from it names a type that exists and
62/// implements `Controller`, or the row does not compile (E0412/E0433 for a
63/// renamed or deleted type, E0277 for one that stopped being a
64/// controller).
65///
66/// It holds `std::any::type_name`, whose exact text Rust does not promise
67/// to keep across compiler versions. So it is an identity for catalogs and
68/// the gates over them within one build — never something to persist, or
69/// to compare with a name written down by hand.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
71pub struct ControllerType {
72    path: &'static str,
73}
74
75impl ControllerType {
76    /// The controller type `C`.
77    #[must_use]
78    pub fn of<C: Controller + ?Sized>() -> Self {
79        Self {
80            path: std::any::type_name::<C>(),
81        }
82    }
83
84    /// The type's full path, generic arguments included.
85    #[must_use]
86    pub const fn path(self) -> &'static str {
87        self.path
88    }
89
90    /// The crate that defines the type: the path's first segment.
91    #[must_use]
92    pub fn krate(self) -> &'static str {
93        self.bare().split("::").next().unwrap_or(self.path)
94    }
95
96    /// The type's own name: the path's last segment, without generic
97    /// arguments.
98    #[must_use]
99    pub fn ident(self) -> &'static str {
100        self.bare().rsplit("::").next().unwrap_or(self.path)
101    }
102
103    /// The path without its generic arguments, which may themselves hold
104    /// `::`.
105    fn bare(self) -> &'static str {
106        self.path.split('<').next().unwrap_or(self.path)
107    }
108}
109
110impl fmt::Display for ControllerType {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        f.write_str(self.path)
113    }
114}
115
116/// Blanket impl so an `Arc<C>` is itself a [`Controller`]. This lets a caller
117/// keep an `Arc<C>` handle (e.g. the kubelet, queried in-process by the
118/// apiserver's `/log` subresource) AND hand the SAME controller to a
119/// [`crate::WatchDriver`] (which takes its controller by value + re-wraps it in
120/// an Arc). Both share one instance — the driver's ticks and the out-of-band
121/// queries see the same internal state.
122#[async_trait]
123impl<C: Controller + ?Sized> Controller for std::sync::Arc<C> {
124    fn name(&self) -> &'static str {
125        (**self).name()
126    }
127    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
128        (**self).tick().await
129    }
130    fn controller_type(&self) -> ControllerType {
131        (**self).controller_type()
132    }
133}
134
135/// One reconciliation attempt's requeue decision.
136///
137/// Moved here (was `engenho_types::reconciler::ReconcileResult`, a dead
138/// duplicate) so it becomes the LIVE requeue vocabulary the loop
139/// propagates. `Done` is the default — every controller that doesn't
140/// schedule a follow-up keeps the pre-unification behavior.
141#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
142pub enum ReconcileResult {
143    /// Reconciliation succeeded; no follow-up scheduled. The next
144    /// invocation comes from the next watch event or the fallback timer.
145    #[default]
146    Done,
147
148    /// Schedule another reconcile after `delay`. Useful for polling
149    /// external state (image pulls, external load-balancer provisioning)
150    /// the apiserver can't surface via a watch.
151    Requeue(Duration),
152
153    /// Like `Requeue` but signalling "I made progress, more work is
154    /// left." Lets a future requeue scheduler prioritize this resource
155    /// over idle ones. The drivers treat it the same as `Requeue` for
156    /// now (the driver's one requeue slot, armed for `delay`).
157    RequeueWithProgress(Duration),
158}
159
160impl ReconcileResult {
161    /// The follow-up delay this result asks for, if any. `Done` →
162    /// `None`; both requeue variants → `Some(delay)`. Read through
163    /// [`crate::next_wake`], which arms the driver's one requeue slot
164    /// when this is `Some` — a slot, never a spawned task, so repeated
165    /// requeues replace each other instead of accumulating.
166    #[must_use]
167    pub fn requeue_after(&self) -> Option<Duration> {
168        match self {
169            Self::Done => None,
170            Self::Requeue(d) | Self::RequeueWithProgress(d) => Some(*d),
171        }
172    }
173}
174
175/// Outcome of one reconcile tick — the report PLUS the requeue decision.
176///
177/// `Deref`s to [`ReconcileReport`] so existing call sites that read
178/// `outcome.objects_changed` / `outcome.objects_examined` keep
179/// compiling unchanged. `From<ReconcileReport>` (result = `Done`) lets
180/// every legacy `Ok(report)` site become `Ok(report.into())`.
181#[derive(Debug, Default, Clone)]
182pub struct ReconcileOutcome {
183    pub report: ReconcileReport,
184    pub result: ReconcileResult,
185    /// The per-object tally, when the tick ran through a
186    /// [`crate::sweep::Sweep`]. `report` is derived from it; this keeps the
187    /// counts `ReconcileReport` has no field for (unchanged, failed).
188    pub sweep: Option<SweepReport>,
189}
190
191impl ReconcileOutcome {
192    /// Build an outcome from a report + an explicit requeue decision.
193    #[must_use]
194    pub fn new(report: ReconcileReport, result: ReconcileResult) -> Self {
195        Self {
196            report,
197            result,
198            sweep: None,
199        }
200    }
201
202    /// Log the tick: the sweep's tally when there is one (it can say that
203    /// objects failed), else the embedded report.
204    pub fn log(&self, controller_name: &str) {
205        match &self.sweep {
206            Some(sweep) => sweep.log(controller_name),
207            None => self.report.log(controller_name),
208        }
209    }
210}
211
212impl From<ReconcileReport> for ReconcileOutcome {
213    fn from(report: ReconcileReport) -> Self {
214        Self::new(report, ReconcileResult::Done)
215    }
216}
217
218impl Deref for ReconcileOutcome {
219    type Target = ReconcileReport;
220    fn deref(&self) -> &Self::Target {
221        &self.report
222    }
223}
224
225/// Outcome of one reconcile tick.
226#[derive(Debug, Default, Clone)]
227pub struct ReconcileReport {
228    pub objects_examined: usize,
229    pub objects_changed: usize,
230    pub objects_skipped: usize,
231    /// Human-readable note for logs.
232    pub note: Option<String>,
233}
234
235impl ReconcileReport {
236    /// Count one write by what it did, never by the fact that it was made.
237    ///
238    /// A write that landed is a change. One the store accepted and did
239    /// nothing with is not counted. One the store refused is a skip: the
240    /// object was reached and left as it was.
241    pub fn record(&mut self, effect: Effect) {
242        match effect {
243            Effect::Written(_) => self.objects_changed += 1,
244            Effect::Unchanged => {}
245            Effect::Rejected(_) => self.objects_skipped += 1,
246        }
247    }
248
249    /// Convenience: log this report at info level via the
250    /// `tracing` crate. The runtime calls this after each tick.
251    pub fn log(&self, controller_name: &str) {
252        if self.objects_changed > 0 || self.objects_skipped > 0 {
253            tracing::info!(
254                controller = controller_name,
255                examined = self.objects_examined,
256                changed = self.objects_changed,
257                skipped = self.objects_skipped,
258                note = self.note.as_deref().unwrap_or(""),
259                "reconcile tick"
260            );
261        } else {
262            tracing::debug!(
263                controller = controller_name,
264                examined = self.objects_examined,
265                "reconcile tick (no-op)"
266            );
267        }
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    /// Test that the Controller trait is object-safe — meaning
276    /// the runtime can hold `Box<dyn Controller>` for dynamic
277    /// dispatch over heterogeneous controller types.
278    #[test]
279    fn controller_trait_is_object_safe() {
280        struct Dummy;
281        #[async_trait]
282        impl Controller for Dummy {
283            fn name(&self) -> &'static str {
284                "dummy"
285            }
286            async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
287                Ok(ReconcileReport::default().into())
288            }
289        }
290        let _boxed: Box<dyn Controller> = Box::new(Dummy);
291    }
292
293    struct Named;
294    #[async_trait]
295    impl Controller for Named {
296        fn name(&self) -> &'static str {
297            "named"
298        }
299        async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
300            Ok(ReconcileReport::default().into())
301        }
302    }
303
304    struct Generic<T>(std::marker::PhantomData<T>);
305    #[async_trait]
306    impl<T: Send + Sync> Controller for Generic<T> {
307        fn name(&self) -> &'static str {
308            "generic"
309        }
310        async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
311            Ok(ReconcileReport::default().into())
312        }
313    }
314
315    /// A controller type is named by its crate and its own name, whatever
316    /// generic arguments it carries (they may hold `::` themselves).
317    #[test]
318    fn a_controller_type_is_its_crate_and_its_name() {
319        let named = ControllerType::of::<Named>();
320        assert_eq!(named.krate(), "engenho_controllers");
321        assert_eq!(named.ident(), "Named");
322        let generic = ControllerType::of::<Generic<std::collections::BTreeMap<String, u8>>>();
323        assert_eq!(generic.krate(), "engenho_controllers");
324        assert_eq!(generic.ident(), "Generic");
325        assert_ne!(named, generic);
326    }
327
328    /// What a controller reports is the type that reconciles: through an
329    /// `Arc` (which the runtime's drivers hold), through a `dyn`, and
330    /// through both — never the wrapper.
331    #[test]
332    fn a_controller_reports_the_type_that_reconciles_not_its_wrapper() {
333        let want = ControllerType::of::<Named>();
334        assert_eq!(Named.controller_type(), want);
335        assert_eq!(std::sync::Arc::new(Named).controller_type(), want);
336        let object: std::sync::Arc<dyn Controller> = std::sync::Arc::new(Named);
337        assert_eq!(object.controller_type(), want);
338        assert_eq!(std::sync::Arc::new(object).controller_type(), want);
339    }
340
341    #[test]
342    fn report_default_is_empty() {
343        let r = ReconcileReport::default();
344        assert_eq!(r.objects_examined, 0);
345        assert_eq!(r.objects_changed, 0);
346        assert_eq!(r.objects_skipped, 0);
347        assert!(r.note.is_none());
348    }
349
350    /// A write is counted by what it did: landed is a change, a `NoOp` is
351    /// nothing, a refusal is a skip. Never "a write was made, add one".
352    #[test]
353    fn a_report_counts_writes_by_their_effect() {
354        use engenho_store::command::ResourceOp;
355        let mut r = ReconcileReport::default();
356        for op in [
357            ResourceOp::Created,
358            ResourceOp::Patched,
359            ResourceOp::NoOp,
360            ResourceOp::NoOp,
361            ResourceOp::Conflict,
362            ResourceOp::PatchRejected,
363        ] {
364            r.record(Effect::of(op));
365        }
366        assert_eq!(r.objects_changed, 2, "only the two writes that landed");
367        assert_eq!(r.objects_skipped, 2, "the two refusals");
368    }
369
370    #[test]
371    fn reconcile_result_default_is_done() {
372        // A controller that doesn't opt into requeue returns the default
373        // — the drivers then behave exactly as the pre-unification loop.
374        assert_eq!(ReconcileResult::default(), ReconcileResult::Done);
375        assert_eq!(ReconcileResult::Done.requeue_after(), None);
376    }
377
378    #[test]
379    fn reconcile_result_requeue_carries_delay() {
380        let d = Duration::from_secs(5);
381        assert_eq!(ReconcileResult::Requeue(d).requeue_after(), Some(d));
382        assert_eq!(
383            ReconcileResult::RequeueWithProgress(d).requeue_after(),
384            Some(d)
385        );
386    }
387
388    #[test]
389    fn outcome_from_report_defaults_to_done() {
390        // Every legacy `Ok(report)` site becomes `Ok(report.into())`
391        // with result = Done (identical behavior).
392        let mut report = ReconcileReport {
393            objects_examined: 3,
394            ..Default::default()
395        };
396        report.record(Effect::of(engenho_store::command::ResourceOp::Created));
397        report.record(Effect::of(engenho_store::command::ResourceOp::Patched));
398        let outcome: ReconcileOutcome = report.into();
399        assert_eq!(outcome.result, ReconcileResult::Done);
400        // Deref reaches the report fields directly.
401        assert_eq!(outcome.objects_examined, 3);
402        assert_eq!(outcome.objects_changed, 2);
403    }
404}