pub mod benchmark;
pub mod vless;
use std::path::{Path, PathBuf};
use std::time::Duration;
use async_trait::async_trait;
use serde_json::Value;
use tokio::process::Command;
use crate::core::{BenchmarkSession, ProxyCore};
use crate::error::{PilotError, Result};
pub struct XrayCore {
pub binary_path: PathBuf,
pub config_path: PathBuf,
pub service_name: String,
}
impl XrayCore {
pub fn new(
binary_path: impl Into<PathBuf>,
config_path: impl Into<PathBuf>,
service_name: String,
) -> Self {
Self {
binary_path: binary_path.into(),
config_path: config_path.into(),
service_name,
}
}
async fn read_config_json(&self) -> Result<Value> {
let raw = tokio::fs::read_to_string(&self.config_path)
.await
.map_err(|err| {
PilotError::Core(format!(
"failed to read xray config {}: {err}",
self.config_path.display()
))
})?;
serde_json::from_str(&raw)
.map_err(|err| PilotError::Core(format!("invalid xray json: {err}")))
}
async fn write_config_atomic(path: &Path, value: &Value) -> Result<()> {
let parent = path.parent().ok_or_else(|| {
PilotError::Core(format!("config path has no parent: {}", path.display()))
})?;
let tmp_path = parent.join(format!(".{}.tmp", std::process::id()));
let serialized = serde_json::to_string_pretty(value)
.map_err(|err| PilotError::Core(format!("failed to serialize xray json: {err}")))?;
tokio::fs::write(&tmp_path, serialized).await?;
tokio::fs::rename(&tmp_path, path).await?;
Ok(())
}
pub async fn upsert_outbound(&self, tag: &str, outbound: Value) -> Result<()> {
let mut json = self.read_config_json().await?;
let outbounds = json
.get_mut("outbounds")
.and_then(Value::as_array_mut)
.ok_or_else(|| PilotError::Core("xray config missing 'outbounds' array".into()))?;
if let Some(existing) = outbounds
.iter_mut()
.find(|item| item.get("tag").and_then(Value::as_str) == Some(tag))
{
*existing = outbound;
} else {
outbounds.push(outbound);
}
Self::write_config_atomic(&self.config_path, &json).await
}
}
#[async_trait]
impl ProxyCore for XrayCore {
fn name(&self) -> &'static str {
"xray"
}
async fn is_installed(&self) -> bool {
tokio::fs::try_exists(&self.binary_path)
.await
.unwrap_or(false)
}
async fn install(&self) -> Result<()> {
Err(PilotError::Core(
"automatic xray binary downloader is planned for the next milestone".into(),
))
}
async fn active_profile(&self) -> Result<Option<String>> {
let json = self.read_config_json().await?;
let tag = json
.get("outbounds")
.and_then(Value::as_array)
.and_then(|arr| arr.first())
.and_then(|item| item.get("tag"))
.and_then(Value::as_str)
.map(ToString::to_string);
Ok(tag)
}
async fn switch_profile(&self, outbound_tag: &str) -> Result<()> {
let mut json = self.read_config_json().await?;
let outbounds = json
.get_mut("outbounds")
.and_then(Value::as_array_mut)
.ok_or_else(|| PilotError::Core("xray config missing 'outbounds' array".into()))?;
let pos = outbounds
.iter()
.position(|item| item.get("tag").and_then(Value::as_str) == Some(outbound_tag))
.ok_or_else(|| {
PilotError::Core(format!(
"outbound tag '{outbound_tag}' not found in xray config"
))
})?;
if pos > 0 {
let selected = outbounds.remove(pos);
outbounds.insert(0, selected);
Self::write_config_atomic(&self.config_path, &json).await?;
}
Ok(())
}
async fn reload(&self) -> Result<()> {
#[cfg(target_os = "linux")]
{
let _ = Command::new("systemctl")
.args(["reset-failed", &self.service_name])
.status()
.await;
let status = Command::new("systemctl")
.args(["reload-or-restart", &self.service_name])
.status()
.await
.map_err(|err| PilotError::Core(format!("failed to invoke systemctl: {err}")))?;
if !status.success() {
return Err(PilotError::Core(format!(
"systemctl reload-or-restart {} exited with {status}",
self.service_name
)));
}
tokio::time::sleep(Duration::from_millis(400)).await;
return Ok(());
}
#[cfg(target_os = "macos")]
{
let status = Command::new("brew")
.args(["services", "restart", &self.service_name])
.status()
.await
.map_err(|err| {
PilotError::Core(format!("failed to invoke brew services: {err}"))
})?;
if !status.success() {
return Err(PilotError::Core(format!(
"brew services restart {} exited with {status}",
self.service_name
)));
}
tokio::time::sleep(Duration::from_millis(400)).await;
return Ok(());
}
#[cfg(target_os = "windows")]
{
let _ = Command::new("taskkill")
.args(["/F", "/IM", "xray.exe"])
.status()
.await;
Command::new(&self.binary_path)
.args(["run", "-c"])
.arg(&self.config_path)
.spawn()
.map_err(|err| PilotError::Core(format!("failed to start xray.exe: {err}")))?;
tokio::time::sleep(Duration::from_millis(400)).await;
return Ok(());
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
Err(PilotError::Core(
"unsupported operating system for xray reload".into(),
))
}
async fn start_benchmark_session(
&self,
outbound_tags: &[String],
) -> Result<Option<Box<dyn BenchmarkSession>>> {
if outbound_tags.is_empty() || !self.is_installed().await {
return Ok(None);
}
let source_config = self.read_config_json().await?;
benchmark::start_xray_benchmark_session(&self.binary_path, &source_config, outbound_tags)
.await
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[tokio::test]
async fn switches_outbound_atomically_and_reads_active_profile() {
let dir = TempDir::new().unwrap();
let cfg_path = dir.path().join("config.json");
let sample = r#"{
"outbounds": [
{"tag": "proxy-de-1", "protocol": "vless"},
{"tag": "proxy-fi-2", "protocol": "vless"}
]
}"#;
tokio::fs::write(&cfg_path, sample).await.unwrap();
let core = XrayCore::new("/usr/local/bin/xray", &cfg_path, "xray".into());
assert_eq!(
core.active_profile().await.unwrap().as_deref(),
Some("proxy-de-1")
);
core.switch_profile("proxy-fi-2").await.unwrap();
assert_eq!(
core.active_profile().await.unwrap().as_deref(),
Some("proxy-fi-2")
);
}
#[tokio::test]
async fn returns_error_for_unknown_outbound_tag() {
let dir = TempDir::new().unwrap();
let cfg_path = dir.path().join("config.json");
tokio::fs::write(&cfg_path, r#"{"outbounds": [{"tag": "proxy-de-1"}]}"#)
.await
.unwrap();
let core = XrayCore::new("/usr/local/bin/xray", &cfg_path, "xray".into());
assert!(core.switch_profile("missing-tag").await.is_err());
}
}