aria2-core 0.3.11

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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! Download dependency resolution.
//!
//! Mirrors C++ `Dependency` class hierarchy. A `Dependency` represents a
//! condition that must be satisfied before a `RequestGroup` can be promoted
//! from reserved to active. The most common dependency is "wait for another
//! download to finish" (e.g. Metalink → torrent download chains).

use std::sync::Arc;

#[cfg(feature = "bittorrent")]
use super::DownloadStatus;
use super::GroupId;
#[cfg(feature = "bittorrent")]
use super::{MetadataInfo, RequestGroup};
#[cfg(feature = "bittorrent")]
use crate::engine::bittorrent::download::command::{
    apply_file_mappings, apply_select_file_filter, build_download_context_from_meta,
};
#[cfg(feature = "bittorrent")]
use crate::util::rwlock_ext::RwLockRecover;
#[cfg(feature = "bittorrent")]
use std::path::PathBuf;
#[cfg(feature = "bittorrent")]
use std::sync::RwLock;

/// A dependency that must be resolved before a download can start.
///
/// Mirrors the C++ `Dependency` base class and its `virtual bool resolve()`
/// method. In Rust, a trait object allows each dependency type to define
/// its own resolution logic.
///
/// The trait also exposes `Any` support for downcasting in the engine loop,
/// such as finding `CompletionDependency` instances when their prerequisite
/// group completes.
pub trait Dependency: Send + Sync + std::fmt::Debug + std::any::Any {
    /// Check whether this dependency has been resolved.
    ///
    /// Returns `true` if the dependency is satisfied and the download
    /// can proceed, `false` if it must remain in the reserved queue.
    fn resolve(&self) -> bool;

    /// Human-readable description of this dependency for logging.
    fn description(&self) -> String;

    /// Support for downcasting. Required for the engine loop to find
    /// specific dependency types (e.g. `CompletionDependency`) in the
    /// reserved queue.
    fn as_any(&self) -> &dyn std::any::Any;
}

/// Dependency on another download completing.
///
/// The dependent download waits in the reserved queue until the
/// prerequisite download finishes. This is used by:
/// - Metalink: parent Metalink download → child torrent downloads
/// - Torrent → magnet: magnet link download triggers torrent download
///
/// Mirrors C++ `DownloadResultDependency` and `GIDDependency`.
#[derive(Debug)]
pub struct CompletionDependency {
    /// GID of the prerequisite download.
    pub depends_on_gid: GroupId,
    /// Shared flag that gets set when the prerequisite completes.
    /// Allows lock-free resolution checking from the promotion path.
    completed: Arc<std::sync::atomic::AtomicBool>,
}

impl CompletionDependency {
    /// Create a new completion dependency on the given GID.
    ///
    /// The `completed` flag starts as `false` and should be set to `true`
    /// by the engine loop when the prerequisite group is demoted to stopped.
    pub fn new(depends_on_gid: GroupId) -> Self {
        Self {
            depends_on_gid,
            completed: Arc::new(std::sync::atomic::AtomicBool::new(false)),
        }
    }

    /// Get a shared reference to the completion flag.
    ///
    /// The engine loop uses this to mark the dependency as resolved
    /// when the prerequisite download finishes.
    pub fn completed_flag(&self) -> Arc<std::sync::atomic::AtomicBool> {
        Arc::clone(&self.completed)
    }

    /// Manually mark this dependency as resolved (for testing).
    pub fn mark_resolved(&self) {
        self.completed
            .store(true, std::sync::atomic::Ordering::Release);
    }
}

/// A completion dependency that installs a parsed torrent context into the
/// payload group before allowing promotion.
#[cfg(feature = "bittorrent")]
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct BtFileMapping {
    /// The torrent-relative path stored in `FileEntry::original_name`.
    pub original_name: String,
    /// Metalink-selected output path.
    pub path: String,
    /// Direct mirrors belonging to the Metalink file.
    pub uris: Vec<String>,
    /// Per-server connection limit copied to the resolved torrent entry.
    pub max_connection_per_server: usize,
    /// Whether all URIs for the entry must use one protocol.
    pub unique_protocol: bool,
}

#[cfg(feature = "bittorrent")]
pub struct BtDependency {
    depends_on_gid: GroupId,
    completed: Arc<std::sync::atomic::AtomicBool>,
    payload: Arc<RwLock<RequestGroup>>,
    /// Metadata source group for Metalink's memory pre-download path.
    metadata_source: Option<Arc<RwLock<RequestGroup>>>,
    file_mappings: Vec<BtFileMapping>,
    torrent_data: Arc<RwLock<Option<Vec<u8>>>>,
    metadata_path: Option<PathBuf>,
    output_path: PathBuf,
    metadata_info: MetadataInfo,
    /// Direct HTTP/FTP mirrors to use when the torrent metaurl fails.
    fallback_uris: Vec<String>,
}

#[cfg(feature = "bittorrent")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BtDependencyResolution {
    /// Metadata was parsed and injected, or direct mirrors were selected.
    Resolved,
    /// The prerequisite is not terminal yet.
    Waiting,
    /// No usable fallback exists for the payload.
    Failed(String),
}

#[cfg(feature = "bittorrent")]
impl std::fmt::Debug for BtDependency {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("BtDependency")
            .field("depends_on_gid", &self.depends_on_gid)
            .field("payload_gid", &self.payload.recover().gid())
            .field(
                "metadata_source_gid",
                &self
                    .metadata_source
                    .as_ref()
                    .map(|source| source.recover().gid()),
            )
            .field("file_mappings", &self.file_mappings)
            .field("metadata_path", &self.metadata_path)
            .field("output_path", &self.output_path)
            .field("metadata_info", &self.metadata_info)
            .field("fallback_uris", &self.fallback_uris)
            .finish()
    }
}

#[cfg(feature = "bittorrent")]
impl BtDependency {
    /// Return the prerequisite metadata task GID.
    pub fn depends_on_gid(&self) -> GroupId {
        self.depends_on_gid
    }

    /// Create a dependency for a payload group and its downloaded torrent data.
    pub fn new(
        depends_on_gid: GroupId,
        payload: Arc<RwLock<RequestGroup>>,
        torrent_data: Vec<u8>,
        output_path: PathBuf,
        metadata_info: MetadataInfo,
    ) -> Self {
        Self::from_source(
            depends_on_gid,
            payload,
            Some(torrent_data),
            None,
            output_path,
            metadata_info,
            Vec::new(),
        )
    }

    /// Create a dependency whose metadata will be read after the prerequisite
    /// task writes its torrent file.
    pub fn new_file(
        depends_on_gid: GroupId,
        payload: Arc<RwLock<RequestGroup>>,
        metadata_path: PathBuf,
        output_path: PathBuf,
        metadata_info: MetadataInfo,
    ) -> Self {
        Self::from_source(
            depends_on_gid,
            payload,
            None,
            Some(metadata_path),
            output_path,
            metadata_info,
            Vec::new(),
        )
    }

    /// Create a file-backed dependency with direct mirrors available as a
    /// fallback when the torrent metadata cannot be downloaded or parsed.
    pub fn new_file_with_fallback(
        depends_on_gid: GroupId,
        payload: Arc<RwLock<RequestGroup>>,
        metadata_path: PathBuf,
        output_path: PathBuf,
        metadata_info: MetadataInfo,
        fallback_uris: Vec<String>,
    ) -> Self {
        Self::from_source(
            depends_on_gid,
            payload,
            None,
            Some(metadata_path),
            output_path,
            metadata_info,
            fallback_uris,
        )
    }

    fn from_source(
        depends_on_gid: GroupId,
        payload: Arc<RwLock<RequestGroup>>,
        torrent_data: Option<Vec<u8>>,
        metadata_path: Option<PathBuf>,
        output_path: PathBuf,
        metadata_info: MetadataInfo,
        fallback_uris: Vec<String>,
    ) -> Self {
        Self {
            depends_on_gid,
            completed: Arc::new(std::sync::atomic::AtomicBool::new(false)),
            payload,
            metadata_source: None,
            file_mappings: Vec::new(),
            torrent_data: Arc::new(RwLock::new(torrent_data)),
            metadata_path,
            output_path,
            metadata_info,
            fallback_uris,
        }
    }

    /// Create a dependency whose prerequisite stores torrent bytes in memory.
    ///
    /// This is the Rust equivalent of Metalink2RequestGroup attaching
    /// `MemoryPreDownloadHandler` to the torrent metaurl request group.
    pub fn new_memory_with_fallback(
        depends_on_gid: GroupId,
        payload: Arc<RwLock<RequestGroup>>,
        metadata_source: Arc<RwLock<RequestGroup>>,
        output_path: PathBuf,
        metadata_info: MetadataInfo,
        fallback_uris: Vec<String>,
    ) -> Self {
        let mut dependency = Self::from_source(
            depends_on_gid,
            payload,
            None,
            None,
            output_path,
            metadata_info,
            fallback_uris,
        );
        dependency.metadata_source = Some(metadata_source);
        dependency
    }

    /// Attach Metalink-to-torrent file mappings to this dependency.
    pub fn with_file_mappings(mut self, file_mappings: Vec<BtFileMapping>) -> Self {
        self.file_mappings = file_mappings;
        self
    }

    /// Return direct mirrors retained for Metalink fallback.
    pub fn fallback_uris(&self) -> &[String] {
        &self.fallback_uris
    }

    /// Return the selected Metalink-to-torrent file mappings.
    pub fn file_mappings(&self) -> &[BtFileMapping] {
        &self.file_mappings
    }

    /// Whether the prerequisite stores its torrent bytes in memory.
    pub fn uses_memory_source(&self) -> bool {
        self.metadata_source.is_some() || self.torrent_data.recover().is_some()
    }

    /// Configure the path written by the prerequisite metadata task.
    pub fn set_metadata_path(&mut self, path: PathBuf) {
        self.metadata_path = Some(path);
    }

    /// Return the configured metadata file path.
    pub fn metadata_path(&self) -> Option<&std::path::Path> {
        self.metadata_path.as_deref()
    }

    /// Resolve the dependency after its prerequisite reaches a terminal
    /// state. A failed metadata path is recoverable only when direct mirrors
    /// were retained by the Metalink graph.
    pub fn resolve_after_prerequisite(
        &self,
        prerequisite_status: &DownloadStatus,
    ) -> BtDependencyResolution {
        if self.resolve() {
            return BtDependencyResolution::Resolved;
        }

        if matches!(prerequisite_status, DownloadStatus::Complete) {
            if let Some(source) = &self.metadata_source {
                if let Some(data) = source.recover().in_memory_data() {
                    if let Err(error) = self.resolve_metadata_bytes(data) {
                        return self.fallback_or_fail(error);
                    }
                } else {
                    return self.fallback_or_fail(
                        "in-memory torrent metadata source has no data".to_string(),
                    );
                }
            } else if let Some(metadata_path) = self.metadata_path()
                && let Err(error) = self.resolve_metadata_file(metadata_path)
            {
                return self.fallback_or_fail(error);
            }
            return if self.resolve() {
                BtDependencyResolution::Resolved
            } else {
                self.fallback_or_fail("torrent metadata source is unavailable".to_string())
            };
        }

        self.fallback_or_fail(format!(
            "metadata prerequisite ended in {}",
            prerequisite_status
        ))
    }

    fn fallback_or_fail(&self, reason: String) -> BtDependencyResolution {
        if !self.fallback_uris.is_empty() {
            self.payload
                .recover_mut()
                .replace_uris(self.fallback_uris.clone());
            self.completed
                .store(true, std::sync::atomic::Ordering::Release);
            tracing::warn!(
                payload_gid = self.payload.recover().gid().value(),
                error = %reason,
                fallback_count = self.fallback_uris.len(),
                "Torrent metadata failed; falling back to direct Metalink mirrors"
            );
            BtDependencyResolution::Resolved
        } else {
            BtDependencyResolution::Failed(reason)
        }
    }

    /// Resolve downloaded metadata from the file written by the prerequisite group.
    pub fn resolve_metadata_file(&self, path: &std::path::Path) -> Result<(), String> {
        if self.resolve() {
            return Ok(());
        }
        let data = std::fs::read(path).map_err(|error| {
            format!(
                "Failed to read torrent metadata '{}': {error}",
                path.display()
            )
        })?;
        self.resolve_metadata_bytes(data)
    }

    /// Mark metadata complete and resolve it immediately when the torrent is valid.
    pub fn mark_metadata_complete(&self) -> Result<(), String> {
        if self.resolve() {
            return Ok(());
        }

        let data = self
            .torrent_data
            .recover()
            .as_ref()
            .cloned()
            .ok_or_else(|| "Torrent metadata source is file-backed".to_string())?;
        self.resolve_metadata_bytes(data)
    }

    fn resolve_metadata_bytes(&self, data: Vec<u8>) -> Result<(), String> {
        // Validate the metadata before consuming the source so callers can
        // retry after a parse failure.
        let meta = aria2_protocol::bittorrent::torrent::parser::TorrentMeta::parse(&data)
            .map_err(|error| format!("Torrent metadata parse failed: {error}"))?;
        if self.torrent_data.recover().is_some() {
            self.torrent_data
                .recover_mut()
                .take()
                .ok_or_else(|| "Torrent metadata has already been consumed".to_string())?;
        }
        let ctx = build_download_context_from_meta(
            &meta,
            self.output_path.to_string_lossy().into_owned(),
            &[],
        )
        .map_err(|error| error.to_string())?;
        let mut ctx = ctx;
        apply_file_mappings(&mut ctx, &self.file_mappings).map_err(|error| error.to_string())?;
        let select_file = self.payload.recover().options().select_file.clone();
        apply_select_file_filter(&mut ctx, select_file.as_deref())
            .map_err(|error| error.to_string())?;
        let payload = self.payload.recover();
        payload.set_bt_metadata_data(data.clone());
        payload.set_bt_metadata(
            meta.num_pieces() as u32,
            meta.info.piece_length,
            meta.info_hash.as_hex(),
        );
        payload.set_metadata_info(self.metadata_info.clone());
        payload.set_download_context(Arc::new(ctx));
        self.completed
            .store(true, std::sync::atomic::Ordering::Release);
        Ok(())
    }
}

#[cfg(feature = "bittorrent")]
impl Dependency for BtDependency {
    fn resolve(&self) -> bool {
        self.completed.load(std::sync::atomic::Ordering::Acquire)
    }

    fn description(&self) -> String {
        format!(
            "Waiting for torrent metadata download #{}",
            self.depends_on_gid.to_hex_string()
        )
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl Dependency for CompletionDependency {
    fn resolve(&self) -> bool {
        self.completed.load(std::sync::atomic::Ordering::Acquire)
    }

    fn description(&self) -> String {
        format!(
            "Waiting for download #{} to complete",
            self.depends_on_gid.to_hex_string()
        )
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// A dependency that is always resolved (no-op).
///
/// Used as a default when a group has no dependencies.
#[derive(Debug)]
pub struct NoDependency;

impl Dependency for NoDependency {
    fn resolve(&self) -> bool {
        true
    }

    fn description(&self) -> String {
        "No dependency".to_string()
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(feature = "bittorrent")]
    use crate::request::request_group::{DownloadOptions, MetadataInfo, RequestGroup};
    #[cfg(feature = "bittorrent")]
    use crate::util::rwlock_ext::RwLockRecover;
    #[cfg(feature = "bittorrent")]
    use std::path::PathBuf;
    #[cfg(feature = "bittorrent")]
    use std::sync::{Arc, RwLock};

    #[cfg(feature = "bittorrent")]
    fn minimal_torrent() -> Vec<u8> {
        let mut data = b"d8:announce28:http://tracker.test/announce4:infod6:lengthi0e4:name4:test12:piece lengthi16384e6:pieces20:".to_vec();
        data.extend_from_slice(&[
            0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60,
            0x18, 0x90, 0xaf, 0xd8, 0x07, 0x09,
        ]);
        data.extend_from_slice(b"ee");
        data
    }

    #[cfg(feature = "bittorrent")]
    #[test]
    fn bt_dependency_reads_file_backed_metadata() {
        let path = std::env::temp_dir().join(format!(
            "aria2-rust-bt-dependency-{}.torrent",
            std::process::id()
        ));
        std::fs::write(&path, minimal_torrent()).expect("write torrent metadata");
        let payload = Arc::new(RwLock::new(RequestGroup::new(
            GroupId::new(3),
            vec!["bt://payload".to_string()],
            DownloadOptions::default(),
        )));
        let dependency = BtDependency::new_file(
            GroupId::new(1),
            Arc::clone(&payload),
            path.clone(),
            PathBuf::from("payload.bin"),
            MetadataInfo::new(GroupId::new(1), "https://example.test/payload.torrent"),
        );

        dependency
            .resolve_metadata_file(&path)
            .expect("file-backed metadata should resolve");
        assert!(dependency.resolve());
        assert!(payload.recover().get_download_context().is_some());
        let _ = std::fs::remove_file(path);
    }

    #[cfg(feature = "bittorrent")]
    #[test]
    fn bt_dependency_injects_context_before_resolution() {
        let payload = Arc::new(RwLock::new(RequestGroup::new(
            GroupId::new(2),
            vec!["bt://payload".to_string()],
            DownloadOptions::default(),
        )));
        let dependency = BtDependency::new(
            GroupId::new(1),
            Arc::clone(&payload),
            minimal_torrent(),
            PathBuf::from("payload.bin"),
            MetadataInfo::new(GroupId::new(1), "https://example.test/payload.torrent"),
        );

        assert!(!dependency.resolve());
        dependency
            .mark_metadata_complete()
            .expect("valid torrent metadata should resolve");
        assert!(dependency.resolve());
        let group = payload.recover();
        assert_eq!(group.get_bt_piece_length(), 16_384);
        assert!(group.get_download_context().is_some());
        assert_eq!(
            group.metadata_info().expect("metadata provenance").gid(),
            Some(GroupId::new(1))
        );
    }

    #[cfg(feature = "bittorrent")]
    #[test]
    fn bt_dependency_falls_back_after_failed_prerequisite() {
        let payload = Arc::new(RwLock::new(RequestGroup::new(
            GroupId::new(12),
            vec!["bt://payload".to_string()],
            DownloadOptions::default(),
        )));
        let dependency = BtDependency::new_file_with_fallback(
            GroupId::new(11),
            Arc::clone(&payload),
            PathBuf::from("missing.torrent"),
            PathBuf::from("payload.bin"),
            MetadataInfo::new(GroupId::new(11), "https://example.test/payload.torrent"),
            vec!["https://mirror.test/payload.bin".to_string()],
        );

        assert_eq!(
            dependency.resolve_after_prerequisite(&DownloadStatus::Error(
                "metadata request failed".to_string()
            )),
            BtDependencyResolution::Resolved
        );
        assert!(dependency.resolve());
        assert_eq!(
            payload
                .recover()
                .uris()
                .iter()
                .map(|uri| uri.as_ref())
                .collect::<Vec<_>>(),
            vec!["https://mirror.test/payload.bin"]
        );
    }

    #[cfg(feature = "bittorrent")]
    #[test]
    fn bt_dependency_without_fallback_reports_terminal_failure() {
        let payload = Arc::new(RwLock::new(RequestGroup::new(
            GroupId::new(13),
            vec!["bt://payload".to_string()],
            DownloadOptions::default(),
        )));
        let dependency = BtDependency::new_file(
            GroupId::new(11),
            Arc::clone(&payload),
            PathBuf::from("missing.torrent"),
            PathBuf::from("payload.bin"),
            MetadataInfo::new(GroupId::new(11), "https://example.test/payload.torrent"),
        );

        assert!(matches!(
            dependency.resolve_after_prerequisite(&DownloadStatus::Error(
                "metadata request failed".to_string()
            )),
            BtDependencyResolution::Failed(_)
        ));
        assert!(!dependency.resolve());
    }

    #[test]
    fn test_no_dependency_always_resolved() {
        let dep = NoDependency;
        assert!(dep.resolve());
        assert_eq!(dep.description(), "No dependency");
    }

    #[test]
    fn test_completion_dependency_initially_unresolved() {
        let dep = CompletionDependency::new(GroupId::new(1));
        assert!(!dep.resolve());
        assert!(dep.description().contains("#0000000000000001"));
    }

    #[test]
    fn test_completion_dependency_resolved_after_mark() {
        let dep = CompletionDependency::new(GroupId::new(42));
        assert!(!dep.resolve());

        dep.mark_resolved();
        assert!(dep.resolve());
    }

    #[test]
    fn test_completion_dependency_shared_flag() {
        let dep = CompletionDependency::new(GroupId::new(1));
        let flag = dep.completed_flag();

        assert!(!dep.resolve());

        // Setting the flag from a different reference resolves the dependency.
        flag.store(true, std::sync::atomic::Ordering::Release);
        assert!(dep.resolve());
    }
}