engenho_controllers/
runtime.rs1use 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 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
35impl From<&engenho_config::ControllersConfig> for RuntimeConfig {
39 fn from(top: &engenho_config::ControllersConfig) -> Self {
40 let engenho_config::ControllersConfig {
44 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 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 let RuntimeConfig { default_interval } = config;
77 Self {
78 default_interval,
79 controllers: Vec::new(),
80 }
81 }
82
83 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 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 #[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 #[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
131async fn tick_forever(controller: Arc<dyn Controller>, interval: Duration) -> Infallible {
133 let mut failures = ConsecutiveFailures::default();
136 loop {
137 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 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 #[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 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 tokio::time::sleep(Duration::from_millis(50)).await;
289 for h in handles {
290 h.abort();
291 }
292 }
293}