Skip to main content

proxy_pilot/config/
mod.rs

1use std::fmt;
2use std::path::Path;
3
4use serde::{Deserialize, Serialize};
5
6use crate::error::{PilotError, Result};
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct AppConfig {
10    pub core: CoreConfig,
11    #[serde(default)]
12    pub routing: RoutingConfig,
13    pub profiles: Vec<ProfileConfig>,
14    pub probe: ProbeConfig,
15    pub notify: NotifyConfig,
16}
17
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct RoutingConfig {
20    /// "whitelist" (recommended: only listed domains use proxy, everything else goes direct)
21    /// or "bypass_ir" (everything uses proxy except geosite:ir / geoip:ir).
22    #[serde(default = "default_routing_mode")]
23    pub mode: String,
24    #[serde(default)]
25    pub whitelist_domains: Vec<String>,
26}
27
28fn default_routing_mode() -> String {
29    "whitelist".to_string()
30}
31
32impl Default for RoutingConfig {
33    fn default() -> Self {
34        Self {
35            mode: default_routing_mode(),
36            whitelist_domains: Vec::new(),
37        }
38    }
39}
40
41#[derive(Debug, Clone, Serialize, Deserialize)]
42pub struct CoreConfig {
43    pub kind: String,
44    pub binary_path: String,
45    pub config_path: String,
46    pub service_name: String,
47    pub local_proxy: String,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51pub struct ProfileConfig {
52    pub name: String,
53    pub outbound_tag: String,
54    pub priority: u32,
55}
56
57#[derive(Debug, Clone, Serialize, Deserialize)]
58pub struct ProbeConfig {
59    pub interval_secs: u64,
60    pub timeout_secs: u64,
61    pub failure_threshold: u32,
62    pub recovery_threshold: u32,
63    /// Optional latency ceiling in milliseconds; slower responses trigger failover.
64    #[serde(default)]
65    pub max_latency_ms: Option<u64>,
66    /// Periodic background re-benchmark interval in seconds (0 disables it).
67    #[serde(default = "default_benchmark_interval_secs")]
68    pub benchmark_interval_secs: u64,
69    /// Remove profiles that stay continuously unhealthy for this many hours (0 disables it).
70    #[serde(default = "default_auto_prune_after_hours")]
71    pub auto_prune_after_hours: u64,
72    /// Optional direct (non-proxied) URL used to verify the host server's own internet
73    /// connectivity before auto-pruning dead profiles (e.g., a local/domestic site).
74    #[serde(default)]
75    pub direct_check_url: Option<String>,
76    pub targets: Vec<ProbeTarget>,
77}
78
79fn default_benchmark_interval_secs() -> u64 {
80    900
81}
82
83fn default_auto_prune_after_hours() -> u64 {
84    24
85}
86
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct ProbeTarget {
89    pub name: String,
90    pub url: String,
91    pub expected_status: Vec<u16>,
92    pub blocked_status: Vec<u16>,
93}
94
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct NotifyConfig {
97    pub cooldown_secs: u64,
98    pub bale: Option<BaleConfig>,
99}
100
101#[derive(Clone, Serialize, Deserialize)]
102pub struct BaleConfig {
103    pub enabled: bool,
104    pub bot_token: String,
105    pub chat_id: String,
106}
107
108impl fmt::Debug for BaleConfig {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        f.debug_struct("BaleConfig")
111            .field("enabled", &self.enabled)
112            .field("bot_token", &"[REDACTED]")
113            .field("chat_id", &self.chat_id)
114            .finish()
115    }
116}
117
118impl BaleConfig {
119    /// Resolve bot token from `BALE_BOT_TOKEN` env var if set, falling back to config.yaml.
120    pub fn resolved_token(&self) -> String {
121        if let Ok(token) = std::env::var("BALE_BOT_TOKEN")
122            && !token.trim().is_empty()
123        {
124            return token;
125        }
126        self.bot_token.clone()
127    }
128}
129
130impl AppConfig {
131    /// Load and parse configuration from a YAML file without requiring non-empty profiles.
132    pub async fn load_raw(path: &Path) -> Result<Self> {
133        let raw = tokio::fs::read_to_string(path).await.map_err(|err| {
134            PilotError::Config(format!("failed to read {}: {err}", path.display()))
135        })?;
136        Self::parse_yaml(&raw)
137    }
138
139    /// Load and validate configuration from a YAML file.
140    pub async fn load(path: &Path) -> Result<Self> {
141        let cfg = Self::load_raw(path).await?;
142        cfg.validate()?;
143        Ok(cfg)
144    }
145
146    pub fn parse_yaml(raw: &str) -> Result<Self> {
147        serde_yaml::from_str(raw).map_err(|err| PilotError::Config(format!("invalid yaml: {err}")))
148    }
149
150    pub fn validate(&self) -> Result<()> {
151        if self.profiles.is_empty() {
152            return Err(PilotError::Config(
153                "at least one profile is required".into(),
154            ));
155        }
156        if self.probe.targets.is_empty() {
157            return Err(PilotError::Config(
158                "at least one probe target is required".into(),
159            ));
160        }
161        if self.probe.failure_threshold == 0 || self.probe.recovery_threshold == 0 {
162            return Err(PilotError::Config(
163                "failure_threshold and recovery_threshold must be >= 1".into(),
164            ));
165        }
166        if self.probe.interval_secs == 0 || self.probe.timeout_secs == 0 {
167            return Err(PilotError::Config(
168                "interval_secs and timeout_secs must be >= 1".into(),
169            ));
170        }
171        if matches!(self.probe.max_latency_ms, Some(0)) {
172            return Err(PilotError::Config("max_latency_ms must be >= 1".into()));
173        }
174        Ok(())
175    }
176
177    /// Atomically write configuration back to disk.
178    pub async fn save_atomic(&self, path: &Path) -> Result<()> {
179        let parent = path.parent().ok_or_else(|| {
180            PilotError::Config(format!("config path has no parent: {}", path.display()))
181        })?;
182        let tmp_path = parent.join(format!(".config.{}.tmp", std::process::id()));
183        let yaml = serde_yaml::to_string(self)
184            .map_err(|err| PilotError::Config(format!("failed to serialize yaml: {err}")))?;
185        tokio::fs::write(&tmp_path, yaml).await?;
186        #[cfg(unix)]
187        {
188            use std::os::unix::fs::PermissionsExt;
189            tokio::fs::set_permissions(&tmp_path, std::fs::Permissions::from_mode(0o600)).await?;
190        }
191        tokio::fs::rename(&tmp_path, path).await?;
192        Ok(())
193    }
194
195    pub fn add_profile(&mut self, profile: ProfileConfig) -> Result<()> {
196        if self.profiles.iter().any(|p| p.name == profile.name) {
197            return Err(PilotError::Config(format!(
198                "profile '{}' already exists",
199                profile.name
200            )));
201        }
202        self.profiles.push(profile);
203        Ok(())
204    }
205
206    pub fn remove_profile(&mut self, name: &str) -> Result<()> {
207        let before = self.profiles.len();
208        self.profiles.retain(|p| p.name != name);
209        if self.profiles.len() == before {
210            return Err(PilotError::Config(format!("profile '{name}' not found")));
211        }
212        Ok(())
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219
220    #[test]
221    fn parses_example_config() {
222        let raw = include_str!("../../config.example.yaml");
223        let cfg = AppConfig::parse_yaml(raw).unwrap();
224        cfg.validate().unwrap();
225        assert_eq!(cfg.core.kind, "xray");
226        assert_eq!(cfg.profiles.len(), 2);
227        assert_eq!(cfg.probe.targets.len(), 3);
228    }
229
230    #[test]
231    fn rejects_empty_profiles() {
232        let raw = include_str!("../../config.example.yaml");
233        let mut cfg = AppConfig::parse_yaml(raw).unwrap();
234        cfg.profiles.clear();
235        assert!(cfg.validate().is_err());
236    }
237
238    #[tokio::test]
239    async fn load_raw_allows_empty_profiles_and_supports_adding_first_profile() {
240        let dir = tempfile::TempDir::new().unwrap();
241        let cfg_path = dir.path().join("config.yaml");
242        let raw = include_str!("../../config.example.yaml");
243        let mut cfg = AppConfig::parse_yaml(raw).unwrap();
244        cfg.profiles.clear();
245        cfg.save_atomic(&cfg_path).await.unwrap();
246
247        assert!(AppConfig::load(&cfg_path).await.is_err());
248
249        let mut loaded = AppConfig::load_raw(&cfg_path).await.unwrap();
250        assert!(loaded.profiles.is_empty());
251        loaded
252            .add_profile(ProfileConfig {
253                name: "first-node".into(),
254                outbound_tag: "vless-first-node".into(),
255                priority: 1,
256            })
257            .unwrap();
258        loaded.save_atomic(&cfg_path).await.unwrap();
259
260        let validated = AppConfig::load(&cfg_path).await.unwrap();
261        assert_eq!(validated.profiles.len(), 1);
262        assert_eq!(validated.profiles[0].name, "first-node");
263    }
264
265    #[test]
266    fn add_and_remove_profile_handles_duplicates_and_missing() {
267        let raw = include_str!("../../config.example.yaml");
268        let mut cfg = AppConfig::parse_yaml(raw).unwrap();
269        let dup = cfg.profiles[0].clone();
270        assert!(cfg.add_profile(dup).is_err());
271        assert!(cfg.remove_profile("non-existent").is_err());
272
273        let name = cfg.profiles[0].name.clone();
274        cfg.remove_profile(&name).unwrap();
275        assert!(!cfg.profiles.iter().any(|p| p.name == name));
276    }
277
278    #[test]
279    fn bale_config_debug_redacts_bot_token() {
280        let bale = BaleConfig {
281            enabled: true,
282            bot_token: "123456:SECRET_TOKEN".into(),
283            chat_id: "99999".into(),
284        };
285        let debug_str = format!("{bale:?}");
286        assert!(!debug_str.contains("SECRET_TOKEN"));
287        assert!(debug_str.contains("[REDACTED]"));
288    }
289}