1use std::collections::{BTreeMap, BTreeSet};
23use std::net::{IpAddr, Ipv4Addr};
24use std::str::FromStr;
25
26pub const GRACE: std::time::Duration = std::time::Duration::from_secs(5);
30
31pub const STRIKES_BEFORE_REBUILD: u32 = 2;
34
35pub const RETRY_AFTER_TICKS: &[u32] = &[2, 4, 8, 20, 40];
46
47pub const MAX_DOWN_RETRIES: u32 = 6;
52
53pub fn should_publish(health: &MdnsHealth, changed: bool) -> bool {
63 match health {
64 MdnsHealth::Pending => false,
65 MdnsHealth::Healthy => changed,
66 MdnsHealth::Degraded { .. } | MdnsHealth::Undiscoverable { .. } => true,
67 }
68}
69
70pub const PEER_PROOF_WINDOW_MS: u64 = 15 * 60 * 1000;
72
73static LAST_INBOUND_PEER_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
76
77pub fn is_remote_peer(peer: IpAddr, own: &std::collections::HashSet<IpAddr>) -> bool {
81 !peer.is_loopback() && !peer.is_unspecified() && !own.contains(&peer)
82}
83
84pub fn note_inbound_peer(peer: IpAddr) {
88 if is_remote_peer(peer, &crate::backend::lan::listeners::cached_local_addresses()) {
89 LAST_INBOUND_PEER_MS.store(agentmux_common::time::now_ms_u64(), std::sync::atomic::Ordering::Relaxed);
90 }
91}
92
93pub fn last_inbound_peer_ms() -> Option<u64> {
95 match LAST_INBOUND_PEER_MS.load(std::sync::atomic::Ordering::Relaxed) {
96 0 => None,
97 ms => Some(ms),
98 }
99}
100
101pub fn with_peer_proof(health: MdnsHealth, last_inbound_peer_ms: Option<u64>, now_ms: u64) -> MdnsHealth {
106 let proven = last_inbound_peer_ms.is_some_and(|t| now_ms.saturating_sub(t) <= PEER_PROOF_WINDOW_MS);
107 match health {
108 MdnsHealth::Undiscoverable { .. } if proven => MdnsHealth::Healthy,
109 other => other,
110 }
111}
112
113pub fn corrected(health: MdnsHealth) -> MdnsHealth {
115 with_peer_proof(health, last_inbound_peer_ms(), agentmux_common::time::now_ms_u64())
116}
117
118#[derive(Debug, Clone, PartialEq, Eq, Default)]
119pub enum MdnsHealth {
120 #[default]
122 Pending,
123 Healthy,
126 Degraded { missing: Vec<Ipv4Addr> },
129 Undiscoverable { missing: Vec<Ipv4Addr> },
131}
132
133impl MdnsHealth {
134 #[cfg(test)]
135 pub fn is_undiscoverable(&self) -> bool {
136 matches!(self, MdnsHealth::Undiscoverable { .. })
137 }
138
139 pub fn wire_state(&self) -> &'static str {
141 match self {
142 MdnsHealth::Pending => "pending",
143 MdnsHealth::Healthy => "healthy",
144 MdnsHealth::Degraded { .. } => "degraded",
145 MdnsHealth::Undiscoverable { .. } => "undiscoverable",
146 }
147 }
148
149 pub fn missing(&self) -> &[Ipv4Addr] {
150 match self {
151 MdnsHealth::Degraded { missing } | MdnsHealth::Undiscoverable { missing } => missing,
152 _ => &[],
153 }
154 }
155}
156
157pub fn ipv4_in(payload: &str) -> Vec<Ipv4Addr> {
163 payload
164 .split(|c: char| !(c.is_ascii_digit() || c == '.'))
165 .filter(|t| !t.is_empty())
166 .filter_map(|t| Ipv4Addr::from_str(t).ok())
167 .collect()
168}
169
170pub fn expected_by_interface(
179 local: impl IntoIterator<Item = (String, IpAddr)>,
180) -> Vec<BTreeSet<Ipv4Addr>> {
181 let mut by_name: BTreeMap<String, BTreeSet<Ipv4Addr>> = BTreeMap::new();
182 for (name, addr) in local {
183 let IpAddr::V4(v4) = addr else { continue };
184 if v4.is_loopback()
185 || v4.is_unspecified()
186 || v4.is_link_local()
187 || v4.is_multicast()
188 || v4.is_broadcast()
189 {
190 continue;
191 }
192 by_name.entry(name).or_default().insert(v4);
193 }
194 by_name.into_values().collect()
195}
196
197pub fn evaluate(expected: &[BTreeSet<Ipv4Addr>], announced: &BTreeSet<Ipv4Addr>) -> MdnsHealth {
201 if expected.is_empty() {
202 return MdnsHealth::Healthy;
203 }
204 let missing: Vec<Ipv4Addr> = expected
205 .iter()
206 .filter(|iface| iface.is_disjoint(announced))
207 .filter_map(|iface| iface.iter().next().copied())
208 .collect();
209 if missing.is_empty() {
210 MdnsHealth::Healthy
211 } else if missing.len() == expected.len() {
212 MdnsHealth::Undiscoverable { missing }
213 } else {
214 MdnsHealth::Degraded { missing }
215 }
216}
217
218pub fn verdict(
226 monitored: bool,
227 since_start: std::time::Duration,
228 expected: &[BTreeSet<Ipv4Addr>],
229 announced: &BTreeSet<Ipv4Addr>,
230) -> MdnsHealth {
231 if !monitored || since_start < GRACE {
232 return MdnsHealth::Pending;
233 }
234 evaluate(expected, announced)
235}
236
237#[derive(Debug, PartialEq, Eq)]
238pub enum Action {
239 Nothing,
240 Rebuild,
242}
243
244#[derive(Debug, Default)]
246pub struct Watchdog {
247 strikes: u32,
248 rebuilds: u32,
249 cooldown: u32,
251 down_retries: u32,
252}
253
254impl Watchdog {
255 pub fn rebuilds(&self) -> u32 {
256 self.rebuilds
257 }
258
259 pub fn retry_in_ticks(&self) -> u32 {
261 self.cooldown
262 }
263
264 pub fn reset(&mut self) {
266 *self = Watchdog::default();
267 }
268
269 pub fn observe_down(&mut self) -> bool {
273 if self.down_retries < MAX_DOWN_RETRIES {
274 self.down_retries += 1;
275 true
276 } else {
277 false
278 }
279 }
280
281 pub fn observe(&mut self, health: &MdnsHealth) -> Action {
282 self.down_retries = 0;
284 self.cooldown = self.cooldown.saturating_sub(1);
286 match health {
287 MdnsHealth::Pending => Action::Nothing,
289 MdnsHealth::Healthy => {
290 *self = Watchdog { down_retries: 0, ..Watchdog::default() };
291 Action::Nothing
292 }
293 MdnsHealth::Degraded { .. } => {
294 self.strikes = 0;
295 Action::Nothing
296 }
297 MdnsHealth::Undiscoverable { .. } => {
298 if self.rebuilds == 0 {
299 self.strikes += 1;
301 if self.strikes < STRIKES_BEFORE_REBUILD {
302 return Action::Nothing;
303 }
304 } else if self.cooldown > 0 {
305 return Action::Nothing;
307 }
308 self.strikes = 0;
309 self.rebuilds += 1;
310 let step = (self.rebuilds as usize - 1).min(RETRY_AFTER_TICKS.len() - 1);
311 self.cooldown = RETRY_AFTER_TICKS[step];
312 Action::Rebuild
313 }
314 }
315 }
316}
317
318#[cfg(test)]
319mod tests {
320 use super::*;
321
322 fn ip(s: &str) -> Ipv4Addr {
323 s.parse().unwrap()
324 }
325 fn set(v: &[&str]) -> BTreeSet<Ipv4Addr> {
326 v.iter().map(|s| ip(s)).collect()
327 }
328 fn ifaces(v: &[&str]) -> Vec<BTreeSet<Ipv4Addr>> {
330 v.iter().map(|s| set(&[s])).collect()
331 }
332 fn undiscoverable() -> MdnsHealth {
333 MdnsHealth::Undiscoverable { missing: vec![ip("192.168.1.26")] }
334 }
335
336 #[test]
337 fn a_peer_that_reached_us_overrides_an_undiscoverable_verdict() {
338 let now = 10_000_000;
339 let recent = Some(now - 60_000);
340 assert_eq!(with_peer_proof(undiscoverable(), recent, now), MdnsHealth::Healthy);
341 assert_eq!(with_peer_proof(undiscoverable(), Some(now - PEER_PROOF_WINDOW_MS), now), MdnsHealth::Healthy);
343 assert!(with_peer_proof(undiscoverable(), Some(now - PEER_PROOF_WINDOW_MS - 1), now).is_undiscoverable());
344 assert!(with_peer_proof(undiscoverable(), None, now).is_undiscoverable());
346 let degraded = MdnsHealth::Degraded { missing: vec![ip("198.51.100.9")] };
348 assert_eq!(with_peer_proof(degraded.clone(), recent, now), degraded);
349 assert_eq!(with_peer_proof(MdnsHealth::Pending, recent, now), MdnsHealth::Pending);
350 }
351
352 #[test]
353 fn proof_keeps_the_rebuild_count_from_climbing() {
354 let mut w = Watchdog::default();
355 assert_eq!(w.observe(&undiscoverable()), Action::Nothing);
356 assert_eq!(w.observe(&undiscoverable()), Action::Rebuild);
357 assert_eq!(w.rebuilds(), 1);
358 for _ in 0..40 {
360 let h = with_peer_proof(undiscoverable(), Some(1), 2);
361 assert_eq!(w.observe(&h), Action::Nothing);
362 }
363 assert_eq!(w.rebuilds(), 0);
364 }
365
366 #[test]
367 fn this_host_talking_to_itself_is_not_a_peer() {
368 let own: std::collections::HashSet<IpAddr> = ["198.51.100.20".parse().unwrap()].into_iter().collect();
369 assert!(!is_remote_peer("127.0.0.1".parse().unwrap(), &own));
370 assert!(!is_remote_peer("::1".parse().unwrap(), &own));
371 assert!(!is_remote_peer("0.0.0.0".parse().unwrap(), &own));
372 assert!(!is_remote_peer("198.51.100.20".parse().unwrap(), &own));
374 assert!(is_remote_peer("198.51.100.30".parse().unwrap(), &own));
375 }
376
377 #[test]
378 fn parses_the_registration_payload_shape() {
379 let got = ipv4_in("[192.168.1.26, 172.17.16.1, fe80::1]");
381 assert_eq!(got, vec![ip("192.168.1.26"), ip("172.17.16.1")]);
382 }
383
384 #[test]
385 fn parses_the_host_colon_addr_payload_shape() {
386 assert_eq!(ipv4_in("Area54.local.:192.168.1.26"), vec![ip("192.168.1.26")]);
387 assert!(ipv4_in("Area54.local.").is_empty());
389 assert!(ipv4_in("").is_empty());
390 }
391
392 #[test]
393 fn expected_drops_everything_a_peer_could_not_use() {
394 let local = [
395 ("lo", "127.0.0.1"),
396 ("any", "0.0.0.0"),
397 ("apipa", "169.254.21.81"),
398 ("mc", "224.0.0.251"),
399 ("bc", "255.255.255.255"),
400 ("Ethernet", "192.168.1.26"),
401 ("vEthernet", "172.17.16.1"),
402 ("v6only", "fe80::1"),
403 ]
404 .map(|(n, a)| (n.to_string(), a.parse::<IpAddr>().unwrap()));
405 assert_eq!(expected_by_interface(local), vec![set(&["192.168.1.26"]), set(&["172.17.16.1"])]);
406 }
407
408 #[test]
409 fn two_addresses_on_one_interface_are_one_group() {
410 let local = [("Ethernet", "192.168.1.26"), ("Ethernet", "192.168.1.27"), ("Wi-Fi", "10.0.0.5")]
411 .map(|(n, a)| (n.to_string(), a.parse::<IpAddr>().unwrap()));
412 assert_eq!(
413 expected_by_interface(local),
414 vec![set(&["192.168.1.26", "192.168.1.27"]), set(&["10.0.0.5"])]
415 );
416 }
417
418 #[test]
419 fn nothing_to_announce_on_is_not_a_fault() {
420 assert_eq!(evaluate(&[], &set(&[])), MdnsHealth::Healthy);
421 }
422
423 #[test]
424 fn announced_on_all_expected_is_healthy() {
425 let e = ifaces(&["192.168.1.26", "172.17.16.1"]);
426 assert_eq!(evaluate(&e, &set(&["192.168.1.26", "172.17.16.1"])), MdnsHealth::Healthy);
427 }
428
429 #[test]
432 fn an_interface_is_covered_by_any_one_of_its_addresses() {
433 let e = vec![set(&["192.168.1.26", "192.168.1.27"])];
434 assert_eq!(evaluate(&e, &set(&["192.168.1.26"])), MdnsHealth::Healthy);
435 assert_eq!(evaluate(&e, &set(&["192.168.1.27"])), MdnsHealth::Healthy);
436 }
437
438 #[test]
439 fn announcements_outside_the_expected_set_prove_nothing() {
440 let e = ifaces(&["192.168.1.26"]);
441 assert!(evaluate(&e, &set(&["10.9.9.9"])).is_undiscoverable());
442 }
443
444 #[test]
445 fn the_area54_case_is_undiscoverable() {
446 let e = ifaces(&["192.168.1.26", "172.17.16.1"]);
448 let h = evaluate(&e, &set(&[]));
449 assert_eq!(h.wire_state(), "undiscoverable");
450 assert_eq!(h.missing(), &[ip("192.168.1.26"), ip("172.17.16.1")]);
451 }
452
453 #[test]
454 fn a_missing_virtual_adapter_alone_is_only_degraded() {
455 let e = ifaces(&["192.168.1.26", "172.17.16.1"]);
456 let h = evaluate(&e, &set(&["192.168.1.26"]));
457 assert_eq!(h, MdnsHealth::Degraded { missing: vec![ip("172.17.16.1")] });
458 assert!(!h.is_undiscoverable());
459 }
460
461 #[test]
462 fn a_standing_problem_is_resent_every_tick_so_a_late_window_learns_of_it() {
463 let bad = undiscoverable();
465 for _ in 0..3 {
466 assert!(should_publish(&bad, false), "unchanged but still broken: resend");
467 }
468 let degraded = MdnsHealth::Degraded { missing: vec![ip("172.17.16.1")] };
469 assert!(should_publish(°raded, false));
470 }
471
472 #[test]
473 fn healthy_is_only_sent_on_change_and_pending_never() {
474 assert!(should_publish(&MdnsHealth::Healthy, true), "recovery must clear a warning");
475 assert!(!should_publish(&MdnsHealth::Healthy, false));
476 assert!(!should_publish(&MdnsHealth::Pending, true));
477 assert!(!should_publish(&MdnsHealth::Pending, false));
478 }
479
480 #[test]
481 fn a_down_daemon_is_retried_a_bounded_number_of_times() {
482 let mut w = Watchdog::default();
483 let tries = (0..20).filter(|_| w.observe_down()).count() as u32;
484 assert_eq!(tries, MAX_DOWN_RETRIES);
485 }
486
487 #[test]
488 fn a_failed_rebuild_does_not_wipe_the_rebuild_budget() {
489 let mut w = Watchdog::default();
492 w.observe(&undiscoverable());
493 assert_eq!(w.observe(&undiscoverable()), Action::Rebuild);
494 assert_eq!(w.rebuilds(), 1);
495 assert!(w.observe_down());
496 assert!(w.observe_down());
497 assert_eq!(w.rebuilds(), 1, "still counted while the daemon is down");
498 }
499
500 #[test]
501 fn a_daemon_coming_back_restores_the_retries() {
502 let mut w = Watchdog::default();
503 while w.observe_down() {}
504 assert!(!w.observe_down(), "exhausted");
505 w.observe(&MdnsHealth::Pending); assert!(w.observe_down(), "retries start over");
507 }
508
509 #[test]
510 fn no_monitor_means_no_verdict_however_long_it_has_been() {
511 let e = ifaces(&["192.168.1.26"]);
513 let long_ago = GRACE * 100;
514 assert_eq!(verdict(false, long_ago, &e, &set(&[])), MdnsHealth::Pending);
515 assert_eq!(verdict(false, long_ago, &e, &set(&["192.168.1.26"])), MdnsHealth::Pending);
516 }
517
518 #[test]
519 fn a_monitored_daemon_gets_its_start_up_grace_then_a_verdict() {
520 let e = ifaces(&["192.168.1.26"]);
521 assert_eq!(verdict(true, GRACE / 2, &e, &set(&[])), MdnsHealth::Pending);
522 assert!(verdict(true, GRACE, &e, &set(&[])).is_undiscoverable());
523 assert_eq!(verdict(true, GRACE, &e, &set(&["192.168.1.26"])), MdnsHealth::Healthy);
524 }
525
526 #[test]
527 fn one_miss_is_not_enough_to_rebuild() {
528 let mut w = Watchdog::default();
529 assert_eq!(w.observe(&undiscoverable()), Action::Nothing);
530 assert_eq!(w.rebuilds(), 0);
531 }
532
533 #[test]
534 fn two_consecutive_misses_rebuild_and_a_pending_verdict_does_not_count() {
535 let mut w = Watchdog::default();
536 assert_eq!(w.observe(&undiscoverable()), Action::Nothing);
537 assert_eq!(w.observe(&MdnsHealth::Pending), Action::Nothing);
539 assert_eq!(w.observe(&undiscoverable()), Action::Rebuild);
540 assert_eq!(w.rebuilds(), 1);
541 }
542
543 #[test]
544 fn a_healthy_tick_resets_the_strikes() {
545 let mut w = Watchdog::default();
546 w.observe(&undiscoverable());
547 w.observe(&MdnsHealth::Healthy);
548 assert_eq!(w.observe(&undiscoverable()), Action::Nothing, "strikes restarted");
549 }
550
551 #[test]
555 fn rebuilds_back_off_and_never_stop() {
556 let mut w = Watchdog::default();
557 let mut at = Vec::new();
558 for tick in 1..=400u32 {
559 if w.observe(&undiscoverable()) == Action::Rebuild {
560 at.push(tick);
561 }
562 }
563 let gaps: Vec<u32> = at.windows(2).map(|p| p[1] - p[0]).collect();
564 assert_eq!(at[0], 2, "the first rebuild needs two misses in a row");
565 assert_eq!(&gaps[..5], &[2, 4, 8, 20, 40], "{at:?}");
566 assert!(gaps[5..].iter().all(|g| *g == 40), "settles at one attempt per 40 ticks: {gaps:?}");
567 assert!(400 - at.last().unwrap() < 40, "still retrying at the end: {at:?}");
568 assert!(at.len() > 10, "far more than the old cap of 3: {}", at.len());
569 }
570
571 #[test]
575 fn a_holder_that_lets_go_minutes_later_is_still_recovered() {
576 const HOLDER_LEAVES_AT_TICK: u32 = 28; let mut w = Watchdog::default();
578 let mut recovered_ok = false;
579 let mut recovered_at = None;
580 for tick in 1..=200u32 {
581 let health = if recovered_ok { MdnsHealth::Healthy } else { undiscoverable() };
582 if w.observe(&health) == Action::Rebuild {
583 recovered_ok = tick >= HOLDER_LEAVES_AT_TICK;
585 }
586 if recovered_ok && recovered_at.is_none() {
587 recovered_at = Some(tick);
588 }
589 }
590 let at = recovered_at.expect("it must recover once the holder lets go");
591 assert!((HOLDER_LEAVES_AT_TICK..HOLDER_LEAVES_AT_TICK + 40).contains(&at), "recovered at tick {at}");
592 assert_eq!(w.rebuilds(), 0, "full health restores the budget");
593 }
594
595 #[test]
596 fn the_next_attempt_time_is_exposed_for_the_log_line() {
597 let mut w = Watchdog::default();
598 w.observe(&undiscoverable());
599 assert_eq!(w.observe(&undiscoverable()), Action::Rebuild);
600 assert_eq!(w.retry_in_ticks(), RETRY_AFTER_TICKS[0]);
601 }
602
603 #[test]
604 fn recovery_restores_the_rebuild_budget() {
605 let mut w = Watchdog::default();
606 for _ in 0..40 {
607 w.observe(&undiscoverable());
608 }
609 w.observe(&MdnsHealth::Healthy);
610 assert_eq!(w.rebuilds(), 0);
611 w.observe(&undiscoverable());
612 assert_eq!(w.observe(&undiscoverable()), Action::Rebuild);
613 }
614
615 #[test]
616 fn degraded_does_not_clear_the_rebuild_count_but_does_clear_strikes() {
617 let mut w = Watchdog::default();
618 w.observe(&undiscoverable());
619 w.observe(&undiscoverable()); assert_eq!(w.rebuilds(), 1);
621 w.observe(&MdnsHealth::Degraded { missing: vec![ip("172.17.16.1")] });
622 assert_eq!(w.rebuilds(), 1, "only full health restores the budget");
623 }
624}