1use std::time::Duration;
2
3use tokio::task::JoinSet;
4
5use crate::config::{ProbeTarget, ProfileConfig};
6use crate::core::ProxyCore;
7use crate::error::Result;
8use crate::probe::{HealthProbe, ProbeOutcome};
9
10#[derive(Debug, Clone)]
11pub struct BenchmarkResult {
12 pub profile: ProfileConfig,
13 pub latency: Option<Duration>,
14 pub error: Option<String>,
15}
16
17impl BenchmarkResult {
18 pub fn is_healthy(&self) -> bool {
19 self.latency.is_some()
20 }
21}
22
23pub async fn benchmark_profiles<F>(
30 core: &dyn ProxyCore,
31 fallback_probe: &dyn HealthProbe,
32 make_probe: F,
33 profiles: &[ProfileConfig],
34 targets: &[ProbeTarget],
35) -> Result<Vec<BenchmarkResult>>
36where
37 F: Fn(&str) -> Result<Box<dyn HealthProbe>> + Send + Sync,
38{
39 let tags: Vec<String> = profiles.iter().map(|p| p.outbound_tag.clone()).collect();
40 let mut results = if let Some(session) = core.start_benchmark_session(&tags).await? {
41 let parallel_results =
42 run_parallel_probes(session.endpoints(), &make_probe, profiles, targets).await;
43 let _ = session.shutdown().await;
44 parallel_results
45 } else {
46 run_sequential_probes(core, fallback_probe, profiles, targets).await?
47 };
48
49 results.sort_by_key(|r| r.latency.unwrap_or(Duration::MAX));
50
51 if let Some(fastest) = results.iter().find(|r| r.is_healthy()) {
52 core.switch_profile(&fastest.profile.outbound_tag).await?;
53 core.reload().await?;
54 }
55
56 Ok(results)
57}
58
59pub async fn benchmark_profiles_isolated<F>(
64 core: &dyn ProxyCore,
65 make_probe: F,
66 profiles: &[ProfileConfig],
67 targets: &[ProbeTarget],
68) -> Result<Option<Vec<BenchmarkResult>>>
69where
70 F: Fn(&str) -> Result<Box<dyn HealthProbe>> + Send + Sync,
71{
72 let tags: Vec<String> = profiles.iter().map(|p| p.outbound_tag.clone()).collect();
73 let Some(session) = core.start_benchmark_session(&tags).await? else {
74 return Ok(None);
75 };
76
77 let mut results =
78 run_parallel_probes(session.endpoints(), &make_probe, profiles, targets).await;
79 let _ = session.shutdown().await;
80 results.sort_by_key(|r| r.latency.unwrap_or(Duration::MAX));
81 Ok(Some(results))
82}
83
84async fn run_parallel_probes<F>(
85 endpoints: &std::collections::HashMap<String, String>,
86 make_probe: &F,
87 profiles: &[ProfileConfig],
88 targets: &[ProbeTarget],
89) -> Vec<BenchmarkResult>
90where
91 F: Fn(&str) -> Result<Box<dyn HealthProbe>> + Send + Sync,
92{
93 let mut join_set: JoinSet<BenchmarkResult> = JoinSet::new();
94 let mut immediate_failures = Vec::new();
95
96 for profile in profiles {
97 let Some(endpoint) = endpoints.get(&profile.outbound_tag) else {
98 immediate_failures.push(BenchmarkResult {
99 profile: profile.clone(),
100 latency: None,
101 error: Some(format!(
102 "outbound tag '{}' not found in proxy core config",
103 profile.outbound_tag
104 )),
105 });
106 continue;
107 };
108
109 let probe = match make_probe(endpoint) {
110 Ok(p) => p,
111 Err(err) => {
112 immediate_failures.push(BenchmarkResult {
113 profile: profile.clone(),
114 latency: None,
115 error: Some(err.to_string()),
116 });
117 continue;
118 }
119 };
120
121 let profile_clone = profile.clone();
122 let targets_clone = targets.to_vec();
123 join_set.spawn(async move {
124 match probe_profile(probe.as_ref(), &targets_clone).await {
125 Ok((latency, error)) => BenchmarkResult {
126 profile: profile_clone,
127 latency,
128 error,
129 },
130 Err(err) => BenchmarkResult {
131 profile: profile_clone,
132 latency: None,
133 error: Some(err.to_string()),
134 },
135 }
136 });
137 }
138
139 let mut results = immediate_failures;
140 while let Some(joined) = join_set.join_next().await {
141 if let Ok(res) = joined {
142 results.push(res);
143 }
144 }
145 results
146}
147
148async fn run_sequential_probes(
149 core: &dyn ProxyCore,
150 probe: &dyn HealthProbe,
151 profiles: &[ProfileConfig],
152 targets: &[ProbeTarget],
153) -> Result<Vec<BenchmarkResult>> {
154 let mut results = Vec::with_capacity(profiles.len());
155
156 for profile in profiles {
157 if let Err(err) = core.switch_profile(&profile.outbound_tag).await {
158 results.push(BenchmarkResult {
159 profile: profile.clone(),
160 latency: None,
161 error: Some(err.to_string()),
162 });
163 continue;
164 }
165 if let Err(err) = core.reload().await {
166 results.push(BenchmarkResult {
167 profile: profile.clone(),
168 latency: None,
169 error: Some(err.to_string()),
170 });
171 continue;
172 }
173
174 let (latency, error) = probe_profile(probe, targets).await?;
175 results.push(BenchmarkResult {
176 profile: profile.clone(),
177 latency,
178 error,
179 });
180 }
181
182 Ok(results)
183}
184
185async fn probe_profile(
186 probe: &dyn HealthProbe,
187 targets: &[ProbeTarget],
188) -> Result<(Option<Duration>, Option<String>)> {
189 let mut total = Duration::ZERO;
190 for target in targets {
191 match probe.check(target).await? {
192 ProbeOutcome::Healthy { latency, .. } => total += latency,
193 ProbeOutcome::GeoBlocked { status } => {
194 return Ok((
195 None,
196 Some(format!("{} geo-blocked (HTTP {status})", target.name)),
197 ));
198 }
199 ProbeOutcome::Unreachable { reason } => {
200 return Ok((
201 None,
202 Some(format!("{} unreachable ({reason})", target.name)),
203 ));
204 }
205 }
206 }
207 let avg = total / (targets.len().max(1) as u32);
208 Ok((Some(avg), None))
209}
210
211#[cfg(test)]
212mod tests {
213 use std::sync::{Arc, Mutex};
214
215 use async_trait::async_trait;
216
217 use super::*;
218
219 struct MockBenchCore {
220 active: Arc<Mutex<String>>,
221 }
222
223 #[async_trait]
224 impl ProxyCore for MockBenchCore {
225 fn name(&self) -> &'static str {
226 "mock"
227 }
228 async fn is_installed(&self) -> bool {
229 true
230 }
231 async fn install(&self) -> Result<()> {
232 Ok(())
233 }
234 async fn active_profile(&self) -> Result<Option<String>> {
235 Ok(Some(self.active.lock().unwrap().clone()))
236 }
237 async fn switch_profile(&self, outbound_tag: &str) -> Result<()> {
238 *self.active.lock().unwrap() = outbound_tag.to_string();
239 Ok(())
240 }
241 async fn reload(&self) -> Result<()> {
242 Ok(())
243 }
244 }
245
246 struct LatencyProbe {
247 active: Arc<Mutex<String>>,
248 }
249
250 #[async_trait]
251 impl HealthProbe for LatencyProbe {
252 async fn check(&self, _target: &ProbeTarget) -> Result<ProbeOutcome> {
253 let tag = self.active.lock().unwrap().clone();
254 match tag.as_str() {
255 "slow" => Ok(ProbeOutcome::Healthy {
256 status: 204,
257 latency: Duration::from_millis(350),
258 }),
259 "fast" => Ok(ProbeOutcome::Healthy {
260 status: 204,
261 latency: Duration::from_millis(80),
262 }),
263 _ => Ok(ProbeOutcome::Unreachable {
264 reason: "timeout".into(),
265 }),
266 }
267 }
268 }
269
270 #[tokio::test]
271 async fn benchmarks_sorts_by_latency_and_activates_fastest() {
272 let active = Arc::new(Mutex::new(String::new()));
273 let core = MockBenchCore {
274 active: Arc::clone(&active),
275 };
276 let probe = LatencyProbe {
277 active: Arc::clone(&active),
278 };
279 let profiles = vec![
280 ProfileConfig {
281 name: "slow-node".into(),
282 outbound_tag: "slow".into(),
283 priority: 1,
284 },
285 ProfileConfig {
286 name: "dead-node".into(),
287 outbound_tag: "dead".into(),
288 priority: 2,
289 },
290 ProfileConfig {
291 name: "fast-node".into(),
292 outbound_tag: "fast".into(),
293 priority: 3,
294 },
295 ];
296 let targets = vec![ProbeTarget {
297 name: "youtube".into(),
298 url: "https://www.youtube.com/generate_204".into(),
299 expected_status: vec![204],
300 blocked_status: vec![403, 429],
301 }];
302
303 let results = benchmark_profiles(
304 &core,
305 &probe,
306 |_| {
307 Ok(Box::new(LatencyProbe {
308 active: Arc::clone(&active),
309 }))
310 },
311 &profiles,
312 &targets,
313 )
314 .await
315 .unwrap();
316
317 assert_eq!(results[0].profile.name, "fast-node");
318 assert!(results[0].is_healthy());
319 assert_eq!(results[1].profile.name, "slow-node");
320 assert!(!results[2].is_healthy());
321 assert_eq!(*active.lock().unwrap(), "fast");
322 }
323
324 struct MockParallelSession {
325 endpoints: std::collections::HashMap<String, String>,
326 shutdown_called: Arc<Mutex<bool>>,
327 }
328
329 #[async_trait]
330 impl crate::core::BenchmarkSession for MockParallelSession {
331 fn endpoints(&self) -> &std::collections::HashMap<String, String> {
332 &self.endpoints
333 }
334
335 async fn shutdown(self: Box<Self>) -> Result<()> {
336 *self.shutdown_called.lock().unwrap() = true;
337 Ok(())
338 }
339 }
340
341 struct MockParallelCore {
342 active: Arc<Mutex<String>>,
343 reload_count: Arc<Mutex<u32>>,
344 shutdown_called: Arc<Mutex<bool>>,
345 }
346
347 #[async_trait]
348 impl ProxyCore for MockParallelCore {
349 fn name(&self) -> &'static str {
350 "mock-parallel"
351 }
352 async fn is_installed(&self) -> bool {
353 true
354 }
355 async fn install(&self) -> Result<()> {
356 Ok(())
357 }
358 async fn active_profile(&self) -> Result<Option<String>> {
359 Ok(Some(self.active.lock().unwrap().clone()))
360 }
361 async fn switch_profile(&self, outbound_tag: &str) -> Result<()> {
362 *self.active.lock().unwrap() = outbound_tag.to_string();
363 Ok(())
364 }
365 async fn reload(&self) -> Result<()> {
366 *self.reload_count.lock().unwrap() += 1;
367 Ok(())
368 }
369 async fn start_benchmark_session(
370 &self,
371 outbound_tags: &[String],
372 ) -> Result<Option<Box<dyn crate::core::BenchmarkSession>>> {
373 let mut endpoints = std::collections::HashMap::new();
374 for tag in outbound_tags {
375 if tag != "missing" {
376 endpoints.insert(tag.clone(), format!("socks5h://127.0.0.1:{}", tag));
377 }
378 }
379 Ok(Some(Box::new(MockParallelSession {
380 endpoints,
381 shutdown_called: Arc::clone(&self.shutdown_called),
382 })))
383 }
384 }
385
386 struct EndpointProbe {
387 endpoint: String,
388 }
389
390 #[async_trait]
391 impl HealthProbe for EndpointProbe {
392 async fn check(&self, _target: &ProbeTarget) -> Result<ProbeOutcome> {
393 if self.endpoint.ends_with("fast") {
394 Ok(ProbeOutcome::Healthy {
395 status: 204,
396 latency: Duration::from_millis(60),
397 })
398 } else if self.endpoint.ends_with("slow") {
399 Ok(ProbeOutcome::Healthy {
400 status: 204,
401 latency: Duration::from_millis(240),
402 })
403 } else {
404 Ok(ProbeOutcome::Unreachable {
405 reason: "connection refused".into(),
406 })
407 }
408 }
409 }
410
411 #[tokio::test]
412 async fn benchmarks_in_parallel_with_isolated_session_and_reloads_once() {
413 let active = Arc::new(Mutex::new("direct".to_string()));
414 let reload_count = Arc::new(Mutex::new(0u32));
415 let shutdown_called = Arc::new(Mutex::new(false));
416 let core = MockParallelCore {
417 active: Arc::clone(&active),
418 reload_count: Arc::clone(&reload_count),
419 shutdown_called: Arc::clone(&shutdown_called),
420 };
421 let fallback_probe = EndpointProbe {
422 endpoint: "unused".into(),
423 };
424 let profiles = vec![
425 ProfileConfig {
426 name: "slow-node".into(),
427 outbound_tag: "slow".into(),
428 priority: 1,
429 },
430 ProfileConfig {
431 name: "missing-node".into(),
432 outbound_tag: "missing".into(),
433 priority: 2,
434 },
435 ProfileConfig {
436 name: "fast-node".into(),
437 outbound_tag: "fast".into(),
438 priority: 3,
439 },
440 ProfileConfig {
441 name: "dead-node".into(),
442 outbound_tag: "dead".into(),
443 priority: 4,
444 },
445 ];
446 let targets = vec![ProbeTarget {
447 name: "youtube".into(),
448 url: "https://www.youtube.com/generate_204".into(),
449 expected_status: vec![204],
450 blocked_status: vec![403, 429],
451 }];
452
453 let results = benchmark_profiles(
454 &core,
455 &fallback_probe,
456 |endpoint| {
457 Ok(Box::new(EndpointProbe {
458 endpoint: endpoint.to_string(),
459 }))
460 },
461 &profiles,
462 &targets,
463 )
464 .await
465 .unwrap();
466
467 assert_eq!(results.len(), 4);
468 assert_eq!(results[0].profile.name, "fast-node");
469 assert_eq!(results[0].latency, Some(Duration::from_millis(60)));
470 assert_eq!(results[1].profile.name, "slow-node");
471 assert!(!results[2].is_healthy());
472 assert!(!results[3].is_healthy());
473 assert_eq!(*active.lock().unwrap(), "fast");
474 assert_eq!(*reload_count.lock().unwrap(), 1);
475 assert!(*shutdown_called.lock().unwrap());
476 }
477}