proxy-pilot 0.6.1

Core-agnostic proxy health monitor, automatic failover daemon, and multi-channel alerting tool for Linux servers.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
use std::time::Duration;

use tokio::task::JoinSet;

use crate::config::{ProbeTarget, ProfileConfig};
use crate::core::ProxyCore;
use crate::error::Result;
use crate::probe::{HealthProbe, ProbeOutcome};

#[derive(Debug, Clone)]
pub struct BenchmarkResult {
    pub profile: ProfileConfig,
    pub latency: Option<Duration>,
    pub error: Option<String>,
}

impl BenchmarkResult {
    pub fn is_healthy(&self) -> bool {
        self.latency.is_some()
    }
}

/// Test every profile through the proxy core, sort healthy profiles by lowest average latency,
/// and activate the fastest healthy profile if one exists.
///
/// When the core supports an isolated [`crate::core::BenchmarkSession`], all profiles are
/// probed concurrently without touching the live proxy service until the single winning
/// profile is activated. Otherwise, falls back to sequential switch+reload probing.
pub async fn benchmark_profiles<F>(
    core: &dyn ProxyCore,
    fallback_probe: &dyn HealthProbe,
    make_probe: F,
    profiles: &[ProfileConfig],
    targets: &[ProbeTarget],
) -> Result<Vec<BenchmarkResult>>
where
    F: Fn(&str) -> Result<Box<dyn HealthProbe>> + Send + Sync,
{
    let tags: Vec<String> = profiles.iter().map(|p| p.outbound_tag.clone()).collect();
    let mut results = if let Some(session) = core.start_benchmark_session(&tags).await? {
        let parallel_results =
            run_parallel_probes(session.endpoints(), &make_probe, profiles, targets).await;
        let _ = session.shutdown().await;
        parallel_results
    } else {
        run_sequential_probes(core, fallback_probe, profiles, targets).await?
    };

    results.sort_by_key(|r| r.latency.unwrap_or(Duration::MAX));

    if let Some(fastest) = results.iter().find(|r| r.is_healthy()) {
        core.switch_profile(&fastest.profile.outbound_tag).await?;
        core.reload().await?;
    }

    Ok(results)
}

/// Probe all profiles concurrently in an isolated session without touching the live proxy.
///
/// Returns `Ok(None)` when the proxy core does not support non-disruptive isolated sessions,
/// so background daemon tasks never interrupt active traffic.
pub async fn benchmark_profiles_isolated<F>(
    core: &dyn ProxyCore,
    make_probe: F,
    profiles: &[ProfileConfig],
    targets: &[ProbeTarget],
) -> Result<Option<Vec<BenchmarkResult>>>
where
    F: Fn(&str) -> Result<Box<dyn HealthProbe>> + Send + Sync,
{
    let tags: Vec<String> = profiles.iter().map(|p| p.outbound_tag.clone()).collect();
    let Some(session) = core.start_benchmark_session(&tags).await? else {
        return Ok(None);
    };

    let mut results =
        run_parallel_probes(session.endpoints(), &make_probe, profiles, targets).await;
    let _ = session.shutdown().await;
    results.sort_by_key(|r| r.latency.unwrap_or(Duration::MAX));
    Ok(Some(results))
}

async fn run_parallel_probes<F>(
    endpoints: &std::collections::HashMap<String, String>,
    make_probe: &F,
    profiles: &[ProfileConfig],
    targets: &[ProbeTarget],
) -> Vec<BenchmarkResult>
where
    F: Fn(&str) -> Result<Box<dyn HealthProbe>> + Send + Sync,
{
    let mut join_set: JoinSet<BenchmarkResult> = JoinSet::new();
    let mut immediate_failures = Vec::new();

    for profile in profiles {
        let Some(endpoint) = endpoints.get(&profile.outbound_tag) else {
            immediate_failures.push(BenchmarkResult {
                profile: profile.clone(),
                latency: None,
                error: Some(format!(
                    "outbound tag '{}' not found in proxy core config",
                    profile.outbound_tag
                )),
            });
            continue;
        };

        let probe = match make_probe(endpoint) {
            Ok(p) => p,
            Err(err) => {
                immediate_failures.push(BenchmarkResult {
                    profile: profile.clone(),
                    latency: None,
                    error: Some(err.to_string()),
                });
                continue;
            }
        };

        let profile_clone = profile.clone();
        let targets_clone = targets.to_vec();
        join_set.spawn(async move {
            match probe_profile(probe.as_ref(), &targets_clone).await {
                Ok((latency, error)) => BenchmarkResult {
                    profile: profile_clone,
                    latency,
                    error,
                },
                Err(err) => BenchmarkResult {
                    profile: profile_clone,
                    latency: None,
                    error: Some(err.to_string()),
                },
            }
        });
    }

    let mut results = immediate_failures;
    while let Some(joined) = join_set.join_next().await {
        if let Ok(res) = joined {
            results.push(res);
        }
    }
    results
}

async fn run_sequential_probes(
    core: &dyn ProxyCore,
    probe: &dyn HealthProbe,
    profiles: &[ProfileConfig],
    targets: &[ProbeTarget],
) -> Result<Vec<BenchmarkResult>> {
    let mut results = Vec::with_capacity(profiles.len());

    for profile in profiles {
        if let Err(err) = core.switch_profile(&profile.outbound_tag).await {
            results.push(BenchmarkResult {
                profile: profile.clone(),
                latency: None,
                error: Some(err.to_string()),
            });
            continue;
        }
        if let Err(err) = core.reload().await {
            results.push(BenchmarkResult {
                profile: profile.clone(),
                latency: None,
                error: Some(err.to_string()),
            });
            continue;
        }

        let (latency, error) = probe_profile(probe, targets).await?;
        results.push(BenchmarkResult {
            profile: profile.clone(),
            latency,
            error,
        });
    }

    Ok(results)
}

async fn probe_profile(
    probe: &dyn HealthProbe,
    targets: &[ProbeTarget],
) -> Result<(Option<Duration>, Option<String>)> {
    let mut total = Duration::ZERO;
    for target in targets {
        match probe.check(target).await? {
            ProbeOutcome::Healthy { latency, .. } => total += latency,
            ProbeOutcome::GeoBlocked { status } => {
                return Ok((
                    None,
                    Some(format!("{} geo-blocked (HTTP {status})", target.name)),
                ));
            }
            ProbeOutcome::Unreachable { reason } => {
                return Ok((
                    None,
                    Some(format!("{} unreachable ({reason})", target.name)),
                ));
            }
        }
    }
    let avg = total / (targets.len().max(1) as u32);
    Ok((Some(avg), None))
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Mutex};

    use async_trait::async_trait;

    use super::*;

    struct MockBenchCore {
        active: Arc<Mutex<String>>,
    }

    #[async_trait]
    impl ProxyCore for MockBenchCore {
        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(Some(self.active.lock().unwrap().clone()))
        }
        async fn switch_profile(&self, outbound_tag: &str) -> Result<()> {
            *self.active.lock().unwrap() = outbound_tag.to_string();
            Ok(())
        }
        async fn reload(&self) -> Result<()> {
            Ok(())
        }
    }

    struct LatencyProbe {
        active: Arc<Mutex<String>>,
    }

    #[async_trait]
    impl HealthProbe for LatencyProbe {
        async fn check(&self, _target: &ProbeTarget) -> Result<ProbeOutcome> {
            let tag = self.active.lock().unwrap().clone();
            match tag.as_str() {
                "slow" => Ok(ProbeOutcome::Healthy {
                    status: 204,
                    latency: Duration::from_millis(350),
                }),
                "fast" => Ok(ProbeOutcome::Healthy {
                    status: 204,
                    latency: Duration::from_millis(80),
                }),
                _ => Ok(ProbeOutcome::Unreachable {
                    reason: "timeout".into(),
                }),
            }
        }
    }

    #[tokio::test]
    async fn benchmarks_sorts_by_latency_and_activates_fastest() {
        let active = Arc::new(Mutex::new(String::new()));
        let core = MockBenchCore {
            active: Arc::clone(&active),
        };
        let probe = LatencyProbe {
            active: Arc::clone(&active),
        };
        let profiles = vec![
            ProfileConfig {
                name: "slow-node".into(),
                outbound_tag: "slow".into(),
                priority: 1,
            },
            ProfileConfig {
                name: "dead-node".into(),
                outbound_tag: "dead".into(),
                priority: 2,
            },
            ProfileConfig {
                name: "fast-node".into(),
                outbound_tag: "fast".into(),
                priority: 3,
            },
        ];
        let targets = vec![ProbeTarget {
            name: "youtube".into(),
            url: "https://www.youtube.com/generate_204".into(),
            expected_status: vec![204],
            blocked_status: vec![403, 429],
        }];

        let results = benchmark_profiles(
            &core,
            &probe,
            |_| {
                Ok(Box::new(LatencyProbe {
                    active: Arc::clone(&active),
                }))
            },
            &profiles,
            &targets,
        )
        .await
        .unwrap();

        assert_eq!(results[0].profile.name, "fast-node");
        assert!(results[0].is_healthy());
        assert_eq!(results[1].profile.name, "slow-node");
        assert!(!results[2].is_healthy());
        assert_eq!(*active.lock().unwrap(), "fast");
    }

    struct MockParallelSession {
        endpoints: std::collections::HashMap<String, String>,
        shutdown_called: Arc<Mutex<bool>>,
    }

    #[async_trait]
    impl crate::core::BenchmarkSession for MockParallelSession {
        fn endpoints(&self) -> &std::collections::HashMap<String, String> {
            &self.endpoints
        }

        async fn shutdown(self: Box<Self>) -> Result<()> {
            *self.shutdown_called.lock().unwrap() = true;
            Ok(())
        }
    }

    struct MockParallelCore {
        active: Arc<Mutex<String>>,
        reload_count: Arc<Mutex<u32>>,
        shutdown_called: Arc<Mutex<bool>>,
    }

    #[async_trait]
    impl ProxyCore for MockParallelCore {
        fn name(&self) -> &'static str {
            "mock-parallel"
        }
        async fn is_installed(&self) -> bool {
            true
        }
        async fn install(&self) -> Result<()> {
            Ok(())
        }
        async fn active_profile(&self) -> Result<Option<String>> {
            Ok(Some(self.active.lock().unwrap().clone()))
        }
        async fn switch_profile(&self, outbound_tag: &str) -> Result<()> {
            *self.active.lock().unwrap() = outbound_tag.to_string();
            Ok(())
        }
        async fn reload(&self) -> Result<()> {
            *self.reload_count.lock().unwrap() += 1;
            Ok(())
        }
        async fn start_benchmark_session(
            &self,
            outbound_tags: &[String],
        ) -> Result<Option<Box<dyn crate::core::BenchmarkSession>>> {
            let mut endpoints = std::collections::HashMap::new();
            for tag in outbound_tags {
                if tag != "missing" {
                    endpoints.insert(tag.clone(), format!("socks5h://127.0.0.1:{}", tag));
                }
            }
            Ok(Some(Box::new(MockParallelSession {
                endpoints,
                shutdown_called: Arc::clone(&self.shutdown_called),
            })))
        }
    }

    struct EndpointProbe {
        endpoint: String,
    }

    #[async_trait]
    impl HealthProbe for EndpointProbe {
        async fn check(&self, _target: &ProbeTarget) -> Result<ProbeOutcome> {
            if self.endpoint.ends_with("fast") {
                Ok(ProbeOutcome::Healthy {
                    status: 204,
                    latency: Duration::from_millis(60),
                })
            } else if self.endpoint.ends_with("slow") {
                Ok(ProbeOutcome::Healthy {
                    status: 204,
                    latency: Duration::from_millis(240),
                })
            } else {
                Ok(ProbeOutcome::Unreachable {
                    reason: "connection refused".into(),
                })
            }
        }
    }

    #[tokio::test]
    async fn benchmarks_in_parallel_with_isolated_session_and_reloads_once() {
        let active = Arc::new(Mutex::new("direct".to_string()));
        let reload_count = Arc::new(Mutex::new(0u32));
        let shutdown_called = Arc::new(Mutex::new(false));
        let core = MockParallelCore {
            active: Arc::clone(&active),
            reload_count: Arc::clone(&reload_count),
            shutdown_called: Arc::clone(&shutdown_called),
        };
        let fallback_probe = EndpointProbe {
            endpoint: "unused".into(),
        };
        let profiles = vec![
            ProfileConfig {
                name: "slow-node".into(),
                outbound_tag: "slow".into(),
                priority: 1,
            },
            ProfileConfig {
                name: "missing-node".into(),
                outbound_tag: "missing".into(),
                priority: 2,
            },
            ProfileConfig {
                name: "fast-node".into(),
                outbound_tag: "fast".into(),
                priority: 3,
            },
            ProfileConfig {
                name: "dead-node".into(),
                outbound_tag: "dead".into(),
                priority: 4,
            },
        ];
        let targets = vec![ProbeTarget {
            name: "youtube".into(),
            url: "https://www.youtube.com/generate_204".into(),
            expected_status: vec![204],
            blocked_status: vec![403, 429],
        }];

        let results = benchmark_profiles(
            &core,
            &fallback_probe,
            |endpoint| {
                Ok(Box::new(EndpointProbe {
                    endpoint: endpoint.to_string(),
                }))
            },
            &profiles,
            &targets,
        )
        .await
        .unwrap();

        assert_eq!(results.len(), 4);
        assert_eq!(results[0].profile.name, "fast-node");
        assert_eq!(results[0].latency, Some(Duration::from_millis(60)));
        assert_eq!(results[1].profile.name, "slow-node");
        assert!(!results[2].is_healthy());
        assert!(!results[3].is_healthy());
        assert_eq!(*active.lock().unwrap(), "fast");
        assert_eq!(*reload_count.lock().unwrap(), 1);
        assert!(*shutdown_called.lock().unwrap());
    }
}