1use std::convert::Infallible;
95use std::sync::Arc;
96use std::time::Duration;
97
98use engenho_store::{StoreMesh, WatchEvent, WatchGone, WatchSignal, WatchStream};
99use tokio::time::Instant;
100use tracing::{debug, info, warn};
101
102use shigoto_types::failure::FailureKind;
103
104use crate::contain::{TickState, contained};
105use crate::controller::{Controller, ReconcileOutcome};
106use crate::curve::{Curve, Streak};
107use crate::error::ControllerError;
108use crate::heartbeat::{Heartbeat, TickClass};
109
110#[derive(Clone, Debug)]
112pub enum KindFilter {
113 All,
115 Kinds(Vec<String>),
119}
120
121impl KindFilter {
122 #[must_use]
124 pub fn kind(name: impl Into<String>) -> Self {
125 Self::Kinds(vec![name.into()])
126 }
127
128 #[must_use]
130 pub fn wakes_on(&self, kind: &str) -> bool {
131 match self {
132 Self::All => true,
133 Self::Kinds(list) => list.iter().any(|k| k == kind),
134 }
135 }
136
137 #[must_use]
140 pub fn wakes_on_nothing(&self) -> bool {
141 matches!(self, Self::Kinds(list) if list.is_empty())
142 }
143
144 fn matches(&self, ev: &WatchEvent) -> bool {
145 self.wakes_on(&ev.key.kind)
146 }
147}
148
149#[derive(Clone, Debug)]
150pub struct WatchDriverConfig {
151 pub filter: KindFilter,
153 pub debounce: Duration,
156 pub fallback_interval: Duration,
162 pub stuck_tick_after: Duration,
172 pub tick_state: TickState,
181}
182
183impl Default for WatchDriverConfig {
184 fn default() -> Self {
185 Self {
186 filter: KindFilter::All,
187 debounce: Duration::from_millis(50),
188 fallback_interval: Duration::from_secs(30),
189 stuck_tick_after: Duration::from_secs(120),
190 tick_state: TickState::Stateful,
191 }
192 }
193}
194
195pub struct WatchDriver<C: Controller> {
199 controller: Arc<C>,
200 store: Arc<StoreMesh>,
201 config: WatchDriverConfig,
202 beat: Arc<Heartbeat>,
203}
204
205impl<C: Controller + 'static> WatchDriver<C> {
206 #[must_use]
207 pub fn new(controller: C, store: Arc<StoreMesh>, config: WatchDriverConfig) -> Self {
208 Self {
209 controller: Arc::new(controller),
210 store,
211 config,
212 beat: Arc::new(Heartbeat::new()),
213 }
214 }
215
216 #[must_use]
219 pub fn heartbeat(&self) -> Arc<Heartbeat> {
220 self.beat.clone()
221 }
222
223 #[must_use]
226 pub fn wakes(&self) -> &KindFilter {
227 &self.config.filter
228 }
229
230 pub async fn run(self) -> Infallible {
234 run(self.controller, self.store, self.config, self.beat).await
235 }
236
237 pub async fn tick_once(
242 &self,
243 ) -> Result<crate::controller::ReconcileOutcome, crate::error::ControllerError> {
244 self.controller.tick().await
245 }
246}
247
248pub const RESUBSCRIBE: Curve = Curve::from_millis::<100, 30_000>();
255
256pub const TRANSIENT_RETRY: Curve = Curve::from_millis::<1_000, 60_000>();
265
266#[async_trait::async_trait]
274trait WatchSource: Send + Sync {
275 async fn watch(&self) -> Result<WatchStream, WatchGone>;
276}
277
278#[async_trait::async_trait]
279impl WatchSource for StoreMesh {
280 async fn watch(&self) -> Result<WatchStream, WatchGone> {
281 StoreMesh::watch(self).await
282 }
283}
284
285async fn subscribe<S: WatchSource + ?Sized>(
291 source: &S,
292 controller: &'static str,
293 delay: Duration,
294) -> Option<WatchStream> {
295 if !delay.is_zero() {
296 tokio::time::sleep(delay).await;
297 }
298 match source.watch().await {
299 Ok(s) => Some(s),
300 Err(e) => {
301 warn!(
302 controller,
303 error = %e,
304 "watch subscribe failed; fallback-tick only until the next attempt"
305 );
306 None
307 }
308 }
309}
310
311async fn resubscribe<S: WatchSource + ?Sized>(
314 source: &S,
315 controller: &'static str,
316 attempts: &mut Streak,
317) -> Option<WatchStream> {
318 subscribe(source, controller, attempts.miss()).await
319}
320
321async fn run<C: Controller + ?Sized + 'static, S: WatchSource + ?Sized>(
322 controller: Arc<C>,
323 store: Arc<S>,
324 config: WatchDriverConfig,
325 beat: Arc<Heartbeat>,
326) -> Infallible {
327 let WatchDriverConfig {
331 filter,
332 debounce,
333 fallback_interval,
334 stuck_tick_after,
335 tick_state,
336 } = config;
337 let name = controller.name();
338 let mut rx = subscribe(store.as_ref(), name, Duration::ZERO).await;
339 let mut resubscribes = Streak::new(RESUBSCRIBE);
343 let mut ticker = Ticker {
348 controller,
349 stuck_after: stuck_tick_after,
350 tick_state,
351 slot: RequeueSlot::default(),
352 failures: ConsecutiveFailures::default(),
353 beat,
354 };
355
356 info!(
357 controller = name,
358 debounce_ms = millis(debounce),
359 fallback_s = if fallback_interval == Duration::MAX {
360 0
361 } else {
362 fallback_interval.as_secs()
363 },
364 "watch driver started"
365 );
366
367 if filter.wakes_on_nothing() {
390 ticker.tick().await;
391 }
392 loop {
393 match wait_for_relevant_event(rx.as_mut(), &filter, fallback_interval, ticker.slot).await {
394 EventOrTimer::Event => {
395 resubscribes.reset();
396 tokio::time::sleep(debounce).await;
398 let gone = rx
402 .as_mut()
403 .and_then(|stream| drain_pending(stream, name, &filter));
404 ticker.tick().await;
405 if let Some(gone) = gone {
406 warn!(
407 controller = name,
408 gone = %gone,
409 "watch stream gone while coalescing; re-subscribing"
410 );
411 rx = resubscribe(store.as_ref(), name, &mut resubscribes).await;
412 }
413 }
414 EventOrTimer::Gone(gone) => {
415 warn!(
416 controller = name,
417 gone = %gone,
418 "watch stream gone; ticking + re-subscribing"
419 );
420 ticker.tick().await;
421 rx = resubscribe(store.as_ref(), name, &mut resubscribes).await;
422 }
423 EventOrTimer::StreamEnded => {
424 warn!(
428 controller = name,
429 "watch stream ended; ticking + re-subscribing (not a shutdown)"
430 );
431 ticker.tick().await;
432 rx = resubscribe(store.as_ref(), name, &mut resubscribes).await;
433 }
434 wake @ (EventOrTimer::Requeue | EventOrTimer::FallbackTimer) => {
435 debug!(controller = name, ?wake, "timer wake");
436 ticker.tick().await;
437 if rx.is_none() {
443 rx = resubscribe(store.as_ref(), name, &mut resubscribes).await;
444 }
445 }
446 }
447 }
448}
449
450#[derive(Debug, Clone, Copy, PartialEq, Eq)]
457pub struct ConsecutiveFailures(Streak);
458
459impl Default for ConsecutiveFailures {
460 fn default() -> Self {
461 Self(Streak::new(TRANSIENT_RETRY))
462 }
463}
464
465impl ConsecutiveFailures {
466 #[must_use]
468 pub const fn count(&self) -> u32 {
469 self.0.misses()
470 }
471}
472
473#[must_use]
490pub fn next_wake(
491 result: &Result<ReconcileOutcome, ControllerError>,
492 failures: &mut ConsecutiveFailures,
493) -> Option<Duration> {
494 match result {
495 Ok(outcome) => {
496 failures.0.reset();
497 outcome.result.requeue_after()
498 }
499 Err(e) => {
500 let owed = failures.0.miss();
501 match e.classify() {
502 FailureKind::Declarative => None,
503 FailureKind::Transient => Some(owed),
504 #[allow(
509 clippy::match_same_arms,
510 reason = "the known class and the unknown ones are separate decisions that happen to agree today"
511 )]
512 _ => Some(owed),
513 }
514 }
515 }
516}
517
518pub(crate) fn log_tick(
522 controller: &'static str,
523 result: &Result<ReconcileOutcome, ControllerError>,
524 wake: Option<Duration>,
525) {
526 match (result, wake) {
527 (Ok(outcome), None) => outcome.log(controller),
528 (Ok(outcome), Some(after)) => {
529 outcome.log(controller);
530 debug!(
531 controller,
532 after_ms = millis(after),
533 "controller requested requeue"
534 );
535 }
536 (Err(ControllerError::Panicked(panic)), _) => tracing::error!(
537 controller,
538 %panic,
539 "reconcile tick PANICKED and was contained (stateless); no targeted retry \u{2014} \
540 the next event or the fallback re-ticks it"
541 ),
542 (Err(e), None) => tracing::error!(
543 controller,
544 error = %e,
545 "reconcile failed (declarative — surfacing, not scheduling a targeted retry)"
546 ),
547 (Err(e), Some(after)) => warn!(
548 controller,
549 error = %e,
550 after_ms = millis(after),
551 "reconcile failed (transient — scheduling a targeted retry)"
552 ),
553 }
554}
555
556fn millis(d: Duration) -> u64 {
559 u64::try_from(d.as_millis()).unwrap_or(u64::MAX)
560}
561
562#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
569struct RequeueSlot {
570 at: Option<Instant>,
571}
572
573impl RequeueSlot {
574 fn clear(&mut self) {
576 self.at = None;
577 }
578
579 fn arm(&mut self, deadline: Instant) {
582 self.at = Some(self.at.map_or(deadline, |at| at.min(deadline)));
583 }
584
585 async fn due(self) {
587 match self.at {
588 Some(at) => tokio::time::sleep_until(at).await,
589 None => std::future::pending::<()>().await,
590 }
591 }
592}
593
594struct Ticker<C: Controller + ?Sized + 'static> {
598 controller: Arc<C>,
599 stuck_after: Duration,
600 tick_state: TickState,
601 slot: RequeueSlot,
602 failures: ConsecutiveFailures,
603 beat: Arc<Heartbeat>,
604}
605
606impl<C: Controller + ?Sized + 'static> Ticker<C> {
607 async fn tick(&mut self) {
614 self.slot.clear();
615 self.beat.begin();
616 let result = tick_observed(&self.controller, self.stuck_after, self.tick_state).await;
617 self.beat.end(TickClass::of(&result));
618 let wake = next_wake(&result, &mut self.failures);
619 log_tick(self.controller.name(), &result, wake);
620 if let Some(deadline) = wake.and_then(|after| Instant::now().checked_add(after)) {
621 self.slot.arm(deadline);
622 }
623 }
624}
625
626#[derive(Debug)]
627enum EventOrTimer {
628 Event,
629 Gone(WatchGone),
631 Requeue,
634 FallbackTimer,
635 StreamEnded,
643}
644
645async fn wait_for_relevant_event(
649 rx: Option<&mut WatchStream>,
650 filter: &KindFilter,
651 fallback_interval: Duration,
652 slot: RequeueSlot,
653) -> EventOrTimer {
654 let fallback = tokio::time::sleep(fallback_interval);
655 tokio::pin!(fallback);
656 let requeue = slot.due();
657 tokio::pin!(requeue);
658
659 let Some(rx) = rx else {
661 return tokio::select! {
662 biased;
663 () = &mut requeue => EventOrTimer::Requeue,
664 () = &mut fallback => EventOrTimer::FallbackTimer,
665 };
666 };
667
668 loop {
669 tokio::select! {
670 biased;
671 res = rx.next() => match res {
672 Some(Ok(WatchSignal::Event(ev))) => {
673 if filter.matches(&ev) {
674 return EventOrTimer::Event;
675 }
676 }
678 Some(Ok(WatchSignal::Bookmark(_))) => {}
681 Some(Err(gone)) => return EventOrTimer::Gone(gone),
682 None => return EventOrTimer::StreamEnded,
683 },
684 () = &mut requeue => return EventOrTimer::Requeue,
685 () = &mut fallback => return EventOrTimer::FallbackTimer,
686 }
687 }
688}
689
690#[must_use = "the terminal is one-shot: drop it and the subscription is silently dead"]
701fn drain_pending(
702 stream: &mut WatchStream,
703 controller_name: &'static str,
704 filter: &KindFilter,
705) -> Option<WatchGone> {
706 while let Some(item) = stream.try_next() {
707 match item {
708 Ok(WatchSignal::Event(ev)) => {
709 if filter.matches(&ev) {
710 debug!(controller = controller_name, key = %ev.key.label(), "coalesced event");
711 }
712 }
713 Ok(WatchSignal::Bookmark(_)) => {}
714 Err(gone) => return Some(gone),
715 }
716 }
717 None
718}
719
720async fn tick_observed<C: Controller + ?Sized + 'static>(
729 controller: &Arc<C>,
730 stuck_after: Duration,
731 tick_state: TickState,
732) -> Result<ReconcileOutcome, ControllerError> {
733 let name = controller.name();
734 let tick = async { controller.tick().await };
735 match tick_state {
736 TickState::Stateless => match observed(name, contained(tick), stuck_after).await {
737 Ok(result) => result,
738 Err(panic) => Err(ControllerError::Panicked(panic)),
739 },
740 TickState::Stateful => observed(name, tick, stuck_after).await,
741 }
742}
743
744async fn observed<F: std::future::Future>(
754 controller: &'static str,
755 tick: F,
756 stuck_after: Duration,
757) -> F::Output {
758 let started = std::time::Instant::now();
759 tokio::pin!(tick);
760 loop {
761 if let Ok(outcome) = tokio::time::timeout(stuck_after, &mut tick).await {
762 return outcome;
763 }
764 tracing::error!(
765 controller,
766 elapsed_s = started.elapsed().as_secs(),
767 "reconcile tick has NOT returned; this controller is blocked (not cancelled \u{2014} cancelling mid-tick would strand side effects)"
768 );
769 }
770}
771
772#[cfg(test)]
773mod tests {
774 use super::*;
775 use serde_json::Value;
776
777 fn ev(kind: &str, name: &str) -> WatchEvent {
778 use engenho_store::ResourceKey;
779 WatchEvent {
780 kind: engenho_store::WatchEventKind::Added,
781 object: Value::Null,
782 key: ResourceKey::namespaced("", "v1", kind, "default", name),
783 resource_version: 1,
784 }
785 }
786
787 #[test]
788 fn kind_filter_all_matches_anything() {
789 let f = KindFilter::All;
790 assert!(f.matches(&ev("Pod", "x")));
791 assert!(f.matches(&ev("Service", "x")));
792 }
793
794 #[test]
795 fn kind_filter_specific_matches_only_listed() {
796 let f = KindFilter::Kinds(vec!["Pod".into(), "Endpoints".into()]);
797 assert!(f.matches(&ev("Pod", "x")));
798 assert!(f.matches(&ev("Endpoints", "x")));
799 assert!(!f.matches(&ev("Service", "x")));
800 }
801
802 #[test]
803 fn kind_filter_kind_helper() {
804 let f = KindFilter::kind("Pod");
805 assert!(f.matches(&ev("Pod", "p")));
806 assert!(!f.matches(&ev("Node", "n")));
807 }
808
809 #[test]
810 fn config_default_is_sensible() {
811 let cfg = WatchDriverConfig::default();
812 assert_eq!(cfg.debounce, Duration::from_millis(50));
813 assert_eq!(cfg.fallback_interval, Duration::from_secs(30));
814 assert!(matches!(cfg.filter, KindFilter::All));
815 }
816
817 use engenho_store::watch_backend::WatcherRegistry;
843 use engenho_store::{Change, ChangeKind, ResourceKey, Revision, VersionMeta, WatchOpts};
844
845 fn change(rev: u64) -> Change {
846 change_at(Revision(rev))
847 }
848
849 fn change_at(r: Revision) -> Change {
850 Change {
851 revision: r,
852 key: ResourceKey::namespaced("", "v1", "Pod", "default", "p1"),
853 kind: ChangeKind::Put,
854 value: serde_json::json!({"spec": {}}),
855 prior: None,
856 version_meta: VersionMeta::created_at(r),
857 }
858 }
859
860 fn overflowed_stream() -> WatchStream {
862 let mut reg = WatcherRegistry::new();
863 let stream = reg.register_captured(
864 Vec::new(),
865 Revision::ZERO,
866 &WatchOpts {
867 from: Revision::ZERO,
868 buffer: 2,
869 bookmark_every: Duration::ZERO,
870 },
871 );
872 for rev in 1..=8 {
873 reg.fan_change(&change(rev));
874 }
875 stream
876 }
877
878 #[test]
879 fn a_terminal_reached_while_coalescing_is_returned_to_the_caller() {
880 let mut stream = overflowed_stream();
881
882 let gone = drain_pending(&mut stream, "t", &KindFilter::All);
883
884 assert!(
885 gone.is_some(),
886 "the drain consumed the one-shot terminal and reported nothing; \
887 that is the exact swallow that retired the kubelet"
888 );
889 assert!(matches!(gone, Some(WatchGone::Overflow { .. })));
890 }
891
892 #[tokio::test]
896 async fn the_drained_stream_is_finished_so_the_terminal_is_the_only_notice() {
897 let mut stream = overflowed_stream();
898
899 let _ = drain_pending(&mut stream, "t", &KindFilter::All);
900
901 assert!(
902 stream.next().await.is_none(),
903 "expected the stream to be over after its terminal was read"
904 );
905 }
906
907 use std::sync::Mutex;
923 use std::sync::atomic::{AtomicUsize, Ordering};
924
925 use crate::controller::{ReconcileReport, ReconcileResult};
926
927 const HOUR: Duration = Duration::from_secs(3600);
928 const EVENT_EVERY: Duration = Duration::from_secs(5);
929 const FALLBACK: Duration = Duration::from_secs(30);
930 const TICK_TAKES: Duration = Duration::from_millis(100);
931 const REQUEUE_AFTER: Duration = Duration::from_secs(1);
932
933 const EVENTS: u64 = HOUR.as_secs() / EVENT_EVERY.as_secs();
934 const FALLBACKS: u64 = HOUR.as_secs() / FALLBACK.as_secs();
935 const WITHOUT_TARGETED_RETRY: u64 = EVENTS + FALLBACKS;
937 const ONE_SLOT_CEILING: u64 = HOUR.as_secs() / REQUEUE_AFTER.as_secs() + WITHOUT_TARGETED_RETRY;
940 const _: () = assert!(ONE_SLOT_CEILING == 4440, "the plan's bound, derived");
941
942 #[derive(Clone, Copy, Debug)]
943 enum Answer {
944 Done,
945 Requeue(Duration),
946 Transient,
947 Declarative,
948 Panic,
950 }
951
952 impl Answer {
953 fn result(self) -> Result<ReconcileOutcome, ControllerError> {
954 match self {
955 Self::Done => Ok(ReconcileOutcome::new(
956 ReconcileReport::default(),
957 ReconcileResult::Done,
958 )),
959 Self::Requeue(after) => Ok(ReconcileOutcome::new(
960 ReconcileReport::default(),
961 ReconcileResult::Requeue(after),
962 )),
963 Self::Transient => Err(ControllerError::Store(
964 engenho_store::StoreError::ClientWriteFailed("connection refused".into()),
965 )),
966 Self::Declarative => Err(ControllerError::InvalidResource(
967 "spec.template is required".into(),
968 )),
969 Self::Panic => panic!("probe tick tripped over a bad object"),
970 }
971 }
972 }
973
974 #[derive(Debug, Default, Clone, Copy)]
975 struct Stats {
976 ticks: u64,
977 in_flight: u64,
978 max_in_flight: u64,
979 last_start: Option<Instant>,
980 max_gap: Duration,
982 }
983
984 struct Probe {
987 answer: Answer,
988 takes: Duration,
990 stats: Mutex<Stats>,
991 starts: Mutex<Vec<Instant>>,
993 }
994
995 impl Probe {
996 fn new(answer: Answer) -> Arc<Self> {
997 Self::taking(answer, TICK_TAKES)
998 }
999
1000 fn taking(answer: Answer, takes: Duration) -> Arc<Self> {
1001 Arc::new(Self {
1002 answer,
1003 takes,
1004 stats: Mutex::new(Stats::default()),
1005 starts: Mutex::new(Vec::new()),
1006 })
1007 }
1008
1009 fn stats(&self) -> Stats {
1010 *self.stats.lock().unwrap()
1011 }
1012
1013 fn gaps(&self) -> Vec<Duration> {
1015 gaps(&self.starts.lock().unwrap())
1016 }
1017 }
1018
1019 fn gaps(at: &[Instant]) -> Vec<Duration> {
1020 at.windows(2).map(|w| w[1] - w[0]).collect()
1021 }
1022
1023 #[async_trait::async_trait]
1024 impl Controller for Probe {
1025 fn name(&self) -> &'static str {
1026 "probe"
1027 }
1028
1029 async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
1030 {
1031 let now = Instant::now();
1032 let mut s = self.stats.lock().unwrap();
1033 if let Some(prev) = s.last_start {
1034 s.max_gap = s.max_gap.max(now - prev);
1035 }
1036 s.last_start = Some(now);
1037 s.ticks += 1;
1038 s.in_flight += 1;
1039 s.max_in_flight = s.max_in_flight.max(s.in_flight);
1040 self.starts.lock().unwrap().push(now);
1041 }
1042 tokio::time::sleep(self.takes).await;
1043 self.stats.lock().unwrap().in_flight -= 1;
1044 self.answer.result()
1045 }
1046 }
1047
1048 struct Feed {
1052 state: Mutex<(WatcherRegistry, Revision)>,
1053 refuse_next: AtomicUsize,
1054 accepted: AtomicUsize,
1055 end_every_stream: bool,
1058 asked: Mutex<Vec<Instant>>,
1060 }
1061
1062 impl Feed {
1063 fn new() -> Arc<Self> {
1064 Self::refusing(0)
1065 }
1066
1067 fn refusing(n: usize) -> Arc<Self> {
1068 Arc::new(Self {
1069 state: Mutex::new((WatcherRegistry::new(), Revision::ZERO)),
1070 refuse_next: AtomicUsize::new(n),
1071 accepted: AtomicUsize::new(0),
1072 end_every_stream: false,
1073 asked: Mutex::new(Vec::new()),
1074 })
1075 }
1076
1077 fn ending_every_stream() -> Arc<Self> {
1078 Arc::new(Self {
1079 state: Mutex::new((WatcherRegistry::new(), Revision::ZERO)),
1080 refuse_next: AtomicUsize::new(0),
1081 accepted: AtomicUsize::new(0),
1082 end_every_stream: true,
1083 asked: Mutex::new(Vec::new()),
1084 })
1085 }
1086
1087 fn emit(&self) {
1088 let mut state = self.state.lock().unwrap();
1089 let (reg, rev) = &mut *state;
1090 *rev = rev.next();
1091 reg.fan_change(&change_at(*rev));
1092 }
1093 }
1094
1095 #[async_trait::async_trait]
1096 impl WatchSource for Feed {
1097 async fn watch(&self) -> Result<WatchStream, WatchGone> {
1098 self.asked.lock().unwrap().push(Instant::now());
1099 let refused = self
1100 .refuse_next
1101 .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1))
1102 .is_ok();
1103 if refused {
1104 return Err(WatchGone::CompactedTooOld {
1105 requested: Revision::ZERO,
1106 compacted: Revision::ZERO,
1107 });
1108 }
1109 self.accepted.fetch_add(1, Ordering::SeqCst);
1110 let opts = |from| WatchOpts {
1111 from,
1112 buffer: 1024,
1113 bookmark_every: Duration::ZERO,
1114 };
1115 if self.end_every_stream {
1116 return Ok(WatcherRegistry::new().register_captured(
1119 Vec::new(),
1120 Revision::ZERO,
1121 &opts(Revision::ZERO),
1122 ));
1123 }
1124 let mut state = self.state.lock().unwrap();
1125 let (reg, rev) = &mut *state;
1126 Ok(reg.register_captured(Vec::new(), *rev, &opts(*rev)))
1127 }
1128 }
1129
1130 async fn an_hour_of(probe: &Arc<Probe>, feed: &Arc<Feed>) -> Stats {
1133 drive(probe, feed, FALLBACK, Some(EVENT_EVERY), HOUR).await
1134 }
1135
1136 async fn drive(
1139 probe: &Arc<Probe>,
1140 feed: &Arc<Feed>,
1141 fallback: Duration,
1142 event_every: Option<Duration>,
1143 run_for: Duration,
1144 ) -> Stats {
1145 let config = WatchDriverConfig {
1146 fallback_interval: fallback,
1147 ..WatchDriverConfig::default()
1148 };
1149 let driver = tokio::spawn(run(
1150 probe.clone(),
1151 feed.clone(),
1152 config,
1153 Arc::new(Heartbeat::new()),
1154 ));
1155 let events = event_every.map(|every| {
1156 let feed = feed.clone();
1157 tokio::spawn(async move {
1158 loop {
1159 tokio::time::sleep(every).await;
1160 feed.emit();
1161 }
1162 })
1163 });
1164 tokio::time::sleep(run_for).await;
1165 driver.abort();
1166 let _ = driver.await;
1167 if let Some(events) = events {
1168 events.abort();
1169 let _ = events.await;
1170 }
1171 probe.stats()
1172 }
1173
1174 async fn ticks_before_the_fallback(filter: KindFilter) -> u64 {
1177 let probe = Probe::new(Answer::Done);
1178 let config = WatchDriverConfig {
1179 filter,
1180 fallback_interval: Duration::from_secs(600),
1181 ..WatchDriverConfig::default()
1182 };
1183 let driver = tokio::spawn(run(
1184 probe.clone(),
1185 Feed::new(),
1186 config,
1187 Arc::new(Heartbeat::new()),
1188 ));
1189 tokio::time::sleep(Duration::from_secs(60)).await;
1190 driver.abort();
1191 let _ = driver.await;
1192 probe.stats().ticks
1193 }
1194
1195 #[tokio::test(start_paused = true)]
1196 async fn a_poller_ticks_at_start_and_an_event_driven_driver_waits() {
1197 assert!(KindFilter::Kinds(Vec::new()).wakes_on_nothing());
1198 assert!(!KindFilter::kind("Pod").wakes_on_nothing());
1199 assert!(!KindFilter::All.wakes_on_nothing());
1200 assert_eq!(
1201 ticks_before_the_fallback(KindFilter::Kinds(Vec::new())).await,
1202 1,
1203 "a driver no event wakes polls first"
1204 );
1205 assert_eq!(
1206 ticks_before_the_fallback(KindFilter::kind("Pod")).await,
1207 0,
1208 "an event-driven driver is woken by its events"
1209 );
1210 }
1211
1212 #[tokio::test(start_paused = true)]
1213 async fn a_controller_that_always_requeues_gets_one_slot_not_a_chain() {
1214 let probe = Probe::new(Answer::Requeue(REQUEUE_AFTER));
1215 let s = an_hour_of(&probe, &Feed::new()).await;
1216
1217 assert_eq!(
1218 s.max_in_flight, 1,
1219 "{} ticks of one controller ran at once; a driver has one slot",
1220 s.max_in_flight
1221 );
1222 assert!(
1223 s.ticks <= ONE_SLOT_CEILING,
1224 "{} ticks in an hour, above the one-slot ceiling of {ONE_SLOT_CEILING}: \
1225 re-ticks are piling up",
1226 s.ticks
1227 );
1228 assert!(
1230 s.ticks > WITHOUT_TARGETED_RETRY,
1231 "{} ticks is no more than events + fallback explain; the requeue was dropped",
1232 s.ticks
1233 );
1234 assert!(
1235 s.max_gap <= REQUEUE_AFTER + TICK_TAKES + Duration::from_millis(10),
1236 "a {:?} gap between ticks: the 1 s requeue was not kept",
1237 s.max_gap
1238 );
1239 }
1240
1241 #[tokio::test(start_paused = true)]
1242 async fn a_controller_that_always_fails_transiently_gets_one_slot_not_a_chain() {
1243 let probe = Probe::new(Answer::Transient);
1244 assert!(
1245 next_wake(
1246 &Answer::Transient.result(),
1247 &mut ConsecutiveFailures::default()
1248 )
1249 .is_some(),
1250 "precondition: a Transient error is retried"
1251 );
1252 let s = an_hour_of(&probe, &Feed::new()).await;
1253
1254 assert_eq!(
1255 s.max_in_flight, 1,
1256 "{} failing ticks ran at once; retries must share one slot",
1257 s.max_in_flight
1258 );
1259 assert!(
1260 s.ticks <= ONE_SLOT_CEILING,
1261 "{} retries in an hour, above the one-slot ceiling of {ONE_SLOT_CEILING}",
1262 s.ticks
1263 );
1264 }
1265
1266 #[tokio::test(start_paused = true)]
1267 async fn a_declarative_failure_is_ticked_by_events_and_the_fallback_only() {
1268 let probe = Probe::new(Answer::Declarative);
1269 let s = an_hour_of(&probe, &Feed::new()).await;
1270
1271 assert!(
1272 s.ticks <= WITHOUT_TARGETED_RETRY,
1273 "{} ticks: a broken declaration got a targeted retry",
1274 s.ticks
1275 );
1276 assert!(
1279 s.ticks + 1 >= EVENTS,
1280 "{} ticks for {EVENTS} events: the driver stopped ticking a failing controller",
1281 s.ticks
1282 );
1283 }
1284
1285 #[tokio::test(start_paused = true)]
1290 async fn a_fallback_of_duration_max_never_fires() {
1291 let day = Duration::from_secs(24 * 3600);
1292
1293 let disabled = Probe::new(Answer::Done);
1294 let s = drive(&disabled, &Feed::new(), Duration::MAX, None, day).await;
1295 assert_eq!(
1296 s.ticks, 0,
1297 "{} ticks in a quiet day with the fallback disabled",
1298 s.ticks
1299 );
1300
1301 let enabled = Probe::new(Answer::Done);
1304 let s = drive(&enabled, &Feed::new(), FALLBACK, None, day).await;
1305 let period = u64::try_from((FALLBACK + TICK_TAKES).as_millis()).unwrap();
1306 let expected = u64::try_from(day.as_millis()).unwrap() / period;
1307 assert!(
1308 s.ticks.abs_diff(expected) <= 1,
1309 "{} fallback ticks in a quiet day, expected about {expected}",
1310 s.ticks
1311 );
1312 }
1313
1314 #[tokio::test(start_paused = true)]
1318 async fn a_refused_subscription_is_retried_even_when_requeues_outpace_the_fallback() {
1319 let probe = Probe::new(Answer::Requeue(REQUEUE_AFTER));
1320 let feed = Feed::refusing(3);
1321 let _ = an_hour_of(&probe, &feed).await;
1322
1323 assert!(
1324 feed.accepted.load(Ordering::SeqCst) >= 1,
1325 "the store refused three subscriptions and the driver never asked again"
1326 );
1327 }
1328
1329 #[test]
1330 fn next_wake_on_a_declarative_error_is_none() {
1331 let mut failures = ConsecutiveFailures::default();
1332 for _ in 0..3 {
1333 assert_eq!(
1334 next_wake(&Answer::Declarative.result(), &mut failures),
1335 None
1336 );
1337 }
1338 }
1339
1340 #[test]
1341 fn next_wake_follows_the_outcome() {
1342 let d = Duration::from_millis(250);
1343 let ok = |result| Ok(ReconcileOutcome::new(ReconcileReport::default(), result));
1344 let mut failures = ConsecutiveFailures::default();
1345 assert_eq!(next_wake(&ok(ReconcileResult::Done), &mut failures), None);
1346 assert_eq!(
1347 next_wake(&ok(ReconcileResult::Requeue(d)), &mut failures),
1348 Some(d)
1349 );
1350 assert_eq!(
1351 next_wake(&ok(ReconcileResult::RequeueWithProgress(d)), &mut failures),
1352 Some(d)
1353 );
1354 assert_eq!(
1356 next_wake(&Answer::Transient.result(), &mut failures),
1357 Some(Duration::from_secs(1))
1358 );
1359 }
1360
1361 #[tokio::test(start_paused = true)]
1373 async fn transient_retry_gaps_grow_until_the_cap() {
1374 const KICK: Duration = Duration::from_secs(90);
1375 const _: () = assert!(KICK.as_millis() > TRANSIENT_RETRY.cap().as_millis() + 100);
1376 let probe = Probe::new(Answer::Transient);
1377 let _ = drive(&probe, &Feed::new(), KICK, None, Duration::from_secs(600)).await;
1378 let gaps = probe.gaps();
1379 let cap = TRANSIENT_RETRY.cap() + TICK_TAKES;
1380
1381 assert_eq!(
1382 gaps.first().copied(),
1383 Some(TRANSIENT_RETRY.base() + TICK_TAKES),
1384 "the first retry is at the base: {gaps:?}"
1385 );
1386 assert_grows_then_holds(&gaps, cap);
1387 assert!(
1388 gaps.iter().filter(|g| **g == cap).count() >= 3,
1389 "ten minutes of failure never reached the {cap:?} cap: {gaps:?}"
1390 );
1391 }
1392
1393 fn assert_grows_then_holds(gaps: &[Duration], cap: Duration) {
1396 assert!(gaps.len() >= 3, "too few retries to see a curve: {gaps:?}");
1397 for pair in gaps.windows(2) {
1398 let (a, b) = (pair[0], pair[1]);
1399 assert!(b <= cap, "a {b:?} gap is past the {cap:?} cap: {gaps:?}");
1400 if a < cap {
1401 assert!(
1402 b == cap || b.as_micros() * 10 >= a.as_micros() * 18,
1403 "{a:?} then {b:?}: the retry gap did not grow 1.8x toward the cap: {gaps:?}"
1404 );
1405 } else {
1406 assert_eq!(b, cap, "past the cap the gap holds: {gaps:?}");
1407 }
1408 }
1409 }
1410
1411 #[test]
1412 fn a_success_resets_the_retry_curve() {
1413 let mut failures = ConsecutiveFailures::default();
1414 let owed: Vec<_> = (0..4)
1415 .map(|_| next_wake(&Answer::Transient.result(), &mut failures))
1416 .collect();
1417 assert_eq!(
1418 owed,
1419 [1, 2, 4, 8].map(|s| Some(Duration::from_secs(s))),
1420 "consecutive failures walk the curve"
1421 );
1422 assert_eq!(failures.count(), 4);
1423
1424 let _ = next_wake(&Answer::Done.result(), &mut failures);
1425 assert_eq!(failures.count(), 0, "an Ok ends the streak");
1426 assert_eq!(
1427 next_wake(&Answer::Transient.result(), &mut failures),
1428 Some(TRANSIENT_RETRY.base()),
1429 "the first failure after a success is retried at the base again"
1430 );
1431 }
1432
1433 #[test]
1436 fn a_declarative_failure_extends_the_streak_without_a_retry() {
1437 let mut failures = ConsecutiveFailures::default();
1438 assert_eq!(
1439 next_wake(&Answer::Declarative.result(), &mut failures),
1440 None
1441 );
1442 assert_eq!(failures.count(), 1);
1443 assert_eq!(
1444 next_wake(&Answer::Transient.result(), &mut failures),
1445 Some(TRANSIENT_RETRY.delay(1))
1446 );
1447 }
1448
1449 #[tokio::test(start_paused = true)]
1453 async fn resubscribe_gaps_grow_until_the_cap() {
1454 let probe = Probe::taking(Answer::Done, Duration::ZERO);
1455 let feed = Feed::ending_every_stream();
1456 let _ = drive(&probe, &feed, HOUR, None, Duration::from_secs(300)).await;
1457 let gaps = gaps(&feed.asked.lock().unwrap());
1458
1459 assert_eq!(
1460 gaps.first().copied(),
1461 Some(RESUBSCRIBE.base()),
1462 "the first re-subscribe waits the base: {gaps:?}"
1463 );
1464 assert_grows_then_holds(&gaps, RESUBSCRIBE.cap());
1465 assert!(
1466 gaps.iter().filter(|g| **g == RESUBSCRIBE.cap()).count() >= 3,
1467 "five minutes of ended streams never reached the cap: {gaps:?}"
1468 );
1469 }
1470
1471 #[test]
1472 fn the_slot_keeps_the_earlier_deadline_and_a_tick_clears_it() {
1473 let now = Instant::now();
1474 let mut slot = RequeueSlot::default();
1475 slot.arm(now + Duration::from_secs(5));
1476 slot.arm(now + Duration::from_secs(1));
1477 slot.arm(now + Duration::from_secs(3));
1478 assert_eq!(slot.at, Some(now + Duration::from_secs(1)));
1479 slot.clear();
1480 assert_eq!(slot, RequeueSlot::default());
1481 }
1482
1483 async fn heartbeat_of(probe: &Arc<Probe>, run_for: Duration) -> Arc<Heartbeat> {
1492 let beat = Arc::new(Heartbeat::new());
1493 let config = WatchDriverConfig {
1494 fallback_interval: FALLBACK,
1495 ..WatchDriverConfig::default()
1496 };
1497 let driver = tokio::spawn(run(probe.clone(), Feed::new(), config, beat.clone()));
1498 tokio::time::sleep(run_for).await;
1499 driver.abort();
1500 let _ = driver.await;
1501 beat
1502 }
1503
1504 #[tokio::test(start_paused = true)]
1505 async fn every_tick_is_recorded_in_the_heartbeat_with_its_class() {
1506 for (answer, class) in [
1507 (Answer::Done, TickClass::Done),
1508 (Answer::Requeue(REQUEUE_AFTER), TickClass::Requeued),
1509 (Answer::Transient, TickClass::Transient),
1510 (Answer::Declarative, TickClass::Declarative),
1511 ] {
1512 let probe = Probe::new(answer);
1513 let beat = heartbeat_of(&probe, Duration::from_secs(95))
1514 .await
1515 .snapshot();
1516 let ticks = probe.stats().ticks;
1517
1518 assert!(ticks >= 3, "{answer:?}: only {ticks} ticks in 95 s");
1519 assert_eq!(
1520 beat.ticks_started, ticks,
1521 "{answer:?}: the heartbeat missed a tick the controller saw"
1522 );
1523 assert!(
1525 beat.ticks_finished + 1 >= beat.ticks_started,
1526 "{answer:?}: {beat:?}"
1527 );
1528 assert_eq!(beat.last_class, Some(class), "{answer:?}: {beat:?}");
1529 assert!(beat.last_end.is_some() && beat.last_start.is_some());
1530 }
1531 }
1532
1533 #[tokio::test(start_paused = true)]
1536 async fn a_tick_in_progress_reads_as_in_flight() {
1537 let probe = Probe::taking(Answer::Done, Duration::from_secs(20));
1538 let beat = Arc::new(Heartbeat::new());
1539 let config = WatchDriverConfig {
1540 fallback_interval: FALLBACK,
1541 ..WatchDriverConfig::default()
1542 };
1543 let driver = tokio::spawn(run(probe.clone(), Feed::new(), config, beat.clone()));
1544 tokio::time::sleep(FALLBACK + Duration::from_secs(5)).await;
1546 let mid = beat.snapshot();
1547 driver.abort();
1548 let _ = driver.await;
1549
1550 assert!(
1551 mid.in_flight(),
1552 "a 20 s tick 5 s in is not in flight: {mid:?}"
1553 );
1554 assert_eq!((mid.ticks_started, mid.ticks_finished), (1, 0));
1555 assert_eq!(mid.last_class, None, "no tick has ended yet: {mid:?}");
1556 assert!(mid.last_start.is_some());
1557 }
1558
1559 async fn a_panicking_driver(
1569 tick_state: TickState,
1570 ) -> (
1571 Arc<Probe>,
1572 Arc<Heartbeat>,
1573 tokio::task::JoinHandle<Infallible>,
1574 ) {
1575 let probe = Probe::new(Answer::Panic);
1576 let beat = Arc::new(Heartbeat::new());
1577 let config = WatchDriverConfig {
1578 fallback_interval: FALLBACK,
1579 tick_state,
1580 ..WatchDriverConfig::default()
1581 };
1582 let driver = tokio::spawn(run(probe.clone(), Feed::new(), config, beat.clone()));
1583 tokio::time::sleep(FALLBACK * 3 + Duration::from_secs(5)).await;
1584 (probe, beat, driver)
1585 }
1586
1587 #[tokio::test(start_paused = true)]
1592 async fn a_stateless_panic_is_contained_counted_and_reticked_by_the_fallback() {
1593 let (probe, beat, driver) = a_panicking_driver(TickState::Stateless).await;
1594 let still_running = !driver.is_finished();
1595 driver.abort();
1596 let _ = driver.await;
1597 let ticks = probe.stats().ticks;
1598 let snap = beat.snapshot();
1599
1600 assert!(
1601 still_running,
1602 "a contained panic ended the driver: one bad object retired the controller"
1603 );
1604 assert_eq!(
1605 ticks, 3,
1606 "95 s with a 30 s fallback and no events is three ticks: a panic is \
1607 re-ticked by the fallback and never by a targeted retry"
1608 );
1609 assert_eq!(
1610 snap.panics, ticks,
1611 "every panicked tick is counted: {snap:?}"
1612 );
1613 assert_eq!(
1614 snap.ticks_finished, ticks,
1615 "each panicked tick ended: {snap:?}"
1616 );
1617 assert_eq!(snap.last_class, Some(TickClass::Panicked), "{snap:?}");
1618 }
1619
1620 #[tokio::test(start_paused = true)]
1624 async fn a_stateful_panic_ends_the_driver_task() {
1625 let (probe, beat, driver) = a_panicking_driver(TickState::Stateful).await;
1626 assert!(driver.is_finished(), "a stateful driver survived its panic");
1627 let ended = match driver.await {
1628 Ok(never) => match never {},
1629 Err(ended) => ended,
1630 };
1631 let snap = beat.snapshot();
1632
1633 assert!(
1634 ended.is_panic(),
1635 "the driver's task ended but not by panic: {ended:?}"
1636 );
1637 assert_eq!(
1638 probe.stats().ticks,
1639 1,
1640 "a stateful controller was re-ticked over the state its panic tore"
1641 );
1642 assert!(
1643 snap.in_flight(),
1644 "the panicked tick never ended; its heartbeat must not say it did: {snap:?}"
1645 );
1646 assert_eq!(
1647 snap.panics, 0,
1648 "the driver does not count a panic it did not contain — the task's \
1649 owner does: {snap:?}"
1650 );
1651 }
1652
1653 #[test]
1656 fn a_driver_is_stateful_unless_told_otherwise() {
1657 assert_eq!(WatchDriverConfig::default().tick_state, TickState::Stateful);
1658 }
1659
1660 #[test]
1663 fn a_contained_panic_gets_no_targeted_retry() {
1664 let mut failures = ConsecutiveFailures::default();
1665 let panicked = Err(ControllerError::Panicked(crate::PanicMessage::Opaque));
1666 assert_eq!(next_wake(&panicked, &mut failures), None);
1667 assert_eq!(failures.count(), 1);
1668 }
1669
1670 #[derive(Default)]
1671 struct Recorded(Mutex<Vec<String>>);
1672
1673 struct Fields<'a>(&'a mut String);
1674
1675 impl tracing::field::Visit for Fields<'_> {
1676 fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
1677 self.0.push_str(&format!("{}={value:?} ", field.name()));
1678 }
1679 }
1680
1681 struct Recorder(Arc<Recorded>);
1682
1683 impl tracing::Subscriber for Recorder {
1684 fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
1685 true
1686 }
1687 fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
1688 tracing::span::Id::from_u64(1)
1689 }
1690 fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
1691 fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
1692 fn event(&self, event: &tracing::Event<'_>) {
1693 let mut line = format!("{} ", event.metadata().level());
1694 event.record(&mut Fields(&mut line));
1695 self.0.0.lock().unwrap().push(line);
1696 }
1697 fn enter(&self, _: &tracing::span::Id) {}
1698 fn exit(&self, _: &tracing::span::Id) {}
1699 }
1700
1701 fn logged(f: impl FnOnce()) -> Vec<String> {
1702 let recorded = Arc::new(Recorded::default());
1703 tracing::subscriber::with_default(Recorder(recorded.clone()), f);
1704 let lines = recorded.0.lock().unwrap().clone();
1705 lines
1706 }
1707
1708 #[test]
1709 fn a_failed_tick_is_logged_with_its_retry_in_milliseconds() {
1710 let transient = logged(|| {
1711 log_tick(
1712 "probe",
1713 &Answer::Transient.result(),
1714 Some(Duration::from_millis(1500)),
1715 );
1716 });
1717 assert_eq!(transient.len(), 1, "{transient:?}");
1718 assert!(transient[0].starts_with("WARN "), "{transient:?}");
1719 assert!(transient[0].contains("after_ms=1500 "), "{transient:?}");
1720
1721 let declarative = logged(|| log_tick("probe", &Answer::Declarative.result(), None));
1722 assert_eq!(declarative.len(), 1, "{declarative:?}");
1723 assert!(declarative[0].starts_with("ERROR "), "{declarative:?}");
1724 }
1725
1726 #[test]
1727 fn millis_is_whole_milliseconds_and_saturates() {
1728 assert_eq!(millis(Duration::from_millis(1500)), 1500);
1729 assert_eq!(millis(Duration::from_micros(2999)), 2);
1730 assert_eq!(millis(Duration::MAX), u64::MAX);
1731 }
1732
1733 #[tokio::test(start_paused = true)]
1734 async fn a_driver_hands_out_the_heartbeat_it_records_into_and_ticks_its_controller() {
1735 let router = engenho_store::InProcessRouter::new();
1736 let cfg = engenho_store::default_config("watch-driver-handle").unwrap();
1737 let store = Arc::new(
1738 StoreMesh::start(1, "in-process://1".into(), router, cfg)
1739 .await
1740 .unwrap(),
1741 );
1742 let probe = Arc::try_unwrap(Probe::new(Answer::Requeue(REQUEUE_AFTER)))
1743 .unwrap_or_else(|_| unreachable!("a fresh probe has one owner"));
1744 let driver = WatchDriver::new(probe, store, WatchDriverConfig::default());
1745 assert!(Arc::ptr_eq(&driver.heartbeat(), &driver.beat));
1746 let outcome = driver.tick_once().await.expect("the probe requeues");
1747 assert_eq!(outcome.result.requeue_after(), Some(REQUEUE_AFTER));
1748 }
1749}