Skip to main content

agentmux_srv_core/connectivity/
probe.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The active probe: while a service is believed down, check it on a capped
5//! backoff (`tracker::PROBE_FIRST_MS` doubling to `tracker::PROBE_MAX_MS`),
6//! so its recovery shows even when nothing else is calling. An online
7//! service is never probed on a timer, only once when the OS reports a
8//! network change (`netchange`).
9
10use std::future::Future;
11use std::pin::Pin;
12use std::sync::Arc;
13use std::time::Duration;
14
15use super::{Outcome, Service, Shared};
16
17/// Milliseconds since the epoch; injected so tests run on tokio's paused clock.
18pub type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;
19
20/// Checks one service; resolves to what it found.
21pub trait Prober: Send + Sync + 'static {
22    fn probe(&self, service: Service) -> Pin<Box<dyn Future<Output = Outcome> + Send>>;
23}
24
25/// The longest one probe may take, whatever the prober does: a DNS lookup
26/// that hangs mustn't leave the service unprobed.
27const PROBE_TIMEOUT: Duration = Duration::from_secs(15);
28const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
29const HEAD_TIMEOUT: Duration = Duration::from_secs(10);
30
31/// Runs the probes as they fall due, one at a time per service, until srv
32/// exits. Holds no lock across an await; a probe's result carries the ticket
33/// it was started with, so one that outlives its schedule changes nothing.
34pub(super) async fn drive(shared: Arc<Shared>, prober: Arc<dyn Prober>, clock: Clock) {
35    loop {
36        let due = shared.tracker().take_due_probes(clock());
37        for (service, ticket) in due {
38            let (shared, prober, clock) = (shared.clone(), prober.clone(), clock.clone());
39            tokio::spawn(async move {
40                let outcome = tokio::time::timeout(PROBE_TIMEOUT, prober.probe(service.clone()))
41                    .await
42                    .unwrap_or_else(|_| Outcome::Unreachable("probe timed out".to_string()));
43                tracing::debug!(service = %service.id(), ?outcome, "connectivity: probed");
44                let changed = shared.tracker().probe_finished(&service, ticket, outcome, clock());
45                shared.publish(changed);
46                // The next probe is scheduled now.
47                shared.wake.notify_one();
48            });
49        }
50        let next = shared.tracker().next_probe_due();
51        match next {
52            Some(due_ms) => {
53                let wait = Duration::from_millis(u64::try_from(due_ms - clock()).unwrap_or(0));
54                tokio::select! {
55                    _ = tokio::time::sleep(wait) => {}
56                    _ = shared.wake.notified() => {}
57                }
58            }
59            None => shared.wake.notified().await,
60        }
61    }
62}
63
64/// Whether srv's requests go through a proxy: reqwest, as srv builds it,
65/// reads these variables. A direct TCP connect would then test a path srv
66/// doesn't use, so the probe sends only the HEAD, through reqwest.
67fn proxy_configured() -> bool {
68    ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"]
69        .iter()
70        .any(|var| std::env::var(var).is_ok_and(|v| !v.trim().is_empty()))
71}
72
73/// The real probe: a TCP connect to the service's host, then a HEAD to its
74/// base URL; any HTTP response is an answer.
75pub(super) struct NetProber {
76    http: reqwest::Client,
77}
78
79impl NetProber {
80    pub(super) fn new() -> Self {
81        let http = crate::http_client::builder()
82            .user_agent(crate::muxbus::relay::USER_AGENT)
83            .connect_timeout(CONNECT_TIMEOUT)
84            .timeout(HEAD_TIMEOUT)
85            .build()
86            .unwrap_or_else(|_| crate::http_client::client());
87        Self { http }
88    }
89}
90
91async fn probe_url(http: reqwest::Client, url: String) -> Outcome {
92    let parsed = match reqwest::Url::parse(&url) {
93        Ok(u) => u,
94        Err(e) => return Outcome::Unreachable(format!("bad address {url}: {e}")),
95    };
96    if !proxy_configured() {
97        let (Some(host), Some(port)) = (parsed.host_str(), parsed.port_or_known_default()) else {
98            return Outcome::Unreachable(format!("bad address {url}"));
99        };
100        match tokio::time::timeout(CONNECT_TIMEOUT, tokio::net::TcpStream::connect((host, port))).await {
101            Ok(Ok(_)) => {}
102            Ok(Err(e)) => return Outcome::Unreachable(e.to_string()),
103            Err(_) => return Outcome::Unreachable("connect timed out".to_string()),
104        }
105    }
106    super::http_outcome(&http.head(parsed).send().await)
107        .unwrap_or_else(|| Outcome::Unreachable("the probe request couldn't be built".to_string()))
108}
109
110impl Prober for NetProber {
111    fn probe(&self, service: Service) -> Pin<Box<dyn Future<Output = Outcome> + Send>> {
112        Box::pin(probe_url(self.http.clone(), service.probe_url()))
113    }
114}
115
116#[cfg(test)]
117#[path = "probe_tests.rs"]
118mod tests;