|
| 1 | +use std::io::{Read, Write}; |
| 2 | + |
| 3 | +use crossbeam::channel; |
| 4 | +use reqwest::blocking::Client as HttpClient; |
| 5 | +use sha2::Digest; |
| 6 | + |
| 7 | +use crate::tools::validation::normalize_checksum; |
| 8 | + |
| 9 | +#[derive(Debug, thiserror::Error)] |
| 10 | +pub enum DownloadError { |
| 11 | + #[error("failed to download {path}: {details}")] |
| 12 | + DownloadFailed { path: String, details: String }, |
| 13 | + #[error("size mismatch for {path}: expected {expected} bytes, got {actual} bytes")] |
| 14 | + SizeMismatch { |
| 15 | + path: String, |
| 16 | + expected: u64, |
| 17 | + actual: u64, |
| 18 | + }, |
| 19 | + #[error("checksum mismatch for {path}: expected {expected}, got {actual}")] |
| 20 | + ChecksumMismatch { |
| 21 | + path: String, |
| 22 | + expected: String, |
| 23 | + actual: String, |
| 24 | + }, |
| 25 | + #[error("invalid checksum: {0}")] |
| 26 | + InvalidChecksum(String), |
| 27 | + #[error("writer error: {0}")] |
| 28 | + WriterError(#[from] std::io::Error), |
| 29 | + #[error("invalid path: {0}")] |
| 30 | + InvalidPath(String), |
| 31 | +} |
| 32 | + |
| 33 | +/// A single file download task. |
| 34 | +#[derive(Clone)] |
| 35 | +pub struct DownloadTask<W> { |
| 36 | + pub rel_path: String, |
| 37 | + pub url: String, |
| 38 | + pub writer: W, |
| 39 | + pub expected_size: u64, |
| 40 | + pub expected_checksum: String, |
| 41 | +} |
| 42 | + |
| 43 | +/// Download multiple files in parallel. |
| 44 | +pub fn download_tasks<W: Write + Send>( |
| 45 | + http: &HttpClient, |
| 46 | + tasks: Vec<DownloadTask<W>>, |
| 47 | + max_parallel: usize, |
| 48 | +) -> Result<(), DownloadError> { |
| 49 | + if tasks.is_empty() { |
| 50 | + return Ok(()); |
| 51 | + } |
| 52 | + |
| 53 | + if max_parallel <= 1 || tasks.len() == 1 { |
| 54 | + for mut task in tasks { |
| 55 | + download_one(http, &mut task)?; |
| 56 | + } |
| 57 | + return Ok(()); |
| 58 | + } |
| 59 | + |
| 60 | + let (tx, rx) = channel::unbounded::<DownloadTask<W>>(); |
| 61 | + for task in tasks { |
| 62 | + tx.send(task).expect("channel open"); |
| 63 | + } |
| 64 | + drop(tx); |
| 65 | + |
| 66 | + crossbeam::scope(|scope| { |
| 67 | + let mut handles = Vec::new(); |
| 68 | + let worker_count = max_parallel.min(rx.len().max(1)); |
| 69 | + for _ in 0..worker_count { |
| 70 | + let rx = rx.clone(); |
| 71 | + let http = http.clone(); |
| 72 | + handles.push(scope.spawn(move |_| { |
| 73 | + for mut task in rx.iter() { |
| 74 | + download_one(&http, &mut task)?; |
| 75 | + } |
| 76 | + Ok::<(), DownloadError>(()) |
| 77 | + })); |
| 78 | + } |
| 79 | + |
| 80 | + for handle in handles { |
| 81 | + handle.join().expect("thread panicked")?; |
| 82 | + } |
| 83 | + |
| 84 | + Ok(()) |
| 85 | + }) |
| 86 | + .expect("scope failed") |
| 87 | +} |
| 88 | + |
| 89 | +/// Download a single file with checksum verification. |
| 90 | +fn download_one<W: Write>( |
| 91 | + http: &HttpClient, |
| 92 | + task: &mut DownloadTask<W>, |
| 93 | +) -> Result<(), DownloadError> { |
| 94 | + // if let Some(parent) = task.dest.parent() { |
| 95 | + // fs::create_dir_all(parent)?; |
| 96 | + // } |
| 97 | + |
| 98 | + // let tmp = temp_path(&task.dest)?; |
| 99 | + |
| 100 | + let mut resp = http |
| 101 | + .get(&task.url) |
| 102 | + .send() |
| 103 | + .map_err(|e| DownloadError::DownloadFailed { |
| 104 | + path: task.rel_path.clone(), |
| 105 | + details: e.to_string(), |
| 106 | + })?; |
| 107 | + |
| 108 | + if !resp.status().is_success() { |
| 109 | + return Err(DownloadError::DownloadFailed { |
| 110 | + path: task.rel_path.clone(), |
| 111 | + details: format!("HTTP {}", resp.status()), |
| 112 | + }); |
| 113 | + } |
| 114 | + |
| 115 | + let sink = &mut task.writer; |
| 116 | + let mut hasher = sha2::Sha256::new(); |
| 117 | + let mut buf = [0u8; 1024 * 64]; |
| 118 | + let mut total = 0u64; |
| 119 | + |
| 120 | + loop { |
| 121 | + let read = resp.read(&mut buf)?; |
| 122 | + if read == 0 { |
| 123 | + break; |
| 124 | + } |
| 125 | + sink.write_all(&buf[..read])?; |
| 126 | + hasher.update(&buf[..read]); |
| 127 | + total += read as u64; |
| 128 | + } |
| 129 | + |
| 130 | + let digest = format!("{:x}", hasher.finalize()); |
| 131 | + let expected_checksum = |
| 132 | + normalize_checksum(&task.expected_checksum).map_err(DownloadError::InvalidChecksum)?; |
| 133 | + |
| 134 | + if total != task.expected_size { |
| 135 | + return Err(DownloadError::SizeMismatch { |
| 136 | + path: task.rel_path.clone(), |
| 137 | + expected: task.expected_size, |
| 138 | + actual: total, |
| 139 | + }); |
| 140 | + } |
| 141 | + if digest != expected_checksum { |
| 142 | + return Err(DownloadError::ChecksumMismatch { |
| 143 | + path: task.rel_path.clone(), |
| 144 | + expected: expected_checksum, |
| 145 | + actual: digest, |
| 146 | + }); |
| 147 | + } |
| 148 | + |
| 149 | + // if task.dest.exists() { |
| 150 | + // fs::remove_file(&task.dest)?; |
| 151 | + // } |
| 152 | + |
| 153 | + // fs::rename(tmp, &task.dest)?; |
| 154 | + |
| 155 | + Ok(()) |
| 156 | +} |
| 157 | + |
| 158 | +// /// Generate a temporary file path for downloads. |
| 159 | +// fn temp_path(dest: &Path) -> Result<PathBuf, RegistryError> { |
| 160 | +// let file_name = dest |
| 161 | +// .file_name() |
| 162 | +// .ok_or_else(|| RegistryError::InvalidPath("missing file name".to_string()))? |
| 163 | +// .to_string_lossy(); |
| 164 | +// Ok(dest.with_file_name(format!(".{file_name}.partial"))) |
| 165 | +// } |
0 commit comments