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
95fn default_empty_profiles_reminder_secs() -> u64 {
96    300
97}
98
99#[derive(Debug, Clone, Serialize, Deserialize)]
100pub struct NotifyConfig {
101    pub cooldown_secs: u64,
102    #[serde(default = "default_empty_profiles_reminder_secs")]
103    pub empty_profiles_reminder_secs: u64,
104    pub bale: Option<BaleConfig>,
105}
106
107#[derive(Clone, Serialize, Deserialize)]
108pub struct BaleConfig {
109    pub enabled: bool,
110    pub bot_token: String,
111    pub chat_id: String,
112}
113
114impl fmt::Debug for BaleConfig {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        f.debug_struct("BaleConfig")
117            .field("enabled", &self.enabled)
118            .field("bot_token", &"[REDACTED]")
119            .field("chat_id", &self.chat_id)
120            .finish()
121    }
122}
123
124impl BaleConfig {
125    /// Resolve bot token from `BALE_BOT_TOKEN` env var if set, falling back to config.yaml.
126    pub fn resolved_token(&self) -> String {
127        if let Ok(token) = std::env::var("BALE_BOT_TOKEN")
128            && !token.trim().is_empty()
129        {
130            return token;
131        }
132        self.bot_token.clone()
133    }
134}
135
136impl AppConfig {
137    /// Load and parse configuration from a YAML file without requiring non-empty profiles.
138    pub async fn load_raw(path: &Path) -> Result<Self> {
139        let raw = tokio::fs::read_to_string(path).await.map_err(|err| {
140            PilotError::Config(format!("failed to read {}: {err}", path.display()))
141        })?;
142        Self::parse_yaml(&raw)
143    }
144
145    /// Load and validate configuration from a YAML file.
146    pub async fn load(path: &Path) -> Result<Self> {
147        let cfg = Self::load_raw(path).await?;
148        cfg.validate()?;
149        Ok(cfg)
150    }
151
152    pub fn parse_yaml(raw: &str) -> Result<Self> {
153        serde_yaml::from_str(raw).map_err(|err| PilotError::Config(format!("invalid yaml: {err}")))
154    }
155
156    pub fn validate(&self) -> Result<()> {
157        if self.profiles.is_empty() {
158            return Err(PilotError::Config(
159                "at least one profile is required".into(),
160            ));
161        }
162        if self.probe.targets.is_empty() {
163            return Err(PilotError::Config(
164                "at least one probe target is required".into(),
165            ));
166        }
167        if self.probe.failure_threshold == 0 || self.probe.recovery_threshold == 0 {
168            return Err(PilotError::Config(
169                "failure_threshold and recovery_threshold must be >= 1".into(),
170            ));
171        }
172        if self.probe.interval_secs == 0 || self.probe.timeout_secs == 0 {
173            return Err(PilotError::Config(
174                "interval_secs and timeout_secs must be >= 1".into(),
175            ));
176        }
177        if matches!(self.probe.max_latency_ms, Some(0)) {
178            return Err(PilotError::Config("max_latency_ms must be >= 1".into()));
179        }
180        Ok(())
181    }
182
183    /// Atomically write configuration back to disk.
184    pub async fn save_atomic(&self, path: &Path) -> Result<()> {
185        let parent = path.parent().ok_or_else(|| {
186            PilotError::Config(format!("config path has no parent: {}", path.display()))
187        })?;
188        let tmp_path = parent.join(format!(".config.{}.tmp", std::process::id()));
189        let yaml = serde_yaml::to_string(self)
190            .map_err(|err| PilotError::Config(format!("failed to serialize yaml: {err}")))?;
191        tokio::fs::write(&tmp_path, yaml).await?;
192        #[cfg(unix)]
193        {
194            use std::os::unix::fs::PermissionsExt;
195            tokio::fs::set_permissions(&tmp_path, std::fs::Permissions::from_mode(0o600)).await?;
196        }
197        tokio::fs::rename(&tmp_path, path).await?;
198        Ok(())
199    }
200
201    pub fn add_profile(&mut self, profile: ProfileConfig) -> Result<()> {
202        if self.profiles.iter().any(|p| p.name == profile.name) {
203            return Err(PilotError::Config(format!(
204                "profile '{}' already exists",
205                profile.name
206            )));
207        }
208        self.profiles.push(profile);
209        Ok(())
210    }
211
212    pub fn remove_profile(&mut self, name: &str) -> Result<()> {
213        let before = self.profiles.len();
214        self.profiles.retain(|p| p.name != name);
215        if self.profiles.len() == before {
216            return Err(PilotError::Config(format!("profile '{name}' not found")));
217        }
218        Ok(())
219    }
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    #[test]
227    fn parses_example_config() {
228        let raw = include_str!("../../config.example.yaml");
229        let cfg = AppConfig::parse_yaml(raw).unwrap();
230        cfg.validate().unwrap();
231        assert_eq!(cfg.core.kind, "xray");
232        assert_eq!(cfg.profiles.len(), 2);
233        assert_eq!(cfg.probe.targets.len(), 3);
234    }
235
236    #[test]
237    fn rejects_empty_profiles() {
238        let raw = include_str!("../../config.example.yaml");
239        let mut cfg = AppConfig::parse_yaml(raw).unwrap();
240        cfg.profiles.clear();
241        assert!(cfg.validate().is_err());
242    }
243
244    #[tokio::test]
245    async fn load_raw_allows_empty_profiles_and_supports_adding_first_profile() {
246        let dir = tempfile::TempDir::new().unwrap();
247        let cfg_path = dir.path().join("config.yaml");
248        let raw = include_str!("../../config.example.yaml");
249        let mut cfg = AppConfig::parse_yaml(raw).unwrap();
250        cfg.profiles.clear();
251        cfg.save_atomic(&cfg_path).await.unwrap();
252
253        assert!(AppConfig::load(&cfg_path).await.is_err());
254
255        let mut loaded = AppConfig::load_raw(&cfg_path).await.unwrap();
256        assert!(loaded.profiles.is_empty());
257        loaded
258            .add_profile(ProfileConfig {
259                name: "first-node".into(),
260                outbound_tag: "vless-first-node".into(),
261                priority: 1,
262            })
263            .unwrap();
264        loaded.save_atomic(&cfg_path).await.unwrap();
265
266        let validated = AppConfig::load(&cfg_path).await.unwrap();
267        assert_eq!(validated.profiles.len(), 1);
268        assert_eq!(validated.profiles[0].name, "first-node");
269    }
270
271    #[test]
272    fn add_and_remove_profile_handles_duplicates_and_missing() {
273        let raw = include_str!("../../config.example.yaml");
274        let mut cfg = AppConfig::parse_yaml(raw).unwrap();
275        let dup = cfg.profiles[0].clone();
276        assert!(cfg.add_profile(dup).is_err());
277        assert!(cfg.remove_profile("non-existent").is_err());
278
279        let name = cfg.profiles[0].name.clone();
280        cfg.remove_profile(&name).unwrap();
281        assert!(!cfg.profiles.iter().any(|p| p.name == name));
282    }
283
284    #[test]
285    fn bale_config_debug_redacts_bot_token() {
286        let bale = BaleConfig {
287            enabled: true,
288            bot_token: "123456:SECRET_TOKEN".into(),
289            chat_id: "99999".into(),
290        };
291        let debug_str = format!("{bale:?}");
292        assert!(!debug_str.contains("SECRET_TOKEN"));
293        assert!(debug_str.contains("[REDACTED]"));
294    }
295}