use crate::error::Result;
use std::path::{Path, PathBuf};
use super::control_file::ControlFile;
pub struct ResumeHelper {
output_path: PathBuf,
control_path: PathBuf,
continue_opt: bool,
}
#[derive(Debug, Clone)]
pub struct ResumeState {
pub existing_length: u64,
pub control_file: Option<ControlFile>,
pub start_offset: u64,
pub should_resume: bool,
pub is_complete: bool,
}
pub(crate) fn is_sequential_checkpoint(cf: &ControlFile, total_length: u64) -> bool {
cf.total_length() == total_length
&& !cf.is_torrent_checkpoint()
&& cf
.piece_length()
.is_some_and(|piece_length| u64::from(piece_length) >= total_length)
}
fn in_flight_prefix(cf: &ControlFile, index: u64) -> u64 {
const BLOCK_SIZE: u64 = 16 * 1024;
let Some(piece_length) = cf.piece_length().map(u64::from) else {
return 0;
};
let Some(expected_length) = index
.checked_mul(piece_length)
.and_then(|offset| cf.total_length().checked_sub(offset))
.map(|remaining| remaining.min(piece_length))
else {
return 0;
};
if expected_length == 0 {
return 0;
}
cf.in_flight_pieces()
.iter()
.find(|piece| u64::from(piece.index) == index && u64::from(piece.length) == expected_length)
.map(|piece| {
let blocks = (0..piece.bitfield.len() * 8)
.take_while(|block| piece.bitfield[block / 8] & (1 << (7 - block % 8)) != 0)
.count() as u64;
blocks.saturating_mul(BLOCK_SIZE).min(expected_length)
})
.unwrap_or(0)
}
impl ResumeHelper {
pub fn new(output_path: &Path, continue_opt: bool) -> Self {
let control_path = ControlFile::control_path_for(output_path);
Self {
output_path: output_path.to_path_buf(),
control_path,
continue_opt,
}
}
pub fn control_path(&self) -> &Path {
&self.control_path
}
pub async fn detect(&self, total_length: u64) -> Result<ResumeState> {
let file_exists = self.output_path.exists();
if !file_exists && self.control_path.exists() {
tokio::fs::remove_file(&self.control_path)
.await
.map_err(|error| {
crate::error::Aria2Error::FileIo(format!(
"Failed to remove defunct control file {}: {}",
self.control_path.display(),
error
))
})?;
}
if !self.continue_opt {
return Ok(ResumeState {
existing_length: 0,
control_file: None,
start_offset: 0,
should_resume: false,
is_complete: false,
});
}
let existing_length = if file_exists {
tokio::fs::metadata(&self.output_path)
.await
.map(|m| m.len())
.unwrap_or(0)
} else {
0
};
if !file_exists && !self.control_path.exists() {
return Ok(ResumeState {
existing_length: 0,
control_file: None,
start_offset: 0,
should_resume: false,
is_complete: false,
});
}
let ctrl = ControlFile::load(&self.control_path).await?;
let (start_offset, should_resume, is_complete) = match (&ctrl, existing_length) {
(Some(cf), _) => {
let offset = match cf.piece_length().map(u64::from) {
Some(piece_length)
if !is_sequential_checkpoint(cf, cf.total_length())
&& (cf.completed_pieces() > 0 || !cf.in_flight_pieces().is_empty()) =>
{
let leading_pieces =
(0..).take_while(|&index| cf.is_piece_done(index)).count() as u64;
let run_end = leading_pieces.saturating_mul(piece_length);
let run = run_end.min(cf.total_length()).min(cf.completed_length());
if run == run_end {
run + in_flight_prefix(cf, leading_pieces)
} else {
run
}
}
_ => cf.completed_length(),
};
let complete =
cf.completed_length() >= total_length && cf.total_length() == total_length;
let should_resume = cf.completed_pieces() > 0 || offset > 0;
(offset, should_resume, complete)
}
(_, len) if len >= total_length && total_length > 0 => (0, false, true),
(_, len) if len > 0 => (len, true, false),
_ => (0, false, false),
};
Ok(ResumeState {
existing_length,
control_file: ctrl,
start_offset,
should_resume,
is_complete,
})
}
pub fn build_range_header(state: &ResumeState) -> Option<String> {
if state.should_resume && state.start_offset > 0 {
Some(format!("bytes={}-", state.start_offset))
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_detect_no_continue() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("test.bin");
tokio::fs::write(&path, b"partial data").await.unwrap();
let helper = ResumeHelper::new(&path, false);
let state = helper.detect(1000).await.unwrap();
assert!(!state.should_resume);
assert_eq!(state.start_offset, 0);
}
#[tokio::test]
async fn test_detect_no_file_no_control() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("nonexistent.bin");
let helper = ResumeHelper::new(&path, true);
let state = helper.detect(10000).await.unwrap();
assert!(!state.should_resume);
assert_eq!(state.start_offset, 0);
}
#[tokio::test]
async fn test_detect_partial_file_no_control() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("partial.bin");
tokio::fs::write(&path, vec![0xAB; 500]).await.unwrap();
let helper = ResumeHelper::new(&path, true);
let state = helper.detect(2000).await.unwrap();
assert!(state.should_resume);
assert_eq!(state.start_offset, 500);
assert_eq!(state.existing_length, 500);
assert!(!state.is_complete);
}
#[tokio::test]
async fn test_detect_partial_file_when_remote_length_is_unknown() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("unknown-length.bin");
tokio::fs::write(&path, vec![0xAB; 500]).await.unwrap();
let helper = ResumeHelper::new(&path, true);
let state = helper.detect(0).await.unwrap();
assert!(state.should_resume);
assert_eq!(state.start_offset, 500);
assert_eq!(
ResumeHelper::build_range_header(&state).as_deref(),
Some("bytes=500-")
);
assert!(!state.is_complete);
}
#[tokio::test]
async fn test_detect_with_control_file() {
let dir = tempfile::tempdir().unwrap();
let out_path = dir.path().join("download.iso");
let ctrl_path = ControlFile::control_path_for(&out_path);
tokio::fs::write(&out_path, vec![0xCD; 300]).await.unwrap();
let mut cf = ControlFile::open_or_create(&ctrl_path, 1000, 10)
.await
.unwrap();
cf.mark_piece_done(0);
cf.mark_piece_done(1);
cf.mark_piece_done(2);
cf.save().await.unwrap();
let helper = ResumeHelper::new(&out_path, true);
let state = helper.detect(1000).await.unwrap();
assert!(state.should_resume);
assert!(state.control_file.is_some());
assert_eq!(state.start_offset, 300);
assert!(!state.is_complete);
}
#[tokio::test]
async fn split_checkpoint_resumes_from_only_the_contiguous_prefix() {
let dir = tempfile::tempdir().unwrap();
let out_path = dir.path().join("split-gap.bin");
let control_path = ControlFile::control_path_for(&out_path);
let total_length = 1000;
let piece_length = 100;
tokio::fs::write(&out_path, vec![0xCD; total_length as usize])
.await
.unwrap();
let mut control = ControlFile::open_or_create_with_piece_length(
&control_path,
total_length,
piece_length,
)
.await
.unwrap();
control.mark_piece_done(0);
control.mark_piece_done(2);
control.save().await.unwrap();
let state = ResumeHelper::new(&out_path, true).detect(0).await.unwrap();
assert!(state.should_resume);
assert_eq!(state.start_offset, piece_length as u64);
assert_eq!(
ResumeHelper::build_range_header(&state).as_deref(),
Some("bytes=100-")
);
}
#[tokio::test]
async fn split_checkpoint_with_in_flight_pieces_is_not_read_as_a_prefix() {
use crate::filesystem::control_file::ControlFileInFlightPiece;
let dir = tempfile::tempdir().unwrap();
let out_path = dir.path().join("split-in-flight.bin");
let control_path = ControlFile::control_path_for(&out_path);
let total_length = 256 * 1024;
let piece_length = 64 * 1024;
tokio::fs::write(&out_path, vec![0xCD; total_length as usize])
.await
.unwrap();
let mut control = ControlFile::open_or_create_with_piece_length(
&control_path,
total_length,
piece_length,
)
.await
.unwrap();
control.set_in_flight_pieces(vec![
ControlFileInFlightPiece {
index: 0,
length: piece_length,
bitfield: vec![0b1100_0000],
},
ControlFileInFlightPiece {
index: 2,
length: piece_length,
bitfield: vec![0b1110_0000],
},
]);
control.update_completed_length(80 * 1024);
control.save().await.unwrap();
let state = ResumeHelper::new(&out_path, true).detect(0).await.unwrap();
assert!(state.should_resume);
assert_eq!(state.start_offset, 32 * 1024);
control.mark_piece_done(0);
control.mark_piece_done(1);
control.set_in_flight_pieces(vec![ControlFileInFlightPiece {
index: 2,
length: piece_length,
bitfield: vec![0b1110_0000],
}]);
control.update_completed_length(176 * 1024);
control.save().await.unwrap();
let state = ResumeHelper::new(&out_path, true).detect(0).await.unwrap();
assert_eq!(state.start_offset, 176 * 1024);
}
#[tokio::test]
async fn split_checkpoint_ignores_in_flight_piece_longer_than_file_tail() {
use crate::filesystem::control_file::ControlFileInFlightPiece;
let dir = tempfile::tempdir().unwrap();
let out_path = dir.path().join("short-tail.bin");
let control_path = ControlFile::control_path_for(&out_path);
let total_length = 100 * 1024;
let piece_length = 64 * 1024;
tokio::fs::write(&out_path, vec![0xCD; total_length as usize])
.await
.unwrap();
let mut control = ControlFile::open_or_create_with_piece_length(
&control_path,
total_length,
piece_length,
)
.await
.unwrap();
control.mark_piece_done(0);
control.set_in_flight_pieces(vec![ControlFileInFlightPiece {
index: 1,
length: piece_length,
bitfield: vec![0b1110_0000],
}]);
control.update_completed_length(80 * 1024);
control.save().await.unwrap();
let state = ResumeHelper::new(&out_path, true).detect(0).await.unwrap();
assert!(state.should_resume);
assert_eq!(state.start_offset, piece_length as u64);
assert!(state.start_offset <= total_length);
}
#[tokio::test]
async fn recognizes_single_piece_checkpoint_as_a_sequential_prefix() {
let dir = tempfile::tempdir().unwrap();
let control_path = dir.path().join("sequential.aria2");
let total_length = 1000;
let control = ControlFile::open_or_create_with_piece_length(
&control_path,
total_length,
total_length as u32,
)
.await
.unwrap();
assert!(is_sequential_checkpoint(&control, total_length));
}
#[tokio::test]
async fn test_defunct_control_file_is_removed_when_output_is_missing() {
let dir = tempfile::tempdir().unwrap();
let out_path = dir.path().join("missing.bin");
let ctrl_path = ControlFile::control_path_for(&out_path);
let cf = ControlFile::open_or_create(&ctrl_path, 1000, 10)
.await
.unwrap();
cf.save().await.unwrap();
assert!(ctrl_path.exists());
let helper = ResumeHelper::new(&out_path, true);
let state = helper.detect(1000).await.unwrap();
assert!(!state.should_resume);
assert_eq!(state.start_offset, 0);
assert!(!ctrl_path.exists());
}
#[tokio::test]
async fn test_detect_file_already_complete() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("complete.bin");
tokio::fs::write(&path, vec![0x42; 1024]).await.unwrap();
let helper = ResumeHelper::new(&path, true);
let state = helper.detect(1024).await.unwrap();
assert!(!state.should_resume);
assert!(state.is_complete);
}
#[tokio::test]
async fn test_build_range_header() {
let state = ResumeState {
existing_length: 500,
control_file: None,
start_offset: 500,
should_resume: true,
is_complete: false,
};
let header = ResumeHelper::build_range_header(&state);
assert_eq!(header, Some("bytes=500-".to_string()));
}
#[tokio::test]
async fn test_build_range_header_no_resume() {
let state = ResumeState {
existing_length: 0,
control_file: None,
start_offset: 0,
should_resume: false,
is_complete: false,
};
let header = ResumeHelper::build_range_header(&state);
assert!(header.is_none());
}
#[tokio::test]
async fn test_build_range_header_zero_offset() {
let state = ResumeState {
existing_length: 0,
control_file: None,
start_offset: 0,
should_resume: true,
is_complete: false,
};
let header = ResumeHelper::build_range_header(&state);
assert!(header.is_none());
}
#[tokio::test]
async fn test_control_path_generation() {
let helper = ResumeHelper::new(Path::new("/downloads/bigfile.iso"), true);
let cp = helper.control_path();
assert!(cp.to_str().unwrap().ends_with(".aria2"));
}
#[tokio::test]
async fn test_detect_preallocated_file_with_control_file_no_pieces() {
let dir = tempfile::tempdir().unwrap();
let out_path = dir.path().join("prealloc.bin");
let ctrl_path = ControlFile::control_path_for(&out_path);
let total_length: u64 = 10000;
tokio::fs::write(&out_path, vec![0x00; total_length as usize])
.await
.unwrap();
let mut cf = ControlFile::open_or_create(&ctrl_path, total_length, 1)
.await
.unwrap();
cf.update_completed_length(4000);
cf.save().await.unwrap();
let helper = ResumeHelper::new(&out_path, true);
let state = helper.detect(total_length).await.unwrap();
assert!(
state.should_resume,
"should_resume must be true when control file has completed_length > 0"
);
assert!(
!state.is_complete,
"is_complete must be false — only 4000/10000 bytes downloaded"
);
assert_eq!(
state.start_offset, 4000,
"start_offset should be the control file's completed_length"
);
}
#[tokio::test]
async fn test_detect_control_file_completed_length_equals_total() {
let dir = tempfile::tempdir().unwrap();
let out_path = dir.path().join("done.bin");
let ctrl_path = ControlFile::control_path_for(&out_path);
let total_length: u64 = 5000;
tokio::fs::write(&out_path, vec![0x42; total_length as usize])
.await
.unwrap();
let mut cf = ControlFile::open_or_create(&ctrl_path, total_length, 1)
.await
.unwrap();
cf.update_completed_length(total_length);
cf.save().await.unwrap();
let helper = ResumeHelper::new(&out_path, true);
let state = helper.detect(total_length).await.unwrap();
assert!(
state.is_complete,
"is_complete must be true when completed_length >= total_length"
);
}
#[tokio::test]
async fn test_detect_preallocated_file_with_zero_control_progress() {
let dir = tempfile::tempdir().unwrap();
let out_path = dir.path().join("fresh-prealloc.bin");
let ctrl_path = ControlFile::control_path_for(&out_path);
let total_length = 4096;
tokio::fs::write(&out_path, vec![0u8; total_length as usize])
.await
.unwrap();
let cf = ControlFile::open_or_create(&ctrl_path, total_length, 1)
.await
.unwrap();
cf.save().await.unwrap();
let state = ResumeHelper::new(&out_path, true)
.detect(total_length)
.await
.unwrap();
assert!(!state.should_resume);
assert!(!state.is_complete);
assert_eq!(state.start_offset, 0);
}
}