Skip to main content

engenho_controllers/
runtime.rs

1//! `ControllerRuntime` — runs N [`Controller`] impls on a shared
2//! tokio runtime with per-controller intervals.
3//!
4//! An embedder instantiates one [`ControllerRuntime`], registers
5//! controllers, and calls [`ControllerRuntime::spawn`], which spawns one
6//! interval tick loop per controller. Each loop logs how every tick ended.
7//!
8//! The daemon does not run controllers this way: it runs each one under a
9//! [`WatchDriver`](crate::WatchDriver) as a child of engenho-runtime's
10//! closed catalog (see [`ControllerRuntime::spawn`]).
11
12use std::convert::Infallible;
13use std::sync::Arc;
14use std::time::Duration;
15
16use tokio::task::JoinHandle;
17
18use crate::controller::Controller;
19use crate::watch_driver::{ConsecutiveFailures, log_tick, next_wake};
20
21#[derive(Clone, Copy, Debug)]
22pub struct RuntimeConfig {
23    /// Default reconcile interval if a controller doesn't specify one.
24    pub default_interval: Duration,
25}
26
27impl Default for RuntimeConfig {
28    fn default() -> Self {
29        Self {
30            default_interval: Duration::from_secs(10),
31        }
32    }
33}
34
35/// Wire engenho-config's top-level `ControllersConfig` into the runtime.
36/// The single `fallback_interval_seconds` becomes `default_interval` —
37/// individual controllers can still override per-registration.
38impl From<&engenho_config::ControllersConfig> for RuntimeConfig {
39    fn from(top: &engenho_config::ControllersConfig) -> Self {
40        // Every field is named, so a field added to ControllersConfig does
41        // not compile here (E0027) until someone decides whether this
42        // runtime reads it.
43        let engenho_config::ControllersConfig {
44            // Not read: this runtime has no per-controller gate, no
45            // namespace scope and no event debounce. It ticks whatever is
46            // registered, on an interval.
47            enable: _,
48            namespace: _,
49            debounce_milliseconds: _,
50            job_selector: _,
51            fallback_interval_seconds,
52        } = top;
53        Self {
54            default_interval: Duration::from_secs(u64::from(*fallback_interval_seconds)),
55        }
56    }
57}
58
59impl From<engenho_config::ControllersConfig> for RuntimeConfig {
60    fn from(top: engenho_config::ControllersConfig) -> Self {
61        (&top).into()
62    }
63}
64
65pub struct ControllerRuntime {
66    /// The interval a controller registered without one ticks at.
67    default_interval: Duration,
68    controllers: Vec<(Arc<dyn Controller>, Duration)>,
69}
70
71impl ControllerRuntime {
72    #[must_use]
73    pub fn new(config: RuntimeConfig) -> Self {
74        // Destructured with no `..`: a field added to RuntimeConfig does
75        // not compile here (E0027) until this constructor consumes it.
76        let RuntimeConfig { default_interval } = config;
77        Self {
78            default_interval,
79            controllers: Vec::new(),
80        }
81    }
82
83    /// Register a controller with the default interval.
84    pub fn register<C: Controller + 'static>(&mut self, controller: C) -> &mut Self {
85        let interval = self.default_interval;
86        self.controllers.push((Arc::new(controller), interval));
87        self
88    }
89
90    /// Register a controller with an explicit interval.
91    pub fn register_with_interval<C: Controller + 'static>(
92        &mut self,
93        controller: C,
94        interval: Duration,
95    ) -> &mut Self {
96        self.controllers.push((Arc::new(controller), interval));
97        self
98    }
99
100    /// Spawn the per-controller tick loops. Returns one `JoinHandle`
101    /// per controller. The caller can abort each handle to stop a
102    /// controller individually.
103    ///
104    /// ★ NOT A PRODUCTION PATH. The daemon runs every controller as a
105    /// `Child` of engenho-runtime's closed catalog, owned by one child set
106    /// that `main` watches; nothing in the daemon calls this. It stays for
107    /// embedders and tests that want interval-only ticking — and its loops
108    /// are `-> Infallible` like a `WatchDriver`'s, so a loop that returns is
109    /// a type error here too. A controller that belongs in the daemon gets
110    /// a catalog row, not a spawn through this.
111    #[must_use]
112    pub fn spawn(self) -> Vec<JoinHandle<Infallible>> {
113        self.controllers
114            .into_iter()
115            .map(|(controller, interval)| tokio::spawn(tick_forever(controller, interval)))
116            .collect()
117    }
118
119    /// Number of registered controllers (for testing + telemetry).
120    #[must_use]
121    pub fn len(&self) -> usize {
122        self.controllers.len()
123    }
124
125    #[must_use]
126    pub fn is_empty(&self) -> bool {
127        self.controllers.is_empty()
128    }
129}
130
131/// One controller's interval loop. It never returns.
132async fn tick_forever(controller: Arc<dyn Controller>, interval: Duration) -> Infallible {
133    // This controller's failed ticks in a row: its Transient retries grow on
134    // the same curve as a WatchDriver's.
135    let mut failures = ConsecutiveFailures::default();
136    loop {
137        // The interval-only path consumes the typed outcome through the SAME
138        // decision as the WatchDriver (`next_wake`): a requeue or a Transient
139        // error re-ticks at its delay, capped at the interval (never wait
140        // LONGER than the fallback would); `Done` and a Declarative error
141        // wait the normal interval. One sequential sleep is this loop's one
142        // requeue slot.
143        let result = controller.tick().await;
144        let wake = next_wake(&result, &mut failures);
145        log_tick(controller.name(), &result, wake);
146        let next_delay = wake.map_or(interval, |after| after.min(interval));
147        tokio::time::sleep(next_delay).await;
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154    use crate::controller::{Controller, ReconcileOutcome, ReconcileReport};
155    use crate::error::ControllerError;
156    use async_trait::async_trait;
157
158    struct Counter {
159        name: &'static str,
160    }
161
162    #[async_trait]
163    impl Controller for Counter {
164        fn name(&self) -> &'static str {
165            self.name
166        }
167        async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
168            Ok(ReconcileReport {
169                objects_examined: 1,
170                ..Default::default()
171            }
172            .into())
173        }
174    }
175
176    /// A controller that always fails Transiently, recording when each
177    /// tick started.
178    struct AlwaysTransient {
179        starts: Arc<std::sync::Mutex<Vec<tokio::time::Instant>>>,
180    }
181
182    #[async_trait]
183    impl Controller for AlwaysTransient {
184        fn name(&self) -> &'static str {
185            "always_transient"
186        }
187        async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
188            self.starts
189                .lock()
190                .unwrap()
191                .push(tokio::time::Instant::now());
192            Err(ControllerError::Store(
193                engenho_store::StoreError::ClientWriteFailed("no leader".into()),
194            ))
195        }
196    }
197
198    /// The interval-only loop owns a failure streak too: its Transient
199    /// retries grow on the same curve as a `WatchDriver`'s, capped at the
200    /// interval, instead of re-ticking at a flat second.
201    #[tokio::test(start_paused = true)]
202    async fn runtime_transient_retries_grow_up_to_the_interval() {
203        let interval = Duration::from_secs(30);
204        let starts = Arc::new(std::sync::Mutex::new(Vec::new()));
205        let mut rt = ControllerRuntime::new(RuntimeConfig {
206            default_interval: interval,
207        });
208        rt.register(AlwaysTransient {
209            starts: starts.clone(),
210        });
211        let handles = rt.spawn();
212        tokio::time::sleep(Duration::from_secs(180)).await;
213        for h in handles {
214            h.abort();
215        }
216        let at = starts.lock().unwrap().clone();
217        let gaps: Vec<u64> = at
218            .windows(2)
219            .map(|w| u64::try_from((w[1] - w[0]).as_millis()).unwrap())
220            .collect();
221        assert_eq!(
222            gaps.get(..6),
223            Some(&[1_000, 2_000, 4_000, 8_000, 16_000, 30_000][..]),
224            "retry gaps must double from 1 s and stop at the interval: {gaps:?}"
225        );
226        assert!(
227            gaps[5..].iter().all(|g| *g == 30_000),
228            "past the cap the interval holds: {gaps:?}"
229        );
230    }
231
232    #[test]
233    fn runtime_starts_empty() {
234        let rt = ControllerRuntime::new(RuntimeConfig::default());
235        assert!(rt.is_empty());
236        assert_eq!(rt.len(), 0);
237    }
238
239    #[test]
240    fn runtime_config_from_engenho_config_carries_fallback_interval() {
241        use engenho_config::{ControllerEnable, ControllersConfig};
242        let top = ControllersConfig {
243            enable: ControllerEnable {
244                replicaset: true,
245                deployment: true,
246                statefulset: true,
247                daemonset: true,
248                job: true,
249                cronjob: true,
250                endpoints: true,
251                service_routing: true,
252                gc: true,
253                crd: true,
254                namespace: true,
255                pv_binder: true,
256                pdb: true,
257                hpa: false,
258            },
259            namespace: String::new(),
260            fallback_interval_seconds: 45,
261            debounce_milliseconds: 100,
262            job_selector: engenho_config::JobSelector::Generated,
263        };
264        let runtime: RuntimeConfig = (&top).into();
265        assert_eq!(runtime.default_interval, Duration::from_secs(45));
266        // From-owned variant works too.
267        let runtime_owned: RuntimeConfig = top.into();
268        assert_eq!(runtime_owned.default_interval, Duration::from_secs(45));
269    }
270
271    #[test]
272    fn runtime_registers_multiple_controllers() {
273        let mut rt = ControllerRuntime::new(RuntimeConfig::default());
274        rt.register(Counter { name: "a" });
275        rt.register(Counter { name: "b" });
276        rt.register_with_interval(Counter { name: "c" }, Duration::from_secs(60));
277        assert_eq!(rt.len(), 3);
278    }
279
280    #[tokio::test]
281    async fn runtime_spawn_runs_at_least_one_tick() {
282        let mut rt = ControllerRuntime::new(RuntimeConfig {
283            default_interval: Duration::from_millis(10),
284        });
285        rt.register(Counter { name: "t" });
286        let handles = rt.spawn();
287        // Let it tick a few times.
288        tokio::time::sleep(Duration::from_millis(50)).await;
289        for h in handles {
290            h.abort();
291        }
292    }
293}