Skip to main content

proxy_pilot/probe/
http.rs

1use std::time::{Duration, Instant};
2
3use async_trait::async_trait;
4use reqwest::{Client, Proxy};
5
6use crate::config::ProbeTarget;
7use crate::error::{PilotError, Result};
8use crate::probe::{HealthProbe, ProbeOutcome};
9
10/// HTTP/HTTPS health probe routed through a fixed local proxy (SOCKS5 or HTTP).
11pub struct HttpHealthProbe {
12    client: Client,
13}
14
15impl HttpHealthProbe {
16    pub fn new(proxy_url: &str, timeout: Duration) -> Result<Self> {
17        let proxy = Proxy::all(proxy_url)
18            .map_err(|err| PilotError::Probe(format!("invalid proxy url {proxy_url}: {err}")))?;
19        let client = Client::builder()
20            .proxy(proxy)
21            .connect_timeout(timeout)
22            .timeout(timeout)
23            .redirect(reqwest::redirect::Policy::none())
24            .build()
25            .map_err(|err| PilotError::Probe(format!("failed to build probe client: {err}")))?;
26        Ok(Self { client })
27    }
28
29    /// Build a direct (non-proxied) HTTP probe to verify the host server's own connectivity.
30    pub fn direct(timeout: Duration) -> Result<Self> {
31        let client = Client::builder()
32            .no_proxy()
33            .connect_timeout(timeout)
34            .timeout(timeout)
35            .redirect(reqwest::redirect::Policy::none())
36            .build()
37            .map_err(|err| {
38                PilotError::Probe(format!("failed to build direct probe client: {err}"))
39            })?;
40        Ok(Self { client })
41    }
42}
43
44pub fn classify_status(status: u16, target: &ProbeTarget, latency: Duration) -> ProbeOutcome {
45    if target.blocked_status.contains(&status) {
46        return ProbeOutcome::GeoBlocked { status };
47    }
48    if target.expected_status.contains(&status) || (200..400).contains(&status) {
49        return ProbeOutcome::Healthy { status, latency };
50    }
51    ProbeOutcome::Unreachable {
52        reason: format!("unexpected HTTP status {status}"),
53    }
54}
55
56#[async_trait]
57impl HealthProbe for HttpHealthProbe {
58    async fn check(&self, target: &ProbeTarget) -> Result<ProbeOutcome> {
59        let started = Instant::now();
60        match self.client.get(&target.url).send().await {
61            Ok(resp) => {
62                let status = resp.status().as_u16();
63                Ok(classify_status(status, target, started.elapsed()))
64            }
65            Err(err) => Ok(ProbeOutcome::Unreachable {
66                reason: err.to_string(),
67            }),
68        }
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75
76    fn sample_target() -> ProbeTarget {
77        ProbeTarget {
78            name: "gemini".into(),
79            url: "https://generativelanguage.googleapis.com/".into(),
80            expected_status: vec![200, 404],
81            blocked_status: vec![403, 429],
82        }
83    }
84
85    #[test]
86    fn classifies_expected_blocked_and_unexpected_statuses() {
87        let target = sample_target();
88        let latency = Duration::from_millis(120);
89
90        assert_eq!(
91            classify_status(404, &target, latency),
92            ProbeOutcome::Healthy {
93                status: 404,
94                latency
95            }
96        );
97        assert_eq!(
98            classify_status(403, &target, latency),
99            ProbeOutcome::GeoBlocked { status: 403 }
100        );
101        assert_eq!(
102            classify_status(429, &target, latency),
103            ProbeOutcome::GeoBlocked { status: 429 }
104        );
105        assert!(matches!(
106            classify_status(502, &target, latency),
107            ProbeOutcome::Unreachable { .. }
108        ));
109    }
110}