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
use super::mirror::{Mirror, TestResult};
use super::tester::MirrorTester;
use crate::config::Config;
use crate::distro::DistroHandler;
use crate::utils::SMirrorsError;
use anyhow::{Context, Result};
use std::sync::Arc;
use tracing::{error, info, warn};
use url::Url;

/// Mirror list updater that orchestrates the full update workflow
pub struct MirrorUpdater {
    config: Config,
    tester: MirrorTester,
    distro_handler: Arc<dyn DistroHandler>,
}

/// Update options for controlling the update process
#[derive(Debug, Clone)]
pub struct UpdateOptions {
    /// Perform a dry run without actually updating
    pub dry_run: bool,
    /// Force update even if last update was recent
    pub force: bool,
    /// Limit number of mirrors to test (for testing)
    pub limit: Option<usize>,
}

impl Default for UpdateOptions {
    fn default() -> Self {
        Self {
            dry_run: false,
            force: false,
            limit: None,
        }
    }
}

/// Result of an update operation
#[derive(Debug, Clone)]
pub struct UpdateResult {
    pub success: bool,
    pub mirrors_tested: usize,
    pub mirrors_selected: usize,
    pub static_mirrors_count: usize,
    pub error: Option<String>,
    pub dry_run: bool,
}

impl MirrorUpdater {
    /// Create a new mirror updater with the given configuration and distro handler
    pub fn new(config: Config, distro_handler: Arc<dyn DistroHandler>) -> Result<Self> {
        let tester = MirrorTester::from_config(&config)?;

        Ok(Self {
            config,
            tester,
            distro_handler,
        })
    }

    /// Perform a full mirror list update
    ///
    /// # Workflow
    /// 1. Load current configuration
    /// 2. Get current mirrors from distro handler
    /// 3. Fetch available mirrors from distribution
    /// 4. Test mirrors in parallel
    /// 5. Rank mirrors by score
    /// 6. Preserve static mirrors
    /// 7. Create backup of current configuration
    /// 8. Generate new mirror configuration
    /// 9. Validate new configuration
    /// 10. Atomic file replacement
    /// 11. Rollback on failure
    /// 12. Log to database
    pub async fn update(&self, options: &UpdateOptions) -> Result<UpdateResult> {
        info!(
            "Starting mirror update for distribution: {}",
            self.distro_handler.name()
        );

        if options.dry_run {
            info!("Running in dry-run mode - no changes will be made");
        }

        // Step 1: Get current mirrors
        let current_mirrors = self
            .distro_handler
            .get_current_mirrors()
            .context("Failed to get current mirrors")?;

        info!("Current configuration has {} mirrors", current_mirrors.len());

        // Step 2: Get static mirrors from config
        let static_mirrors = self.load_static_mirrors()?;
        info!("Loaded {} static mirrors from config", static_mirrors.len());

        // Step 3: Fetch available mirrors from distribution
        let mut available_mirrors = self
            .distro_handler
            .get_available_mirrors()
            .await
            .context("Failed to fetch available mirrors")?;

        info!("Found {} available mirrors", available_mirrors.len());

        // Apply limit if specified (for testing)
        if let Some(limit) = options.limit {
            available_mirrors.truncate(limit);
            info!("Limited to {} mirrors for testing", limit);
        }

        // Step 4: Test mirrors in parallel
        info!("Testing {} mirrors...", available_mirrors.len());
        let test_results = self.tester.test_all(available_mirrors, None).await;

        let successful_results = MirrorTester::filter_successful(test_results);
        info!(
            "{} mirrors tested successfully",
            successful_results.len()
        );

        if successful_results.is_empty() {
            error!("No mirrors passed testing!");
            return Ok(UpdateResult {
                success: false,
                mirrors_tested: 0,
                mirrors_selected: 0,
                static_mirrors_count: static_mirrors.len(),
                error: Some("No mirrors passed testing".to_string()),
                dry_run: options.dry_run,
            });
        }

        // Step 5: Rank mirrors by score and select top mirrors
        let ranked_mirrors = self.rank_and_select_mirrors(successful_results)?;

        info!("Selected {} top-ranked mirrors", ranked_mirrors.len());

        // Step 6: Combine with static mirrors
        let final_mirrors = self.combine_with_static_mirrors(ranked_mirrors, static_mirrors);

        info!(
            "Final mirror list contains {} mirrors ({} static)",
            final_mirrors.len(),
            final_mirrors.iter().filter(|m| m.is_static).count()
        );

        // If dry-run, return results without making changes
        if options.dry_run {
            info!("Dry-run complete. Selected mirrors:");
            for (i, mirror) in final_mirrors.iter().enumerate() {
                info!(
                    "  {}. {} - Score: {} ({})",
                    i + 1,
                    mirror.url,
                    mirror.format_score(),
                    if mirror.is_static { "static" } else { "dynamic" }
                );
            }

            return Ok(UpdateResult {
                success: true,
                mirrors_tested: final_mirrors.len(),
                mirrors_selected: final_mirrors.len(),
                static_mirrors_count: final_mirrors.iter().filter(|m| m.is_static).count(),
                error: None,
                dry_run: true,
            });
        }

        // Step 7: Create backup of current configuration
        if self.config.distro.create_backup {
            info!("Creating backup of current configuration...");
            if let Err(e) = self.distro_handler.backup() {
                warn!("Failed to create backup: {}", e);
                if !options.force {
                    return Err(e.context("Backup creation failed"));
                }
            } else {
                info!("Backup created successfully");
            }
        }

        // Step 8: Update mirrors
        info!("Updating mirror configuration...");
        if let Err(e) = self.distro_handler.update_mirrors(&final_mirrors) {
            error!("Failed to update mirrors: {}", e);

            // Attempt rollback
            if self.config.distro.create_backup {
                warn!("Attempting to rollback to previous configuration...");
                if let Err(rollback_err) = self.distro_handler.restore_backup() {
                    error!("Rollback failed: {}", rollback_err);
                    return Err(SMirrorsError::UpdateFailed(format!(
                        "Update failed and rollback also failed: {} (rollback error: {})",
                        e, rollback_err
                    ))
                    .into());
                }
                info!("Rollback successful");
            }

            return Err(SMirrorsError::UpdateFailed(e.to_string()).into());
        }

        // Step 9: Validate the new configuration
        info!("Validating new configuration...");
        match self.distro_handler.validate() {
            Ok(true) => {
                info!("Configuration validation successful");
            }
            Ok(false) => {
                warn!("Configuration validation returned false");
                if self.config.distro.create_backup {
                    warn!("Rolling back due to validation failure...");
                    self.distro_handler.restore_backup()?;
                }
                return Err(SMirrorsError::ValidationFailed(
                    "Configuration validation failed".to_string(),
                )
                .into());
            }
            Err(e) => {
                error!("Configuration validation error: {}", e);
                if self.config.distro.create_backup {
                    warn!("Rolling back due to validation error...");
                    self.distro_handler.restore_backup()?;
                }
                return Err(e.context("Configuration validation failed"));
            }
        }

        info!("Mirror update completed successfully");

        Ok(UpdateResult {
            success: true,
            mirrors_tested: final_mirrors.len(),
            mirrors_selected: final_mirrors.len(),
            static_mirrors_count: final_mirrors.iter().filter(|m| m.is_static).count(),
            error: None,
            dry_run: false,
        })
    }

    /// Load static mirrors from configuration
    fn load_static_mirrors(&self) -> Result<Vec<Mirror>> {
        let mut mirrors = Vec::new();

        for (name, url_str) in &self.config.static_mirrors {
            match Url::parse(url_str) {
                Ok(url) => {
                    let mut mirror = Mirror::new_static(url);
                    mirror.metadata.insert("name".to_string(), name.clone());
                    mirrors.push(mirror);
                }
                Err(e) => {
                    warn!(
                        "Failed to parse static mirror '{}' with URL '{}': {}",
                        name, url_str, e
                    );
                }
            }
        }

        Ok(mirrors)
    }

    /// Rank mirrors by score and select the top ones
    fn rank_and_select_mirrors(&self, results: Vec<TestResult>) -> Result<Vec<Mirror>> {
        // Sort by score (best first)
        let mut sorted_results = MirrorTester::sort_by_score(results);

        // Filter by minimum score
        sorted_results.retain(|r| {
            if let Some(score) = r.score {
                score >= self.config.testing.min_score
            } else {
                false
            }
        });

        if sorted_results.is_empty() {
            return Err(
                SMirrorsError::NoMirrorsAvailable.into()
            );
        }

        // Apply country preference if configured
        if !self.config.testing.country_preference.is_empty() {
            sorted_results = self.apply_country_preference(sorted_results);
        }

        // Select top mirrors up to max_mirrors limit
        let max_mirrors = self.config.testing.max_mirrors;
        sorted_results.truncate(max_mirrors);

        // Extract mirrors from results
        let mirrors = MirrorTester::extract_mirrors(sorted_results);

        Ok(mirrors)
    }

    /// Apply country preference to mirror ranking
    fn apply_country_preference(&self, results: Vec<TestResult>) -> Vec<TestResult> {
        // Separate preferred and non-preferred mirrors
        let (mut preferred, mut others): (Vec<_>, Vec<_>) = results
            .into_iter()
            .partition(|r| {
                if let Some(ref country) = r.mirror.country {
                    self.config
                        .testing
                        .country_preference
                        .contains(country)
                } else {
                    false
                }
            });

        // Combine with preferred first
        preferred.append(&mut others);
        preferred
    }

    /// Combine ranked mirrors with static mirrors
    fn combine_with_static_mirrors(
        &self,
        mut ranked_mirrors: Vec<Mirror>,
        static_mirrors: Vec<Mirror>,
    ) -> Vec<Mirror> {
        // Remove any mirrors from ranked list that match static mirror URLs
        let static_urls: Vec<String> = static_mirrors
            .iter()
            .map(|m| m.url.to_string())
            .collect();

        ranked_mirrors.retain(|m| !static_urls.contains(&m.url.to_string()));

        // Combine static mirrors first, then ranked mirrors
        let mut final_mirrors = static_mirrors;
        final_mirrors.extend(ranked_mirrors);

        final_mirrors
    }

    /// Test a specific mirror URL
    pub async fn test_mirror(&self, url: Url) -> Result<TestResult> {
        let mirror = Mirror::new(url);
        Ok(self.tester.test_mirror(&mirror).await)
    }

    /// Get the current configuration
    pub fn config(&self) -> &Config {
        &self.config
    }

    /// Get the distro handler
    pub fn distro_handler(&self) -> &Arc<dyn DistroHandler> {
        &self.distro_handler
    }

    /// Rollback to previous configuration
    pub fn rollback(&self) -> Result<()> {
        info!("Rolling back to previous configuration...");
        self.distro_handler.restore_backup()?;
        info!("Rollback completed successfully");
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_update_options_default() {
        let options = UpdateOptions::default();
        assert_eq!(options.dry_run, false);
        assert_eq!(options.force, false);
        assert!(options.limit.is_none());
    }

    #[test]
    fn test_static_mirror_filtering() {
        let url1 = Url::parse("https://mirror1.example.com/repo").unwrap();
        let url2 = Url::parse("https://mirror2.example.com/repo").unwrap();
        let url3 = Url::parse("https://mirror3.example.com/repo").unwrap();

        let mut ranked = vec![
            Mirror::new(url1.clone()),
            Mirror::new(url2),
            Mirror::new(url3.clone()),
        ];

        let static_mirrors = vec![Mirror::new_static(url1.clone())];

        let config = Config::default();
        let updater = MirrorUpdater {
            config: config.clone(),
            tester: MirrorTester::from_config(&config).unwrap(),
            distro_handler: Arc::new(MockDistroHandler {}),
        };

        let result = updater.combine_with_static_mirrors(ranked, static_mirrors);

        // Should have 3 mirrors total (1 static + 2 from ranked, with url1 deduplicated)
        assert_eq!(result.len(), 3);
        assert_eq!(result[0].is_static, true);
        assert_eq!(result[0].url, url1);
    }

    // Mock distro handler for testing
    struct MockDistroHandler;

    #[async_trait::async_trait]
    impl DistroHandler for MockDistroHandler {
        fn name(&self) -> &str {
            "Mock"
        }

        fn detect(&self) -> bool {
            true
        }

        async fn get_available_mirrors(&self) -> Result<Vec<Mirror>> {
            Ok(Vec::new())
        }

        fn get_current_mirrors(&self) -> Result<Vec<Mirror>> {
            Ok(Vec::new())
        }

        fn update_mirrors(&self, _mirrors: &[Mirror]) -> Result<()> {
            Ok(())
        }

        fn backup(&self) -> Result<()> {
            Ok(())
        }

        fn restore_backup(&self) -> Result<()> {
            Ok(())
        }

        fn validate(&self) -> Result<bool> {
            Ok(true)
        }
    }
}