Skip to main content

proxy_pilot/engine/
mod.rs

1pub mod benchmark;
2pub mod state;
3
4use std::collections::HashMap;
5use std::path::PathBuf;
6use std::time::{Duration, Instant};
7
8use crate::config::{AppConfig, ProbeTarget, ProfileConfig};
9use crate::core::ProxyCore;
10use crate::engine::benchmark::benchmark_profiles_isolated;
11use crate::engine::state::{FailoverAction, FailoverState};
12use crate::error::Result;
13use crate::notify::{AlertEvent, AlertSeverity, Notifier};
14use crate::probe::{HealthProbe, ProbeOutcome};
15
16pub type ProbeFactory = Box<dyn Fn(&str) -> Result<Box<dyn HealthProbe>> + Send + Sync>;
17
18pub struct Watchdog {
19    config: AppConfig,
20    config_path: Option<PathBuf>,
21    core: Box<dyn ProxyCore>,
22    probe: Box<dyn HealthProbe>,
23    direct_probe: Option<Box<dyn HealthProbe>>,
24    probe_factory: Option<ProbeFactory>,
25    notifiers: Vec<Box<dyn Notifier>>,
26    state: FailoverState,
27    last_critical_alert: Option<Instant>,
28    unhealthy_since: HashMap<String, Instant>,
29}
30
31impl Watchdog {
32    pub fn new(
33        config: AppConfig,
34        core: Box<dyn ProxyCore>,
35        probe: Box<dyn HealthProbe>,
36        notifiers: Vec<Box<dyn Notifier>>,
37    ) -> Self {
38        let state = FailoverState::new(config.profiles.clone(), config.probe.failure_threshold);
39        Self {
40            config,
41            config_path: None,
42            core,
43            probe,
44            direct_probe: None,
45            probe_factory: None,
46            notifiers,
47            state,
48            last_critical_alert: None,
49            unhealthy_since: HashMap::new(),
50        }
51    }
52
53    pub fn with_periodic_benchmark(
54        mut self,
55        config_path: Option<PathBuf>,
56        probe_factory: ProbeFactory,
57    ) -> Self {
58        self.config_path = config_path;
59        self.probe_factory = Some(probe_factory);
60        self
61    }
62
63    pub fn with_direct_probe(mut self, direct_probe: Box<dyn HealthProbe>) -> Self {
64        self.direct_probe = Some(direct_probe);
65        self
66    }
67
68    pub async fn run_forever(&mut self) -> Result<()> {
69        let mut ticker =
70            tokio::time::interval(Duration::from_secs(self.config.probe.interval_secs));
71        let bench_secs = self.config.probe.benchmark_interval_secs;
72        let mut bench_ticker = if bench_secs > 0 && self.probe_factory.is_some() {
73            let mut interval = tokio::time::interval(Duration::from_secs(bench_secs));
74            interval.tick().await;
75            Some(interval)
76        } else {
77            None
78        };
79        tracing::info!(
80            core = self.core.name(),
81            benchmark_interval_secs = bench_secs,
82            "proxy-pilot watchdog started"
83        );
84
85        loop {
86            tokio::select! {
87                _ = ticker.tick() => {
88                    if let Err(err) = self.run_once().await {
89                        tracing::error!(error = %err, "watchdog cycle failed");
90                    }
91                }
92                _ = async {
93                    if let Some(interval) = bench_ticker.as_mut() {
94                        interval.tick().await;
95                    } else {
96                        std::future::pending::<()>().await;
97                    }
98                } => {
99                    if let Err(err) = self.run_periodic_benchmark().await {
100                        tracing::error!(error = %err, "periodic background benchmark failed");
101                    }
102                }
103                _ = tokio::signal::ctrl_c() => {
104                    tracing::info!("shutdown signal received, stopping watchdog");
105                    break;
106                }
107            }
108        }
109        Ok(())
110    }
111
112    /// Run a non-disruptive parallel benchmark in the background, refresh profile priorities
113    /// and recovery states, persist updated priorities to disk, and recover if active is dead.
114    pub async fn run_periodic_benchmark(&mut self) -> Result<bool> {
115        let Some(factory) = self.probe_factory.as_ref() else {
116            return Ok(false);
117        };
118        let Some(results) = benchmark_profiles_isolated(
119            self.core.as_ref(),
120            |endpoint| factory(endpoint),
121            &self.config.profiles,
122            &self.config.probe.targets,
123        )
124        .await?
125        else {
126            tracing::debug!("skipping periodic benchmark: core has no isolated session support");
127            return Ok(false);
128        };
129
130        let mut reordered = Vec::with_capacity(results.len());
131        let mut ranked_state = Vec::with_capacity(results.len());
132        let now = Instant::now();
133        for res in &results {
134            if res.is_healthy() {
135                self.unhealthy_since.remove(&res.profile.outbound_tag);
136            } else {
137                self.unhealthy_since
138                    .entry(res.profile.outbound_tag.clone())
139                    .or_insert(now);
140            }
141            ranked_state.push((res.profile.clone(), res.is_healthy()));
142            reordered.push(res.profile.clone());
143        }
144
145        let healthy_count = results.iter().filter(|r| r.is_healthy()).count();
146        let pruned_names = self
147            .prune_stale_profiles(&mut reordered, &mut ranked_state, healthy_count, now)
148            .await;
149
150        for (idx, profile) in reordered.iter_mut().enumerate() {
151            profile.priority = (idx + 1) as u32;
152            ranked_state[idx].0.priority = profile.priority;
153        }
154
155        let top_name = reordered.first().map(|p| p.name.as_str()).unwrap_or("none");
156        tracing::info!(
157            healthy = healthy_count,
158            total = reordered.len(),
159            pruned = pruned_names.len(),
160            fastest = top_name,
161            "periodic background benchmark updated profile priorities"
162        );
163
164        let recovered = self.state.apply_benchmark_order(ranked_state);
165        self.config.profiles = reordered;
166
167        if let Some(path) = self.config_path.as_deref()
168            && let Err(err) = self.config.save_atomic(path).await
169        {
170            tracing::warn!(error = %err, "failed to persist updated profile priorities");
171        }
172
173        if !pruned_names.is_empty() {
174            self.notify_all(&AlertEvent {
175                severity: AlertSeverity::Info,
176                title: "حذف خودکار کانفیگ‌های خراب".into(),
177                message: format!(
178                    "کانفیگ‌های زیر پس از {} ساعت خرابی مداوم حذف شدند:\n- {}",
179                    self.config.probe.auto_prune_after_hours,
180                    pruned_names.join("\n- ")
181                ),
182            })
183            .await;
184        }
185
186        if let Some(target) = recovered {
187            tracing::info!(
188                profile = %target.name,
189                "active profile was unhealthy; auto-recovering to fastest healthy profile"
190            );
191            self.core.switch_profile(&target.outbound_tag).await?;
192            self.core.reload().await?;
193        }
194
195        Ok(true)
196    }
197
198    async fn prune_stale_profiles(
199        &mut self,
200        reordered: &mut Vec<ProfileConfig>,
201        ranked_state: &mut Vec<(ProfileConfig, bool)>,
202        healthy_count: usize,
203        now: Instant,
204    ) -> Vec<String> {
205        let hours = self.config.probe.auto_prune_after_hours;
206        if hours == 0 || healthy_count == 0 {
207            return Vec::new();
208        }
209        let max_age = Duration::from_secs(hours.saturating_mul(3600));
210        let has_stale = reordered.iter().any(|p| {
211            self.unhealthy_since
212                .get(&p.outbound_tag)
213                .is_some_and(|since| now.saturating_duration_since(*since) >= max_age)
214        });
215        if !has_stale || !self.is_host_internet_up().await {
216            return Vec::new();
217        }
218
219        let mut pruned = Vec::new();
220        let mut idx = 0;
221        while idx < reordered.len() {
222            let tag = &reordered[idx].outbound_tag;
223            let is_stale = self
224                .unhealthy_since
225                .get(tag)
226                .is_some_and(|since| now.saturating_duration_since(*since) >= max_age);
227            if is_stale {
228                let removed = reordered.remove(idx);
229                ranked_state.remove(idx);
230                self.unhealthy_since.remove(&removed.outbound_tag);
231                pruned.push(removed.name);
232            } else {
233                idx += 1;
234            }
235        }
236        pruned
237    }
238
239    async fn is_host_internet_up(&self) -> bool {
240        let Some(url) = self
241            .config
242            .probe
243            .direct_check_url
244            .as_deref()
245            .filter(|u| !u.trim().is_empty())
246        else {
247            return true;
248        };
249        let Some(direct) = self.direct_probe.as_ref() else {
250            return true;
251        };
252        let target = ProbeTarget {
253            name: "direct-check".into(),
254            url: url.to_string(),
255            expected_status: vec![200, 204, 301, 302],
256            blocked_status: vec![],
257        };
258        match direct.check(&target).await {
259            Ok(ProbeOutcome::Healthy { .. }) => true,
260            _ => {
261                tracing::warn!(%url, "direct host internet check failed; skipping auto-prune");
262                false
263            }
264        }
265    }
266
267    pub async fn run_once(&mut self) -> Result<()> {
268        let (all_healthy, reason) = self.probe_all_targets().await?;
269        match self.state.record_probe(all_healthy) {
270            FailoverAction::Stay => {
271                tracing::debug!("active profile is healthy");
272            }
273            FailoverAction::Degraded { failures } => {
274                tracing::warn!(failures, %reason, "probe failed (anti-flapping buffer)");
275            }
276            FailoverAction::SwitchTo { from, to } => {
277                tracing::warn!(%from, to = %to.name, %reason, "switching active profile");
278                self.core.switch_profile(&to.outbound_tag).await?;
279                self.core.reload().await?;
280            }
281            FailoverAction::AllUnhealthy { failed } => {
282                tracing::error!(%failed, %reason, "all configured profiles are unhealthy");
283                if self.can_send_critical_alert() {
284                    self.last_critical_alert = Some(Instant::now());
285                    self.notify_all(&AlertEvent {
286                        severity: AlertSeverity::Critical,
287                        title: "قطع کامل همه کانفیگ‌های پراکسی".into(),
288                        message: format!(
289                            "آخرین کانفیگ «{failed}» هم قطع شد ({reason}).\nهیچ کانفیگ سالمی برای سوییچ باقی نمانده است."
290                        ),
291                    })
292                    .await;
293                }
294            }
295        }
296        Ok(())
297    }
298
299    async fn probe_all_targets(&self) -> Result<(bool, String)> {
300        let max_latency = self.config.probe.max_latency_ms.map(Duration::from_millis);
301        for target in &self.config.probe.targets {
302            match self.probe.check(target).await? {
303                ProbeOutcome::Healthy { latency, .. } => {
304                    if let Some(limit) = max_latency
305                        && latency > limit
306                    {
307                        return Ok((
308                            false,
309                            format!(
310                                "{} too slow ({}ms > {}ms)",
311                                target.name,
312                                latency.as_millis(),
313                                limit.as_millis()
314                            ),
315                        ));
316                    }
317                }
318                ProbeOutcome::GeoBlocked { status } => {
319                    return Ok((
320                        false,
321                        format!("{} geo-blocked (HTTP {status})", target.name),
322                    ));
323                }
324                ProbeOutcome::Unreachable { reason } => {
325                    return Ok((false, format!("{} unreachable ({reason})", target.name)));
326                }
327            }
328        }
329        Ok((true, String::new()))
330    }
331
332    fn can_send_critical_alert(&self) -> bool {
333        match self.last_critical_alert {
334            None => true,
335            Some(last) => last.elapsed() >= Duration::from_secs(self.config.notify.cooldown_secs),
336        }
337    }
338
339    async fn notify_all(&self, event: &AlertEvent) {
340        for notifier in &self.notifiers {
341            if let Err(err) = notifier.send(event).await {
342                tracing::error!(channel = notifier.channel_name(), error = %err, "alert delivery failed");
343            }
344        }
345    }
346}
347
348#[cfg(test)]
349mod tests {
350    use std::sync::{Arc, Mutex};
351
352    use async_trait::async_trait;
353
354    use super::*;
355    use crate::config::{
356        CoreConfig, NotifyConfig, ProbeConfig, ProbeTarget, ProfileConfig, RoutingConfig,
357    };
358
359    struct MockCore {
360        switched: Arc<Mutex<Vec<String>>>,
361        reloads: Arc<Mutex<u32>>,
362    }
363
364    #[async_trait]
365    impl ProxyCore for MockCore {
366        fn name(&self) -> &'static str {
367            "mock"
368        }
369        async fn is_installed(&self) -> bool {
370            true
371        }
372        async fn install(&self) -> Result<()> {
373            Ok(())
374        }
375        async fn active_profile(&self) -> Result<Option<String>> {
376            Ok(self.switched.lock().unwrap().last().cloned())
377        }
378        async fn switch_profile(&self, outbound_tag: &str) -> Result<()> {
379            self.switched.lock().unwrap().push(outbound_tag.to_string());
380            Ok(())
381        }
382        async fn reload(&self) -> Result<()> {
383            *self.reloads.lock().unwrap() += 1;
384            Ok(())
385        }
386    }
387
388    struct FailingProbe;
389
390    #[async_trait]
391    impl HealthProbe for FailingProbe {
392        async fn check(&self, _target: &ProbeTarget) -> Result<ProbeOutcome> {
393            Ok(ProbeOutcome::GeoBlocked { status: 403 })
394        }
395    }
396
397    struct MockNotifier {
398        alerts: Arc<Mutex<Vec<AlertEvent>>>,
399    }
400
401    #[async_trait]
402    impl Notifier for MockNotifier {
403        fn channel_name(&self) -> &'static str {
404            "mock-bale"
405        }
406        async fn send(&self, event: &AlertEvent) -> Result<()> {
407            self.alerts.lock().unwrap().push(event.clone());
408            Ok(())
409        }
410    }
411
412    fn sample_config() -> AppConfig {
413        AppConfig {
414            core: CoreConfig {
415                kind: "xray".into(),
416                binary_path: "/usr/local/bin/xray".into(),
417                config_path: "/usr/local/etc/xray/config.json".into(),
418                service_name: "xray".into(),
419                local_proxy: "socks5h://127.0.0.1:10808".into(),
420            },
421            routing: RoutingConfig::default(),
422            profiles: vec![
423                ProfileConfig {
424                    name: "p1".into(),
425                    outbound_tag: "tag-1".into(),
426                    priority: 1,
427                },
428                ProfileConfig {
429                    name: "p2".into(),
430                    outbound_tag: "tag-2".into(),
431                    priority: 2,
432                },
433            ],
434            probe: ProbeConfig {
435                interval_secs: 30,
436                timeout_secs: 5,
437                failure_threshold: 1,
438                recovery_threshold: 2,
439                max_latency_ms: None,
440                benchmark_interval_secs: 900,
441                auto_prune_after_hours: 24,
442                direct_check_url: None,
443                targets: vec![ProbeTarget {
444                    name: "gemini".into(),
445                    url: "https://generativelanguage.googleapis.com/".into(),
446                    expected_status: vec![200, 404],
447                    blocked_status: vec![403, 429],
448                }],
449            },
450            notify: NotifyConfig {
451                cooldown_secs: 300,
452                empty_profiles_reminder_secs: 300,
453                bale: None,
454            },
455        }
456    }
457
458    #[tokio::test]
459    async fn silent_failover_and_alert_only_when_all_unhealthy_with_cooldown() {
460        let switched = Arc::new(Mutex::new(Vec::new()));
461        let reloads = Arc::new(Mutex::new(0u32));
462        let alerts = Arc::new(Mutex::new(Vec::new()));
463
464        let core = Box::new(MockCore {
465            switched: Arc::clone(&switched),
466            reloads: Arc::clone(&reloads),
467        });
468        let probe = Box::new(FailingProbe);
469        let notifier = Box::new(MockNotifier {
470            alerts: Arc::clone(&alerts),
471        });
472
473        let mut wd = Watchdog::new(sample_config(), core, probe, vec![notifier]);
474
475        // 1st failure: switches silently from p1 to p2 (no alert).
476        wd.run_once().await.unwrap();
477        assert_eq!(*switched.lock().unwrap(), vec!["tag-2".to_string()]);
478        assert_eq!(*reloads.lock().unwrap(), 1);
479        assert!(alerts.lock().unwrap().is_empty());
480
481        // 2nd failure: p2 also fails -> AllUnhealthy -> sends 1 critical alert.
482        wd.run_once().await.unwrap();
483        assert_eq!(alerts.lock().unwrap().len(), 1);
484
485        // 3rd failure within cooldown: suppressed (still 1 alert).
486        wd.run_once().await.unwrap();
487        assert_eq!(alerts.lock().unwrap().len(), 1);
488    }
489
490    struct SlowProbe(Duration);
491
492    #[async_trait]
493    impl HealthProbe for SlowProbe {
494        async fn check(&self, _target: &ProbeTarget) -> Result<ProbeOutcome> {
495            Ok(ProbeOutcome::Healthy {
496                status: 204,
497                latency: self.0,
498            })
499        }
500    }
501
502    #[tokio::test]
503    async fn triggers_failover_when_latency_exceeds_max_latency_ms() {
504        let switched = Arc::new(Mutex::new(Vec::new()));
505        let reloads = Arc::new(Mutex::new(0u32));
506        let mut cfg = sample_config();
507        cfg.probe.max_latency_ms = Some(1000);
508
509        let core = Box::new(MockCore {
510            switched: Arc::clone(&switched),
511            reloads: Arc::clone(&reloads),
512        });
513        let probe = Box::new(SlowProbe(Duration::from_millis(2500)));
514
515        let mut wd = Watchdog::new(cfg, core, probe, vec![]);
516        wd.run_once().await.unwrap();
517
518        assert_eq!(*switched.lock().unwrap(), vec!["tag-2".to_string()]);
519        assert_eq!(*reloads.lock().unwrap(), 1);
520    }
521}