aria2-core 0.3.8

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
//! Active output path registry — prevents silent filename collisions between concurrent downloads.
//!
//! When multiple `DownloadCommand` instances target the same output directory with the same
//! inferred filename, the last writer would silently overwrite previous results. This module
//! provides a process-wide registry that detects such collisions and automatically appends
//! a `.N` suffix (aria2-compatible style) to produce unique filenames.

use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, info, warn};

use crate::error::{Aria2Error, Result};
use crate::filesystem::control_file::ControlFile;

/// Compatibility policy used when selecting a local output path.
///
/// This captures the pre-local-file decisions made by aria2's
/// `RequestGroup::adjustFilename` and `shouldCancelDownloadForSafety`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OutputPathPolicy {
    /// Permit replacing an existing output file from scratch.
    pub allow_overwrite: bool,
    /// Select a numbered output when an existing file cannot be reused.
    pub auto_file_renaming: bool,
    /// Reuse an existing file without a control file when it is no larger
    /// than the known remote file.
    pub continue_download: bool,
    /// Existing data is eligible for a pre-download integrity check.
    pub check_integrity: bool,
    /// Known remote length, when the protocol has already provided it.
    pub total_length: Option<u64>,
}

impl Default for OutputPathPolicy {
    fn default() -> Self {
        Self {
            allow_overwrite: false,
            auto_file_renaming: true,
            continue_download: false,
            check_integrity: false,
            total_length: None,
        }
    }
}

/// Process-wide registry of output paths that are currently being written by active downloads.
///
/// All download command types (`DownloadCommand`, `MetalinkDownloadCommand`,
/// `ConcurrentDownloadCommand`) consult this registry **before** opening their disk writer,
/// so that concurrent downloads targeting the same filename receive distinct paths.
pub struct ActiveOutputRegistry {
    inner: Arc<RwLock<HashSet<PathBuf>>>,
}

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

impl ActiveOutputRegistry {
    /// Create a new empty registry.
    pub fn new() -> Self {
        Self {
            inner: Arc::new(RwLock::new(HashSet::new())),
        }
    }

    /// Resolve the final output path for a download, registering it to prevent collisions.
    ///
    /// If `desired` is not currently claimed by another active download, it is registered
    /// and returned as-is. If a collision is detected, the method appends `.1`, `.2`,
    /// etc. (before the file extension) until an unused name is found.
    ///
    /// # Returns
    ///
    /// The resolved `PathBuf` that the caller should use for all subsequent disk I/O.
    /// The caller **must** call [`Self::release`] when the download finishes (success or failure).
    pub async fn resolve(&self, desired: &Path) -> PathBuf {
        let mut registry = self.inner.write().await;

        if !registry.contains(desired) {
            registry.insert(desired.to_path_buf());
            debug!(
                "Output path registered (no conflict): {}",
                desired.display()
            );
            return desired.to_path_buf();
        }

        // Collision detected — generate unique name with numeric suffix.
        let stem = desired
            .file_stem()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_default();

        let ext = desired
            .extension()
            .map(|e| format!(".{}", e.to_string_lossy()))
            .unwrap_or_default();

        let parent = desired.parent().unwrap_or_else(|| Path::new("."));

        let mut counter: u32 = 1;
        loop {
            let candidate = parent.join(format!("{}.{}{}", stem, counter, ext));

            // Check both the in-progress registry AND the filesystem to avoid conflicts
            // with previously completed downloads that happened to use the same suffix.
            if !registry.contains(&candidate) && !candidate.exists() {
                registry.insert(candidate.clone());
                warn!(
                    "Filename collision: '{}' is already in use. Resolved to '{}'",
                    desired.display(),
                    candidate.display()
                );
                return candidate;
            }

            counter += 1;

            // Safety upper bound to prevent unbounded looping in pathological cases.
            if counter > 10_000 {
                let fallback = parent.join(format!("{}.{}", stem, counter));
                registry.insert(fallback.clone());
                warn!(
                    "Exhausted normal suffix range for '{}', using fallback '{}'",
                    desired.display(),
                    fallback.display()
                );
                return fallback;
            }
        }
    }

    /// Resolve and register an output path using aria2-compatible file policy.
    ///
    /// A control file takes precedence over the existence of the data file.
    /// Without a control file, an existing output is reusable only when
    /// overwrite, integrity checking, or compatible `--continue` semantics
    /// explicitly allow it. Otherwise the original `.N` filename policy is
    /// applied, or `FileAlreadyExists` is returned when auto-renaming is off.
    pub async fn resolve_with_policy(
        &self,
        desired: &Path,
        policy: OutputPathPolicy,
    ) -> Result<PathBuf> {
        let mut registry = self.inner.write().await;
        let desired_claimed = registry.contains(desired);
        let desired_exists = desired.exists();
        let desired_has_control = ControlFile::control_path_for(desired).exists();

        let reusable_existing = desired_exists
            && !desired_claimed
            && (policy.allow_overwrite
                || desired_has_control
                || policy.check_integrity
                || (policy.continue_download
                    && compatible_existing_length(desired, policy.total_length)));

        if !desired_claimed && (!desired_exists || reusable_existing) {
            registry.insert(desired.to_path_buf());
            debug!(
                path = %desired.display(),
                reused = desired_exists,
                "Output path registered"
            );
            return Ok(desired.to_path_buf());
        }

        if !policy.auto_file_renaming {
            return Err(Aria2Error::FileAlreadyExists(desired.display().to_string()));
        }

        let (stem, ext) = split_filename_for_aria2(desired);
        let parent = desired.parent().unwrap_or_else(|| Path::new("."));
        for counter in 1..10_000u32 {
            let candidate = parent.join(format!("{stem}.{counter}{ext}"));
            let candidate_has_control = ControlFile::control_path_for(&candidate).exists();
            if !registry.contains(&candidate) && (!candidate.exists() || candidate_has_control) {
                registry.insert(candidate.clone());
                warn!(
                    original = %desired.display(),
                    resolved = %candidate.display(),
                    "Filename collision resolved"
                );
                return Ok(candidate);
            }
        }

        Err(Aria2Error::FileRenamingFailed(
            desired.display().to_string(),
        ))
    }

    /// Release a previously-resolved path from the registry.
    ///
    /// Must be called when a download completes (success or failure) so that the path
    /// becomes available for future downloads if needed.
    pub async fn release(&self, path: &Path) {
        let mut registry = self.inner.write().await;
        if registry.remove(path) {
            debug!("Output path released: {}", path.display());
        }
    }

    /// Return the number of paths currently registered (for diagnostics / testing).
    pub async fn len(&self) -> usize {
        self.inner.read().await.len()
    }

    /// Check whether the registry is empty.
    pub async fn is_empty(&self) -> bool {
        self.inner.read().await.is_empty()
    }
}

fn compatible_existing_length(path: &Path, total_length: Option<u64>) -> bool {
    match total_length {
        Some(total_length) => std::fs::metadata(path)
            .map(|metadata| metadata.len() <= total_length)
            .unwrap_or(false),
        // A normal HTTP GET learns the entity length from its response. An
        // explicit --continue still makes an existing local prefix reusable
        // before that response arrives; the Range request validates it.
        None => path.exists(),
    }
}

/// Split a path using the same extension rules as aria2's
/// `RequestGroup::tryAutoFileRenaming`.
fn split_filename_for_aria2(path: &Path) -> (String, String) {
    let file_name = path
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default();
    let extension_start = file_name
        .rfind('.')
        .filter(|index| *index > 0 && *index + 1 < file_name.len());
    match extension_start {
        Some(index) => (
            file_name[..index].to_string(),
            file_name[index..].to_string(),
        ),
        None => (file_name, String::new()),
    }
}

// ---------------------------------------------------------------------------
// Global singleton — every download command shares the same instance so that
// cross-task collisions are caught regardless of how commands are spawned.
// ---------------------------------------------------------------------------

use std::sync::OnceLock;

/// Global singleton registry instance. Initialized on first access.
static GLOBAL_REGISTRY: OnceLock<ActiveOutputRegistry> = OnceLock::new();

/// Obtain a reference to the global `ActiveOutputRegistry`.
pub fn global_registry() -> &'static ActiveOutputRegistry {
    GLOBAL_REGISTRY.get_or_init(|| {
        info!("Global ActiveOutputRegistry initialized");
        ActiveOutputRegistry::new()
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::Aria2Error;
    use crate::filesystem::control_file::ControlFile;

    #[tokio::test]
    async fn test_no_collision_when_unique() {
        let reg = ActiveOutputRegistry::new();
        let p1 = reg.resolve(Path::new("/tmp/file.txt")).await;
        assert_eq!(p1, PathBuf::from("/tmp/file.txt"));
        assert_eq!(reg.len().await, 1);
    }

    #[tokio::test]
    async fn test_collision_generates_suffix() {
        let reg = ActiveOutputRegistry::new();

        let p1 = reg.resolve(Path::new("/tmp/file.txt")).await;
        let p2 = reg.resolve(Path::new("/tmp/file.txt")).await;

        assert_eq!(p1, PathBuf::from("/tmp/file.txt"));
        assert_eq!(p2, PathBuf::from("/tmp/file.1.txt"));
        assert_eq!(reg.len().await, 2);
    }

    #[tokio::test]
    async fn test_triple_collision() {
        let reg = ActiveOutputRegistry::new();

        let _p1 = reg.resolve(Path::new("/tmp/data.bin")).await;
        let _p2 = reg.resolve(Path::new("/tmp/data.bin")).await;
        let p3 = reg.resolve(Path::new("/tmp/data.bin")).await;

        assert_eq!(p3, PathBuf::from("/tmp/data.2.bin"));
    }

    #[tokio::test]
    async fn test_release_allows_reuse() {
        let reg = ActiveOutputRegistry::new();

        let p1 = reg.resolve(Path::new("/tmp/reusable.txt")).await;
        reg.release(&p1).await;
        assert!(reg.is_empty().await);

        // After release, the same path can be claimed again.
        let p2 = reg.resolve(Path::new("/tmp/reusable.txt")).await;
        assert_eq!(p2, PathBuf::from("/tmp/reusable.txt"));
    }

    #[tokio::test]
    async fn test_no_extension_handling() {
        let reg = ActiveOutputRegistry::new();

        let p1 = reg.resolve(Path::new("/tmp/Makefile")).await;
        let p2 = reg.resolve(Path::new("/tmp/Makefile")).await;

        assert_eq!(p1, PathBuf::from("/tmp/Makefile"));
        // Files without extension should still get suffixed correctly.
        assert_eq!(p2, PathBuf::from("/tmp/Makefile.1"));
    }

    #[tokio::test]
    async fn test_global_singleton() {
        let r1 = global_registry();
        let r2 = global_registry();
        // Both references must point to the same underlying registry.
        assert!(Arc::ptr_eq(&r1.inner, &r2.inner));
    }

    #[tokio::test]
    async fn existing_file_is_auto_renamed_by_default() {
        let dir = tempfile::tempdir().unwrap();
        let desired = dir.path().join("download.bin");
        tokio::fs::write(&desired, b"existing").await.unwrap();

        let registry = ActiveOutputRegistry::new();
        let resolved = registry
            .resolve_with_policy(&desired, OutputPathPolicy::default())
            .await
            .unwrap();

        assert_eq!(resolved, dir.path().join("download.1.bin"));
        assert_eq!(tokio::fs::read(&desired).await.unwrap(), b"existing");
    }

    #[tokio::test]
    async fn allow_overwrite_keeps_existing_file() {
        let dir = tempfile::tempdir().unwrap();
        let desired = dir.path().join("download.bin");
        tokio::fs::write(&desired, b"existing").await.unwrap();

        let registry = ActiveOutputRegistry::new();
        let resolved = registry
            .resolve_with_policy(
                &desired,
                OutputPathPolicy {
                    allow_overwrite: true,
                    ..OutputPathPolicy::default()
                },
            )
            .await
            .unwrap();

        assert_eq!(resolved, desired);
    }

    #[tokio::test]
    async fn continue_keeps_partial_file_when_length_is_compatible() {
        let dir = tempfile::tempdir().unwrap();
        let desired = dir.path().join("download.bin");
        tokio::fs::write(&desired, b"partial").await.unwrap();

        let registry = ActiveOutputRegistry::new();
        let resolved = registry
            .resolve_with_policy(
                &desired,
                OutputPathPolicy {
                    continue_download: true,
                    total_length: Some(100),
                    ..OutputPathPolicy::default()
                },
            )
            .await
            .unwrap();

        assert_eq!(resolved, desired);
    }

    #[tokio::test]
    async fn existing_file_without_auto_rename_returns_file_exists() {
        let dir = tempfile::tempdir().unwrap();
        let desired = dir.path().join("download.bin");
        tokio::fs::write(&desired, b"existing").await.unwrap();

        let registry = ActiveOutputRegistry::new();
        let error = registry
            .resolve_with_policy(
                &desired,
                OutputPathPolicy {
                    auto_file_renaming: false,
                    ..OutputPathPolicy::default()
                },
            )
            .await
            .expect_err("existing output must not be silently overwritten");

        assert!(matches!(error, Aria2Error::FileAlreadyExists(_)));
    }

    #[tokio::test]
    async fn existing_control_file_reuses_output_path() {
        let dir = tempfile::tempdir().unwrap();
        let desired = dir.path().join("download.bin");
        tokio::fs::write(&desired, b"partial").await.unwrap();
        let control = ControlFile::control_path_for(&desired);
        tokio::fs::write(&control, b"control").await.unwrap();

        let registry = ActiveOutputRegistry::new();
        let resolved = registry
            .resolve_with_policy(&desired, OutputPathPolicy::default())
            .await
            .unwrap();

        assert_eq!(resolved, desired);
    }

    #[tokio::test]
    async fn occupied_output_is_renamed_even_when_overwrite_is_allowed() {
        let dir = tempfile::tempdir().unwrap();
        let desired = dir.path().join("download.bin");
        let registry = ActiveOutputRegistry::new();
        let first = registry
            .resolve_with_policy(
                &desired,
                OutputPathPolicy {
                    allow_overwrite: true,
                    ..OutputPathPolicy::default()
                },
            )
            .await
            .unwrap();
        let second = registry
            .resolve_with_policy(
                &desired,
                OutputPathPolicy {
                    allow_overwrite: true,
                    ..OutputPathPolicy::default()
                },
            )
            .await
            .unwrap();

        assert_eq!(first, desired);
        assert_eq!(second, dir.path().join("download.1.bin"));
    }
}