aria2-core 0.3.7

aria2-rust core download engine: multi-protocol segmented downloads, rate limiting, configuration, session persistence, and BitTorrent seeding
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! Validation framework for configuration options.
//!
//! Provides [`OptionError`], [`OptionValidator`], concrete validators
//! ([`RangeValidator`], [`ChoiceValidator`], [`UrlValidator`],
//! [`PathValidator`], [`RegexValidator`]), [`OptionDefinition`],
//! and [`DependencyChecker`].

use std::collections::HashMap;
use std::fmt;
use std::path::Path;

use serde_json::Value;

// =========================================================================
// Error Type
// =========================================================================

/// Error type for option validation failures.
#[derive(Debug, Clone)]
pub enum OptionError {
    TypeMismatch {
        expected: String,
        got: String,
    },
    OutOfRange {
        value: String,
        min: String,
        max: String,
    },
    InvalidChoice {
        value: String,
        allowed: Vec<String>,
    },
    InvalidUrl {
        url: String,
        reason: String,
    },
    InvalidPath {
        path: String,
        reason: String,
    },
    PatternMismatch {
        value: String,
        pattern: String,
    },
    DependencyConflict {
        option: String,
        conflicts_with: String,
    },
    MissingDependency {
        option: String,
        requires: String,
    },
}

impl fmt::Display for OptionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TypeMismatch { expected, got } => {
                write!(
                    f,
                    "type mismatch for option: expected '{}', got '{}'",
                    expected, got
                )
            }
            Self::OutOfRange { value, min, max } => {
                write!(f, "value '{}' is out of range [{}..{}]", value, min, max)
            }
            Self::InvalidChoice { value, allowed } => {
                write!(
                    f,
                    "invalid choice '{}', allowed values: {}",
                    value,
                    allowed.join(", ")
                )
            }
            Self::InvalidUrl { url, reason } => {
                write!(f, "invalid URL '{}': {}", url, reason)
            }
            Self::InvalidPath { path, reason } => {
                write!(f, "invalid path '{}': {}", path, reason)
            }
            Self::PatternMismatch { value, pattern } => {
                write!(f, "value '{}' does not match pattern '{}'", value, pattern)
            }
            Self::DependencyConflict {
                option,
                conflicts_with,
            } => {
                write!(f, "option '{}' conflicts with '{}'", option, conflicts_with)
            }
            Self::MissingDependency { option, requires } => {
                write!(f, "option '{}' requires '{}' to be set", option, requires)
            }
        }
    }
}

impl std::error::Error for OptionError {}

// =========================================================================
// Validator Trait
// =========================================================================

/// Trait for validating configuration option values.
pub trait OptionValidator: Send + Sync {
    fn validate(&self, name: &str, value: &Value) -> Result<(), OptionError>;
    fn description(&self) -> &str;
}

// =========================================================================
// Concrete Validators
// =========================================================================

/// Validates that numeric values fall within a specified range.
#[derive(Debug, Clone)]
pub struct RangeValidator<T> {
    min: T,
    max: T,
}

impl<T> RangeValidator<T>
where
    T: PartialOrd + fmt::Display + Clone + 'static,
{
    pub fn new(min: T, max: T) -> Self {
        Self { min, max }
    }
}

impl OptionValidator for RangeValidator<i64> {
    fn validate(&self, _name: &str, value: &Value) -> Result<(), OptionError> {
        match value.as_i64() {
            Some(n) if n >= self.min && n <= self.max => Ok(()),
            Some(n) => Err(OptionError::OutOfRange {
                value: n.to_string(),
                min: self.min.to_string(),
                max: self.max.to_string(),
            }),
            None => Err(OptionError::TypeMismatch {
                expected: "integer".to_string(),
                got: format!("{:?}", value),
            }),
        }
    }

    fn description(&self) -> &str {
        "range validator (inclusive bounds)"
    }
}

impl OptionValidator for RangeValidator<f64> {
    fn validate(&self, _name: &str, value: &Value) -> Result<(), OptionError> {
        match value.as_f64() {
            Some(v) if v >= self.min && v <= self.max => Ok(()),
            Some(v) => Err(OptionError::OutOfRange {
                value: format!("{}", v),
                min: format!("{}", self.min),
                max: format!("{}", self.max),
            }),
            None => Err(OptionError::TypeMismatch {
                expected: "float".to_string(),
                got: format!("{:?}", value),
            }),
        }
    }

    fn description(&self) -> &str {
        "range validator for floating-point numbers"
    }
}

impl OptionValidator for RangeValidator<u64> {
    fn validate(&self, _name: &str, value: &Value) -> Result<(), OptionError> {
        match value.as_u64() {
            Some(n) if n >= self.min && n <= self.max => Ok(()),
            Some(n) => Err(OptionError::OutOfRange {
                value: n.to_string(),
                min: self.min.to_string(),
                max: self.max.to_string(),
            }),
            None => Err(OptionError::TypeMismatch {
                expected: "unsigned integer".to_string(),
                got: format!("{:?}", value),
            }),
        }
    }

    fn description(&self) -> &str {
        "range validator for unsigned integers"
    }
}

/// Validates that string values are in a predefined whitelist of choices.
#[derive(Debug, Clone)]
pub struct ChoiceValidator {
    allowed: Vec<String>,
}

impl ChoiceValidator {
    pub fn new(allowed: Vec<String>) -> Self {
        Self { allowed }
    }

    pub fn allowed_values(&self) -> &[String] {
        &self.allowed
    }
}

impl OptionValidator for ChoiceValidator {
    fn validate(&self, _name: &str, value: &Value) -> Result<(), OptionError> {
        match value.as_str() {
            Some(s) if self.allowed.iter().any(|a| a == s) => Ok(()),
            Some(s) => Err(OptionError::InvalidChoice {
                value: s.to_string(),
                allowed: self.allowed.clone(),
            }),
            None => Err(OptionError::TypeMismatch {
                expected: "string".to_string(),
                got: format!("{:?}", value),
            }),
        }
    }

    fn description(&self) -> &str {
        "choice validator (enum whitelist)"
    }
}

/// Validates URL strings for proper format and supported schemes.
#[derive(Debug, Clone, Copy)]
pub struct UrlValidator;

impl UrlValidator {
    pub fn new() -> Self {
        Self
    }

    fn is_valid_url(url: &str) -> Result<(), String> {
        if url.is_empty() {
            return Err("URL is empty".to_string());
        }

        if !url.contains("://") {
            return Err(format!("missing scheme separator in '{}'", url));
        }

        let scheme = url.split("://").next().unwrap_or("");
        if scheme.is_empty() {
            return Err("scheme is empty".to_string());
        }

        if !scheme
            .chars()
            .all(|c| c.is_alphanumeric() || c == '+' || c == '-' || c == '.')
        {
            return Err(format!("invalid scheme '{}'", scheme));
        }

        let after_scheme = url.split_once("://").map(|x| x.1).unwrap_or("");
        if after_scheme.is_empty() {
            return Err("no host/path after scheme".to_string());
        }

        Ok(())
    }
}

impl Default for UrlValidator {
    fn default() -> Self {
        Self::new()
    }
}

impl OptionValidator for UrlValidator {
    fn validate(&self, _name: &str, value: &Value) -> Result<(), OptionError> {
        match value.as_str() {
            Some(url) => Self::is_valid_url(url).map_err(|reason| OptionError::InvalidUrl {
                url: url.to_string(),
                reason,
            }),
            None => Err(OptionError::TypeMismatch {
                expected: "string (URL)".to_string(),
                got: format!("{:?}", value),
            }),
        }
    }

    fn description(&self) -> &str {
        "URL format validator"
    }
}

/// Validates file system paths for existence and writability.
#[derive(Debug, Clone)]
pub struct PathValidator {
    must_exist: bool,
    writable: bool,
}

impl PathValidator {
    pub fn new(must_exist: bool, writable: bool) -> Self {
        Self {
            must_exist,
            writable,
        }
    }
}

impl OptionValidator for PathValidator {
    fn validate(&self, _name: &str, value: &Value) -> Result<(), OptionError> {
        match value.as_str() {
            Some(path_str) => {
                let path = Path::new(path_str);

                if self.must_exist && !path.exists() {
                    return Err(OptionError::InvalidPath {
                        path: path_str.to_string(),
                        reason: "path does not exist".to_string(),
                    });
                }

                if self.writable {
                    let check_path = if path.exists() {
                        path.as_os_str().to_owned()
                    } else {
                        match path.parent() {
                            Some(parent) if !parent.as_os_str().is_empty() => {
                                parent.as_os_str().to_owned()
                            }
                            _ => path.as_os_str().to_owned(),
                        }
                    };

                    if let Some(check_path_str) = check_path.to_str() {
                        let check_path = Path::new(check_path_str);
                        if check_path.exists() {
                            match std::fs::metadata(check_path) {
                                Ok(meta) => {
                                    #[cfg(unix)]
                                    {
                                        use std::os::unix::fs::PermissionsExt;
                                        let mode = meta.permissions().mode();
                                        let user_writable = mode & 0o200 != 0;
                                        if !user_writable && meta.is_dir() {
                                            return Err(OptionError::InvalidPath {
                                                path: path_str.to_string(),
                                                reason: "path is not writable".to_string(),
                                            });
                                        }
                                    }
                                    #[cfg(not(unix))]
                                    {
                                        let _ = &meta;
                                    }
                                }
                                Err(e) => {
                                    return Err(OptionError::InvalidPath {
                                        path: path_str.to_string(),
                                        reason: format!("cannot access path: {}", e),
                                    });
                                }
                            }
                        }
                    }
                }

                Ok(())
            }
            None => Err(OptionError::TypeMismatch {
                expected: "string (path)".to_string(),
                got: format!("{:?}", value),
            }),
        }
    }

    fn description(&self) -> &str {
        "file system path validator"
    }
}

/// Validates string values against a custom regular expression pattern.
#[derive(Debug, Clone)]
pub struct RegexValidator {
    pattern: String,
    compiled: regex::Regex,
}

impl RegexValidator {
    pub fn new(pattern: &str) -> Self {
        let compiled = regex::Regex::new(pattern).expect("Invalid regex pattern in RegexValidator");
        Self {
            pattern: pattern.to_string(),
            compiled,
        }
    }

    pub fn pattern(&self) -> &str {
        &self.pattern
    }
}

impl OptionValidator for RegexValidator {
    fn validate(&self, _name: &str, value: &Value) -> Result<(), OptionError> {
        match value.as_str() {
            Some(s) if self.compiled.is_match(s) => Ok(()),
            Some(s) => Err(OptionError::PatternMismatch {
                value: s.to_string(),
                pattern: self.pattern.clone(),
            }),
            None => Err(OptionError::TypeMismatch {
                expected: "string".to_string(),
                got: format!("{:?}", value),
            }),
        }
    }

    fn description(&self) -> &str {
        "custom regex pattern validator"
    }
}

// =========================================================================
// Extended Definition with Validation
// =========================================================================

/// Extended definition for a configuration option with dynamic validation support.
pub struct OptionDefinition {
    pub name: &'static str,
    pub description: &'static str,
    pub default_value: Value,
    pub validator: Option<Box<dyn OptionValidator>>,
}

impl OptionDefinition {
    pub fn new(name: &'static str, description: &'static str, default_value: Value) -> Self {
        Self {
            name,
            description,
            default_value,
            validator: None,
        }
    }

    pub fn with_validator(mut self, validator: Box<dyn OptionValidator>) -> Self {
        self.validator = Some(validator);
        self
    }

    pub fn validate(&self, value: &Value) -> Result<(), OptionError> {
        match &self.validator {
            Some(validator) => validator.validate(self.name, value),
            None => Ok(()),
        }
    }

    pub fn get_default_or_fallback<'a>(&'a self, fallback: &'a Value) -> &'a Value {
        match &self.default_value {
            Value::Null => fallback,
            other => other,
        }
    }
}

// =========================================================================
// Dependency Checker
// =========================================================================

/// Checks dependencies between configuration options.
pub struct DependencyChecker {
    mutual_exclusions: Vec<(String, String)>,
    requirements: Vec<(String, String)>,
}

impl DependencyChecker {
    pub fn new() -> Self {
        Self {
            mutual_exclusions: Vec::new(),
            requirements: Vec::new(),
        }
    }

    pub fn add_mutual_exclusion(&mut self, opt_a: String, opt_b: String) {
        self.mutual_exclusions.push((opt_a, opt_b));
    }

    pub fn add_requirement(&mut self, option: String, requires: String) {
        self.requirements.push((option, requires));
    }

    pub fn check(&self, options: &HashMap<String, Value>) -> Vec<OptionError> {
        let mut errors = Vec::new();

        for (opt_a, opt_b) in &self.mutual_exclusions {
            let a_set = options.get(opt_a).is_some_and(|v| !v.is_null());
            let b_set = options.get(opt_b).is_some_and(|v| !v.is_null());

            if a_set && b_set {
                errors.push(OptionError::DependencyConflict {
                    option: opt_a.clone(),
                    conflicts_with: opt_b.clone(),
                });
            }
        }

        for (option, requires) in &self.requirements {
            let option_set = options.get(option).is_some_and(|v| !v.is_null());
            let required_set = options.get(requires).is_some_and(|v| !v.is_null());

            if option_set && !required_set {
                errors.push(OptionError::MissingDependency {
                    option: option.clone(),
                    requires: requires.clone(),
                });
            }
        }

        errors
    }

    pub fn mutual_exclusion_count(&self) -> usize {
        self.mutual_exclusions.len()
    }

    pub fn requirement_count(&self) -> usize {
        self.requirements.len()
    }
}

impl Default for DependencyChecker {
    fn default() -> Self {
        Self::new()
    }
}