Skip to main content

agentmux_srv_core/connectivity/
tracker.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The reachability state machine and the probe schedule, with no I/O and no
5//! clock of its own: every call takes `now_ms`, so tests drive time.
6
7use std::collections::{BTreeMap, VecDeque};
8
9use super::{ConnectivityStatus, Outcome, Reachability, Service, ServiceStatus};
10
11/// Consecutive transport failures, with no answer between, that make a
12/// service `Offline`.
13pub(super) const OFFLINE_AFTER: u32 = 3;
14/// How far back failures count toward keeping a service `Degraded`.
15pub(super) const DEGRADED_WINDOW_MS: i64 = 60_000;
16/// Failures within [`DEGRADED_WINDOW_MS`] that keep a service `Degraded`
17/// after an answer; one stray reset is not worth a warning.
18pub(super) const DEGRADED_MIN_FAILURES: usize = 2;
19/// The first probe's delay after a service stops being `Online`, doubled
20/// after each probe that still finds it down, up to [`PROBE_MAX_MS`].
21pub(super) const PROBE_FIRST_MS: i64 = 5_000;
22pub(super) const PROBE_MAX_MS: i64 = 60_000;
23
24/// How many panes' own model API addresses are tracked at once. Past it, the oldest one that is online or
25/// not checked yet is dropped to make room; if every one is in trouble, a new one is not tracked.
26pub(super) const MAX_PANE_ADDRESSES: usize = 8;
27/// A probe that is scheduled or running: while its service isn't `Online`, or once after the OS reported a
28/// network change.
29#[derive(Debug, Clone, PartialEq)]
30struct ProbeSchedule {
31    due_ms: i64,
32    interval_ms: i64,
33    /// The running probe's ticket; only its result is applied.
34    in_flight: Option<u64>,
35    /// The network changed while the probe ran: its answer is about the old one, so the next
36    /// probe is due at once.
37    again: bool,
38}
39
40#[derive(Debug, Clone)]
41struct Entry {
42    state: Reachability,
43    since_ms: i64,
44    consecutive_failures: u32,
45    /// When the latest transport failures happened, within
46    /// [`DEGRADED_WINDOW_MS`]; no more than the count that matters.
47    recent_failures: VecDeque<i64>,
48    last_error: Option<String>,
49    probe: Option<ProbeSchedule>,
50}
51
52impl Entry {
53    fn new(now_ms: i64) -> Self {
54        Self {
55            state: Reachability::Online,
56            since_ms: now_ms,
57            consecutive_failures: 0,
58            recent_failures: VecDeque::new(),
59            last_error: None,
60            probe: None,
61        }
62    }
63
64    /// A service not checked yet, its first probe due now.
65    fn unchecked(now_ms: i64) -> Self {
66        let probe = Some(ProbeSchedule { due_ms: now_ms, interval_ms: PROBE_FIRST_MS, in_flight: None, again: false });
67        Self { state: Reachability::Unknown, probe, ..Self::new(now_ms) }
68    }
69
70    fn forget_old_failures(&mut self, now_ms: i64) {
71        while self.recent_failures.front().is_some_and(|t| now_ms - t > DEGRADED_WINDOW_MS) {
72            self.recent_failures.pop_front();
73        }
74    }
75
76    /// Applies one outcome; `probed` says it came from a probe of a service believed down,
77    /// so its failure confirms it.
78    fn apply(&mut self, outcome: Outcome, probed: bool, now_ms: i64) -> Reachability {
79        self.forget_old_failures(now_ms);
80        match outcome {
81            Outcome::Answered => {
82                self.consecutive_failures = 0;
83                let mixed = self.state == Reachability::Degraded && self.recent_failures.len() >= DEGRADED_MIN_FAILURES;
84                if mixed {
85                    Reachability::Degraded
86                } else {
87                    Reachability::Online
88                }
89            }
90            Outcome::Unreachable(error) => {
91                self.consecutive_failures = self.consecutive_failures.saturating_add(1);
92                self.recent_failures.push_back(now_ms);
93                if self.recent_failures.len() > DEGRADED_MIN_FAILURES {
94                    self.recent_failures.pop_front();
95                }
96                self.last_error = Some(error);
97                if probed || self.consecutive_failures >= OFFLINE_AFTER || self.state == Reachability::Offline {
98                    Reachability::Offline
99                } else {
100                    Reachability::Degraded
101                }
102            }
103        }
104    }
105
106    /// Moves to `next`; returns whether the state changed. Leaving `Online`
107    /// schedules the first probe, reaching it drops the schedule.
108    fn enter(&mut self, next: Reachability, now_ms: i64) -> bool {
109        if next == self.state {
110            return false;
111        }
112        if next == Reachability::Online {
113            self.probe = None;
114            self.last_error = None;
115        } else if self.state == Reachability::Online {
116            self.probe = Some(ProbeSchedule { due_ms: now_ms + PROBE_FIRST_MS, interval_ms: PROBE_FIRST_MS, in_flight: None, again: false });
117        }
118        self.state = next;
119        self.since_ms = now_ms;
120        true
121    }
122}
123
124/// Every service's reachability, and the internet's, derived from them.
125#[derive(Debug)]
126pub(super) struct Tracker {
127    services: BTreeMap<Service, Entry>,
128    internet: (Reachability, i64),
129    revision: u64,
130    next_ticket: u64,
131}
132
133impl Tracker {
134    /// `first_revision` starts above any earlier srv's, so a window that
135    /// outlives an srv restart still takes the new one's status as newer.
136    pub(super) fn new(first_revision: u64, now_ms: i64) -> Self {
137        Self { services: BTreeMap::new(), internet: (Reachability::Online, now_ms), revision: first_revision, next_ticket: 0 }
138    }
139
140    /// Lists `service` as not checked yet, with a probe due now, unless it
141    /// has already reported. Returns the new status when it was added.
142    pub(super) fn seed(&mut self, service: Service, now_ms: i64) -> Option<ConnectivityStatus> {
143        if self.services.contains_key(&service) || !self.make_room(&service) {
144            return None;
145        }
146        self.services.insert(service, Entry::unchecked(now_ms));
147        self.changed(true, now_ms)
148    }
149
150    /// An outcome from a request a subsystem made. Returns the new status
151    /// when a state changed; a new error text alone waits for the next one.
152    pub(super) fn report(&mut self, service: Service, outcome: Outcome, now_ms: i64) -> Option<ConnectivityStatus> {
153        if !self.make_room(&service) {
154            return None;
155        }
156        let entry = self.services.entry(service).or_insert_with(|| Entry::new(now_ms));
157        let next = entry.apply(outcome, false, now_ms);
158        let changed = entry.enter(next, now_ms);
159        self.changed(changed, now_ms)
160    }
161
162    /// Whether `service` can be added: a pane's own address counts against [`MAX_PANE_ADDRESSES`], and the
163    /// oldest one that is fine (or never checked) goes when the list is full.
164    fn make_room(&mut self, service: &Service) -> bool {
165        if !matches!(service, Service::ModelApiAt(..)) || self.services.contains_key(service) {
166            return true;
167        }
168        let at: Vec<(&Service, &Entry)> = self.services.iter().filter(|(s, _)| matches!(s, Service::ModelApiAt(..))).collect();
169        if at.len() < MAX_PANE_ADDRESSES {
170            return true;
171        }
172        let oldest = at
173            .iter()
174            .filter(|(_, e)| matches!(e.state, Reachability::Online | Reachability::Unknown))
175            .min_by_key(|(_, e)| e.since_ms)
176            .map(|(s, _)| (*s).clone());
177        match oldest {
178            Some(old) => {
179                self.services.remove(&old);
180                true
181            }
182            None => false,
183        }
184    }
185
186    /// The probes due at `now_ms`, each with the ticket its result must
187    /// carry; they count as running until [`Tracker::probe_finished`].
188    pub(super) fn take_due_probes(&mut self, now_ms: i64) -> Vec<(Service, u64)> {
189        let mut due = Vec::new();
190        for (service, entry) in &mut self.services {
191            if let Some(probe) = entry.probe.as_mut().filter(|p| p.in_flight.is_none() && p.due_ms <= now_ms) {
192                self.next_ticket += 1;
193                probe.in_flight = Some(self.next_ticket);
194                due.push((service.clone(), self.next_ticket));
195            }
196        }
197        due
198    }
199
200    /// When the next probe that isn't running is due, if any is scheduled.
201    pub(super) fn next_probe_due(&self) -> Option<i64> {
202        self.services
203            .values()
204            .filter_map(|e| e.probe.as_ref().filter(|p| p.in_flight.is_none()).map(|p| p.due_ms))
205            .min()
206    }
207
208    /// A probe's result. Ignored unless it is the probe still expected: the
209    /// service may have come back, or gone down again, while it ran.
210    pub(super) fn probe_finished(&mut self, service: &Service, ticket: u64, outcome: Outcome, now_ms: i64) -> Option<ConnectivityStatus> {
211        let entry = self.services.get_mut(service)?;
212        if entry.probe.as_ref().and_then(|p| p.in_flight) != Some(ticket) {
213            return None;
214        }
215        // A probe of a service believed down confirms what it finds; one of an online service, sent
216        // because the network changed, counts like any other request until it is repeated.
217        let probed = entry.state != Reachability::Online;
218        // The network changed again while this probe ran: its answer is about the old one.
219        let repeat = entry.probe.as_ref().is_some_and(|p| p.in_flight == Some(ticket) && p.again);
220        let next = entry.apply(outcome, probed, now_ms);
221        let changed = entry.enter(next, now_ms);
222        if repeat {
223            // Whatever the answer did to the schedule (an answer drops it, leaving `Online` makes a
224            // fresh one), the next probe is due at once, with the backoff started over.
225            entry.probe = Some(ProbeSchedule { due_ms: now_ms, interval_ms: PROBE_FIRST_MS, in_flight: None, again: false });
226        } else if entry.state == Reachability::Online {
227            entry.probe = None;
228        } else if let Some(probe) = entry.probe.as_mut().filter(|p| p.in_flight == Some(ticket)) {
229            // Leaving `Online` has scheduled a fresh first probe; otherwise this one backs off.
230            probe.in_flight = None;
231            probe.interval_ms = (probe.interval_ms * 2).min(PROBE_MAX_MS);
232            probe.due_ms = now_ms + probe.interval_ms;
233        }
234        self.changed(changed, now_ms)
235    }
236
237    /// The OS says the network changed (a link, an address, a VPN): what was learned about every
238    /// service may no longer hold. A service believed down is probed at once, with its backoff
239    /// started over; one believed up is checked once; a probe already running is repeated when it
240    /// ends. Returns whether anything is waiting for the probe driver.
241    pub(super) fn network_changed(&mut self, now_ms: i64) -> bool {
242        for entry in self.services.values_mut() {
243            match entry.probe.as_mut() {
244                Some(probe) if probe.in_flight.is_some() => probe.again = true,
245                Some(probe) => {
246                    probe.due_ms = now_ms;
247                    probe.interval_ms = PROBE_FIRST_MS;
248                }
249                None => {
250                    entry.probe = Some(ProbeSchedule { due_ms: now_ms, interval_ms: PROBE_FIRST_MS, in_flight: None, again: false });
251                }
252            }
253        }
254        !self.services.is_empty()
255    }
256
257    /// The internet is `Offline` when two or more services are and none
258    /// answers: one unreachable host is that host's problem (a block, a
259    /// captive portal), not the connection's. One not checked yet says
260    /// nothing either way.
261    fn derive_internet(&self) -> Reachability {
262        let offline = self.services.values().filter(|e| e.state == Reachability::Offline).count();
263        let reachable = self.services.values().any(|e| matches!(e.state, Reachability::Online | Reachability::Degraded));
264        if offline >= 2 && !reachable {
265            Reachability::Offline
266        } else {
267            Reachability::Online
268        }
269    }
270
271    fn changed(&mut self, service_changed: bool, now_ms: i64) -> Option<ConnectivityStatus> {
272        let internet = self.derive_internet();
273        let internet_changed = internet != self.internet.0;
274        if internet_changed {
275            self.internet = (internet, now_ms);
276        }
277        if !service_changed && !internet_changed {
278            return None;
279        }
280        self.revision += 1;
281        Some(self.status())
282    }
283
284    pub(super) fn status(&self) -> ConnectivityStatus {
285        let mut services = vec![ServiceStatus {
286            service: Service::INTERNET_ID.to_string(),
287            label: Service::INTERNET_LABEL.to_string(),
288            state: self.internet.0,
289            since_ms: self.internet.1,
290            last_error: None,
291        }];
292        services.extend(self.services.iter().map(|(service, e)| ServiceStatus {
293            service: service.id(),
294            label: service.label(),
295            state: e.state,
296            since_ms: e.since_ms,
297            last_error: e.last_error.clone(),
298        }));
299        ConnectivityStatus { revision: self.revision, services }
300    }
301}
302
303#[cfg(test)]
304#[path = "tracker_tests.rs"]
305mod tests;