pub mod benchmark;
pub mod state;
use std::collections::HashMap;
use std::path::PathBuf;
use std::time::{Duration, Instant};
use crate::config::{AppConfig, ProbeTarget, ProfileConfig};
use crate::core::ProxyCore;
use crate::engine::benchmark::benchmark_profiles_isolated;
use crate::engine::state::{FailoverAction, FailoverState};
use crate::error::Result;
use crate::notify::{AlertEvent, AlertSeverity, Notifier};
use crate::probe::{HealthProbe, ProbeOutcome};
pub type ProbeFactory = Box<dyn Fn(&str) -> Result<Box<dyn HealthProbe>> + Send + Sync>;
pub struct Watchdog {
config: AppConfig,
config_path: Option<PathBuf>,
core: Box<dyn ProxyCore>,
probe: Box<dyn HealthProbe>,
direct_probe: Option<Box<dyn HealthProbe>>,
probe_factory: Option<ProbeFactory>,
notifiers: Vec<Box<dyn Notifier>>,
state: FailoverState,
last_critical_alert: Option<Instant>,
unhealthy_since: HashMap<String, Instant>,
}
impl Watchdog {
pub fn new(
config: AppConfig,
core: Box<dyn ProxyCore>,
probe: Box<dyn HealthProbe>,
notifiers: Vec<Box<dyn Notifier>>,
) -> Self {
let state = FailoverState::new(config.profiles.clone(), config.probe.failure_threshold);
Self {
config,
config_path: None,
core,
probe,
direct_probe: None,
probe_factory: None,
notifiers,
state,
last_critical_alert: None,
unhealthy_since: HashMap::new(),
}
}
pub fn with_periodic_benchmark(
mut self,
config_path: Option<PathBuf>,
probe_factory: ProbeFactory,
) -> Self {
self.config_path = config_path;
self.probe_factory = Some(probe_factory);
self
}
pub fn with_direct_probe(mut self, direct_probe: Box<dyn HealthProbe>) -> Self {
self.direct_probe = Some(direct_probe);
self
}
pub async fn run_forever(&mut self) -> Result<()> {
let mut ticker =
tokio::time::interval(Duration::from_secs(self.config.probe.interval_secs));
let bench_secs = self.config.probe.benchmark_interval_secs;
let mut bench_ticker = if bench_secs > 0 && self.probe_factory.is_some() {
let mut interval = tokio::time::interval(Duration::from_secs(bench_secs));
interval.tick().await;
Some(interval)
} else {
None
};
tracing::info!(
core = self.core.name(),
benchmark_interval_secs = bench_secs,
"proxy-pilot watchdog started"
);
loop {
tokio::select! {
_ = ticker.tick() => {
if let Err(err) = self.run_once().await {
tracing::error!(error = %err, "watchdog cycle failed");
}
}
_ = async {
if let Some(interval) = bench_ticker.as_mut() {
interval.tick().await;
} else {
std::future::pending::<()>().await;
}
} => {
if let Err(err) = self.run_periodic_benchmark().await {
tracing::error!(error = %err, "periodic background benchmark failed");
}
}
_ = tokio::signal::ctrl_c() => {
tracing::info!("shutdown signal received, stopping watchdog");
break;
}
}
}
Ok(())
}
pub async fn run_periodic_benchmark(&mut self) -> Result<bool> {
let Some(factory) = self.probe_factory.as_ref() else {
return Ok(false);
};
let Some(results) = benchmark_profiles_isolated(
self.core.as_ref(),
|endpoint| factory(endpoint),
&self.config.profiles,
&self.config.probe.targets,
)
.await?
else {
tracing::debug!("skipping periodic benchmark: core has no isolated session support");
return Ok(false);
};
let mut reordered = Vec::with_capacity(results.len());
let mut ranked_state = Vec::with_capacity(results.len());
let now = Instant::now();
for res in &results {
if res.is_healthy() {
self.unhealthy_since.remove(&res.profile.outbound_tag);
} else {
self.unhealthy_since
.entry(res.profile.outbound_tag.clone())
.or_insert(now);
}
ranked_state.push((res.profile.clone(), res.is_healthy()));
reordered.push(res.profile.clone());
}
let healthy_count = results.iter().filter(|r| r.is_healthy()).count();
let pruned_names = self
.prune_stale_profiles(&mut reordered, &mut ranked_state, healthy_count, now)
.await;
for (idx, profile) in reordered.iter_mut().enumerate() {
profile.priority = (idx + 1) as u32;
ranked_state[idx].0.priority = profile.priority;
}
let top_name = reordered.first().map(|p| p.name.as_str()).unwrap_or("none");
tracing::info!(
healthy = healthy_count,
total = reordered.len(),
pruned = pruned_names.len(),
fastest = top_name,
"periodic background benchmark updated profile priorities"
);
let recovered = self.state.apply_benchmark_order(ranked_state);
self.config.profiles = reordered;
if let Some(path) = self.config_path.as_deref()
&& let Err(err) = self.config.save_atomic(path).await
{
tracing::warn!(error = %err, "failed to persist updated profile priorities");
}
if !pruned_names.is_empty() {
self.notify_all(&AlertEvent {
severity: AlertSeverity::Info,
title: "حذف خودکار کانفیگهای خراب".into(),
message: format!(
"کانفیگهای زیر پس از {} ساعت خرابی مداوم حذف شدند:\n- {}",
self.config.probe.auto_prune_after_hours,
pruned_names.join("\n- ")
),
})
.await;
}
if let Some(target) = recovered {
tracing::info!(
profile = %target.name,
"active profile was unhealthy; auto-recovering to fastest healthy profile"
);
self.core.switch_profile(&target.outbound_tag).await?;
self.core.reload().await?;
}
Ok(true)
}
async fn prune_stale_profiles(
&mut self,
reordered: &mut Vec<ProfileConfig>,
ranked_state: &mut Vec<(ProfileConfig, bool)>,
healthy_count: usize,
now: Instant,
) -> Vec<String> {
let hours = self.config.probe.auto_prune_after_hours;
if hours == 0 || healthy_count == 0 {
return Vec::new();
}
let max_age = Duration::from_secs(hours.saturating_mul(3600));
let has_stale = reordered.iter().any(|p| {
self.unhealthy_since
.get(&p.outbound_tag)
.is_some_and(|since| now.saturating_duration_since(*since) >= max_age)
});
if !has_stale || !self.is_host_internet_up().await {
return Vec::new();
}
let mut pruned = Vec::new();
let mut idx = 0;
while idx < reordered.len() {
let tag = &reordered[idx].outbound_tag;
let is_stale = self
.unhealthy_since
.get(tag)
.is_some_and(|since| now.saturating_duration_since(*since) >= max_age);
if is_stale {
let removed = reordered.remove(idx);
ranked_state.remove(idx);
self.unhealthy_since.remove(&removed.outbound_tag);
pruned.push(removed.name);
} else {
idx += 1;
}
}
pruned
}
async fn is_host_internet_up(&self) -> bool {
let Some(url) = self
.config
.probe
.direct_check_url
.as_deref()
.filter(|u| !u.trim().is_empty())
else {
return true;
};
let Some(direct) = self.direct_probe.as_ref() else {
return true;
};
let target = ProbeTarget {
name: "direct-check".into(),
url: url.to_string(),
expected_status: vec![200, 204, 301, 302],
blocked_status: vec![],
};
match direct.check(&target).await {
Ok(ProbeOutcome::Healthy { .. }) => true,
_ => {
tracing::warn!(%url, "direct host internet check failed; skipping auto-prune");
false
}
}
}
pub async fn run_once(&mut self) -> Result<()> {
let (all_healthy, reason) = self.probe_all_targets().await?;
match self.state.record_probe(all_healthy) {
FailoverAction::Stay => {
tracing::debug!("active profile is healthy");
}
FailoverAction::Degraded { failures } => {
tracing::warn!(failures, %reason, "probe failed (anti-flapping buffer)");
}
FailoverAction::SwitchTo { from, to } => {
tracing::warn!(%from, to = %to.name, %reason, "switching active profile");
self.core.switch_profile(&to.outbound_tag).await?;
self.core.reload().await?;
}
FailoverAction::AllUnhealthy { failed } => {
tracing::error!(%failed, %reason, "all configured profiles are unhealthy");
if self.can_send_critical_alert() {
self.last_critical_alert = Some(Instant::now());
self.notify_all(&AlertEvent {
severity: AlertSeverity::Critical,
title: "قطع کامل همه کانفیگهای پراکسی".into(),
message: format!(
"آخرین کانفیگ «{failed}» هم قطع شد ({reason}).\nهیچ کانفیگ سالمی برای سوییچ باقی نمانده است."
),
})
.await;
}
}
}
Ok(())
}
async fn probe_all_targets(&self) -> Result<(bool, String)> {
let max_latency = self.config.probe.max_latency_ms.map(Duration::from_millis);
for target in &self.config.probe.targets {
match self.probe.check(target).await? {
ProbeOutcome::Healthy { latency, .. } => {
if let Some(limit) = max_latency
&& latency > limit
{
return Ok((
false,
format!(
"{} too slow ({}ms > {}ms)",
target.name,
latency.as_millis(),
limit.as_millis()
),
));
}
}
ProbeOutcome::GeoBlocked { status } => {
return Ok((
false,
format!("{} geo-blocked (HTTP {status})", target.name),
));
}
ProbeOutcome::Unreachable { reason } => {
return Ok((false, format!("{} unreachable ({reason})", target.name)));
}
}
}
Ok((true, String::new()))
}
fn can_send_critical_alert(&self) -> bool {
match self.last_critical_alert {
None => true,
Some(last) => last.elapsed() >= Duration::from_secs(self.config.notify.cooldown_secs),
}
}
async fn notify_all(&self, event: &AlertEvent) {
for notifier in &self.notifiers {
if let Err(err) = notifier.send(event).await {
tracing::error!(channel = notifier.channel_name(), error = %err, "alert delivery failed");
}
}
}
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use super::*;
use crate::config::{
CoreConfig, NotifyConfig, ProbeConfig, ProbeTarget, ProfileConfig, RoutingConfig,
};
struct MockCore {
switched: Arc<Mutex<Vec<String>>>,
reloads: Arc<Mutex<u32>>,
}
#[async_trait]
impl ProxyCore for MockCore {
fn name(&self) -> &'static str {
"mock"
}
async fn is_installed(&self) -> bool {
true
}
async fn install(&self) -> Result<()> {
Ok(())
}
async fn active_profile(&self) -> Result<Option<String>> {
Ok(self.switched.lock().unwrap().last().cloned())
}
async fn switch_profile(&self, outbound_tag: &str) -> Result<()> {
self.switched.lock().unwrap().push(outbound_tag.to_string());
Ok(())
}
async fn reload(&self) -> Result<()> {
*self.reloads.lock().unwrap() += 1;
Ok(())
}
}
struct FailingProbe;
#[async_trait]
impl HealthProbe for FailingProbe {
async fn check(&self, _target: &ProbeTarget) -> Result<ProbeOutcome> {
Ok(ProbeOutcome::GeoBlocked { status: 403 })
}
}
struct MockNotifier {
alerts: Arc<Mutex<Vec<AlertEvent>>>,
}
#[async_trait]
impl Notifier for MockNotifier {
fn channel_name(&self) -> &'static str {
"mock-bale"
}
async fn send(&self, event: &AlertEvent) -> Result<()> {
self.alerts.lock().unwrap().push(event.clone());
Ok(())
}
}
fn sample_config() -> AppConfig {
AppConfig {
core: CoreConfig {
kind: "xray".into(),
binary_path: "/usr/local/bin/xray".into(),
config_path: "/usr/local/etc/xray/config.json".into(),
service_name: "xray".into(),
local_proxy: "socks5h://127.0.0.1:10808".into(),
},
routing: RoutingConfig::default(),
profiles: vec![
ProfileConfig {
name: "p1".into(),
outbound_tag: "tag-1".into(),
priority: 1,
},
ProfileConfig {
name: "p2".into(),
outbound_tag: "tag-2".into(),
priority: 2,
},
],
probe: ProbeConfig {
interval_secs: 30,
timeout_secs: 5,
failure_threshold: 1,
recovery_threshold: 2,
max_latency_ms: None,
benchmark_interval_secs: 900,
auto_prune_after_hours: 24,
direct_check_url: None,
targets: vec![ProbeTarget {
name: "gemini".into(),
url: "https://generativelanguage.googleapis.com/".into(),
expected_status: vec![200, 404],
blocked_status: vec![403, 429],
}],
},
notify: NotifyConfig {
cooldown_secs: 300,
bale: None,
},
}
}
#[tokio::test]
async fn silent_failover_and_alert_only_when_all_unhealthy_with_cooldown() {
let switched = Arc::new(Mutex::new(Vec::new()));
let reloads = Arc::new(Mutex::new(0u32));
let alerts = Arc::new(Mutex::new(Vec::new()));
let core = Box::new(MockCore {
switched: Arc::clone(&switched),
reloads: Arc::clone(&reloads),
});
let probe = Box::new(FailingProbe);
let notifier = Box::new(MockNotifier {
alerts: Arc::clone(&alerts),
});
let mut wd = Watchdog::new(sample_config(), core, probe, vec![notifier]);
wd.run_once().await.unwrap();
assert_eq!(*switched.lock().unwrap(), vec!["tag-2".to_string()]);
assert_eq!(*reloads.lock().unwrap(), 1);
assert!(alerts.lock().unwrap().is_empty());
wd.run_once().await.unwrap();
assert_eq!(alerts.lock().unwrap().len(), 1);
wd.run_once().await.unwrap();
assert_eq!(alerts.lock().unwrap().len(), 1);
}
struct SlowProbe(Duration);
#[async_trait]
impl HealthProbe for SlowProbe {
async fn check(&self, _target: &ProbeTarget) -> Result<ProbeOutcome> {
Ok(ProbeOutcome::Healthy {
status: 204,
latency: self.0,
})
}
}
#[tokio::test]
async fn triggers_failover_when_latency_exceeds_max_latency_ms() {
let switched = Arc::new(Mutex::new(Vec::new()));
let reloads = Arc::new(Mutex::new(0u32));
let mut cfg = sample_config();
cfg.probe.max_latency_ms = Some(1000);
let core = Box::new(MockCore {
switched: Arc::clone(&switched),
reloads: Arc::clone(&reloads),
});
let probe = Box::new(SlowProbe(Duration::from_millis(2500)));
let mut wd = Watchdog::new(cfg, core, probe, vec![]);
wd.run_once().await.unwrap();
assert_eq!(*switched.lock().unwrap(), vec!["tag-2".to_string()]);
assert_eq!(*reloads.lock().unwrap(), 1);
}
}