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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
use async_trait::async_trait;
use futures::StreamExt;
use std::sync::Arc;
use std::time::Duration;
use tracing::{debug, info, warn};
use crate::checksum::checksum::Checksum;
use crate::checksum::message_digest::HashType;
use crate::constants;
use crate::engine::active_output_registry::{OutputPathPolicy, global_registry};
use crate::engine::command::{Command, CommandStatus};
use crate::engine::concurrent_download::{ConcurrentDownloadResult, ConcurrentDownloader};
use crate::engine::download_cookie::CookieHelper;
use crate::engine::range_prober::RangeProber;
use crate::engine::retry_policy::RetryPolicy;
use crate::engine::sequential_download::SequentialDownloader;
use crate::error::{Aria2Error, Result};
use crate::filesystem::file_allocation;
use crate::filesystem::file_allocation_man;
use crate::filesystem::resume_helper::ResumeHelper;
use crate::request::request_group::{DownloadResultCode, GroupId};
use crate::util::rwlock_ext::RwLockRecover;
use super::DownloadCommand;
impl DownloadCommand {
async fn execute_attempt(&mut self, uri: &str) -> Result<()> {
debug!(
"Starting download: {} -> {}",
uri,
self.output_path.display()
);
// Re-check cancellation before the metadata probe and filesystem work
// so a remove issued before execution is honoured immediately.
self.check_cancelled()?;
let release_path = |path: &std::path::Path| {
let path = path.to_path_buf();
async move {
global_registry().release(&path).await;
}
};
let url_for_head = reqwest::Url::parse(uri).ok();
let cookie_hdr_head = if let Some(ref url) = url_for_head {
CookieHelper::new(Arc::clone(&self.cookie_storage), self.cookie_file.clone())
.build_cookie_header_from_url(url)
} else {
String::new()
};
let options = self.group.recover().options_arc();
let known_total_length = self.group.recover().total_length();
let needs_metadata_probe =
options.uses_memory_download() && !options.uses_memory_download_for_uri(uri);
let should_head = options.dry_run
|| (options.use_head && known_total_length == 0)
|| needs_metadata_probe;
let head_resp = if should_head {
let head_req = self.request_policy.apply(
self.client.head(uri),
(!cookie_hdr_head.is_empty()).then_some(cookie_hdr_head.as_str()),
&[],
);
head_req.send().await.ok()
} else {
None
};
let head_content_type = head_resp.as_ref().and_then(|response| {
response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
});
if let Some(content_type) = head_content_type {
self.group.recover().set_content_type(content_type);
if !options.dry_run && options.uses_memory_download_for_content_type(content_type) {
self.group.recover().mark_in_memory_download();
return self.execute_in_memory(uri).await;
}
}
let (total_length, head_supports_range) = if let Some(ref resp) = head_resp {
let tl = resp
.headers()
.get(reqwest::header::CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<u64>().ok())
.unwrap_or(0);
let sr = resp
.headers()
.get("Accept-Ranges")
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.to_lowercase().contains("bytes"));
(tl, sr)
} else {
(known_total_length, false)
};
// `dry_run` is a metadata-only HTTP operation. The HEAD above checks
// availability and discovers the size, but no range probe, output
// directory, collision resolution, resume inspection, allocation, or
// GET request may follow it.
if options.dry_run {
self.completed_bytes = total_length;
{
let group = self.group.recover();
group.set_total_length(total_length);
group.update_progress(total_length);
group.set_checksum_verified(true);
}
self.group.recover_mut().complete()?;
self.completed = true;
return Ok(());
}
if let Some(parent) = self.output_path.parent()
&& !parent.exists()
{
std::fs::create_dir_all(parent).map_err(|e| {
Aria2Error::Fatal(crate::error::FatalError::Config(format!(
"Failed to create directory: {}",
e
)))
})?;
}
let supports_range = if head_supports_range {
true
} else if total_length > constants::CONCURRENT_MIN_FILE_SIZE as u64 {
let prober = RangeProber::new(Arc::clone(&self.client), self.request_policy.clone())
.with_cookie_header(
url_for_head
.as_ref()
.map(|url| {
self.create_cookie_helper()
.build_cookie_header_from_url(url)
})
.filter(|header| !header.is_empty()),
);
prober.probe_range_support(uri, total_length).await
} else {
false
};
let original_path = self.output_path.clone();
if options.remove_control_file {
let control_path =
crate::filesystem::control_file::ControlFile::control_path_for(&original_path);
match tokio::fs::remove_file(&control_path).await {
Ok(()) => info!(path = %control_path.display(), "Removed requested control file"),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => {
return Err(Aria2Error::FileIo(format!(
"Failed to remove control file {}: {}",
control_path.display(),
error
)));
}
}
}
if !self.output_path_resolved {
self.output_path = global_registry()
.resolve_with_policy(
&original_path,
OutputPathPolicy {
allow_overwrite: options.allow_overwrite,
auto_file_renaming: options.auto_file_renaming,
continue_download: options.continue_download,
check_integrity: self.check_integrity,
total_length: (total_length > 0).then_some(total_length),
},
)
.await?;
self.output_path_resolved = true;
} else {
// A mirror failover re-enters this attempt with the same command.
// Reclaim the already-resolved path instead of applying the
// filesystem collision policy a second time and renaming the
// partial/preallocated output.
self.output_path = global_registry().resolve(&self.output_path).await;
}
if self.output_path != original_path {
info!(
"Filename collision resolved: '{}' -> '{}'",
original_path.display(),
self.output_path.display()
);
}
let continue_download = options.continue_download;
let resume_helper = ResumeHelper::new(&self.output_path, continue_download);
let mut resume_state = match resume_helper.detect(total_length).await {
Ok(state) => state,
Err(error) => {
release_path(&self.output_path).await;
return Err(error);
}
};
// When resuming from a paused state, never short-circuit as "complete" --
// the file on disk may be a preallocated sparse file that matches
// total_length but hasn't actually been fully written. A download that
// was explicitly paused by the user must always continue from where it
// left off, relying on the control file's bitfield to determine which
// ranges still need fetching.
let was_paused = self.group.recover().is_paused_flag();
if resume_state.is_complete && !was_paused && !self.check_integrity {
info!(
"File already exists completely, skipping download: {} ({} bytes)",
self.output_path.display(),
resume_state.existing_length
);
self.completed_bytes = resume_state.existing_length;
{
let g = self.group.recover();
g.set_total_length(self.completed_bytes);
g.update_progress(self.completed_bytes);
g.set_completed_length(self.completed_bytes);
}
{
let mut g = self.group.recover_mut();
g.complete()?;
}
self.completed = true;
release_path(&self.output_path).await;
return Ok(());
}
// Final cancellation check before kicking off the (potentially long)
// network transfer. If the task was removed during the HEAD probe or
// resume detection, abort now rather than downloading data that will
// just be discarded. This is placed before spawn_progress_aggregator
// so a cancelled task does not spawn an unnecessary aggregator task.
// Release the registered output path so future downloads can reuse
// the filename.
if let Err(e) = self.check_cancelled() {
release_path(&self.output_path).await;
return Err(e);
}
// Initialize tail reclaim progress tracking before the download loop.
// Mirrors C++ DownloadCommand constructor which initializes
// lastTailReclaimSessionDownloadLength_ to 0.
self.update_tail_reclaim_progress();
let download_result: Result<()> = async {
// --check-integrity: when the download context carries piece
// hashes (e.g. Metalink), verify the existing file chunk-by-chunk
// before allocating/downloading (mirrors C++ CheckIntegrityMan +
// CheckIntegrityCommand). No-op when there is nothing to validate.
if self.check_integrity && total_length > 0 {
use crate::checksum::check_integrity::{
man as ci_man, IntegrityTrailingGarbageAction,
};
IntegrityTrailingGarbageAction::single_file(
self.output_path.clone(),
total_length,
)
.apply()
.await?;
use crate::checksum::message_digest::HashType;
// Extract owned data first so the RwLock guard is dropped
// before any await (guard is not Send).
let piece_info = self
.group
.recover()
.get_download_context()
.map(|ctx| {
(
ctx.get_piece_hashes()
.iter()
.map(|hash| hash.to_string())
.collect(),
ctx.get_piece_length() as u64,
ctx.get_piece_hash_type().to_string(),
)
});
if let Some((hashes, piece_len, hash_type)) = piece_info {
let algo = if hash_type.is_empty() {
// Empty piece-hash metadata is the legacy SHA-1
// default used by BitTorrent-style contexts.
HashType::Sha1
} else {
HashType::from_str(&hash_type).ok_or_else(|| {
Aria2Error::Parse(format!(
"unknown piece hash algorithm: {hash_type}"
))
})?
};
if let Some(task) = ci_man::file_task(
&self.output_path,
piece_len.max(1),
total_length,
hashes,
algo,
)? {
let gid = self.group.recover().gid().value();
info!(gid, "Checking integrity of existing data against piece hashes");
let outcome = ci_man::enqueue_with_outcome_for_group(
&ci_man::shared(),
Arc::clone(&self.group),
task,
)
.await?;
let ok = outcome.verified;
if !ok {
warn!(
gid,
"Integrity check failed; discarding resume state and re-downloading"
);
// C++ StreamCheckIntegrityEntry::onDownloadIncomplete()
// sends the request back through allocation/download rather
// than terminating the request. Do not reuse offsets derived
// from data that failed validation.
resume_state.should_resume = false;
resume_state.start_offset = 0;
resume_state.is_complete = false;
} else {
info!(gid, "Integrity check passed");
// A successful pre-download integrity check proves
// the complete existing file is already usable. Do
// not issue a range request at EOF or reallocate it.
if resume_state.existing_length >= total_length {
self.completed_bytes = total_length;
resume_state.start_offset = total_length;
resume_state.is_complete = true;
{
let mut group = self.group.recover_mut();
group.set_completed_length(total_length);
group.complete()?;
}
self.completed = true;
release_path(&self.output_path).await;
return Ok(());
}
}
}
}
}
if total_length > 0 {
// Queue the allocation through the shared FileAllocationMan
// (mirrors C++ FileAllocationMan + FileAllocationCommand):
// the background worker drives chunked allocation sequentially
// across downloads and yields between chunks, so a huge
// zero-fill never blocks a worker thread or starves other
// downloads. This task resumes once the file is ready.
let strategy = file_allocation::AllocationStrategy::from_str(&self.file_allocation);
if strategy != file_allocation::AllocationStrategy::None {
let gid = self.group.recover().gid().value();
file_allocation_man::enqueue_path(
&file_allocation_man::shared(),
&self.output_path,
total_length,
strategy,
self.secure_falloc,
gid,
)
.await?;
}
}
let options = self.group.recover().options_arc();
let requested_split = options.split.unwrap_or(constants::DEFAULT_SPLIT);
let min_split_size = self.group.recover().effective_min_split_size();
let split = crate::engine::concurrent_download::effective_segment_count(
total_length,
requested_split,
min_split_size,
) as u16;
let cookie_helper = self.create_cookie_helper();
let progress_updater = self.create_progress_updater();
if self.should_use_concurrent(total_length, supports_range, split)
&& !options.http_accept_gzip
{
if resume_state.should_resume {
info!(
"Concurrent mode + resume: existing {} bytes, continuing from offset {}",
resume_state.existing_length, resume_state.start_offset
);
}
let max_retries = options.max_retries;
let target_scheme = reqwest::Url::parse(uri)
.ok()
.map(|url| url.scheme().to_owned())
.unwrap_or_else(|| "http".to_string());
let (proxy_user, proxy_passwd) = options.proxy_credentials_for_scheme(
&target_scheme,
);
let auth_options = crate::http::AuthResolveOptions {
http_auth_challenge: options.http_auth_challenge,
no_netrc: options.no_netrc,
http_user: options.http_user.clone(),
http_passwd: options.http_passwd.clone(),
ftp_user: options.ftp_user.clone(),
ftp_passwd: options.ftp_passwd.clone(),
proxy_user,
proxy_passwd,
};
let progress_arc = Arc::clone(&self.progress);
let mut concurrent_downloader = ConcurrentDownloader::new(
Arc::clone(&self.client),
self.output_path.clone(),
self.request_policy.clone(),
auth_options,
options.netrc_path.clone(),
cookie_helper.clone(),
progress_updater.clone(),
Arc::clone(&self.group),
progress_arc,
self.mmap_threshold,
self.file_allocation.clone(),
self.global_limiter.clone(),
);
match concurrent_downloader.execute_with_retry(
uri,
total_length,
&resume_state,
max_retries,
).await {
Ok(ConcurrentDownloadResult::Complete) => return Ok(()),
Ok(ConcurrentDownloadResult::Fallback { completed_ranges }) => {
warn!(
"Concurrent download falling back to sequential mode, preserving {} completed ranges",
completed_ranges.len()
);
let retry_policy = RetryPolicy::new(options.max_retries, options.retry_wait * 1000);
let mut sequential_downloader = SequentialDownloader::new(
Arc::clone(&self.client),
self.output_path.clone(),
self.request_policy.clone(),
cookie_helper,
progress_updater,
Arc::clone(&self.group),
Arc::clone(&self.progress),
self.global_limiter.clone(),
);
let result = sequential_downloader.execute_with_gaps_with_retry(
uri,
total_length,
&completed_ranges,
&retry_policy,
).await;
drop(sequential_downloader);
return result;
}
Err(e) => return Err(e),
}
}
let retry_policy = RetryPolicy::new(options.max_retries, options.retry_wait * 1000);
let mut sequential_downloader = SequentialDownloader::new(
Arc::clone(&self.client),
self.output_path.clone(),
self.request_policy.clone(),
cookie_helper,
progress_updater,
Arc::clone(&self.group),
Arc::clone(&self.progress),
self.global_limiter.clone(),
);
let result = sequential_downloader.execute_with_retry(
uri,
&resume_state,
total_length,
&retry_policy,
).await;
drop(sequential_downloader);
result
}
.await;
// Update tail reclaim tracking after download attempt completes.
// In C++ this is called on every data chunk (executeInternal loop);
// here we update at the boundary since the Rust architecture uses
// async downloaders that manage their own data loops internally.
self.update_tail_reclaim_progress();
if download_result.is_ok() {
// Verify checksum if configured
// Extract checksum config before any .await to avoid holding std::sync::RwLockReadGuard across await points
let checksum_config = {
let g = self.group.recover();
g.options().checksum.clone()
};
if let Some((ref algo, ref expected)) = checksum_config
&& let Some(ht) = HashType::from_str(algo)
{
let cs = Checksum::new(ht, expected)?;
let total_length = self.group.recover().total_length();
let verified =
crate::checksum::check_integrity::man::enqueue_file_checksum_for_group(
&crate::checksum::check_integrity::man::shared(),
Arc::clone(&self.group),
&self.output_path,
total_length,
cs,
)
.await?;
if !verified {
tracing::error!(
algo = %algo,
path = %self.output_path.display(),
"Checksum mismatch"
);
return Err(Aria2Error::Checksum(format!(
"{} checksum mismatch for {}",
algo,
self.output_path.display()
)));
}
tracing::info!(
algo = %algo,
path = %self.output_path.display(),
"Checksum verified successfully"
);
{
let group = self.group.recover();
group.set_checksum_verified(true);
}
}
self.completed = true;
let g = self.group.recover();
let total = g.total_length();
g.update_progress(total);
g.set_completed_length(total);
}
release_path(&self.output_path).await;
download_result
}
}
#[async_trait]
impl Command for DownloadCommand {
async fn execute(&mut self) -> Result<()> {
// Check for early cancellation (task removed before execution started).
self.check_cancelled()?;
if !self.started {
self.group.recover_mut().start()?;
self.started = true;
}
let uris = self.candidate_uris();
let first_uri = uris.first().cloned().ok_or_else(|| {
Aria2Error::Fatal(crate::error::FatalError::Config(
"Download URI is empty".into(),
))
})?;
// MemoryPreDownloadHandler semantics are represented explicitly on
// the group. Follow options also live on payload groups, so deriving
// this from DownloadOptions would incorrectly turn a normal payload
// into an in-memory source download.
if self.group.recover().is_in_memory_download() {
return self.execute_in_memory(&first_uri).await;
}
// One aggregator belongs to the command generation, not to an
// individual mirror attempt. Keeping it alive lets progress continue
// monotonically while a failed resume moves to the next URI.
self.spawn_progress_aggregator();
let mut last_error = None;
let mut candidates = uris.into_iter().peekable();
while let Some(uri) = candidates.next() {
match self.execute_attempt(&uri).await {
Ok(()) => {
self.drain_progress_aggregator().await;
return Ok(());
}
Err(error)
if matches!(
&error,
Aria2Error::Recoverable(crate::error::RecoverableError::CannotResume)
) =>
{
let failure_count = self.group.recover().increase_resume_failure_count();
self.group.recover().add_uri_result(
uri.clone(),
DownloadResultCode::CannotResume.as_code() as u16,
);
last_error = Some(error);
let options = self.group.recover().options_arc();
let limit_reached = options.max_resume_failure_tries > 0
&& failure_count >= options.max_resume_failure_tries;
let no_mirror_left = candidates.peek().is_none();
if !options.always_resume && (limit_reached || no_mirror_left) {
if let Err(reset_error) = self.prepare_fresh_download().await {
last_error = Some(reset_error);
break;
}
match self.execute_attempt(&uri).await {
Ok(()) => {
self.drain_progress_aggregator().await;
return Ok(());
}
Err(error) => last_error = Some(error),
}
break;
}
}
Err(error) => {
last_error = Some(error);
// A request group may contain mirrors. Exhaust the
// candidates before returning the last error so a
// transient or mirror-local failure does not abort the
// whole download prematurely.
if candidates.peek().is_none() {
break;
}
}
}
}
self.drain_progress_aggregator().await;
Err(last_error.unwrap_or_else(|| {
Aria2Error::Fatal(crate::error::FatalError::Config(
"No download URI is available".into(),
))
}))
}
fn status(&self) -> CommandStatus {
if self.completed {
CommandStatus::Completed
} else if self.completed_bytes > 0 {
CommandStatus::Running
} else {
CommandStatus::Pending
}
}
fn gid(&self) -> GroupId {
self.group.recover().gid()
}
fn request_group(
&self,
) -> Option<std::sync::Arc<std::sync::RwLock<crate::request::request_group::RequestGroup>>>
{
Some(std::sync::Arc::clone(&self.group))
}
fn timeout(&self) -> Option<Duration> {
self.group.recover().timeout()
}
}
impl DownloadCommand {
fn candidate_uris(&self) -> Vec<String> {
let mut candidates = Vec::new();
if !self.initial_uri.is_empty() {
candidates.push(self.initial_uri.clone());
}
let group_uris = self.group.recover().uris().to_vec();
for uri in group_uris {
if !uri.is_empty() && !candidates.iter().any(|candidate| candidate == uri.as_ref()) {
candidates.push(uri.to_string());
}
}
candidates
}
/// Reset the shared output for aria2's fresh-download fallback.
///
/// This operation belongs to the command-generation seam: the protocol
/// downloader reports `CannotResume`, while the command decides whether
/// the failure means "try another mirror" or "start from byte zero".
async fn prepare_fresh_download(&mut self) -> Result<()> {
let control_path =
crate::filesystem::control_file::ControlFile::control_path_for(&self.output_path);
match tokio::fs::remove_file(&control_path).await {
Ok(()) => tracing::debug!(
path = %control_path.display(),
"Removed control file before fresh download"
),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => {
return Err(Aria2Error::FileIo(format!(
"Failed to reset control file {}: {}",
control_path.display(),
error
)));
}
}
let file = tokio::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&self.output_path)
.await
.map_err(|error| {
Aria2Error::FileIo(format!(
"Failed to truncate output file {}: {}",
self.output_path.display(),
error
))
})?;
file.sync_data().await.map_err(|error| {
Aria2Error::FileIo(format!(
"Failed to flush truncated output file {}: {}",
self.output_path.display(),
error
))
})?;
drop(file);
self.completed_bytes = 0;
self.progress.set_completed_length(0);
let group = self.group.recover();
group.update_progress(0);
group.set_completed_length(0);
Ok(())
}
/// Download a metadata source into a memory buffer, retrying transient
/// failures according to the original HTTP skip-response contract.
async fn execute_in_memory(&mut self, uri: &str) -> Result<()> {
let options = self.group.recover().options_arc();
let retry_policy =
RetryPolicy::new(options.max_retries, options.retry_wait.saturating_mul(1000));
let mut attempt = 0u32;
loop {
match self.execute_in_memory_attempt(uri).await {
Ok(()) => return Ok(()),
Err(error)
if should_retry_in_memory_error(
&error,
attempt,
&retry_policy,
options.retry_wait,
self.group.recover().can_retry_file_not_found(),
) =>
{
attempt = attempt.saturating_add(1);
if options.retry_wait > 0 {
self.wait_for_retry(Duration::from_secs(options.retry_wait))
.await?;
}
}
Err(error) => return Err(error),
}
}
}
/// Wait between metadata retries while still honoring RequestGroup
/// pause, remove, and halt requests.
pub(super) async fn wait_for_retry(&self, wait: Duration) -> Result<()> {
let notifier = self.group.recover().lifecycle_notifier();
let notified = notifier.notified();
tokio::pin!(notified);
notified.as_mut().enable();
self.check_cancelled()?;
tokio::select! {
_ = tokio::time::sleep(wait) => self.check_cancelled(),
_ = &mut notified => self.check_cancelled(),
}
}
/// Download one metadata source into a memory buffer.
///
/// This is the Rust equivalent of aria2's memory pre-download handler:
/// the response is streamed into an owned `Vec<u8>`, no output path is
/// opened, and the post-download handler consumes the buffer before the
/// parent group is demoted.
async fn execute_in_memory_attempt(&mut self, uri: &str) -> Result<()> {
self.check_cancelled()?;
// A JSON/session restore may already carry the completed metadata
// bytes. Reuse them before opening the network source; this preserves
// `follow-*=mem` across a restart and keeps a completed metadata
// prerequisite from becoming an unnecessary second download.
if let Some(data) = self.group.recover().in_memory_data() {
let completed = data.len() as u64;
let group = self.group.recover();
group.set_total_length(completed);
group.set_completed_length(completed);
if group.content_type().is_none() {
group.set_content_type("application/octet-stream");
}
group.set_in_memory_data(data);
drop(group);
self.completed_bytes = completed;
self.completed = true;
self.group.recover_mut().complete()?;
return Ok(());
}
let url = reqwest::Url::parse(uri).ok();
let cookie_header = url
.as_ref()
.map(|url| {
self.create_cookie_helper()
.build_cookie_header_from_url(url)
})
.filter(|header| !header.is_empty());
let request =
self.request_policy
.apply(self.client.get(uri), cookie_header.as_deref(), &[]);
let response = request.send().await.map_err(|error| {
Aria2Error::Recoverable(crate::error::RecoverableError::TemporaryNetworkFailure {
message: error.to_string(),
})
})?;
let status = response.status();
if !status.is_success() {
if status.as_u16() == 404 {
return Err(self.group.recover().file_not_found_error());
}
if status.is_server_error() {
return Err(Aria2Error::Recoverable(
crate::error::RecoverableError::ServerError {
code: status.as_u16(),
},
));
}
return Err(Aria2Error::Recoverable(
crate::error::RecoverableError::HttpProtocolError {
message: format!("HTTP error: {status}"),
},
));
}
let content_type = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
let expected_length = response.content_length().unwrap_or(0);
let mut data = if expected_length > 0 {
Vec::with_capacity(expected_length.min(usize::MAX as u64) as usize)
} else {
Vec::new()
};
let mut stream = response.bytes_stream();
let mut completed = 0u64;
let lifecycle_notify = self.group.recover().lifecycle_notifier();
loop {
let lifecycle_changed = lifecycle_notify.notified();
tokio::pin!(lifecycle_changed);
lifecycle_changed.as_mut().enable();
self.check_cancelled()?;
let chunk = tokio::select! {
chunk = stream.next() => chunk,
_ = lifecycle_changed => {
self.check_cancelled()?;
continue;
}
};
let Some(chunk) = chunk else {
break;
};
self.check_cancelled()?;
let chunk = chunk.map_err(|error| {
Aria2Error::Recoverable(crate::error::RecoverableError::TemporaryNetworkFailure {
message: error.to_string(),
})
})?;
if !chunk.is_empty() {
// The timeout tracks transport activity, independently of
// buffering and the coarser displayed progress counter.
self.progress.record_network_activity();
}
completed = completed.saturating_add(chunk.len() as u64);
data.extend_from_slice(&chunk);
self.progress.set_completed_length(completed);
self.group.recover().update_progress(completed);
}
let total_length = if expected_length > 0 {
expected_length
} else {
completed
};
let group = self.group.recover();
group.set_total_length(total_length);
group.set_completed_length(completed);
group.mark_in_memory_download();
if let Some(content_type) = content_type {
group.set_content_type(content_type);
}
group.set_in_memory_data(data);
drop(group);
self.completed_bytes = completed;
self.completed = true;
self.group.recover_mut().complete()?;
Ok(())
}
}
/// Return whether an in-memory HTTP metadata failure should start another
/// request. This deliberately has a narrower status policy than the normal
/// file downloader: it mirrors `HttpSkipResponseCommand` for the metadata
/// pre-download path.
pub(super) fn should_retry_in_memory_error(
error: &Aria2Error,
attempt: u32,
retry_policy: &RetryPolicy,
retry_wait_secs: u64,
can_retry_file_not_found: bool,
) -> bool {
if !retry_policy.can_retry_after(attempt.saturating_add(1)) {
return false;
}
match error {
Aria2Error::Recoverable(crate::error::RecoverableError::ResourceNotFound) => {
can_retry_file_not_found
}
Aria2Error::Recoverable(
crate::error::RecoverableError::TemporaryNetworkFailure { .. }
| crate::error::RecoverableError::Timeout,
) => true,
Aria2Error::Recoverable(crate::error::RecoverableError::ServerError { code }) => match code
{
504 => true,
502 | 503 => retry_wait_secs > 0,
_ => false,
},
_ => false,
}
}