proxy-pilot 0.7.1

Core-agnostic proxy health monitor, automatic failover daemon, and multi-channel alerting tool for Linux servers.
Documentation
use std::fmt;
use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::error::{PilotError, Result};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppConfig {
    pub core: CoreConfig,
    #[serde(default)]
    pub routing: RoutingConfig,
    pub profiles: Vec<ProfileConfig>,
    pub probe: ProbeConfig,
    pub notify: NotifyConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoutingConfig {
    /// "whitelist" (recommended: only listed domains use proxy, everything else goes direct)
    /// or "bypass_ir" (everything uses proxy except geosite:ir / geoip:ir).
    #[serde(default = "default_routing_mode")]
    pub mode: String,
    #[serde(default)]
    pub whitelist_domains: Vec<String>,
}

fn default_routing_mode() -> String {
    "whitelist".to_string()
}

impl Default for RoutingConfig {
    fn default() -> Self {
        Self {
            mode: default_routing_mode(),
            whitelist_domains: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoreConfig {
    pub kind: String,
    pub binary_path: String,
    pub config_path: String,
    pub service_name: String,
    pub local_proxy: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProfileConfig {
    pub name: String,
    pub outbound_tag: String,
    pub priority: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProbeConfig {
    pub interval_secs: u64,
    pub timeout_secs: u64,
    pub failure_threshold: u32,
    pub recovery_threshold: u32,
    /// Optional latency ceiling in milliseconds; slower responses trigger failover.
    #[serde(default)]
    pub max_latency_ms: Option<u64>,
    /// Periodic background re-benchmark interval in seconds (0 disables it).
    #[serde(default = "default_benchmark_interval_secs")]
    pub benchmark_interval_secs: u64,
    /// Remove profiles that stay continuously unhealthy for this many hours (0 disables it).
    #[serde(default = "default_auto_prune_after_hours")]
    pub auto_prune_after_hours: u64,
    /// Optional direct (non-proxied) URL used to verify the host server's own internet
    /// connectivity before auto-pruning dead profiles (e.g., a local/domestic site).
    #[serde(default)]
    pub direct_check_url: Option<String>,
    pub targets: Vec<ProbeTarget>,
}

fn default_benchmark_interval_secs() -> u64 {
    900
}

fn default_auto_prune_after_hours() -> u64 {
    24
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProbeTarget {
    pub name: String,
    pub url: String,
    pub expected_status: Vec<u16>,
    pub blocked_status: Vec<u16>,
}

fn default_empty_profiles_reminder_secs() -> u64 {
    300
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotifyConfig {
    pub cooldown_secs: u64,
    #[serde(default = "default_empty_profiles_reminder_secs")]
    pub empty_profiles_reminder_secs: u64,
    pub bale: Option<BaleConfig>,
}

#[derive(Clone, Serialize, Deserialize)]
pub struct BaleConfig {
    pub enabled: bool,
    pub bot_token: String,
    pub chat_id: String,
}

impl fmt::Debug for BaleConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BaleConfig")
            .field("enabled", &self.enabled)
            .field("bot_token", &"[REDACTED]")
            .field("chat_id", &self.chat_id)
            .finish()
    }
}

impl BaleConfig {
    /// Resolve bot token from `BALE_BOT_TOKEN` env var if set, falling back to config.yaml.
    pub fn resolved_token(&self) -> String {
        if let Ok(token) = std::env::var("BALE_BOT_TOKEN")
            && !token.trim().is_empty()
        {
            return token;
        }
        self.bot_token.clone()
    }
}

impl AppConfig {
    /// Load and parse configuration from a YAML file without requiring non-empty profiles.
    pub async fn load_raw(path: &Path) -> Result<Self> {
        let raw = tokio::fs::read_to_string(path).await.map_err(|err| {
            PilotError::Config(format!("failed to read {}: {err}", path.display()))
        })?;
        Self::parse_yaml(&raw)
    }

    /// Load and validate configuration from a YAML file.
    pub async fn load(path: &Path) -> Result<Self> {
        let cfg = Self::load_raw(path).await?;
        cfg.validate()?;
        Ok(cfg)
    }

    pub fn parse_yaml(raw: &str) -> Result<Self> {
        serde_yaml::from_str(raw).map_err(|err| PilotError::Config(format!("invalid yaml: {err}")))
    }

    pub fn validate(&self) -> Result<()> {
        if self.profiles.is_empty() {
            return Err(PilotError::Config(
                "at least one profile is required".into(),
            ));
        }
        if self.probe.targets.is_empty() {
            return Err(PilotError::Config(
                "at least one probe target is required".into(),
            ));
        }
        if self.probe.failure_threshold == 0 || self.probe.recovery_threshold == 0 {
            return Err(PilotError::Config(
                "failure_threshold and recovery_threshold must be >= 1".into(),
            ));
        }
        if self.probe.interval_secs == 0 || self.probe.timeout_secs == 0 {
            return Err(PilotError::Config(
                "interval_secs and timeout_secs must be >= 1".into(),
            ));
        }
        if matches!(self.probe.max_latency_ms, Some(0)) {
            return Err(PilotError::Config("max_latency_ms must be >= 1".into()));
        }
        Ok(())
    }

    /// Atomically write configuration back to disk.
    pub async fn save_atomic(&self, path: &Path) -> Result<()> {
        let parent = path.parent().ok_or_else(|| {
            PilotError::Config(format!("config path has no parent: {}", path.display()))
        })?;
        let tmp_path = parent.join(format!(".config.{}.tmp", std::process::id()));
        let yaml = serde_yaml::to_string(self)
            .map_err(|err| PilotError::Config(format!("failed to serialize yaml: {err}")))?;
        tokio::fs::write(&tmp_path, yaml).await?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            tokio::fs::set_permissions(&tmp_path, std::fs::Permissions::from_mode(0o600)).await?;
        }
        tokio::fs::rename(&tmp_path, path).await?;
        Ok(())
    }

    pub fn add_profile(&mut self, profile: ProfileConfig) -> Result<()> {
        if self.profiles.iter().any(|p| p.name == profile.name) {
            return Err(PilotError::Config(format!(
                "profile '{}' already exists",
                profile.name
            )));
        }
        self.profiles.push(profile);
        Ok(())
    }

    pub fn remove_profile(&mut self, name: &str) -> Result<()> {
        let before = self.profiles.len();
        self.profiles.retain(|p| p.name != name);
        if self.profiles.len() == before {
            return Err(PilotError::Config(format!("profile '{name}' not found")));
        }
        Ok(())
    }
}

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

    #[test]
    fn parses_example_config() {
        let raw = include_str!("../../config.example.yaml");
        let cfg = AppConfig::parse_yaml(raw).unwrap();
        cfg.validate().unwrap();
        assert_eq!(cfg.core.kind, "xray");
        assert_eq!(cfg.profiles.len(), 2);
        assert_eq!(cfg.probe.targets.len(), 3);
    }

    #[test]
    fn rejects_empty_profiles() {
        let raw = include_str!("../../config.example.yaml");
        let mut cfg = AppConfig::parse_yaml(raw).unwrap();
        cfg.profiles.clear();
        assert!(cfg.validate().is_err());
    }

    #[tokio::test]
    async fn load_raw_allows_empty_profiles_and_supports_adding_first_profile() {
        let dir = tempfile::TempDir::new().unwrap();
        let cfg_path = dir.path().join("config.yaml");
        let raw = include_str!("../../config.example.yaml");
        let mut cfg = AppConfig::parse_yaml(raw).unwrap();
        cfg.profiles.clear();
        cfg.save_atomic(&cfg_path).await.unwrap();

        assert!(AppConfig::load(&cfg_path).await.is_err());

        let mut loaded = AppConfig::load_raw(&cfg_path).await.unwrap();
        assert!(loaded.profiles.is_empty());
        loaded
            .add_profile(ProfileConfig {
                name: "first-node".into(),
                outbound_tag: "vless-first-node".into(),
                priority: 1,
            })
            .unwrap();
        loaded.save_atomic(&cfg_path).await.unwrap();

        let validated = AppConfig::load(&cfg_path).await.unwrap();
        assert_eq!(validated.profiles.len(), 1);
        assert_eq!(validated.profiles[0].name, "first-node");
    }

    #[test]
    fn add_and_remove_profile_handles_duplicates_and_missing() {
        let raw = include_str!("../../config.example.yaml");
        let mut cfg = AppConfig::parse_yaml(raw).unwrap();
        let dup = cfg.profiles[0].clone();
        assert!(cfg.add_profile(dup).is_err());
        assert!(cfg.remove_profile("non-existent").is_err());

        let name = cfg.profiles[0].name.clone();
        cfg.remove_profile(&name).unwrap();
        assert!(!cfg.profiles.iter().any(|p| p.name == name));
    }

    #[test]
    fn bale_config_debug_redacts_bot_token() {
        let bale = BaleConfig {
            enabled: true,
            bot_token: "123456:SECRET_TOKEN".into(),
            chat_id: "99999".into(),
        };
        let debug_str = format!("{bale:?}");
        assert!(!debug_str.contains("SECRET_TOKEN"));
        assert!(debug_str.contains("[REDACTED]"));
    }
}