use std::path::Path;
use std::time::Duration;
use crate::cli::{build_core, build_notifiers, notify_all};
use crate::config::{AppConfig, ProfileConfig};
use crate::core::xray::XrayCore;
use crate::engine::benchmark::benchmark_profiles;
use crate::error::{PilotError, Result};
use crate::notify::{AlertEvent, AlertSeverity, Notifier};
use crate::probe::http::HttpHealthProbe;
pub async fn add_profile(
config_path: &Path,
name: String,
outbound_tag: String,
priority: Option<u32>,
) -> Result<()> {
let mut cfg = AppConfig::load_raw(config_path).await?;
let next_priority =
priority.unwrap_or_else(|| cfg.profiles.iter().map(|p| p.priority).max().unwrap_or(0) + 1);
cfg.add_profile(ProfileConfig {
name: name.clone(),
outbound_tag,
priority: next_priority,
})?;
cfg.save_atomic(config_path).await?;
println!("Added profile '{name}' with priority {next_priority}.");
Ok(())
}
pub async fn import_profiles(
config_path: &Path,
file_path: Option<&Path>,
inline_links: &[String],
auto_benchmark: bool,
) -> Result<()> {
let mut cfg = AppConfig::load_raw(config_path).await?;
let lines = read_import_lines(file_path, inline_links).await?;
let xray = XrayCore::new(
&cfg.core.binary_path,
&cfg.core.config_path,
cfg.core.service_name.clone(),
);
let mut next_priority = cfg.profiles.iter().map(|p| p.priority).max().unwrap_or(0) + 1;
let mut added = 0u32;
for line in lines {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
let (name, tag) = if trimmed.starts_with("vless://") {
let parsed = crate::core::xray::vless::parse_vless_uri(trimmed)?;
xray.upsert_outbound(&parsed.outbound_tag, parsed.outbound_json)
.await?;
(parsed.name, parsed.outbound_tag)
} else {
match trimmed.split_once(',') {
Some((n, t)) => (n.trim().to_string(), t.trim().to_string()),
None => (trimmed.to_string(), trimmed.to_string()),
}
};
if cfg
.add_profile(ProfileConfig {
name,
outbound_tag: tag,
priority: next_priority,
})
.is_ok()
{
next_priority += 1;
added += 1;
}
}
cfg.save_atomic(config_path).await?;
println!("Imported {added} new profile(s).");
if auto_benchmark && !cfg.profiles.is_empty() {
println!("Running parallel benchmark to rank profiles and activate the fastest...");
run_benchmark(config_path, false).await?;
}
Ok(())
}
async fn read_import_lines(
file_path: Option<&Path>,
inline_links: &[String],
) -> Result<Vec<String>> {
if let Some(path) = file_path {
let raw = tokio::fs::read_to_string(path).await.map_err(|err| {
PilotError::Config(format!("failed to read {}: {err}", path.display()))
})?;
return Ok(raw.lines().map(ToString::to_string).collect());
}
if !inline_links.is_empty() {
return Ok(inline_links.to_vec());
}
println!("Paste your vless:// links (one per line), then press Enter on an empty line:");
let mut collected = Vec::new();
let stdin = std::io::stdin();
let mut buf = String::new();
while stdin.read_line(&mut buf).is_ok() {
let line = buf.trim().to_string();
buf.clear();
if line.is_empty() {
break;
}
collected.push(line);
}
Ok(collected)
}
pub async fn remove_profile(config_path: &Path, name: &str) -> Result<()> {
let mut cfg = AppConfig::load_raw(config_path).await?;
cfg.remove_profile(name)?;
cfg.save_atomic(config_path).await?;
println!("Removed profile '{name}'.");
Ok(())
}
pub async fn remove_all_profiles(config_path: &Path) -> Result<()> {
let cfg = AppConfig::load_raw(config_path).await?;
let notifiers = build_notifiers(&cfg).unwrap_or_default();
remove_all_profiles_with_notifiers(config_path, ¬ifiers).await
}
async fn remove_all_profiles_with_notifiers(
config_path: &Path,
notifiers: &[Box<dyn Notifier>],
) -> Result<()> {
let mut cfg = AppConfig::load_raw(config_path).await?;
let count = cfg.profiles.len();
if count == 0 {
println!("No profiles to remove.");
notify_all(
notifiers,
&AlertEvent {
severity: AlertSeverity::Warning,
title: "No proxy profiles configured".into(),
message: "0 proxy profiles found in config.yaml. Please import new profiles (`proxy-pilot import`).".into(),
},
)
.await;
return Ok(());
}
cfg.profiles.clear();
cfg.save_atomic(config_path).await?;
println!("Removed all {count} profile(s).");
notify_all(
notifiers,
&AlertEvent {
severity: AlertSeverity::Warning,
title: "All proxy profiles removed".into(),
message: format!(
"All {count} proxy profile(s) were removed from config.yaml. Please import new profiles (`proxy-pilot import`)."
),
},
)
.await;
Ok(())
}
pub async fn list_profiles(config_path: &Path) -> Result<()> {
let mut cfg = AppConfig::load_raw(config_path).await?;
cfg.profiles.sort_by_key(|p| p.priority);
for p in &cfg.profiles {
println!("[{}] {} (tag: {})", p.priority, p.name, p.outbound_tag);
}
Ok(())
}
pub async fn run_benchmark(config_path: &Path, prune_dead: bool) -> Result<()> {
let mut cfg = AppConfig::load(config_path).await?;
let core = build_core(&cfg)?;
let timeout = Duration::from_secs(cfg.probe.timeout_secs);
let probe = HttpHealthProbe::new(&cfg.core.local_proxy, timeout)?;
let results = benchmark_profiles(
core.as_ref(),
&probe,
|endpoint| Ok(Box::new(HttpHealthProbe::new(endpoint, timeout)?)),
&cfg.profiles,
&cfg.probe.targets,
)
.await?;
for res in &results {
match res.latency {
Some(lat) => println!("OK {:15} {:>4} ms", res.profile.name, lat.as_millis()),
None => println!(
"FAIL {:15} {}",
res.profile.name,
res.error.as_deref().unwrap_or("unknown error")
),
}
}
if prune_dead {
let healthy: Vec<ProfileConfig> = results
.into_iter()
.filter(|r| r.is_healthy())
.enumerate()
.map(|(idx, mut r)| {
r.profile.priority = (idx + 1) as u32;
r.profile
})
.collect();
if healthy.is_empty() {
println!("No healthy profiles found; config.yaml left unchanged.");
} else {
let removed = cfg.profiles.len().saturating_sub(healthy.len());
cfg.profiles = healthy;
cfg.save_atomic(config_path).await?;
println!("Pruned {removed} dead profile(s) and saved sorted healthy list.");
}
} else {
cfg.profiles = results
.into_iter()
.enumerate()
.map(|(idx, mut r)| {
r.profile.priority = (idx + 1) as u32;
r.profile
})
.collect();
cfg.save_atomic(config_path).await?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use clap::Parser;
use tempfile::NamedTempFile;
use super::*;
use crate::cli::{Cli, Commands};
const SAMPLE_YAML: &str = include_str!("../../config.example.yaml");
struct MockNotifier {
events: Arc<Mutex<Vec<AlertEvent>>>,
}
#[async_trait]
impl Notifier for MockNotifier {
fn channel_name(&self) -> &'static str {
"mock"
}
async fn send(&self, event: &AlertEvent) -> Result<()> {
self.events.lock().unwrap().push(event.clone());
Ok(())
}
}
#[tokio::test]
async fn remove_all_profiles_clears_config_and_notifies_both_cases() {
let tmp = NamedTempFile::new().unwrap();
tokio::fs::write(tmp.path(), SAMPLE_YAML).await.unwrap();
let events = Arc::new(Mutex::new(Vec::new()));
let notifiers: Vec<Box<dyn Notifier>> = vec![Box::new(MockNotifier {
events: Arc::clone(&events),
})];
remove_all_profiles_with_notifiers(tmp.path(), ¬ifiers)
.await
.unwrap();
let after = AppConfig::load_raw(tmp.path()).await.unwrap();
assert!(after.profiles.is_empty());
remove_all_profiles_with_notifiers(tmp.path(), ¬ifiers)
.await
.unwrap();
let sent = events.lock().unwrap();
assert_eq!(sent.len(), 2);
assert_eq!(sent[0].title, "All proxy profiles removed");
assert_eq!(sent[1].title, "No proxy profiles configured");
}
#[test]
fn cli_remove_accepts_all_or_name_and_rejects_both_or_neither() {
let parsed_all = Cli::try_parse_from(["proxy-pilot", "remove", "--all"]).unwrap();
assert!(matches!(
parsed_all.command,
Commands::Remove {
name: None,
all: true,
..
}
));
let parsed_name = Cli::try_parse_from(["proxy-pilot", "remove", "--name", "de-1"]).unwrap();
assert!(matches!(
parsed_name.command,
Commands::Remove {
name: Some(_),
all: false,
..
}
));
assert!(Cli::try_parse_from(["proxy-pilot", "remove"]).is_err());
assert!(Cli::try_parse_from(["proxy-pilot", "remove", "--all", "--name", "de-1"]).is_err());
}
}