Skip to main content

proxy_pilot/core/xray/
benchmark.rs

1use std::collections::HashMap;
2use std::net::{SocketAddr, TcpListener, TcpStream};
3use std::path::{Path, PathBuf};
4use std::process::Stdio;
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::time::{Duration, Instant};
7
8use async_trait::async_trait;
9use serde_json::{Value, json};
10use tokio::process::{Child, Command};
11
12use crate::core::BenchmarkSession;
13use crate::error::{PilotError, Result};
14
15static BENCH_COUNTER: AtomicU64 = AtomicU64::new(1);
16
17pub struct XrayBenchmarkSession {
18    child: Option<Child>,
19    temp_config_path: PathBuf,
20    endpoints: HashMap<String, String>,
21}
22
23impl Drop for XrayBenchmarkSession {
24    fn drop(&mut self) {
25        if let Some(mut child) = self.child.take() {
26            let _ = child.start_kill();
27        }
28        let _ = std::fs::remove_file(&self.temp_config_path);
29    }
30}
31
32#[async_trait]
33impl BenchmarkSession for XrayBenchmarkSession {
34    fn endpoints(&self) -> &HashMap<String, String> {
35        &self.endpoints
36    }
37
38    async fn shutdown(mut self: Box<Self>) -> Result<()> {
39        if let Some(mut child) = self.child.take() {
40            let _ = child.kill().await;
41            let _ = child.wait().await;
42        }
43        let _ = tokio::fs::remove_file(&self.temp_config_path).await;
44        Ok(())
45    }
46}
47
48/// Spawn an isolated temporary `xray` process with one local SOCKS5 port per matched outbound.
49pub async fn start_xray_benchmark_session(
50    binary_path: &Path,
51    source_config: &Value,
52    outbound_tags: &[String],
53) -> Result<Option<Box<dyn BenchmarkSession>>> {
54    let ports = allocate_free_ports(outbound_tags.len())?;
55    let (bench_config, endpoints) = build_benchmark_config(source_config, outbound_tags, &ports)?;
56    if endpoints.is_empty() {
57        return Ok(None);
58    }
59
60    let first_port = ports[0];
61    let seq = BENCH_COUNTER.fetch_add(1, Ordering::Relaxed);
62    let temp_config_path = std::env::temp_dir().join(format!(
63        "proxy-pilot-bench-{}-{seq}.json",
64        std::process::id()
65    ));
66    let serialized = serde_json::to_string(&bench_config).map_err(|err| {
67        PilotError::Core(format!("failed to serialize benchmark xray json: {err}"))
68    })?;
69    tokio::fs::write(&temp_config_path, serialized).await?;
70
71    let mut child = Command::new(binary_path)
72        .args(["run", "-c"])
73        .arg(&temp_config_path)
74        .stdin(Stdio::null())
75        .stdout(Stdio::null())
76        .stderr(Stdio::null())
77        .kill_on_drop(true)
78        .spawn()
79        .map_err(|err| {
80            let _ = std::fs::remove_file(&temp_config_path);
81            PilotError::Core(format!("failed to start temporary benchmark xray: {err}"))
82        })?;
83
84    if let Err(err) = wait_for_port_ready(first_port, &mut child, Duration::from_secs(3)).await {
85        let _ = child.kill().await;
86        let _ = child.wait().await;
87        let _ = tokio::fs::remove_file(&temp_config_path).await;
88        return Err(err);
89    }
90
91    Ok(Some(Box::new(XrayBenchmarkSession {
92        child: Some(child),
93        temp_config_path,
94        endpoints,
95    })))
96}
97
98/// Build an isolated Xray config JSON mapping one local SOCKS5 inbound port to each matched outbound.
99pub fn build_benchmark_config(
100    source_config: &Value,
101    outbound_tags: &[String],
102    ports: &[u16],
103) -> Result<(Value, HashMap<String, String>)> {
104    let outbounds = source_config
105        .get("outbounds")
106        .and_then(Value::as_array)
107        .ok_or_else(|| PilotError::Core("xray config missing 'outbounds' array".into()))?;
108
109    let mut inbounds = Vec::new();
110    let mut selected_outbounds = Vec::new();
111    let mut rules = Vec::new();
112    let mut endpoints = HashMap::new();
113
114    for (idx, tag) in outbound_tags.iter().enumerate() {
115        let Some(&port) = ports.get(idx) else {
116            break;
117        };
118        let Some(outbound) = outbounds
119            .iter()
120            .find(|item| item.get("tag").and_then(Value::as_str) == Some(tag.as_str()))
121        else {
122            continue;
123        };
124
125        let in_tag = format!("bench-in-{idx}");
126        inbounds.push(json!({
127            "tag": in_tag,
128            "listen": "127.0.0.1",
129            "port": port,
130            "protocol": "socks",
131            "settings": { "udp": false }
132        }));
133        selected_outbounds.push(outbound.clone());
134        rules.push(json!({
135            "type": "field",
136            "inboundTag": [in_tag],
137            "outboundTag": tag
138        }));
139        endpoints.insert(tag.clone(), format!("socks5h://127.0.0.1:{port}"));
140    }
141
142    let config = json!({
143        "log": { "loglevel": "none" },
144        "inbounds": inbounds,
145        "outbounds": selected_outbounds,
146        "routing": {
147            "domainStrategy": "AsIs",
148            "rules": rules
149        }
150    });
151
152    Ok((config, endpoints))
153}
154
155fn allocate_free_ports(count: usize) -> Result<Vec<u16>> {
156    let mut listeners = Vec::with_capacity(count);
157    let mut ports = Vec::with_capacity(count);
158    for _ in 0..count {
159        let listener = TcpListener::bind("127.0.0.1:0").map_err(|err| {
160            PilotError::Core(format!(
161                "failed to allocate ephemeral benchmark port: {err}"
162            ))
163        })?;
164        let port = listener
165            .local_addr()
166            .map_err(|err| PilotError::Core(format!("failed to read allocated port: {err}")))?
167            .port();
168        ports.push(port);
169        listeners.push(listener);
170    }
171    drop(listeners);
172    Ok(ports)
173}
174
175async fn wait_for_port_ready(port: u16, child: &mut Child, timeout: Duration) -> Result<()> {
176    let addr: SocketAddr = ([127, 0, 0, 1], port).into();
177    let deadline = Instant::now() + timeout;
178    while Instant::now() < deadline {
179        if let Ok(Some(status)) = child.try_wait() {
180            return Err(PilotError::Core(format!(
181                "temporary benchmark xray exited early with {status}"
182            )));
183        }
184        if TcpStream::connect_timeout(&addr, Duration::from_millis(80)).is_ok() {
185            return Ok(());
186        }
187        tokio::time::sleep(Duration::from_millis(50)).await;
188    }
189    Err(PilotError::Core(format!(
190        "temporary benchmark xray did not open port {port} within {}ms",
191        timeout.as_millis()
192    )))
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198
199    #[test]
200    fn builds_parallel_benchmark_config_for_matched_outbounds() {
201        let source = json!({
202            "outbounds": [
203                {"tag": "p1", "protocol": "vless"},
204                {"tag": "p2", "protocol": "vless"}
205            ]
206        });
207        let tags = vec!["p1".to_string(), "missing".to_string(), "p2".to_string()];
208        let ports = vec![20001, 20002, 20003];
209
210        let (cfg, endpoints) = build_benchmark_config(&source, &tags, &ports).unwrap();
211        assert_eq!(endpoints.len(), 2);
212        assert_eq!(
213            endpoints.get("p1").map(String::as_str),
214            Some("socks5h://127.0.0.1:20001")
215        );
216        assert_eq!(
217            endpoints.get("p2").map(String::as_str),
218            Some("socks5h://127.0.0.1:20003")
219        );
220        assert!(!endpoints.contains_key("missing"));
221        assert_eq!(cfg["inbounds"].as_array().unwrap().len(), 2);
222        assert_eq!(cfg["outbounds"].as_array().unwrap().len(), 2);
223        assert_eq!(cfg["routing"]["rules"].as_array().unwrap().len(), 2);
224    }
225}