use std::collections::HashMap;
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use async_trait::async_trait;
use serde_json::{Value, json};
use tokio::process::{Child, Command};
use crate::core::BenchmarkSession;
use crate::error::{PilotError, Result};
static BENCH_COUNTER: AtomicU64 = AtomicU64::new(1);
pub struct XrayBenchmarkSession {
child: Option<Child>,
temp_config_path: PathBuf,
endpoints: HashMap<String, String>,
}
impl Drop for XrayBenchmarkSession {
fn drop(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.start_kill();
}
let _ = std::fs::remove_file(&self.temp_config_path);
}
}
#[async_trait]
impl BenchmarkSession for XrayBenchmarkSession {
fn endpoints(&self) -> &HashMap<String, String> {
&self.endpoints
}
async fn shutdown(mut self: Box<Self>) -> Result<()> {
if let Some(mut child) = self.child.take() {
let _ = child.kill().await;
let _ = child.wait().await;
}
let _ = tokio::fs::remove_file(&self.temp_config_path).await;
Ok(())
}
}
pub async fn start_xray_benchmark_session(
binary_path: &Path,
source_config: &Value,
outbound_tags: &[String],
) -> Result<Option<Box<dyn BenchmarkSession>>> {
let ports = allocate_free_ports(outbound_tags.len())?;
let (bench_config, endpoints) = build_benchmark_config(source_config, outbound_tags, &ports)?;
if endpoints.is_empty() {
return Ok(None);
}
let first_port = ports[0];
let seq = BENCH_COUNTER.fetch_add(1, Ordering::Relaxed);
let temp_config_path = std::env::temp_dir().join(format!(
"proxy-pilot-bench-{}-{seq}.json",
std::process::id()
));
let serialized = serde_json::to_string(&bench_config).map_err(|err| {
PilotError::Core(format!("failed to serialize benchmark xray json: {err}"))
})?;
tokio::fs::write(&temp_config_path, serialized).await?;
let mut child = Command::new(binary_path)
.args(["run", "-c"])
.arg(&temp_config_path)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.map_err(|err| {
let _ = std::fs::remove_file(&temp_config_path);
PilotError::Core(format!("failed to start temporary benchmark xray: {err}"))
})?;
if let Err(err) = wait_for_port_ready(first_port, &mut child, Duration::from_secs(3)).await {
let _ = child.kill().await;
let _ = child.wait().await;
let _ = tokio::fs::remove_file(&temp_config_path).await;
return Err(err);
}
Ok(Some(Box::new(XrayBenchmarkSession {
child: Some(child),
temp_config_path,
endpoints,
})))
}
pub fn build_benchmark_config(
source_config: &Value,
outbound_tags: &[String],
ports: &[u16],
) -> Result<(Value, HashMap<String, String>)> {
let outbounds = source_config
.get("outbounds")
.and_then(Value::as_array)
.ok_or_else(|| PilotError::Core("xray config missing 'outbounds' array".into()))?;
let mut inbounds = Vec::new();
let mut selected_outbounds = Vec::new();
let mut rules = Vec::new();
let mut endpoints = HashMap::new();
for (idx, tag) in outbound_tags.iter().enumerate() {
let Some(&port) = ports.get(idx) else {
break;
};
let Some(outbound) = outbounds
.iter()
.find(|item| item.get("tag").and_then(Value::as_str) == Some(tag.as_str()))
else {
continue;
};
let in_tag = format!("bench-in-{idx}");
inbounds.push(json!({
"tag": in_tag,
"listen": "127.0.0.1",
"port": port,
"protocol": "socks",
"settings": { "udp": false }
}));
selected_outbounds.push(outbound.clone());
rules.push(json!({
"type": "field",
"inboundTag": [in_tag],
"outboundTag": tag
}));
endpoints.insert(tag.clone(), format!("socks5h://127.0.0.1:{port}"));
}
let config = json!({
"log": { "loglevel": "none" },
"inbounds": inbounds,
"outbounds": selected_outbounds,
"routing": {
"domainStrategy": "AsIs",
"rules": rules
}
});
Ok((config, endpoints))
}
fn allocate_free_ports(count: usize) -> Result<Vec<u16>> {
let mut listeners = Vec::with_capacity(count);
let mut ports = Vec::with_capacity(count);
for _ in 0..count {
let listener = TcpListener::bind("127.0.0.1:0").map_err(|err| {
PilotError::Core(format!(
"failed to allocate ephemeral benchmark port: {err}"
))
})?;
let port = listener
.local_addr()
.map_err(|err| PilotError::Core(format!("failed to read allocated port: {err}")))?
.port();
ports.push(port);
listeners.push(listener);
}
drop(listeners);
Ok(ports)
}
async fn wait_for_port_ready(port: u16, child: &mut Child, timeout: Duration) -> Result<()> {
let addr: SocketAddr = ([127, 0, 0, 1], port).into();
let deadline = Instant::now() + timeout;
while Instant::now() < deadline {
if let Ok(Some(status)) = child.try_wait() {
return Err(PilotError::Core(format!(
"temporary benchmark xray exited early with {status}"
)));
}
if TcpStream::connect_timeout(&addr, Duration::from_millis(80)).is_ok() {
return Ok(());
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
Err(PilotError::Core(format!(
"temporary benchmark xray did not open port {port} within {}ms",
timeout.as_millis()
)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builds_parallel_benchmark_config_for_matched_outbounds() {
let source = json!({
"outbounds": [
{"tag": "p1", "protocol": "vless"},
{"tag": "p2", "protocol": "vless"}
]
});
let tags = vec!["p1".to_string(), "missing".to_string(), "p2".to_string()];
let ports = vec![20001, 20002, 20003];
let (cfg, endpoints) = build_benchmark_config(&source, &tags, &ports).unwrap();
assert_eq!(endpoints.len(), 2);
assert_eq!(
endpoints.get("p1").map(String::as_str),
Some("socks5h://127.0.0.1:20001")
);
assert_eq!(
endpoints.get("p2").map(String::as_str),
Some("socks5h://127.0.0.1:20003")
);
assert!(!endpoints.contains_key("missing"));
assert_eq!(cfg["inbounds"].as_array().unwrap().len(), 2);
assert_eq!(cfg["outbounds"].as_array().unwrap().len(), 2);
assert_eq!(cfg["routing"]["rules"].as_array().unwrap().len(), 2);
}
}