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()
}
}
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)
}
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());
}
}