From 925d474274f9344951c66cec7567bf026cf0eb99 Mon Sep 17 00:00:00 2001 From: langxp Date: Thu, 26 Nov 2026 17:03:02 +0800 Subject: [PATCH] fix(app): resume interrupted update downloads (#5377) An interrupted update download started again from zero on the next attempt. The update is now downloaded to a .part checkpoint in the app cache, keyed by version, target and signature so the GitHub and CNB sources share it, and later attempts resume it with an HTTP Range request. A 200 answer or a mismatched range replaces the checkpoint safely (the old bytes stay until the new download completes), a 416 for an already complete file is accepted, and the package is verified against its signature before installing; a resumed file that fails verification is discarded and downloaded again. Check and verification are cancellable, and obsolete checkpoints are removed. Co-authored-by: kradme --- src-tauri/Cargo.toml | 2 +- src-tauri/src/commands/window.rs | 74 ++++--- src-tauri/src/updates.rs | 162 +++++++++++++- src-tauri/src/updates/download.rs | 338 ++++++++++++++++++++++++++++++ 4 files changed, 540 insertions(+), 36 deletions(-) create mode 100644 src-tauri/src/updates/download.rs diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 03306949bd..5beeb54000 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -31,6 +31,7 @@ serde_json.workspace = true base64.workspace = true percent-encoding = "2" tokio.workspace = true +reqwest.workspace = true parking_lot.workspace = true blake3.workspace = true tracing.workspace = true @@ -68,7 +69,6 @@ ide-extension = { path = "../crates/ide-extension" } ide-docker = { path = "../crates/ide-docker" } ide-android = { path = "../crates/ide-android" } ide-github = { path = "../crates/ide-github" } -reqwest.workspace = true [dev-dependencies] tempfile.workspace = true diff --git a/src-tauri/src/commands/window.rs b/src-tauri/src/commands/window.rs index 7b737bf4a0..a8a10424ce 100644 --- a/src-tauri/src/commands/window.rs +++ b/src-tauri/src/commands/window.rs @@ -609,7 +609,7 @@ fn configure_updater_client( ide_http::client::with_proxy(builder, proxy).connect_timeout(UPDATER_CONNECT_TIMEOUT) } -fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult> { +pub(crate) fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult> { use tauri_plugin_updater::UpdaterExt; if !updates_configured(app) { return Ok(None); @@ -707,24 +707,23 @@ pub enum UpdateProgress { /// Limits download events to one per whole percent (or per 256 KiB without a length). #[derive(Default)] struct ProgressThrottle { - downloaded: u64, last_step: Option, } impl ProgressThrottle { const UNKNOWN_STEP: u64 = 256 * 1024; - fn chunk(&mut self, len: usize, total: Option) -> Option { - self.downloaded += len as u64; + /// Converts the downloader's absolute byte count into a throttled event. + fn report(&mut self, downloaded: u64, total: Option) -> Option { let step = match total { - Some(t) if t > 0 => self.downloaded.min(t) * 100 / t, - _ => self.downloaded / Self::UNKNOWN_STEP, + Some(t) if t > 0 => downloaded.min(t) * 100 / t, + _ => downloaded / Self::UNKNOWN_STEP, }; if self.last_step == Some(step) { return None; } self.last_step = Some(step); - Some(UpdateProgress::Downloading { downloaded: self.downloaded as f64, total: total.map(|t| t as f64) }) + Some(UpdateProgress::Downloading { downloaded: downloaded as f64, total: total.map(|t| t as f64) }) } } @@ -762,28 +761,22 @@ pub async fn app_install_update( InstallingGuard::acquire().ok_or_else(|| IdeError::unavailable("an update is already being installed"))?; let token = state.host.begin_request(request); let result = async { - let updater = updater(&app, source)?.ok_or_else(|| IdeError::unavailable("updates are not configured"))?; - let update = tokio::select! { - r = updater.check() => r.map_err(|e| IdeError::unavailable(e.to_string()))?, - _ = token.cancelled() => return Err(IdeError::cancelled()), - } - .ok_or_else(|| IdeError::not_found("no update available"))?; let mut throttle = ProgressThrottle::default(); let progress = on_progress.clone(); - let download = update.download( - move |len, total| { - if let Some(p) = throttle.chunk(len, total) { + let downloaded = tokio::select! { + result = crate::updates::download_update(&app, source, &token, move |done, total| { + if let Some(p) = throttle.report(done, total) { let _ = progress.send(p); } - }, - || {}, - ); - let bytes = tokio::select! { - r = download => r.map_err(|e| IdeError::unavailable(e.to_string()))?, + }) => result?, _ = token.cancelled() => return Err(IdeError::cancelled()), }; + let crate::updates::DownloadedUpdate { update, bytes, path } = downloaded; + if token.is_cancelled() { + return Err(IdeError::cancelled()); + } let _ = on_progress.send(UpdateProgress::Installing); - tauri::async_runtime::spawn_blocking(move || { + let installed = tauri::async_runtime::spawn_blocking(move || { #[cfg(windows)] if update.target.ends_with("-portable") { let exe = tauri::utils::platform::current_exe()?; @@ -792,7 +785,11 @@ pub async fn app_install_update( update.install(bytes).map_err(|e| IdeError::internal(e.to_string())) }) .await - .map_err(|e| IdeError::internal(e.to_string()))? + .map_err(|e| IdeError::internal(e.to_string()))?; + if installed.is_ok() { + let _ = tokio::fs::remove_file(path).await; + } + installed } .await; state.host.end_request(request); @@ -923,22 +920,33 @@ mod tests { #[test] fn throttle_reports_each_whole_percent_once() { let mut t = ProgressThrottle::default(); - assert_eq!(downloading(t.chunk(1, Some(1000))), Some((1.0, Some(1000.0)))); - assert_eq!(downloading(t.chunk(5, Some(1000))), None); - assert_eq!(downloading(t.chunk(4, Some(1000))), Some((10.0, Some(1000.0)))); - let reported = (0..99).filter(|_| t.chunk(10, Some(1000)).is_some()).count(); - assert_eq!(reported, 99); - assert_eq!(t.downloaded, 1000); + assert_eq!(downloading(t.report(1, Some(1000))), Some((1.0, Some(1000.0)))); + assert_eq!(downloading(t.report(9, Some(1000))), None); + assert_eq!(downloading(t.report(10, Some(1000))), Some((10.0, Some(1000.0)))); + let reported = (11..=100).filter(|percent| t.report(percent * 10, Some(1000)).is_some()).count(); + assert_eq!(reported, 90); } #[test] fn throttle_without_length_reports_per_step() { let mut t = ProgressThrottle::default(); - assert!(t.chunk(10, None).is_some()); - assert!(t.chunk(1024, None).is_none()); - assert_eq!(downloading(t.chunk(256 * 1024, None)), Some(((256 * 1024 + 1034) as f64, None))); + assert!(t.report(10, None).is_some()); + assert!(t.report(1024, None).is_none()); + assert_eq!(downloading(t.report(256 * 1024 + 1034, None)), Some(((256 * 1024 + 1034) as f64, None))); // A zero length is treated as unknown, not divided by. - assert!(ProgressThrottle::default().chunk(1, Some(0)).is_some()); + assert!(ProgressThrottle::default().report(1, Some(0)).is_some()); + } + + #[test] + fn throttle_uses_absolute_bytes_after_a_full_download_restart() { + let mut t = ProgressThrottle::default(); + let total = 100 * 1024 * 1024; + assert_eq!(downloading(t.report(40 * 1024 * 1024, None)), Some(((40 * 1024 * 1024) as f64, None))); + assert_eq!(downloading(t.report(1024, Some(total))), Some((1024.0, Some(total as f64)))); + assert_eq!( + downloading(t.report(50 * 1024 * 1024, Some(total))), + Some(((50 * 1024 * 1024) as f64, Some(total as f64))) + ); } #[test] diff --git a/src-tauri/src/updates.rs b/src-tauri/src/updates.rs index a3d5304468..da05fa00c5 100644 --- a/src-tauri/src/updates.rs +++ b/src-tauri/src/updates.rs @@ -1,16 +1,28 @@ //! Desktop updater coordination shared by all webviews. -use crate::commands::window::{UpdateSource, check_update, update_endpoint_env, updates_configured}; +mod download; + +use crate::commands::window::{UpdateSource, check_update, update_endpoint_env, updater, updates_configured}; use crate::state::AppState; use ide_core::updates::{UpdateCheck, UpdatePolicy}; -use ide_core::{IdeEvent, IdeResult}; +use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult}; use parking_lot::Mutex; use std::collections::HashSet; +use std::future::Future; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Instant, SystemTime, UNIX_EPOCH}; use tauri::{AppHandle, Manager}; +use tauri_plugin_updater::Update; use tokio::sync::Notify; +/// One verified download, kept on disk until its installer has finished. +pub(crate) struct DownloadedUpdate { + pub update: Update, + pub bytes: Vec, + pub path: PathBuf, +} + /// Tauri patches the installer copies; the raw exe shipped in the portable zip keeps no bundle type. pub fn portable_target(os: &str, arch: &str, bundle: Option) -> Option { (os == "windows" && bundle.is_none()).then(|| format!("windows-{arch}-portable")) @@ -129,6 +141,105 @@ pub async fn check(app: &AppHandle, source: Option) -> IdeResult), +) -> IdeResult { + let updater = updater(app, source)?.ok_or_else(|| IdeError::unavailable("updates are not configured"))?; + let update = + cancellable(token, async { updater.check().await.map_err(|error| IdeError::unavailable(error.to_string())) }) + .await? + .ok_or_else(|| IdeError::not_found("no update available"))?; + let directory = app + .path() + .app_cache_dir() + .map_err(|error| IdeError::internal(format!("update cache directory: {error}")))? + .join("updates"); + tokio::fs::create_dir_all(&directory).await?; + let key = cache_key(&update.version, &update.target, &update.signature); + let path = directory.join(format!("{key}.part")); + if let Err(error) = cleanup_stale_cache_files(&path).await { + tracing::warn!(%error, "cannot clean obsolete update downloads"); + } + let client = ide_http::client::shared()?; + for attempt in 0..3 { + let outcome = + cancellable(token, download::fetch(&client, update.download_url.as_str(), &path, &mut progress)).await?; + match cancellable(token, verify_file(update.clone(), path.clone())).await { + Ok(bytes) => return Ok(DownloadedUpdate { update, bytes, path }), + Err(error) if outcome.resumed && attempt < 2 => { + tracing::warn!(%error, "discarding a mixed update checkpoint"); + tokio::fs::remove_file(&path).await?; + } + Err(_) if outcome.total.is_none() && attempt < 2 => { + tracing::warn!("an update response of unknown length failed verification; resuming"); + } + Err(error) => { + if outcome.resumed || outcome.total.is_some() { + tokio::fs::remove_file(&path).await?; + } + return Err(error); + } + } + } + Err(IdeError::internal("update download did not produce a verified package")) +} + +/// Runs one fallible stage until it finishes or the command is cancelled. The +/// check and signature-verification stages previously escaped cancellation +/// while the download itself was cancellable. +async fn cancellable(token: &CancellationToken, future: impl Future>) -> IdeResult { + tokio::select! { + result = future => result, + _ = token.cancelled() => Err(IdeError::cancelled()), + } +} + +/// Stable cache identity shared by GitHub and CNB for the same signed artifact. +fn cache_key(version: &str, target: &str, signature: &str) -> String { + let hash = blake3::hash(format!("{version}\0{target}\0{signature}").as_bytes()).to_hex(); + format!("{version}-{target}-{hash}") +} + +/// Reads and verifies a completed checkpoint on the blocking pool. +async fn verify_file(update: Update, path: PathBuf) -> IdeResult> { + tauri::async_runtime::spawn_blocking(move || { + let bytes = std::fs::read(path)?; + update.verify(&bytes).map_err(|error| IdeError::internal(error.to_string()))?; + Ok(bytes) + }) + .await + .map_err(|error| IdeError::internal(error.to_string()))? +} + +/// Keeps the current signed artifact's checkpoint and backup while removing +/// obsolete releases and abandoned fallback temporaries. +async fn cleanup_stale_cache_files(path: &Path) -> IdeResult<()> { + let Some(directory) = path.parent() else { return Ok(()) }; + let keep_part = path.file_name(); + let mut keep_backup = path.file_name().unwrap_or_default().to_os_string(); + keep_backup.push(".backup"); + let mut entries = tokio::fs::read_dir(directory).await?; + while let Some(entry) = entries.next_entry().await? { + if !entry.file_type().await?.is_file() { + continue; + } + let name = entry.file_name(); + if Some(name.as_os_str()) == keep_part || name == keep_backup { + continue; + } + let text = name.to_string_lossy(); + if text.ends_with(".part") || text.ends_with(".ready") || text.ends_with(".full") || text.ends_with(".backup") { + let _ = tokio::fs::remove_file(entry.path()).await; + } + } + Ok(()) +} + fn emit_status(state: &AppState) { let status = state.updates.state.lock().policy.status.clone(); state.sink.emit(IdeEvent::UpdateStatusChanged { status }); @@ -195,4 +306,51 @@ mod tests { assert_eq!(ready_owner(Some("main"), &live, &HashSet::new()), None); assert_eq!(ready_owner(Some("closed-window"), &[], &ready), None); } + + /// The cache identity stays stable across mirrors only while the signed bytes do. + #[test] + fn cache_identity_follows_the_signature_not_the_download_url() { + let first = cache_key("0.1.50", "darwin-aarch64", "signature-a"); + assert_eq!(first, cache_key("0.1.50", "darwin-aarch64", "signature-a")); + assert_ne!(first, cache_key("0.1.50", "darwin-aarch64", "signature-b")); + assert_ne!(first, cache_key("0.1.51", "darwin-aarch64", "signature-a")); + } + + /// Starting a download keeps its signed artifact's checkpoint and restores + /// its backup, while obsolete releases and fallback temporaries go away. + #[tokio::test] + async fn stale_update_cache_files_are_removed() { + let dir = tempfile::tempdir().unwrap(); + let current = dir.path().join("current.part"); + for name in + ["current.part", "current.part.backup", "current.part.full", "old.part", "old.ready", "old.part.backup"] + { + tokio::fs::write(dir.path().join(name), b"x").await.unwrap(); + } + tokio::fs::write(dir.path().join("unrelated.json"), b"{}").await.unwrap(); + + cleanup_stale_cache_files(¤t).await.unwrap(); + + assert!(current.exists()); + assert!(dir.path().join("current.part.backup").exists()); + assert!(dir.path().join("unrelated.json").exists()); + for name in ["current.part.full", "old.part", "old.ready", "old.part.backup"] { + assert!(!dir.path().join(name).exists(), "{name} was kept"); + } + } + + /// Signature verification is wrapped in the same cancellation boundary as + /// network work, so a late Cancel cannot fall through into installation. + #[tokio::test] + async fn cancelled_stage_stops_before_installation() { + let token = CancellationToken::new(); + token.cancel(); + let error = cancellable(&token, async { + tokio::time::sleep(std::time::Duration::from_secs(1)).await; + Ok(()) + }) + .await + .unwrap_err(); + assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled); + } } diff --git a/src-tauri/src/updates/download.rs b/src-tauri/src/updates/download.rs new file mode 100644 index 0000000000..b97a838264 --- /dev/null +++ b/src-tauri/src/updates/download.rs @@ -0,0 +1,338 @@ +//! Resumable update downloads for the existing install-and-restart flow. + +use ide_core::{IdeError, IdeResult}; +use reqwest::header::{ACCEPT, ACCEPT_ENCODING, CONTENT_LENGTH, CONTENT_RANGE, RANGE}; +use reqwest::{Client, StatusCode}; +use std::path::{Path, PathBuf}; +use tokio::fs::OpenOptions; +use tokio::io::AsyncWriteExt; + +/// How one request completed: whether it appended to the partial file, and +/// whether the response advertised a total size. +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct Outcome { + pub resumed: bool, + pub total: Option, +} + +/// Appends `url` to `path`, resuming from its current length when the server +/// honours Range. An unsupported Range falls back to replacing the partial file +/// because installing bytes from different representations would be unsafe. +pub(crate) async fn fetch( + client: &Client, + url: &str, + path: &Path, + mut progress: impl FnMut(u64, Option), +) -> IdeResult { + let backup = beside(path, "backup"); + if !path.exists() && backup.exists() { + tokio::fs::rename(&backup, path).await?; + } else if path.exists() { + let _ = tokio::fs::remove_file(backup).await; + } + let mut offset = match tokio::fs::metadata(path).await { + Ok(metadata) => metadata.len(), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => 0, + Err(error) => return Err(error.into()), + }; + + loop { + progress(offset, None); + let mut request = client + .get(url) + .header(ACCEPT, "application/octet-stream") + // A byte offset is only meaningful for the representation the server + // advertised. Automatic content decoding would break that contract. + .header(ACCEPT_ENCODING, "identity"); + if offset > 0 { + request = request.header(RANGE, format!("bytes={offset}-")); + } + let response = request.send().await.map_err(|error| IdeError::unavailable(error.to_string()))?; + let status = response.status(); + + if status == StatusCode::RANGE_NOT_SATISFIABLE && offset > 0 { + let total = + response.headers().get(CONTENT_RANGE).and_then(|value| value.to_str().ok()).and_then(unsatisfied_total); + if total == Some(offset) { + return Ok(Outcome { resumed: true, total }); + } + tokio::fs::remove_file(path).await?; + offset = 0; + continue; + } + + if status == StatusCode::PARTIAL_CONTENT { + let (start, total) = response + .headers() + .get(CONTENT_RANGE) + .and_then(|value| value.to_str().ok()) + .and_then(partial_range) + .ok_or_else(|| IdeError::unavailable("update server sent an invalid Content-Range header"))?; + if start != offset { + // This is not the byte range we asked for. Keep the partial file: + // another mirror may resume it correctly, and this response is not + // safe to append. + return Err(IdeError::unavailable(format!( + "update server returned byte {start} while {offset} was requested" + ))); + } + let mut file = OpenOptions::new().append(true).open(path).await?; + let downloaded = append_body(&mut file, response, offset, total, &mut progress).await?; + ensure_complete(downloaded, total)?; + return Ok(Outcome { resumed: offset > 0, total }); + } + + if status == StatusCode::OK { + let total = response + .headers() + .get(CONTENT_LENGTH) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse().ok()); + if offset > 0 { + replace_with_full(response, path, total, &mut progress).await?; + } else { + let mut file = OpenOptions::new().create(true).write(true).truncate(true).open(path).await?; + let downloaded = append_body(&mut file, response, 0, total, &mut progress).await?; + ensure_complete(downloaded, total)?; + } + return Ok(Outcome { resumed: false, total }); + } + + return Err(IdeError::unavailable(format!("update download failed with HTTP {status}"))); + } +} + +/// Downloads a full response beside the existing partial file. The old bytes +/// stay resumable if the replacement connection fails before completion. +async fn replace_with_full( + response: reqwest::Response, + path: &Path, + total: Option, + progress: &mut impl FnMut(u64, Option), +) -> IdeResult<()> { + let temporary = beside(path, "full"); + let backup = beside(path, "backup"); + let result = async { + let mut file = OpenOptions::new() + .create(true) + .write(true) + .truncate(true) + .open(&temporary) + .await + .map_err(IdeError::from)?; + let downloaded = append_body(&mut file, response, 0, total, progress).await?; + ensure_complete(downloaded, total)?; + let _ = tokio::fs::remove_file(&backup).await; + let had_old = path.exists(); + if had_old { + tokio::fs::rename(path, &backup).await.map_err(IdeError::from)?; + } + if let Err(error) = tokio::fs::rename(&temporary, path).await { + if had_old { + let _ = tokio::fs::rename(&backup, path).await; + } + return Err(IdeError::from(error)); + } + if had_old { + let _ = tokio::fs::remove_file(&backup).await; + } + Ok(()) + } + .await; + if result.is_err() { + let _ = tokio::fs::remove_file(&temporary).await; + } + result +} + +/// Returns a sibling of `path` whose name has `suffix` appended after its full +/// extension sequence, e.g. `update.part` and `full` → `update.part.full`. +fn beside(path: &Path, suffix: &str) -> PathBuf { + let mut name = path.file_name().unwrap_or_default().to_os_string(); + name.push(format!(".{suffix}")); + path.with_file_name(name) +} + +/// Copies one response body into the persistent file and reports absolute +/// progress, including bytes recovered from an earlier process. +async fn append_body( + file: &mut tokio::fs::File, + mut response: reqwest::Response, + offset: u64, + total: Option, + progress: &mut impl FnMut(u64, Option), +) -> IdeResult { + let mut downloaded = offset; + while let Some(chunk) = response.chunk().await.map_err(|error| IdeError::unavailable(error.to_string()))? { + file.write_all(&chunk).await?; + downloaded += chunk.len() as u64; + progress(downloaded, total); + } + file.flush().await?; + file.sync_all().await?; + Ok(downloaded) +} + +/// Rejects a body that ended before the advertised length instead of promoting +/// a truncated installer to the ready state. +fn ensure_complete(downloaded: u64, total: Option) -> IdeResult<()> { + match total { + Some(total) if downloaded != total => { + Err(IdeError::unavailable(format!("update download ended at {downloaded} of {total} bytes"))) + } + _ => Ok(()), + } +} + +/// Parses `bytes start-end/total`, returning the start and known total. +fn partial_range(value: &str) -> Option<(u64, Option)> { + let value = value.strip_prefix("bytes ")?; + let (range, total) = value.split_once('/')?; + let (start, _) = range.split_once('-')?; + let start = start.parse().ok()?; + let total = (total != "*").then(|| total.parse().ok()).flatten(); + Some((start, total)) +} + +/// Parses the total from a `bytes */total` unsatisfied-range response. +fn unsatisfied_total(value: &str) -> Option { + value.strip_prefix("bytes */")?.parse().ok() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::{Read, Write}; + use std::net::TcpListener; + use std::thread; + + /// Starts a one-request HTTP server and returns its URL plus the request line. + fn serve(response: Vec) -> (String, thread::JoinHandle) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + let handle = thread::spawn(move || { + let (mut socket, _) = listener.accept().unwrap(); + let mut request = Vec::new(); + let mut byte = [0]; + while !request.ends_with(b"\r\n\r\n") { + socket.read_exact(&mut byte).unwrap(); + request.push(byte[0]); + } + socket.write_all(&response).unwrap(); + String::from_utf8(request).unwrap() + }); + (format!("http://{address}/update"), handle) + } + + /// Builds a complete HTTP response with a fixed body. + fn http(status: &str, headers: &[(&str, &str)], body: &[u8]) -> Vec { + let mut response = format!("HTTP/1.1 {status}\r\nConnection: close\r\n"); + for (name, value) in headers { + response.push_str(&format!("{name}: {value}\r\n")); + } + response.push_str("\r\n"); + response.into_bytes().into_iter().chain(body.iter().copied()).collect() + } + + /// Drops a body early, then resumes from the bytes already on disk. + #[tokio::test] + async fn a_broken_download_resumes_with_range() { + let client = ide_http::client::shared().unwrap(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("update.part"); + let (url, first) = serve(http("200 OK", &[("Content-Length", "10")], b"abcd")); + assert!(fetch(&client, &url, &path, |_, _| {}).await.is_err()); + first.join().unwrap(); + assert_eq!(tokio::fs::read(&path).await.unwrap(), b"abcd"); + + let (url, second) = serve(http( + "206 Partial Content", + &[("Content-Range", "bytes 4-9/10"), ("Content-Length", "6")], + b"efghij", + )); + let outcome = fetch(&client, &url, &path, |_, _| {}).await.unwrap(); + let request = second.join().unwrap().to_ascii_lowercase(); + assert!(request.contains("range: bytes=4-"), "{request}"); + assert_eq!(outcome, Outcome { resumed: true, total: Some(10) }); + assert_eq!(tokio::fs::read(path).await.unwrap(), b"abcdefghij"); + } + + /// Replaces a stale partial file when a proxy or mirror ignores Range. + #[tokio::test] + async fn a_full_response_after_a_partial_replaces_the_file() { + let client = ide_http::client::shared().unwrap(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("update.part"); + tokio::fs::write(&path, b"stale").await.unwrap(); + let (url, request) = serve(http("200 OK", &[("Content-Length", "7")], b"fresh!!")); + let outcome = fetch(&client, &url, &path, |_, _| {}).await.unwrap(); + assert!(request.join().unwrap().to_ascii_lowercase().contains("range: bytes=5-")); + assert_eq!(outcome, Outcome { resumed: false, total: Some(7) }); + assert_eq!(tokio::fs::read(&path).await.unwrap(), b"fresh!!"); + assert!(!path.with_file_name("update.part.full").exists()); + } + + /// Keeps the older checkpoint when a proxy ignores Range and its full + /// replacement download breaks before completion. + #[tokio::test] + async fn a_broken_full_fallback_preserves_the_previous_partial() { + let client = ide_http::client::shared().unwrap(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("update.part"); + tokio::fs::write(&path, b"stale").await.unwrap(); + let (url, _) = serve(http("200 OK", &[("Content-Length", "10")], b"fresh")); + assert!(fetch(&client, &url, &path, |_, _| {}).await.is_err()); + assert_eq!(tokio::fs::read(&path).await.unwrap(), b"stale"); + assert!(!path.with_file_name("update.part.full").exists()); + } + + /// Accepts `bytes */length` as the only completion signal for an already + /// complete partial file after a process restart. + #[tokio::test] + async fn an_already_complete_partial_file_is_returned_on_416() { + let client = ide_http::client::shared().unwrap(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("update.part"); + tokio::fs::write(&path, b"done").await.unwrap(); + let (url, _) = serve(http("416 Range Not Satisfiable", &[("Content-Range", "bytes */4")], b"")); + assert_eq!(fetch(&client, &url, &path, |_, _| {}).await.unwrap(), Outcome { resumed: true, total: Some(4) }); + } + + /// A close-delimited response has no length to prove a clean EOF; the caller + /// uses this signal to resume instead of discarding a failed checkpoint. + #[tokio::test] + async fn a_close_delimited_response_reports_an_unknown_total() { + let client = ide_http::client::shared().unwrap(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("update.part"); + let (url, _) = serve(http("200 OK", &[], b"body")); + assert_eq!(fetch(&client, &url, &path, |_, _| {}).await.unwrap(), Outcome { resumed: false, total: None }); + assert_eq!(tokio::fs::read(path).await.unwrap(), b"body"); + } + + /// A crash during the full-response swap leaves the old checkpoint in the + /// backup name; the next fetch restores it before calculating Range. + #[tokio::test] + async fn a_backup_checkpoint_is_restored_before_resuming() { + let client = ide_http::client::shared().unwrap(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("update.part"); + tokio::fs::write(beside(&path, "backup"), b"old").await.unwrap(); + let (url, request) = serve(http("416 Range Not Satisfiable", &[("Content-Range", "bytes */3")], b"")); + let outcome = fetch(&client, &url, &path, |_, _| {}).await.unwrap(); + assert!(request.join().unwrap().to_ascii_lowercase().contains("range: bytes=3-")); + assert_eq!(outcome, Outcome { resumed: true, total: Some(3) }); + assert_eq!(tokio::fs::read(&path).await.unwrap(), b"old"); + assert!(!beside(&path, "backup").exists()); + } + + /// Rejects malformed range metadata instead of appending to an unknown slice. + #[test] + fn content_range_parser_only_accepts_byte_ranges() { + assert_eq!(partial_range("bytes 4-9/10"), Some((4, Some(10)))); + assert_eq!(partial_range("bytes 0-0/*"), Some((0, None))); + assert_eq!(partial_range("items 4-9/10"), None); + assert_eq!(unsatisfied_total("bytes */10"), Some(10)); + assert_eq!(unsatisfied_total("bytes 0-1/10"), None); + } +}