proxy-pilot 0.6.2

Core-agnostic proxy health monitor, automatic failover daemon, and multi-channel alerting tool for Linux servers.
Documentation
mod profiles;

use std::path::{Path, PathBuf};
use std::time::Duration;

use clap::{Parser, Subcommand};

use crate::config::AppConfig;
use crate::core::ProxyCore;
use crate::core::xray::XrayCore;
use crate::engine::Watchdog;
use crate::error::{PilotError, Result};
use crate::notify::Notifier;
use crate::notify::bale::BaleNotifier;
use crate::probe::HealthProbe;
use crate::probe::http::HttpHealthProbe;

#[derive(Debug, Parser)]
#[command(
    name = "proxy-pilot",
    version,
    about = "Proxy health monitor and automatic failover daemon"
)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Debug, Subcommand)]
pub enum Commands {
    /// Interactive setup wizard
    Setup,
    /// Run the monitoring and failover daemon
    Run {
        #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
        config: PathBuf,
    },
    /// Show current proxy core and profile status
    Status {
        #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
        config: PathBuf,
    },
    /// Add a new proxy profile to config.yaml (appends without removing existing profiles)
    Add {
        #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
        config: PathBuf,
        #[arg(long)]
        name: String,
        #[arg(long)]
        tag: String,
        #[arg(long)]
        priority: Option<u32>,
    },
    /// Import profiles from a file, inline arguments, or interactive paste (`vless://...` or `name,tag`)
    Import {
        #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
        config: PathBuf,
        #[arg(short, long)]
        file: Option<PathBuf>,
        /// Skip running automatic parallel benchmark after importing
        #[arg(long)]
        no_benchmark: bool,
        /// Optional inline `vless://...` links or `name,tag` entries
        links: Vec<String>,
    },
    /// Remove a proxy profile by name, or remove all profiles with --all
    Remove {
        #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
        config: PathBuf,
        #[arg(long, required_unless_present = "all", conflicts_with = "all")]
        name: Option<String>,
        /// Remove all saved proxy profiles from config.yaml
        #[arg(long, conflicts_with = "name")]
        all: bool,
    },
    /// List all saved proxy profiles
    List {
        #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
        config: PathBuf,
    },
    /// Test all profiles, rank healthy ones by lowest ping, and activate the fastest
    Benchmark {
        #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
        config: PathBuf,
    },
    /// Test all profiles and remove dead/unhealthy ones from config.yaml
    Prune {
        #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
        config: PathBuf,
    },
}

pub async fn dispatch(cli: Cli) -> Result<()> {
    match cli.command {
        Commands::Setup => {
            println!("Interactive setup wizard is planned for the next milestone.");
            println!("For now, copy config.example.yaml to /etc/proxy-pilot/config.yaml.");
            Ok(())
        }
        Commands::Run { config } => run_daemon(&config).await,
        Commands::Status { config } => show_status(&config).await,
        Commands::Add {
            config,
            name,
            tag,
            priority,
        } => profiles::add_profile(&config, name, tag, priority).await,
        Commands::Import {
            config,
            file,
            no_benchmark,
            links,
        } => profiles::import_profiles(&config, file.as_deref(), &links, !no_benchmark).await,
        Commands::Remove { config, name, all } => {
            if all {
                profiles::remove_all_profiles(&config).await
            } else if let Some(name) = name {
                profiles::remove_profile(&config, &name).await
            } else {
                Err(PilotError::Config(
                    "either --name <NAME> or --all must be provided".into(),
                ))
            }
        }
        Commands::List { config } => profiles::list_profiles(&config).await,
        Commands::Benchmark { config } => profiles::run_benchmark(&config, false).await,
        Commands::Prune { config } => profiles::run_benchmark(&config, true).await,
    }
}

pub(super) fn build_core(cfg: &AppConfig) -> Result<Box<dyn ProxyCore>> {
    match cfg.core.kind.as_str() {
        "xray" => Ok(Box::new(XrayCore::new(
            &cfg.core.binary_path,
            &cfg.core.config_path,
            cfg.core.service_name.clone(),
        ))),
        other => Err(PilotError::Config(format!(
            "unsupported core kind: {other}"
        ))),
    }
}

fn build_notifiers(cfg: &AppConfig) -> Result<Vec<Box<dyn Notifier>>> {
    let mut list: Vec<Box<dyn Notifier>> = Vec::new();
    if let Some(bale) = &cfg.notify.bale
        && bale.enabled
    {
        list.push(Box::new(BaleNotifier::new(
            bale.resolved_token(),
            bale.chat_id.clone(),
        )?));
    }
    Ok(list)
}

async fn run_daemon(config_path: &Path) -> Result<()> {
    let cfg = AppConfig::load(config_path).await?;
    let timeout = Duration::from_secs(cfg.probe.timeout_secs);
    let core = build_core(&cfg)?;
    let probe: Box<dyn HealthProbe> =
        Box::new(HttpHealthProbe::new(&cfg.core.local_proxy, timeout)?);
    let notifiers = build_notifiers(&cfg)?;

    let mut watchdog = Watchdog::new(cfg, core, probe, notifiers)
        .with_direct_probe(Box::new(HttpHealthProbe::direct(timeout)?))
        .with_periodic_benchmark(
            Some(config_path.to_path_buf()),
            Box::new(move |endpoint| Ok(Box::new(HttpHealthProbe::new(endpoint, timeout)?))),
        );
    watchdog.run_forever().await
}

async fn show_status(config_path: &Path) -> Result<()> {
    let cfg = AppConfig::load_raw(config_path).await?;
    let core = build_core(&cfg)?;
    let installed = core.is_installed().await;
    let active = core.active_profile().await.unwrap_or(None);

    println!("Core:      {} (installed: {installed})", core.name());
    println!("Active:    {}", active.as_deref().unwrap_or("unknown"));
    println!("Profiles:  {}", cfg.profiles.len());
    println!("Targets:   {}", cfg.probe.targets.len());
    Ok(())
}