smirrors 0.1.0

Automatic mirror list updater for Linux distributions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

use crate::utils::SMirrorsError;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    #[serde(default)]
    pub general: GeneralConfig,
    #[serde(default)]
    pub testing: TestingConfig,
    #[serde(default)]
    pub distro: DistroConfig,
    #[serde(default)]
    pub static_mirrors: HashMap<String, String>,
    #[serde(default)]
    pub logging: LoggingConfig,
    #[serde(default)]
    pub notifications: NotificationConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeneralConfig {
    #[serde(default = "default_interval")]
    pub update_interval: String,
    #[serde(default = "default_true")]
    pub auto_update: bool,
    #[serde(default = "default_concurrent")]
    pub concurrent_tests: usize,
    #[serde(default = "default_timeout")]
    pub timeout: u64,
    #[serde(default = "default_retries")]
    pub retries: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestingConfig {
    #[serde(default = "default_speed_weight")]
    pub speed_weight: f64,
    #[serde(default = "default_latency_weight")]
    pub latency_weight: f64,
    #[serde(default = "default_test_size")]
    pub test_file_size: String,
    #[serde(default = "default_max_mirrors")]
    pub max_mirrors: usize,
    #[serde(default)]
    pub country_preference: Vec<String>,
    #[serde(default = "default_min_score")]
    pub min_score: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DistroConfig {
    #[serde(default)]
    pub auto_detect: bool,
    pub override_distro: Option<String>,
    #[serde(default)]
    pub preserve_comments: bool,
    #[serde(default = "default_true")]
    pub create_backup: bool,
    #[serde(default = "default_backup_count")]
    pub backup_count: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
    #[serde(default = "default_log_level")]
    pub level: String,
    #[serde(default = "default_log_format")]
    pub format: String,
    pub file: Option<PathBuf>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotificationConfig {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default)]
    pub on_success: bool,
    #[serde(default = "default_true")]
    pub on_failure: bool,
}

// Default value functions
fn default_interval() -> String {
    "1h".to_string()
}

fn default_true() -> bool {
    true
}

fn default_concurrent() -> usize {
    10
}

fn default_timeout() -> u64 {
    10
}

fn default_retries() -> u32 {
    3
}

fn default_speed_weight() -> f64 {
    0.7
}

fn default_latency_weight() -> f64 {
    0.3
}

fn default_test_size() -> String {
    "1MB".to_string()
}

fn default_max_mirrors() -> usize {
    5
}

fn default_min_score() -> f64 {
    0.3
}

fn default_backup_count() -> usize {
    5
}

fn default_log_level() -> String {
    "info".to_string()
}

fn default_log_format() -> String {
    "pretty".to_string()
}

impl Default for GeneralConfig {
    fn default() -> Self {
        Self {
            update_interval: default_interval(),
            auto_update: default_true(),
            concurrent_tests: default_concurrent(),
            timeout: default_timeout(),
            retries: default_retries(),
        }
    }
}

impl Default for TestingConfig {
    fn default() -> Self {
        Self {
            speed_weight: default_speed_weight(),
            latency_weight: default_latency_weight(),
            test_file_size: default_test_size(),
            max_mirrors: default_max_mirrors(),
            country_preference: Vec::new(),
            min_score: default_min_score(),
        }
    }
}

impl Default for DistroConfig {
    fn default() -> Self {
        Self {
            auto_detect: true,
            override_distro: None,
            preserve_comments: true,
            create_backup: default_true(),
            backup_count: default_backup_count(),
        }
    }
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: default_log_level(),
            format: default_log_format(),
            file: None,
        }
    }
}

impl Default for NotificationConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            on_success: false,
            on_failure: default_true(),
        }
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            general: GeneralConfig::default(),
            testing: TestingConfig::default(),
            distro: DistroConfig::default(),
            static_mirrors: HashMap::new(),
            logging: LoggingConfig::default(),
            notifications: NotificationConfig::default(),
        }
    }
}

impl Config {
    /// Load configuration from file or create default
    pub fn load() -> Result<Self> {
        let config_path = Self::config_path()?;

        if config_path.exists() {
            let content = std::fs::read_to_string(&config_path)
                .context(format!("Failed to read config file at {:?}", config_path))?;
            let config: Config = toml::from_str(&content)
                .context("Failed to parse configuration file")?;
            config.validate()?;
            Ok(config)
        } else {
            let config = Self::default();
            config.save()?;
            Ok(config)
        }
    }

    /// Load configuration from a specific path
    pub fn load_from(path: &PathBuf) -> Result<Self> {
        if !path.exists() {
            return Err(SMirrorsError::ConfigNotFound(
                path.display().to_string(),
            )
            .into());
        }

        let content = std::fs::read_to_string(path)
            .context(format!("Failed to read config file at {:?}", path))?;
        let config: Config = toml::from_str(&content)
            .context("Failed to parse configuration file")?;
        config.validate()?;
        Ok(config)
    }

    /// Save configuration to file
    pub fn save(&self) -> Result<()> {
        self.validate()?;

        let config_path = Self::config_path()?;

        // Ensure parent directory exists
        if let Some(parent) = config_path.parent() {
            std::fs::create_dir_all(parent)
                .context("Failed to create config directory")?;
        }

        // Write to temporary file first for atomic operation
        let temp_path = config_path.with_extension("toml.tmp");
        let content = toml::to_string_pretty(self)
            .context("Failed to serialize configuration")?;

        std::fs::write(&temp_path, content)
            .context("Failed to write temporary config file")?;

        // Atomic rename
        std::fs::rename(&temp_path, &config_path)
            .context("Failed to save configuration file")?;

        Ok(())
    }

    /// Save configuration to a specific path
    pub fn save_to(&self, path: &PathBuf) -> Result<()> {
        self.validate()?;

        // Ensure parent directory exists
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .context("Failed to create config directory")?;
        }

        let content = toml::to_string_pretty(self)
            .context("Failed to serialize configuration")?;

        std::fs::write(path, content)
            .context("Failed to write configuration file")?;

        Ok(())
    }

    /// Get configuration file path based on privileges
    pub fn config_path() -> Result<PathBuf> {
        if nix::unistd::geteuid().is_root() {
            Ok(PathBuf::from("/etc/smirrors/config.toml"))
        } else {
            let dirs = directories::ProjectDirs::from("com", "smirrors", "smirrors")
                .context("Could not determine config directory")?;
            Ok(dirs.config_dir().join("config.toml"))
        }
    }

    /// Get data directory path based on privileges
    pub fn data_dir() -> Result<PathBuf> {
        if nix::unistd::geteuid().is_root() {
            Ok(PathBuf::from("/var/lib/smirrors"))
        } else {
            let dirs = directories::ProjectDirs::from("com", "smirrors", "smirrors")
                .context("Could not determine data directory")?;
            Ok(dirs.data_local_dir().to_path_buf())
        }
    }

    /// Get cache directory path
    pub fn cache_dir() -> Result<PathBuf> {
        if nix::unistd::geteuid().is_root() {
            Ok(PathBuf::from("/var/cache/smirrors"))
        } else {
            let dirs = directories::ProjectDirs::from("com", "smirrors", "smirrors")
                .context("Could not determine cache directory")?;
            Ok(dirs.cache_dir().to_path_buf())
        }
    }

    /// Validate configuration values
    pub fn validate(&self) -> Result<()> {
        // Validate weights sum to reasonable value
        let weight_sum = self.testing.speed_weight + self.testing.latency_weight;
        if (weight_sum - 1.0).abs() > 0.01 {
            return Err(SMirrorsError::ConfigError(
                "Speed and latency weights should sum to 1.0".to_string(),
            )
            .into());
        }

        // Validate weights are positive
        if self.testing.speed_weight < 0.0 || self.testing.latency_weight < 0.0 {
            return Err(SMirrorsError::ConfigError(
                "Weights must be non-negative".to_string(),
            )
            .into());
        }

        // Validate min_score is between 0 and 1
        if self.testing.min_score < 0.0 || self.testing.min_score > 1.0 {
            return Err(SMirrorsError::ConfigError(
                "Min score must be between 0.0 and 1.0".to_string(),
            )
            .into());
        }

        // Validate concurrent tests is reasonable
        if self.general.concurrent_tests == 0 || self.general.concurrent_tests > 100 {
            return Err(SMirrorsError::ConfigError(
                "Concurrent tests must be between 1 and 100".to_string(),
            )
            .into());
        }

        // Validate max_mirrors is reasonable
        if self.testing.max_mirrors == 0 || self.testing.max_mirrors > 50 {
            return Err(SMirrorsError::ConfigError(
                "Max mirrors must be between 1 and 50".to_string(),
            )
            .into());
        }

        // Validate timeout is reasonable
        if self.general.timeout == 0 || self.general.timeout > 300 {
            return Err(SMirrorsError::ConfigError(
                "Timeout must be between 1 and 300 seconds".to_string(),
            )
            .into());
        }

        // Validate update interval can be parsed
        crate::utils::parse_duration(&self.general.update_interval)
            .context("Invalid update interval format")?;

        // Validate test file size can be parsed
        crate::utils::parse_size(&self.testing.test_file_size)
            .context("Invalid test file size format")?;

        Ok(())
    }

    /// Set a configuration value by key path (e.g., "general.timeout")
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
        let parts: Vec<&str> = key.split('.').collect();
        if parts.len() != 2 {
            return Err(SMirrorsError::ConfigError(
                "Key must be in format 'section.key'".to_string(),
            )
            .into());
        }

        match (parts[0], parts[1]) {
            ("general", "update_interval") => {
                crate::utils::parse_duration(value)?;
                self.general.update_interval = value.to_string();
            }
            ("general", "auto_update") => {
                self.general.auto_update = value.parse()
                    .context("Value must be true or false")?;
            }
            ("general", "concurrent_tests") => {
                self.general.concurrent_tests = value.parse()
                    .context("Value must be a number")?;
            }
            ("general", "timeout") => {
                self.general.timeout = value.parse()
                    .context("Value must be a number")?;
            }
            ("general", "retries") => {
                self.general.retries = value.parse()
                    .context("Value must be a number")?;
            }
            ("testing", "speed_weight") => {
                self.testing.speed_weight = value.parse()
                    .context("Value must be a number")?;
            }
            ("testing", "latency_weight") => {
                self.testing.latency_weight = value.parse()
                    .context("Value must be a number")?;
            }
            ("testing", "test_file_size") => {
                crate::utils::parse_size(value)?;
                self.testing.test_file_size = value.to_string();
            }
            ("testing", "max_mirrors") => {
                self.testing.max_mirrors = value.parse()
                    .context("Value must be a number")?;
            }
            ("testing", "min_score") => {
                self.testing.min_score = value.parse()
                    .context("Value must be a number")?;
            }
            ("logging", "level") => {
                self.logging.level = value.to_string();
            }
            ("logging", "format") => {
                self.logging.format = value.to_string();
            }
            _ => {
                return Err(SMirrorsError::ConfigError(
                    format!("Unknown configuration key: {}", key),
                )
                .into());
            }
        }

        self.validate()?;
        Ok(())
    }

    /// Get a configuration value by key path
    pub fn get(&self, key: &str) -> Option<String> {
        let parts: Vec<&str> = key.split('.').collect();
        if parts.len() != 2 {
            return None;
        }

        match (parts[0], parts[1]) {
            ("general", "update_interval") => Some(self.general.update_interval.clone()),
            ("general", "auto_update") => Some(self.general.auto_update.to_string()),
            ("general", "concurrent_tests") => Some(self.general.concurrent_tests.to_string()),
            ("general", "timeout") => Some(self.general.timeout.to_string()),
            ("general", "retries") => Some(self.general.retries.to_string()),
            ("testing", "speed_weight") => Some(self.testing.speed_weight.to_string()),
            ("testing", "latency_weight") => Some(self.testing.latency_weight.to_string()),
            ("testing", "test_file_size") => Some(self.testing.test_file_size.clone()),
            ("testing", "max_mirrors") => Some(self.testing.max_mirrors.to_string()),
            ("testing", "min_score") => Some(self.testing.min_score.to_string()),
            ("logging", "level") => Some(self.logging.level.clone()),
            ("logging", "format") => Some(self.logging.format.clone()),
            _ => None,
        }
    }

    /// Merge with another config (for overlaying user config on defaults)
    pub fn merge(&mut self, other: &Config) {
        self.general = other.general.clone();
        self.testing = other.testing.clone();
        self.distro = other.distro.clone();
        self.logging = other.logging.clone();
        self.notifications = other.notifications.clone();

        for (key, value) in &other.static_mirrors {
            self.static_mirrors.insert(key.clone(), value.clone());
        }
    }
}