aria2-core 0.2.2

High-performance download engine core: multi-protocol segmented downloads, rate limiting, config management, 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
use std::sync::Arc;
use std::time::Instant;

use futures::StreamExt;
use futures::stream::FuturesUnordered;
use reqwest;

use crate::constants;
use crate::engine::concurrent_segment_manager::ConcurrentSegmentManager;
use crate::engine::download_cookie::CookieHelper;
use crate::engine::download_progress::ProgressUpdater;
use crate::engine::http_segment_downloader::HttpSegmentDownloader;
use crate::error::{Aria2Error, RecoverableError, Result};
use crate::filesystem::disk_writer::{CachedDiskWriter, SeekableDiskWriter};
use crate::filesystem::resume_helper::ResumeState;
use crate::rate_limiter::{RateLimiter, RateLimiterConfig};
use crate::request::request_group::RequestGroup;

type SegmentFetchFuture = std::pin::Pin<
    Box<
        dyn std::future::Future<
                Output = (
                    u32,
                    std::result::Result<bytes::Bytes, crate::error::Aria2Error>,
                ),
            > + Send,
    >,
>;

pub enum ConcurrentDownloadResult {
    Complete,
    Fallback { completed_ranges: Vec<(u64, u64)> },
}

pub struct ConcurrentDownloader {
    client: Arc<reqwest::Client>,
    output_path: std::path::PathBuf,
    headers: Vec<(String, String)>,
    cookie_helper: CookieHelper,
    progress_updater: ProgressUpdater,
    group: Arc<tokio::sync::RwLock<RequestGroup>>,
    mmap_threshold: u64,
    file_allocation: String,
}

impl ConcurrentDownloader {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        client: Arc<reqwest::Client>,
        output_path: std::path::PathBuf,
        headers: Vec<(String, String)>,
        cookie_helper: CookieHelper,
        progress_updater: ProgressUpdater,
        group: Arc<tokio::sync::RwLock<RequestGroup>>,
        mmap_threshold: u64,
        file_allocation: String,
    ) -> Self {
        Self {
            client,
            output_path,
            headers,
            cookie_helper,
            progress_updater,
            group,
            mmap_threshold,
            file_allocation,
        }
    }

    pub async fn execute(
        &mut self,
        uri: &str,
        total_length: u64,
        resume_state: &ResumeState,
        max_retries_per_segment: u32,
    ) -> Result<ConcurrentDownloadResult> {
        {
            let mut g = self.group.write().await;
            g.set_total_length(total_length).await;
            g.set_total_length_atomic(total_length);
        }

        let options = self.group.read().await.options().clone();
        let split = options.split.unwrap_or(1) as usize;
        let max_conn = options
            .max_connection_per_server
            .unwrap_or(constants::DEFAULT_MAX_CONNECTION_PER_SERVER as u16)
            as usize;
        let seg_size = total_length / split as u64;

        tracing::info!(
            "Concurrent download started: split={}, max_conn={}, segment_size={} bytes, total={}",
            split,
            max_conn,
            seg_size,
            total_length
        );

        let mut manager =
            ConcurrentSegmentManager::new(total_length, vec![uri.to_string()], Some(seg_size));
        manager.set_max_connections_per_mirror(max_conn.min(split));
        manager.set_max_retries(max_retries_per_segment);

        let mut consecutive_416_count = 0u32;
        let mut total_416_count = 0u32;
        let fallback_threshold_consecutive = 3u32;
        let fallback_threshold_ratio = 0.2f64;
        let mut should_fallback = false;

        if resume_state.should_resume {
            manager.mark_completed_up_to(resume_state.start_offset, resume_state.existing_length);
            self.progress_updater.reset(resume_state.start_offset);
            tracing::debug!(
                "Resume: marked {} bytes as completed, continuing from offset {}",
                resume_state.existing_length,
                resume_state.start_offset
            );
        } else {
            self.progress_updater.reset(0);
        }

        let cookie_hdr = self.cookie_helper.build_cookie_header(uri);

        let use_mmap = self.file_allocation == "mmap" && total_length >= self.mmap_threshold;
        let mut writer =
            CachedDiskWriter::new_with_mmap(&self.output_path, Some(total_length), None, use_mmap);

        let limiter = options
            .max_download_limit
            .filter(|&r| r > 0)
            .map(|r| RateLimiter::new(&RateLimiterConfig::new(Some(r), None)));
        if let Some(ref limiter) = limiter {
            let g = self.group.read().await;
            g.set_rate_limiter(limiter.clone()).await;
        }

        let mut active: FuturesUnordered<SegmentFetchFuture> = FuturesUnordered::new();
        let mut active_segs: std::collections::HashMap<u32, u64> = std::collections::HashMap::new();
        let mut completed_bytes = if resume_state.should_resume {
            resume_state.start_offset
        } else {
            0
        };

        loop {
            while active.len() < max_conn {
                match manager.next_pending_segment_for_mirror(0) {
                    Some((seg_idx, offset, length)) => {
                        let url = uri.to_string();
                        let dl = HttpSegmentDownloader::new(&self.client);
                        let ch = cookie_hdr.clone();
                        let headers = self.headers.clone();
                        active_segs.insert(seg_idx, offset);
                        let fut = Box::pin(async move {
                            let result = dl
                                .download_range(&url, offset, length, ch.as_deref(), &headers)
                                .await;
                            (seg_idx, result)
                        });
                        active.push(fut);
                        tracing::debug!(
                            seg_idx = seg_idx,
                            offset = offset,
                            length = length,
                            "Spawned segment fetch"
                        );
                    }
                    None => break,
                }
            }

            if active.is_empty() {
                if manager.is_complete() {
                    tracing::debug!("All segments complete");
                    break;
                }
                if manager.has_failed_segments() && !manager.has_pending_segments() {
                    return Err(Aria2Error::Recoverable(
                        RecoverableError::TemporaryNetworkFailure {
                            message: "Concurrent download: all segments failed".into(),
                        },
                    ));
                }
                tracing::warn!(
                    "Concurrent download stuck: no active or pending segments but not complete"
                );
                break;
            }

            if let Some((seg_idx, result)) = active.next().await {
                let offset = active_segs.remove(&seg_idx).unwrap_or(0);
                match result {
                    Ok(data) => {
                        let data_len = data.len();
                        if let Some(ref lim) = limiter {
                            lim.acquire_download(data_len as u64).await;
                        }
                        let data_for_manager = data.clone();
                        writer.write_bytes_at(offset, data).await.map_err(|e| {
                            Aria2Error::Fatal(crate::error::FatalError::Config(format!(
                                "Write failed: {}",
                                e
                            )))
                        })?;
                        manager.complete_segment(seg_idx, data_for_manager);
                        completed_bytes += data_len as u64;

                        self.progress_updater
                            .update_progress(
                                completed_bytes,
                                constants::PROGRESS_UPDATE_BYTES as u64,
                                constants::HTTP_SPEED_UPDATE_INTERVAL_MS,
                            )
                            .await;
                    }
                    Err(e) => {
                        tracing::warn!(seg_idx = seg_idx, error = %e, "Segment download failed");
                        let is_416 = matches!(
                            &e,
                            Aria2Error::Recoverable(RecoverableError::RangeNotSatisfiable { .. })
                        );
                        if is_416 {
                            consecutive_416_count += 1;
                            total_416_count += 1;
                            tracing::warn!(
                                seg_idx = seg_idx,
                                consecutive_416 = consecutive_416_count,
                                total_416 = total_416_count,
                                "RangeNotSatisfiable (416) detected"
                            );
                            let failure_ratio = total_416_count as f64 / split as f64;
                            let threshold_exceeded = consecutive_416_count
                                >= fallback_threshold_consecutive
                                || failure_ratio >= fallback_threshold_ratio;
                            if threshold_exceeded {
                                tracing::warn!(
                                    uri = uri,
                                    consecutive_416 = consecutive_416_count,
                                    failure_ratio = failure_ratio,
                                    "Fallback to sequential mode triggered due to RangeNotSatisfiable errors"
                                );
                                should_fallback = true;
                                break;
                            }
                        } else {
                            consecutive_416_count = 0;
                        }
                        manager.fail_segment(seg_idx);
                    }
                }
            }
        }

        writer.flush().await.map_err(|e| {
            Aria2Error::Fatal(crate::error::FatalError::Config(format!(
                "Flush failed: {}",
                e
            )))
        })?;

        if should_fallback {
            let completed_ranges = manager.completed_ranges();
            tracing::warn!(
                "Fallback: {} completed ranges will be preserved",
                completed_ranges.len()
            );
            return Ok(ConcurrentDownloadResult::Fallback { completed_ranges });
        }

        let final_speed = {
            let g = self.group.read().await;
            let elapsed = g.elapsed_time().await;
            match elapsed {
                Some(d) if d.as_secs_f64() > 0.0 => {
                    (completed_bytes as f64 / d.as_secs_f64()) as u64
                }
                _ => 0,
            }
        };
        {
            let mut g = self.group.write().await;
            g.update_progress(completed_bytes).await;
            g.update_speed(final_speed, 0).await;
            g.set_completed_length(completed_bytes);
            g.set_download_speed_cached(final_speed);
            g.complete().await?;
        }

        tracing::info!(
            "Concurrent download complete: {} ({} bytes)",
            self.output_path.display(),
            completed_bytes
        );
        self.cookie_helper.save_cookies_if_configured();
        Ok(ConcurrentDownloadResult::Complete)
    }

    pub async fn execute_with_retry(
        &mut self,
        uri: &str,
        total_length: u64,
        resume_state: &ResumeState,
        max_retries_per_segment: u32,
    ) -> Result<ConcurrentDownloadResult> {
        tracing::info!(
            "Using concurrent download mode (split={}, max_retries/segment={})",
            self.group.read().await.options().split.unwrap_or(1),
            max_retries_per_segment
        );

        let all_uris: Vec<String> = {
            let g = self.group.read().await;
            g.uris().to_vec()
        };

        if all_uris.len() > 1 {
            tracing::info!(
                "Intelligent multi-mirror selection enabled: {} mirror sources",
                all_uris.len()
            );
            self.execute_with_coordinator(
                &all_uris,
                total_length,
                resume_state,
                max_retries_per_segment,
            )
            .await
        } else {
            self.execute(uri, total_length, resume_state, max_retries_per_segment)
                .await
        }
    }

    async fn execute_with_coordinator(
        &mut self,
        uris: &[String],
        total_length: u64,
        resume_state: &ResumeState,
        max_retries_per_segment: u32,
    ) -> Result<ConcurrentDownloadResult> {
        let split = self.group.read().await.options().split.unwrap_or(1) as u64;
        let segment_size = total_length.div_ceil(split);
        let max_conn = self
            .group
            .read()
            .await
            .options()
            .max_connection_per_server
            .unwrap_or(constants::DEFAULT_MAX_CONNECTION_PER_SERVER as u16)
            as usize;

        let mirror_config = crate::engine::mirror_coordinator::MirrorConfig {
            max_connections_per_mirror: max_conn.min(split as usize),
            max_total_connections: max_conn * uris.len(),
            speed_threshold: constants::MIRROR_SPEED_THRESHOLD,
            cooldown_secs: constants::MIRROR_COOLDOWN_SECS,
            max_retries: max_retries_per_segment,
        };

        let selector = Box::new(
            crate::selector::adaptive_uri_selector::AdaptiveUriSelector::new_with_uris(
                Arc::new(crate::selector::server_stat_man::ServerStatMan::new()),
                uris.to_vec(),
            ),
        );

        let segment_manager = ConcurrentSegmentManager::new_with_selector(
            total_length,
            uris.to_vec(),
            Some(segment_size),
            Arc::new(crate::selector::server_stat_man::ServerStatMan::new()),
            selector,
        );

        let mut coordinator =
            crate::engine::mirror_coordinator::MirrorCoordinator::with_segment_manager(
                Arc::new(crate::selector::server_stat_man::ServerStatMan::new()),
                Box::new(crate::selector::uri_selector::InorderUriSelector::new()),
                segment_manager,
                mirror_config,
                uris.to_vec(),
            );

        if resume_state.should_resume {
            tracing::debug!(
                "Resume: existing {} bytes, continuing from offset {}",
                resume_state.existing_length,
                resume_state.start_offset
            );
        }

        let use_mmap = self.file_allocation == "mmap" && total_length >= self.mmap_threshold;
        let mut writer =
            CachedDiskWriter::new_with_mmap(&self.output_path, Some(total_length), None, use_mmap);
        self.progress_updater.reset(0);

        let mut consecutive_416_count = 0u32;
        let mut total_416_count = 0u32;
        let fallback_threshold_consecutive = 3u32;
        let fallback_threshold_ratio = 0.2f64;
        let mut should_fallback = false;

        while coordinator.has_pending_segments() || !coordinator.is_complete() {
            while let Some((mirror_idx, mirror_url, (seg_idx, offset, length))) =
                coordinator.select_mirror_for_segment()
            {
                tracing::info!(
                    "Starting segment {} download: mirror={}, offset={}, size={}",
                    seg_idx,
                    mirror_idx,
                    offset,
                    length
                );

                let downloader = HttpSegmentDownloader::new(&self.client);
                let seg_start = Instant::now();

                let cookie_hdr = self.cookie_helper.build_cookie_header(&mirror_url);

                let result = downloader
                    .download_range(
                        &mirror_url,
                        offset,
                        length,
                        cookie_hdr.as_deref(),
                        &self.headers,
                    )
                    .await;

                match result {
                    Ok(data) => {
                        let elapsed = seg_start.elapsed();
                        let speed = if elapsed.as_secs_f64() > 0.0 {
                            (data.len() as f64 / elapsed.as_secs_f64()) as u64
                        } else {
                            0
                        };

                        tracing::debug!(
                            "Segment {} complete: {} bytes, speed={} B/s",
                            seg_idx,
                            data.len(),
                            speed
                        );

                        let data_for_coordinator = data.clone();
                        writer.write_bytes_at(offset, data).await.map_err(|e| {
                            Aria2Error::Fatal(crate::error::FatalError::Config(format!(
                                "Write failed: {}",
                                e
                            )))
                        })?;

                        coordinator.on_segment_complete(
                            mirror_idx,
                            seg_idx,
                            data_for_coordinator,
                            speed,
                        );
                    }
                    Err(e) => {
                        tracing::warn!(
                            "Segment {} download failed (mirror={}): {}",
                            seg_idx,
                            mirror_idx,
                            e
                        );

                        let is_416 = matches!(
                            &e,
                            Aria2Error::Recoverable(RecoverableError::RangeNotSatisfiable { .. })
                        );
                        if is_416 {
                            consecutive_416_count += 1;
                            total_416_count += 1;
                            tracing::warn!(
                                seg_idx = seg_idx,
                                consecutive_416 = consecutive_416_count,
                                total_416 = total_416_count,
                                "RangeNotSatisfiable (416) detected"
                            );
                            let failure_ratio = total_416_count as f64 / split as f64;
                            let threshold_exceeded = consecutive_416_count
                                >= fallback_threshold_consecutive
                                || failure_ratio >= fallback_threshold_ratio;
                            if threshold_exceeded {
                                tracing::warn!(
                                    uri = mirror_url,
                                    consecutive_416 = consecutive_416_count,
                                    failure_ratio = failure_ratio,
                                    "Fallback to sequential mode triggered due to RangeNotSatisfiable errors"
                                );
                                should_fallback = true;
                                break;
                            }
                        } else {
                            consecutive_416_count = 0;
                        }

                        let error_code = constants::HTTP_DEFAULT_ERROR_CODE;
                        coordinator.on_segment_failed(mirror_idx, seg_idx, error_code);
                    }
                }

                let completed_bytes = {
                    let total = coordinator.num_segments() as u64;
                    let progress_pct = coordinator.progress();
                    if total > 0 {
                        (progress_pct / 100.0 * total as f64) as u64
                    } else {
                        0
                    }
                };

                self.progress_updater
                    .update_progress(
                        completed_bytes,
                        constants::PROGRESS_UPDATE_BYTES as u64,
                        constants::HTTP_SPEED_UPDATE_INTERVAL_MS,
                    )
                    .await;
            }

            if coordinator.is_complete() {
                break;
            }

            if coordinator.has_failed_segments() {
                tracing::error!("Permanently failed download segments exist");
                return Err(Aria2Error::Recoverable(
                    RecoverableError::TemporaryNetworkFailure {
                        message: "Some download segments permanently failed".into(),
                    },
                ));
            }

            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        }

        writer.flush().await.map_err(|e| {
            Aria2Error::Fatal(crate::error::FatalError::Config(format!(
                "Flush failed: {}",
                e
            )))
        })?;

        if should_fallback {
            let completed_ranges = coordinator.completed_ranges();
            tracing::warn!(
                "Fallback: {} completed ranges will be preserved",
                completed_ranges.len()
            );
            return Ok(ConcurrentDownloadResult::Fallback { completed_ranges });
        }

        let final_speed = {
            let g = self.group.read().await;
            let elapsed = g.elapsed_time().await;
            match elapsed {
                Some(d) if d.as_secs_f64() > 0.0 => {
                    (self.progress_updater.last_progress_update() as f64 / d.as_secs_f64()) as u64
                }
                _ => 0,
            }
        };

        {
            let mut g = self.group.write().await;
            g.set_total_length(self.progress_updater.last_progress_update())
                .await;
            g.set_total_length_atomic(self.progress_updater.last_progress_update());
            g.set_completed_length(self.progress_updater.last_progress_update());
            g.update_speed(final_speed, 0).await;
            g.set_download_speed_cached(final_speed);
            g.complete().await?;
        }

        tracing::info!(
            "Multi-mirror concurrent download complete: {} ({} bytes, {} B/s)",
            self.output_path.display(),
            self.progress_updater.last_progress_update(),
            final_speed
        );
        self.cookie_helper.save_cookies_if_configured();
        Ok(ConcurrentDownloadResult::Complete)
    }
}