proxy-pilot 0.6.1

Core-agnostic proxy health monitor, automatic failover daemon, and multi-channel alerting tool for Linux servers.
Documentation
use std::time::{Duration, Instant};

use async_trait::async_trait;
use reqwest::{Client, Proxy};

use crate::config::ProbeTarget;
use crate::error::{PilotError, Result};
use crate::probe::{HealthProbe, ProbeOutcome};

/// HTTP/HTTPS health probe routed through a fixed local proxy (SOCKS5 or HTTP).
pub struct HttpHealthProbe {
    client: Client,
}

impl HttpHealthProbe {
    pub fn new(proxy_url: &str, timeout: Duration) -> Result<Self> {
        let proxy = Proxy::all(proxy_url)
            .map_err(|err| PilotError::Probe(format!("invalid proxy url {proxy_url}: {err}")))?;
        let client = Client::builder()
            .proxy(proxy)
            .connect_timeout(timeout)
            .timeout(timeout)
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .map_err(|err| PilotError::Probe(format!("failed to build probe client: {err}")))?;
        Ok(Self { client })
    }

    /// Build a direct (non-proxied) HTTP probe to verify the host server's own connectivity.
    pub fn direct(timeout: Duration) -> Result<Self> {
        let client = Client::builder()
            .no_proxy()
            .connect_timeout(timeout)
            .timeout(timeout)
            .redirect(reqwest::redirect::Policy::none())
            .build()
            .map_err(|err| {
                PilotError::Probe(format!("failed to build direct probe client: {err}"))
            })?;
        Ok(Self { client })
    }
}

pub fn classify_status(status: u16, target: &ProbeTarget, latency: Duration) -> ProbeOutcome {
    if target.blocked_status.contains(&status) {
        return ProbeOutcome::GeoBlocked { status };
    }
    if target.expected_status.contains(&status) || (200..400).contains(&status) {
        return ProbeOutcome::Healthy { status, latency };
    }
    ProbeOutcome::Unreachable {
        reason: format!("unexpected HTTP status {status}"),
    }
}

#[async_trait]
impl HealthProbe for HttpHealthProbe {
    async fn check(&self, target: &ProbeTarget) -> Result<ProbeOutcome> {
        let started = Instant::now();
        match self.client.get(&target.url).send().await {
            Ok(resp) => {
                let status = resp.status().as_u16();
                Ok(classify_status(status, target, started.elapsed()))
            }
            Err(err) => Ok(ProbeOutcome::Unreachable {
                reason: err.to_string(),
            }),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_target() -> ProbeTarget {
        ProbeTarget {
            name: "gemini".into(),
            url: "https://generativelanguage.googleapis.com/".into(),
            expected_status: vec![200, 404],
            blocked_status: vec![403, 429],
        }
    }

    #[test]
    fn classifies_expected_blocked_and_unexpected_statuses() {
        let target = sample_target();
        let latency = Duration::from_millis(120);

        assert_eq!(
            classify_status(404, &target, latency),
            ProbeOutcome::Healthy {
                status: 404,
                latency
            }
        );
        assert_eq!(
            classify_status(403, &target, latency),
            ProbeOutcome::GeoBlocked { status: 403 }
        );
        assert_eq!(
            classify_status(429, &target, latency),
            ProbeOutcome::GeoBlocked { status: 429 }
        );
        assert!(matches!(
            classify_status(502, &target, latency),
            ProbeOutcome::Unreachable { .. }
        ));
    }
}