From 49f6e5d0e3238565122dafc7d91b2a3686233b0a Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 03:07:23 -0600 Subject: [PATCH] S007: recovery tests, matrix and notes Co-Authored-By: Claude Opus 5.5 --- Plans/02 Engine/S007-error-recovery.md | 16 +- Plans/INDEX.md | 2 +- crates/core/src/error.rs | 7 +- crates/core/tests/recover.rs | 721 +++++++++++++++++++++++++ docs/DECISIONS.md | 3 + docs/PROGRESS.md | 8 + docs/RECOVERY.md | 78 +++ 7 files changed, 822 insertions(+), 13 deletions(-) create mode 100644 crates/core/tests/recover.rs create mode 100644 docs/RECOVERY.md diff --git a/Plans/02 Engine/S007-error-recovery.md b/Plans/02 Engine/S007-error-recovery.md index 6535fbb..6e5d526 100644 --- a/Plans/02 Engine/S007-error-recovery.md +++ b/Plans/02 Engine/S007-error-recovery.md @@ -12,14 +12,14 @@ Every failure is understood, explained, retried sensibly, and never costs finish ## Steps - [x] Error kinds from 1.17, each with severity, retry rule, plain message (what failed, then why) and fix action; a test asserts every kind has all four and no raw OS text leaks -- [ ] Retry engine: backoff per kind, per-host circuit breaker, limits per task and "retry forever" option, time until next try in the snapshot -- [ ] Network state through NetworkManager D-Bus with a fallback: offline waits instead of failing, resumes on return; captive portal (HTML in place of a file) detected -- [ ] Sleep and wake through logind `PrepareForSleep`: pause cleanly, resume after -- [ ] Disk: full, read-only, folder gone, drive unplugged and back, permission denied; waits and continues when fixed -- [ ] App killed or power lost: auto-resume on next start, with a setting -- [ ] Changed or wrong content (size, validators, HTML for a ZIP): asks to restart, keep both or continue from a new link; never mixes two versions -- [ ] Recovery matrix test: every fault of the test server times early, middle and late in the file; result is an identical file or the exact expected error with bytes kept -- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S007: …`, push +- [x] Retry engine: backoff per kind, per-host circuit breaker, limits per task and "retry forever" option, time until next try in the snapshot +- [x] Network state through NetworkManager D-Bus with a fallback: offline waits instead of failing, resumes on return; captive portal (HTML in place of a file) detected +- [x] Sleep and wake through logind `PrepareForSleep`: pause cleanly, resume after +- [x] Disk: full, read-only, folder gone, drive unplugged and back, permission denied; waits and continues when fixed +- [x] App killed or power lost: auto-resume on next start, with a setting +- [x] Changed or wrong content (size, validators, HTML for a ZIP): asks to restart, keep both or continue from a new link; never mixes two versions +- [x] Recovery matrix test: every fault of the test server times early, middle and late in the file; result is an identical file or the exact expected error with bytes kept +- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S007: …`, push ## End criteria - `nice cargo test -j 2 -p medlar-core --test recover` green diff --git a/Plans/INDEX.md b/Plans/INDEX.md index e0ce406..19b89a2 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -15,7 +15,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H - [x] [S004](02%20Engine/S004-http-core.md) HTTP core with resume and crash-safe files - [x] [S005](02%20Engine/S005-dynamic-parts.md) Dynamic parts and adaptive connections - [x] [S006](02%20Engine/S006-manager.md) Download manager, events and snapshots -- [ ] [S007](02%20Engine/S007-error-recovery.md) Error recovery +- [x] [S007](02%20Engine/S007-error-recovery.md) Error recovery - [ ] [S008](02%20Engine/S008-continue-links.md) Continue from a new link - [ ] [S009](02%20Engine/S009-mirrors-checksums.md) Mirrors, Metalink and checksums - [ ] [S010](02%20Engine/S010-logins-proxies.md) Logins, cookies and proxies diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index 29344d4..f3e089e 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -220,9 +220,6 @@ fn of_net(e: &reqwest::Error) -> ErrorKind { return ErrorKind::Tls; } if let Some(io) = e.downcast_ref::() { - if io.get_ref().is_some_and(|e| e.is::()) { - return ErrorKind::Tls; - } match io.kind() { io::ErrorKind::ConnectionRefused => return ErrorKind::Refused, io::ErrorKind::HostUnreachable | io::ErrorKind::NetworkUnreachable | io::ErrorKind::NetworkDown => return ErrorKind::Unreachable, @@ -234,7 +231,9 @@ fn of_net(e: &reqwest::Error) -> ErrorKind { if e.to_string().starts_with("dns error") { return ErrorKind::Dns; } - source = e.source(); + // An io::Error's source skips what it wraps. + let wrapped = e.downcast_ref::().and_then(|e| e.get_ref()); + source = wrapped.map(|e| e as &(dyn std::error::Error + 'static)).or_else(|| e.source()); } if e.is_timeout() { ErrorKind::Timeout } else { ErrorKind::Cut } } diff --git a/crates/core/tests/recover.rs b/crates/core/tests/recover.rs new file mode 100644 index 0000000..24d7d59 --- /dev/null +++ b/crates/core/tests/recover.rs @@ -0,0 +1,721 @@ +//! Failures of every sort: the file is whole in the end, or the error is the expected one and no byte is lost. + +use medlar_core::adapt::Timing; +use medlar_core::host::{Caps, Hosts}; +use medlar_core::http::{ClientOptions, Options, Shared, client}; +use medlar_core::manager::{Bin, Command, Config, Manager}; +use medlar_core::model::*; +use medlar_core::net_state::Bus; +use medlar_core::recover::Recovery; +use medlar_core::segment::Rules; +use medlar_core::settings::Limits; +use medlar_core::snapshot::TaskView; +use medlar_core::store::Store; +use medlar_testserver::{Faults, TestServer, expected}; +use std::io::{BufRead, BufReader, Read}; +use std::os::fd::OwnedFd; +use std::path::{Path, PathBuf}; +use std::process::{Child, Stdio}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; +use tokio::time::sleep; + +const LIMITS: Limits = Limits { speed: 0, max_active: 8, max_connections: 32, parts_per_download: 2, connections_per_host: 16 }; +const LEN: usize = 1 << 20; + +fn ms(n: u64) -> Duration { + Duration::from_millis(n) +} + +/// Waits are a hundredth of the real ones. +fn quick() -> Recovery { + Recovery { tries: 3, pace: 0.01, ..Recovery::default() } +} + +fn config(dir: &Path, recovery: Recovery) -> Config { + let store = Arc::new(Store::open(&dir.join("medlar.db")).unwrap()); + let client = client(&ClientOptions { idle_timeout: ms(1500), ..ClientOptions::default() }).unwrap(); + let hosts = Hosts::new(Caps { burst: 1000, per_second: 1000.0, ..Caps::default() }); + let options = Options { + rules: Rules { min: 64 * 1024, align: 4096, min_time: ms(50) }, + timing: Timing { settle: ms(100), window: ms(200), hold: ms(2000), refused: ms(60_000) }, + tick: ms(25), + stall: ms(300), + patience: ms(500), + tries: 2, + backoff: ms(20), + max_wait: ms(500), + checkpoint: ms(50), + }; + let mut config = Config::new(Shared { client, store, hosts }, LIMITS); + (config.options, config.bin, config.tick, config.recovery) = (options, Bin::at(dir.join("Trash")), ms(20), recovery); + config +} + +struct Bench { + server: TestServer, + dir: tempfile::TempDir, + manager: Manager, + files: PathBuf, +} + +impl Bench { + async fn new(recovery: Recovery) -> Bench { + let dir = tempfile::tempdir().unwrap(); + let manager = Manager::open(config(dir.path(), recovery)).unwrap(); + Bench { server: TestServer::start().await, files: dir.path().join("files"), dir, manager } + } + + fn restart(self, recovery: Recovery) -> Bench { + drop(self.manager); + let manager = Manager::open(config(self.dir.path(), recovery)).unwrap(); + Bench { manager, ..self } + } + + async fn add(&self, path: &str) -> TaskId { + self.add_url(self.server.url(path), "").await + } + + async fn add_url(&self, url: String, name: &str) -> TaskId { + let task = Task { url, name: name.into(), folder: self.files.clone(), ..Task::default() }; + self.manager.send(Command::Add(Box::new(task))).await.unwrap() + } + + async fn run(&self, command: Command) { + self.manager.send(command).await.unwrap(); + } + + fn view(&self, id: TaskId) -> Arc { + self.manager.snapshot().get(id).unwrap_or_else(|| panic!("{id} is not in the list")).clone() + } + + fn kind(&self, id: TaskId) -> Option { + self.view(id).task.error.as_ref().and_then(|e| e.kind) + } + + async fn until(&self, id: TaskId, what: &str, is: impl Fn(&TaskView) -> bool) -> Arc { + let end = Instant::now() + Duration::from_secs(40); + loop { + let view = self.view(id); + if is(&view) { + return view; + } + assert!(Instant::now() < end, "never {what}: {:?} {:?} {:#?}", view.state(), view.task.error, view.log); + sleep(ms(5)).await; + } + } + + async fn state(&self, id: TaskId, state: State) -> Arc { + self.until(id, state.name(), |v| v.state() == state).await + } + + async fn waits_for(&self, id: TaskId, kind: ErrorKind) -> Arc { + let is = |v: &TaskView| v.state() == State::Waiting && v.task.error.as_ref().is_some_and(|e| e.kind == Some(kind)); + self.until(id, kind.name(), is).await + } + + /// Lets it run slowly until `bytes` are here, and pauses it. + async fn part_of(&self, path: &str, bytes: usize) -> TaskId { + self.server.set_faults(path, Faults { throttle_conn: Some(300_000), ..Faults::default() }); + let id = self.add(path).await; + self.until(id, "under way", |v| v.downloaded >= bytes as u64).await; + self.run(Command::Pause(id)).await; + self.until(id, "stopped", |v| v.connections == 0).await; + self.server.clear_all_faults(); + id + } + + fn check(&self, id: TaskId, seed: u64) { + let task = self.view(id).task.clone(); + let is = std::fs::read(task.folder.join(&task.name)).unwrap_or_else(|e| panic!("{e}: {task:?}")); + let should = expected(seed, 0, LEN); + let same = is.iter().zip(&should).take_while(|(a, b)| a == b).count(); + assert!(is == should, "{} bytes, right until {same}: {task:?}, {:#?}", is.len(), self.view(id).log); + } + + async fn done(&self, id: TaskId, seed: u64) { + self.state(id, State::Done).await; + self.check(id, seed); + } +} + +fn path(seed: u64) -> String { + TestServer::data_path(seed, LEN as u64) +} + +// Retries. + +#[tokio::test(flavor = "multi_thread")] +async fn tries_again_and_says_when() { + let b = Bench::new(Recovery { pace: 0.1, ..quick() }).await; + b.server.set_faults(&path(1), Faults::status(500)); + let id = b.add(&path(1)).await; + let view = b.waits_for(id, ErrorKind::Server).await; + let left = view.retry_at.unwrap() - now(); + assert!(view.fails == 1 && (0..=1500).contains(&left), "{left} ms"); + b.server.clear_all_faults(); + b.done(id, 1).await; + assert_eq!((b.view(id).retry_at, b.view(id).fails), (None, 0)); + + // The server's own wait. + b.server.set_faults(&path(2), Faults { retry_after: Some(2), ..Faults::status(503) }); + let id = b.add(&path(2)).await; + let view = b.waits_for(id, ErrorKind::Busy).await; + assert!(view.retry_at.unwrap() - now() > 1500); + b.server.clear_all_faults(); + b.done(id, 2).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn gives_up_or_never() { + let b = Bench::new(quick()).await; + b.server.set_faults("*", Faults::status(500)); + let id = b.add(&path(1)).await; + b.state(id, State::Failed).await; + assert_eq!((b.view(id).fails, b.kind(id)), (4, Some(ErrorKind::Server))); + let task = Task { url: b.server.url(&path(2)), folder: b.files.clone(), tries: Some(0), ..Task::default() }; + let forever = b.manager.send(Command::Add(Box::new(task))).await.unwrap(); + b.until(forever, "patient", |v| v.fails >= 5).await; + assert_ne!(b.view(forever).state(), State::Failed); + b.server.clear_all_faults(); + b.done(forever, 2).await; + b.run(Command::Resume(id)).await; + b.done(id, 1).await; + + // Nothing to wait for. + b.server.set_faults("*", Faults::status(404)); + b.server.clear_log(); + let id = b.add(&path(3)).await; + b.state(id, State::Failed).await; + sleep(ms(300)).await; + assert_eq!((b.kind(id), b.server.log().len()), (Some(ErrorKind::NotFound), 1)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_failing_host_is_left_alone() { + let b = Bench::new(Recovery { tries: 0, pace: 0.1, ..quick() }).await; + b.server.set_faults("*", Faults::status(500)); + let mut ids = vec![]; + for seed in 0..3 { + ids.push(b.add(&path(seed)).await); + } + for id in &ids { + b.until(*id, "failed once", |v| v.fails > 0).await; + } + let asked = b.server.log().len(); + // It rests for 3 s: nobody else asks. + for seed in 3..6 { + ids.push(b.add(&path(seed)).await); + } + sleep(ms(1500)).await; + assert_eq!(b.server.log().len(), asked); + assert!(b.view(ids[5]).state() == State::Queued); + // One tries. + b.until(ids[5], "tried", |_| b.server.log().len() > asked).await; + sleep(ms(400)).await; + assert!(b.server.log().len() <= asked + 2, "{}", b.server.log().len() - asked); + b.server.clear_all_faults(); + // Asked for by the user: at once. + b.run(Command::Start(ids[4])).await; + for (seed, id) in ids.iter().enumerate() { + b.done(*id, seed as u64).await; + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn nobody_there() { + let b = Bench::new(quick()).await; + let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + let id = b.add_url(format!("http://127.0.0.1:{port}/f.bin"), "").await; + b.state(id, State::Failed).await; + assert_eq!(b.kind(id), Some(ErrorKind::Refused)); + let id = b.add_url("http://medlar-test.invalid/f.bin".into(), "").await; + b.state(id, State::Failed).await; + // A name service that doesn't answer is a timeout. + assert!(matches!(b.kind(id), Some(ErrorKind::Dns | ErrorKind::Timeout)), "{:?}", b.kind(id)); + // A certificate nobody knows. + let tls = TestServer::start_tls().await; + let id = b.add_url(tls.url(&path(1)), "").await; + b.state(id, State::Failed).await; + assert_eq!(b.kind(id), Some(ErrorKind::Tls)); + let error = b.view(id).task.error.clone().unwrap().detail; + assert!(error.starts_with("Secure connection failed. 127.0.0.1:"), "{error}"); + let id = b.add("/redirect/loop").await; + b.state(id, State::Failed).await; + assert_eq!(b.kind(id), Some(ErrorKind::BadLink)); +} + +// The system: a private D-Bus with a NetworkManager and a logind of our own. + +struct Daemon { + child: Child, + address: String, +} + +impl Daemon { + fn start() -> Daemon { + let mut child = std::process::Command::new("dbus-daemon") + .args(["--session", "--nofork", "--print-address=1"]) + .stdout(Stdio::piped()) + .spawn() + .expect("dbus-daemon"); + let mut address = String::new(); + BufReader::new(child.stdout.take().unwrap()).read_line(&mut address).unwrap(); + Daemon { child, address: address.trim().into() } + } + + async fn serve(&self, name: &str, path: &str, interface: I) -> zbus::Connection { + let builder = zbus::connection::Builder::address(self.address.as_str()).unwrap().serve_at(path, interface).unwrap(); + builder.name(name.to_string()).unwrap().build().await.unwrap() + } + + fn recovery(&self) -> Recovery { + Recovery { bus: Bus::At(self.address.clone()), ..quick() } + } +} + +impl Drop for Daemon { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +struct FakeNetwork { + state: u32, + connectivity: u32, +} + +#[zbus::interface(name = "org.freedesktop.NetworkManager")] +impl FakeNetwork { + #[zbus(property)] + fn state(&self) -> u32 { + self.state + } + + #[zbus(property)] + fn connectivity(&self) -> u32 { + self.connectivity + } +} + +const NM: &str = "/org/freedesktop/NetworkManager"; + +async fn set_network(c: &zbus::Connection, state: u32, connectivity: u32) { + let nm = c.object_server().interface::<_, FakeNetwork>(NM).await.unwrap(); + let mut it = nm.get_mut().await; + (it.state, it.connectivity) = (state, connectivity); + it.state_changed(nm.signal_emitter()).await.unwrap(); + it.connectivity_changed(nm.signal_emitter()).await.unwrap(); + drop(it); + sleep(ms(300)).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn offline_waits_and_comes_back() { + let daemon = Daemon::start(); + let nm = daemon.serve("org.freedesktop.NetworkManager", NM, FakeNetwork { state: 20, connectivity: 1 }).await; + let b = Bench::new(daemon.recovery()).await; + sleep(ms(500)).await; + let id = b.part_of(&path(1), LEN / 2).await; + let had = b.view(id).downloaded; + b.server.set_faults("*", Faults { reset_after: Some(0), ..Faults::default() }); + b.run(Command::Resume(id)).await; + b.waits_for(id, ErrorKind::Offline).await; + assert!(b.view(id).downloaded >= had); + let asked = b.server.log().len(); + sleep(ms(500)).await; + assert_eq!((b.server.log().len(), b.view(id).state()), (asked, State::Waiting), "it knows better than to try"); + b.server.clear_all_faults(); + set_network(&nm, 70, 4).await; + b.done(id, 1).await; + assert_eq!(b.view(id).counters.finished, 1); + + // The sign-in page of a hotel. + set_network(&nm, 70, 2).await; + let id = b.add_url(b.server.url("/redirect/1?to=/site/"), "big.zip").await; + b.waits_for(id, ErrorKind::Portal).await; + b.run(Command::Edit { id, edit: Box::new({ let url = b.server.url(&path(2)); move |t| t.url = url }) }).await; + assert_eq!(b.view(id).state(), State::Waiting); + set_network(&nm, 70, 4).await; + b.done(id, 2).await; + + // Connections die unseen while it is away. + b.server.set_faults("*", Faults { stall_after: Some(200_000), ..Faults::default() }); + let id = b.add(&path(3)).await; + b.until(id, "under way", |v| v.downloaded > 0).await; + set_network(&nm, 20, 1).await; + b.server.clear_all_faults(); + set_network(&nm, 70, 4).await; + b.done(id, 3).await; +} + +#[derive(Clone, Default)] +struct FakeLogin(Arc>>); + +#[zbus::interface(name = "org.freedesktop.login1.Manager")] +impl FakeLogin { + fn inhibit(&self, what: &str, _who: &str, _why: &str, mode: &str) -> zbus::zvariant::OwnedFd { + assert_eq!((what, mode), ("sleep", "delay")); + let (reader, writer) = std::io::pipe().unwrap(); + self.0.lock().unwrap().push(reader); + OwnedFd::from(writer).into() + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn sleeps_and_wakes() { + let daemon = Daemon::start(); + let login = FakeLogin::default(); + let bus = daemon.serve("org.freedesktop.login1", "/org/freedesktop/login1", login.clone()).await; + let prepare = async |start: bool| { + bus.emit_signal(None::<&str>, "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "PrepareForSleep", &start).await.unwrap(); + }; + let b = Bench::new(daemon.recovery()).await; + b.server.set_faults("*", Faults { throttle_conn: Some(200_000), ..Faults::default() }); + let id = b.add(&path(1)).await; + b.until(id, "under way", |v| v.downloaded > 50_000).await; + assert_eq!(login.0.lock().unwrap().len(), 1); + + prepare(true).await; + let mut lock = login.0.lock().unwrap().remove(0); + tokio::task::spawn_blocking(move || lock.read_to_end(&mut vec![])).await.unwrap().unwrap(); + // Everything is saved by now. + let view = b.waits_for(id, ErrorKind::Sleep).await; + let saved: u64 = Store::open(&b.dir.path().join("medlar.db")).unwrap().parts(id).unwrap().iter().map(|p| p.done).sum(); + assert!(saved > 50_000 && saved == view.downloaded, "{saved} of {}", view.downloaded); + let other = b.add(&path(2)).await; + sleep(ms(300)).await; + assert_eq!((b.view(id).downloaded, b.view(other).state()), (saved, State::Queued)); + + b.server.clear_all_faults(); + prepare(false).await; + b.done(id, 1).await; + b.done(other, 2).await; + assert_eq!(login.0.lock().unwrap().len(), 1, "ready for the next time"); +} + +// Disks. + +#[tokio::test(flavor = "multi_thread")] +async fn no_permission() { + use std::os::unix::fs::PermissionsExt; + let b = Bench::new(quick()).await; + std::fs::create_dir(&b.files).unwrap(); + let mode = |m| std::fs::set_permissions(&b.files, std::fs::Permissions::from_mode(m)).unwrap(); + mode(0o500); + let id = b.add(&path(1)).await; + let view = b.waits_for(id, ErrorKind::Denied).await; + assert!(view.task.error.as_ref().unwrap().detail.contains(b.files.to_str().unwrap())); + sleep(ms(300)).await; + assert_eq!(b.view(id).state(), State::Waiting); + mode(0o700); + b.done(id, 1).await; + + // The folder goes away with the file in it, and comes back. + let id = b.part_of(&path(2), LEN / 2).await; + let had = b.view(id).downloaded; + let away = b.dir.path().join("away"); + std::fs::rename(&b.files, &away).unwrap(); + b.run(Command::Resume(id)).await; + b.waits_for(id, ErrorKind::FolderGone).await; + assert!(!b.files.exists() && b.view(id).downloaded == had); + std::fs::rename(&away, &b.files).unwrap(); + b.server.clear_log(); + b.done(id, 2).await; + let sent: u64 = b.server.log().iter().map(|r| r.sent).sum(); + assert!(sent < LEN as u64 - had + 300_000, "{sent} sent, {had} were there"); + + // Only the file does. + let id = b.part_of(&path(3), LEN / 2).await; + let file = b.files.join(format!("{}.medlar", b.view(id).task.name)); + std::fs::rename(&file, b.dir.path().join("kept")).unwrap(); + b.run(Command::Resume(id)).await; + b.waits_for(id, ErrorKind::FileGone).await; + std::fs::rename(b.dir.path().join("kept"), &file).unwrap(); + b.done(id, 3).await; +} + +const DISK: &str = "MEDLAR_DISK_TEST_DIR"; + +/// In a mount namespace of its own, where it may mount what it likes. +#[test] +fn disks() { + let dir = tempfile::tempdir().unwrap(); + let status = std::process::Command::new("unshare") + .args(["-Urm"]) + .arg(std::env::current_exe().unwrap()) + .args(["--ignored", "--exact", "disks_child", "--nocapture"]) + .env(DISK, dir.path()) + .status(); + assert!(status.expect("unshare").success()); +} + +fn mount(args: &[&str]) { + assert!(std::process::Command::new(args[0]).args(&args[1..]).status().unwrap().success(), "{args:?}"); +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "started by disks"] +async fn disks_child() { + let Some(dir) = std::env::var_os(DISK).map(PathBuf::from) else { return }; + let mut b = Bench::new(quick()).await; + + // Full, then not. + b.files = dir.join("small"); + std::fs::create_dir(&b.files).unwrap(); + let small = b.files.to_str().unwrap().to_string(); + mount(&["mount", "-t", "tmpfs", "-o", "size=4m", "tmpfs", &small]); + std::fs::write(b.files.join("filler"), vec![0; 7 << 19]).unwrap(); + let id = b.add(&path(1)).await; + b.waits_for(id, ErrorKind::DiskFull).await; + sleep(ms(300)).await; + assert_eq!(b.view(id).state(), State::Waiting); + std::fs::remove_file(b.files.join("filler")).unwrap(); + b.done(id, 1).await; + + // Read-only, then not. + let id = b.part_of(&path(2), LEN / 2).await; + let had = b.view(id).downloaded; + mount(&["mount", "-o", "remount,bind,ro", &small]); + b.run(Command::Resume(id)).await; + b.waits_for(id, ErrorKind::ReadOnly).await; + sleep(ms(300)).await; + assert_eq!((b.view(id).state(), b.view(id).downloaded), (State::Waiting, had)); + mount(&["mount", "-o", "remount,bind,rw", &small]); + b.done(id, 2).await; + + // A drive that is pulled out while it is written to, and put back. + let drive = dir.join("drive"); + b.files = dir.join("mnt"); + for d in [&drive, &b.files] { + std::fs::create_dir(d).unwrap(); + } + let (drive, at) = (drive.to_str().unwrap(), b.files.to_str().unwrap()); + mount(&["mount", "--bind", drive, at]); + b.server.set_faults("*", Faults { throttle_conn: Some(300_000), ..Faults::default() }); + let id = b.add(&path(3)).await; + b.until(id, "under way", |v| v.downloaded > 100_000).await; + mount(&["umount", "-l", at]); + b.run(Command::Pause(id)).await; + b.until(id, "stopped", |v| v.connections == 0).await; + b.run(Command::Resume(id)).await; + b.waits_for(id, ErrorKind::FileGone).await; + std::fs::remove_dir(at).unwrap(); + sleep(ms(300)).await; + assert!(!b.files.exists(), "nothing is made in its place"); + std::fs::create_dir(at).unwrap(); + mount(&["mount", "--bind", drive, at]); + b.done(id, 3).await; + // Gone at the very end. + let id = b.add(&path(4)).await; + b.until(id, "under way", |v| v.downloaded > 100_000).await; + mount(&["umount", "-l", at]); + b.waits_for(id, ErrorKind::FileGone).await; + mount(&["mount", "--bind", drive, at]); + b.done(id, 4).await; + mount(&["umount", "-l", at]); +} + +// The end of the program. + +#[tokio::test(flavor = "multi_thread")] +async fn killed_and_back() { + for auto_resume in [true, false] { + let mut b = Bench::new(quick()).await; + let id = b.part_of(&path(1), LEN / 4).await; + let had = b.view(id).downloaded; + let waiting = b.add(&path(2)).await; + b.done(waiting, 2).await; + drop(std::mem::replace(&mut b.manager, Manager::open(config(b.dir.path(), quick())).unwrap())); + // What a kill leaves behind: still running. + b.manager.close(); + { + let store = Store::open(&b.dir.path().join("medlar.db")).unwrap(); + store.set_state(id, State::Queued, None).unwrap(); + store.set_state(id, State::Running, None).unwrap(); + } + let b = b.restart(Recovery { auto_resume, ..quick() }); + if !auto_resume { + sleep(ms(200)).await; + assert_eq!((b.view(id).state(), b.kind(id)), (State::Paused, Some(ErrorKind::Killed))); + assert_eq!(b.view(id).downloaded, had); + b.run(Command::Resume(id)).await; + } + b.done(id, 1).await; + } + // Closed in order. + let b = Bench::new(Recovery { auto_resume: false, ..quick() }).await; + b.server.set_faults("*", Faults { throttle_conn: Some(200_000), ..Faults::default() }); + let id = b.add(&path(1)).await; + b.until(id, "under way", |v| v.downloaded > 0).await; + let b = b.restart(Recovery { auto_resume: false, ..quick() }); + sleep(ms(200)).await; + assert_eq!(b.view(id).state(), State::Paused); +} + +// Another file than before. + +#[tokio::test(flavor = "multi_thread")] +async fn changed_files_are_never_mixed() { + let b = Bench::new(quick()).await; + let id = b.part_of(&path(1), LEN / 2).await; + let had = b.view(id).downloaded; + b.server.set_faults(&path(1), Faults { version_after_requests: Some(0), ..Faults::default() }); + b.run(Command::Resume(id)).await; + b.state(id, State::Failed).await; + assert_eq!((b.kind(id), b.view(id).downloaded), (Some(ErrorKind::Changed), had)); + + // Keep both. + let new = b.manager.send(Command::KeepBoth(id)).await.unwrap(); + b.state(new, State::Done).await; + let (old, new) = (b.view(id).task.clone(), b.view(new).task.clone()); + assert!(old.state == State::Failed && old.name != new.name); + assert_eq!(b.view(id).downloaded, had); + let newer = std::fs::read(b.files.join(&new.name)).unwrap(); + assert!(newer.len() == LEN && newer != expected(1, 0, LEN)); + + // Start over. + let other = b.part_of(&path(2), LEN / 2).await; + b.server.set_faults(&path(2), Faults { version_after_requests: Some(0), ..Faults::default() }); + b.run(Command::Resume(other)).await; + b.state(other, State::Failed).await; + b.run(Command::Redownload(other)).await; + let view = b.state(other, State::Done).await; + assert_ne!(std::fs::read(b.files.join(&view.task.name)).unwrap(), expected(2, 0, LEN)); + + // Go on from a new link. It is checked as before. + b.server.clear_all_faults(); + let url = b.server.url(&format!("{}?etag=1", path(1))); + b.run(Command::Edit { id, edit: Box::new(move |t| t.url = url) }).await; + b.run(Command::Resume(id)).await; + b.done(id, 1).await; + + // A web page for a ZIP, at the start and later. + let id = b.add_url(b.server.url("/site/"), "big.zip").await; + b.state(id, State::Failed).await; + assert_eq!((b.kind(id), b.view(id).downloaded), (Some(ErrorKind::WrongContent), 0)); + let id = b.part_of(&path(3), LEN / 2).await; + let had = b.view(id).downloaded; + let (site, link) = (b.server.url("/site/"), b.server.url(&path(3))); + b.run(Command::Edit { id, edit: Box::new(move |t| t.url = site) }).await; + b.run(Command::Resume(id)).await; + b.state(id, State::Failed).await; + assert_eq!((b.kind(id), b.view(id).downloaded), (Some(ErrorKind::WrongContent), had)); + b.run(Command::Edit { id, edit: Box::new(move |t| t.url = link) }).await; + b.run(Command::Resume(id)).await; + b.done(id, 3).await; +} + +// The matrix. Its result is in docs/RECOVERY.md. + +/// The outcome when the fault begins before the first byte, and when it begins later. None: the file is whole. +type Row = (&'static str, Faults, Option, Option); + +fn rows() -> Vec { + use ErrorKind::*; + let f = Faults::default; + let status = |code| Faults::status(code); + vec![ + ("throttle_conn", Faults { throttle_conn: Some(400_000), ..f() }, None, None), + ("throttle_total", Faults { throttle_total: Some(600_000), ..f() }, None, None), + ("latency_ms", Faults { latency_ms: Some(100), ..f() }, None, None), + ("stall_after, some bytes each time", Faults { stall_after: Some(60_000), ..f() }, None, None), + ("stall_after, nothing comes", Faults { stall_after: Some(0), ..f() }, Some(Timeout), Some(Timeout)), + ("cut_after, some bytes each time", Faults { cut_after: Some(60_000), ..f() }, None, None), + ("cut_after, nothing comes", Faults { cut_after: Some(0), ..f() }, Some(Cut), Some(Cut)), + ("reset_after, some bytes each time", Faults { reset_after: Some(60_000), ..f() }, None, None), + ("reset_after, nothing comes", Faults { reset_after: Some(0), ..f() }, Some(Cut), Some(Cut)), + ("status 401", status(401), Some(Login), Some(Login)), + ("status 403", status(403), Some(Forbidden), Some(Expired)), + ("status 404", status(404), Some(NotFound), Some(NotFound)), + ("status 410", status(410), Some(NotFound), Some(Expired)), + ("status 416", status(416), Some(Rejected), Some(Rejected)), + ("status 418", status(418), Some(Rejected), Some(Rejected)), + ("status 429", status(429), Some(Busy), Some(Busy)), + ("status 500", status(500), Some(Server), Some(Server)), + ("status 503 with retry_after", Faults { retry_after: Some(1), ..status(503) }, Some(Busy), Some(Busy)), + ("wrong_length, too long", Faults { wrong_length: Some(1000), ..f() }, Some(BadReply), Some(BadReply)), + ("wrong_length, too short", Faults { wrong_length: Some(-1000), ..f() }, Some(BadReply), Some(BadReply)), + ("ignore_range", Faults { ignore_range: true, ..f() }, None, Some(NoResume)), + ("change_after", Faults { change_after: Some(0), ..f() }, None, Some(Changed)), + ("version_after_requests", Faults { version_after_requests: Some(0), ..f() }, None, Some(Changed)), + ("gzip", Faults { gzip: true, ..f() }, Some(BadReply), Some(BadReply)), + ("expire_requests", Faults { expire_requests: Some(0), ..f() }, Some(Forbidden), Some(Expired)), + ("expire_secs, 410", Faults { expire_secs: Some(0), expire_status: Some(410), ..f() }, Some(NotFound), Some(Expired)), + ("max_conns", Faults { max_conns: Some(1), ..f() }, None, None), + ] +} + +async fn cell(name: &str, fault: Faults, at: usize, want: Option) -> std::result::Result<(), String> { + let b = Bench::new(quick()).await; + let (path, at) = (path(7), LEN * at / 100); + let (id, had) = if at == 0 { + b.server.set_faults(&path, fault.clone()); + (b.add(&path).await, 0) + } else { + let id = b.part_of(&path, at).await; + b.server.set_faults(&path, fault.clone()); + let had = b.view(id).downloaded; + b.run(Command::Resume(id)).await; + (id, had) + }; + let end = |v: &TaskView| matches!(v.state(), State::Done | State::Failed); + let view = b.until(id, "over", end).await; + if b.kind(id) != want { + return Err(format!("{name} at {at}: {:?} instead of {want:?}, {:#?}", view.task.error, view.log)); + } + if view.downloaded < had { + return Err(format!("{name} at {at}: {} bytes of {had} left", view.downloaded)); + } + if want.is_none() { + // From the first byte on, these two are simply another file. + if at > 0 || (fault.change_after, fault.version_after_requests) == (None, None) { + b.check(id, 7); + } + return Ok(()); + } + // Cured, it goes on with what it has. + b.server.clear_all_faults(); + b.server.clear_log(); + b.run(Command::Resume(id)).await; + b.done(id, 7).await; + let asked: u64 = b.server.log().iter().filter(|r| r.method == "GET" && r.status == 206).map(|r| r.sent).sum(); + let left = LEN as u64 - view.downloaded; + if asked > left + 400_000 { + return Err(format!("{name} at {at}: {asked} bytes sent for {left}")); + } + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn matrix() { + let mut wrong = vec![]; + for rows in rows().chunks(4) { + let mut cells = tokio::task::JoinSet::new(); + for (name, fault, start, later) in rows.iter().cloned() { + for at in [0, 5, 50, 90] { + let fault = fault.clone(); + cells.spawn(async move { cell(name, fault, at, if at == 0 { start } else { later }).await }); + } + } + while let Some(result) = cells.join_next().await { + match result { + Ok(result) => wrong.extend(result.err()), + Err(e) => wrong.push(format!("{e}")), + } + } + } + assert!(wrong.is_empty(), "{} wrong:\n{}", wrong.len(), wrong.join("\n")); +} + +#[test] +fn every_kind_is_described() { + let text = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/RECOVERY.md")).unwrap(); + for kind in ErrorKind::ALL { + assert!(text.contains(&format!("| `{}` |", kind.name())), "{}", kind.name()); + } + for (name, ..) in rows() { + assert!(text.contains(&format!("| {name} |")), "{name}"); + } +} diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index e87d711..7fd885b 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -30,3 +30,6 @@ - D-023 — 2026-11-25 — Menus are Medlar's own (`ui::menu`), not egui's: one open at a time, own keyboard. Dialogs never close by a click on the scrim (the side sheet does); Enter does the main action unless a button has the focus; dangerous questions start on Cancel. Elevated buttons have no shadow. — egui's arrow keys leave its menus; typed links must not be lost. — 03 and later - D-029 — 2026-11-25 — Running set: at most `max_active`, one place per connection a host gives. Rank: forced start (latest first), priority, running before waiting, queue position, position. A running download gives way to a higher priority, a forced start or an "only", never to a better position; one that can't resume never gives way. Stop = pause and go last. Remove can be undone for 60 s and until the program ends; at the next start it is final. Closing turns running into queued, so that they go on at the next start. — FEATURES 1.1, 2.3, 7.3. — 02, 04, 05 - D-030 — 2026-11-25 — A file name belongs to the unfinished task that has it recorded, even when its file is empty or missing. Looking for a free name and taking it happens under `disk::names()`. Tasks are changed through `Store::edit_task` (one transaction), never read, changed and saved. — The command fuzz mixed up the files of two tasks without this. — 02, 06 +- D-031 — 2026-11-25 — Retries of a task: 10 failures in a row without a new byte (setting, per task, 0 is forever), waits by kind (docs/RECOVERY.md), Retry-After honoured up to 24 h. Three network, busy or server failures of a host in a row shut it for all for 30 s, doubling to 10 min; then one download tries. Start and Resume by the user go past it. 4xx are never repeated blindly. — FEATURES 1.6, 1.17. — 02, 04 +- D-032 — 2026-11-25 — Offline is only believed after a failure: downloads are always tried first, so local servers work without a network. D-Bus is `Bus::Off` by default; the app turns it on. zbus without its tokio feature. Downloads that can't resume are not stopped for sleep or a network change. — Never touch the real system in tests; lose no bytes. — 02, 03, 05 +- D-033 — 2026-11-25 — A started download whose file or folder is gone waits for it (`Error::Missing`) and is never started over, nor its folder made again, by itself. A changed file fails and asks; keeping both leaves the old task as it is and adds a new one. — A pulled-out drive looks like a missing folder. — 02, 04 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 56913bb..59488e8 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -88,5 +88,13 @@ Not done: part events (`Split`…) don't leave the manager; `PartView.id` tells Seen: connections of a host are first come, first served: with more downloads than fit, some run without any until others end (S010). `http::name::no_name_gets_out_of_its_folder` took over 60 s on an overloaded CPU. Boxes were ticked together at the end, against rule 3. Fixed after review: `removed_and_back` had a wrong bound. `received` also counts up to one read beyond the new end of a split part (seen: 147 kB); nothing on disk is fetched again. The test now checks the ranges asked for (60 of 60 runs under load, with 61 kB or more kept). +## S007 — Error recovery (2026-11-25) +Done: `core::error`, `core::recover` (with `sleep`), `core::net_state`, waits in `manager/actor.rs`, `docs/RECOVERY.md` (kinds table for texts and buttons, matrix). Choices: D-031 to D-033. Outside the plan's files: `http` (`Error::Page`, `Error::Missing`), store migration 002 (`tasks.tries`), settings `tries` and `auto_resume`, `zbus` and `futures-lite` in core. +Verified: `--test recover` (13 tests: matrix of 27 faults × 4 moments, fake NetworkManager and logind on a private D-Bus, full, read-only and pulled-out disks in a mount namespace). +- UI: `task.error` has `kind` and `detail` (ready to show); `kind.title()`, `severity()`, `retry()`, `fix().label()`. `TaskView::retry_at` (ms since 1970) and `fails`. `Fix::Choose` = `Redownload` (start over), `KeepBoth`, or `Edit` of the link and `Resume`. `Fix::Restart` = `Redownload`. +- The app must set `config.recovery.bus = Bus::System` (the default is Off, so that tests touch nothing real), `recovery.tries` and `auto_resume` from the settings; `manager.set_recovery()` later. +- A Waiting task with `error: None` is S009's; those with a kind are taken up by the manager at the next start. +Not done: a host name that TLS finds invalid counts as `cut`; the real NetworkManager and logind were never touched; a disk that fills up in the middle is only unit-tested (space is reserved first); 4xx and 5xx texts show the number, not its meaning. Not tried: suspend for real. + ## Later - diff --git a/docs/RECOVERY.md b/docs/RECOVERY.md new file mode 100644 index 0000000..b5f42b8 --- /dev/null +++ b/docs/RECOVERY.md @@ -0,0 +1,78 @@ +# Error recovery + +Code: `core::error` (kinds), `core::recover` (waits, host rests, folders), `core::net_state`, `core::recover::sleep`. Checked by `cargo test -p medlar-core --test recover`. + +## Kinds + +Title and text: `error.` and `error..why` in the catalogue; button: `fix.`. "later a–b s": waits double from a to b, up to the number of tries (10; per task; 0 is forever). + +| Kind | Title | Severity | Tried again | Fix | +|---|---|---|---|---| +| `dns` | Server not found | passing | later 5–300 s | Network settings (`check_network`) | +| `unreachable` | Server out of reach | passing | later 5–300 s | Network settings (`check_network`) | +| `refused` | Connection refused | passing | later 5–300 s | Try again (`try_again`) | +| `timeout` | Server does not answer | passing | later 5–300 s | Try again (`try_again`) | +| `cut` | Connection lost | passing | later 5–300 s | Try again (`try_again`) | +| `busy` | Server is busy | passing | later 30–600 s | Try again (`try_again`) | +| `server` | Server error | passing | later 15–600 s | Try again (`try_again`) | +| `bad_reply` | Wrong answer from the server | passing | later 30–600 s | Try again (`try_again`) | +| `file_busy` | File in use | passing | later 10–120 s | Try again (`try_again`) | +| `offline` | No network | passing | when the network is back | Network settings (`check_network`) | +| `portal` | Network needs a sign-in | blocked | when the network is back | Open sign-in page (`open_portal`) | +| `sleep` | Computer sleeps | passing | on wake | Resume (`resume`) | +| `disk_full` | Disk is full | blocked | when the folder is usable | Free up space (`free_space`) | +| `read_only` | Disk is read-only | blocked | when the folder is usable | Change folder (`change_folder`) | +| `folder_gone` | Folder is gone | blocked | when the folder is usable | Change folder (`change_folder`) | +| `drive_gone` | Drive is gone | blocked | when the folder is usable | Change folder (`change_folder`) | +| `denied` | No permission | blocked | when the folder is usable | Change folder (`change_folder`) | +| `file_gone` | Unfinished file is gone | blocked | when the folder is usable | Start over (`restart`) | +| `login` | Login needed | blocked | no | Sign in (`sign_in`) | +| `forbidden` | Access denied | blocked | no | Get new link (`new_link`) | +| `expired` | Link expired | blocked | no | Get new link (`new_link`) | +| `wrong_content` | Not the file | blocked | no | Get new link (`new_link`) | +| `not_found` | File not found | blocked | no | Edit link (`edit_link`) | +| `rejected` | Request rejected | blocked | no | Edit link (`edit_link`) | +| `bad_link` | Link can't be used | blocked | no | Edit link (`edit_link`) | +| `changed` | File changed on the server | blocked | no | Choose (`choose`) | +| `no_resume` | Can't be continued | blocked | no | Choose (`choose`) | +| `killed` | Interrupted | passing | no | Resume (`resume`) | +| `tls` | Secure connection failed | serious | no | Try again (`try_again`) | +| `disk` | Disk error | serious | later 30–600 s | Change folder (`change_folder`) | +| `list` | Download list not saved | serious | later 30–600 s | Try again (`try_again`) | +| `crashed` | Medlar made a mistake | serious | no | Try again (`try_again`) | + +## Matrix + +Each fault begins at the first byte, or at 5, 50 and 90 % of the file, and stays. "whole": the file is identical. Otherwise the error after the retries; the bytes are kept, and once the fault is gone Resume makes the file whole. + +| Fault | From the first byte | Later | +|---|---|---| +| throttle_conn | whole | whole | +| throttle_total | whole | whole | +| latency_ms | whole | whole | +| stall_after, some bytes each time | whole | whole | +| stall_after, nothing comes | `timeout` | `timeout` | +| cut_after, some bytes each time | whole | whole | +| cut_after, nothing comes | `cut` | `cut` | +| reset_after, some bytes each time | whole | whole | +| reset_after, nothing comes | `cut` | `cut` | +| status 401 | `login` | `login` | +| status 403 | `forbidden` | `expired` | +| status 404 | `not_found` | `not_found` | +| status 410 | `not_found` | `expired` | +| status 416 | `rejected` | `rejected` | +| status 418 | `rejected` | `rejected` | +| status 429 | `busy` | `busy` | +| status 500 | `server` | `server` | +| status 503 with retry_after | `busy` | `busy` | +| wrong_length, too long | `bad_reply` | `bad_reply` | +| wrong_length, too short | `bad_reply` | `bad_reply` | +| ignore_range | whole | `no_resume` | +| change_after | whole (simply another file) | `changed` | +| version_after_requests | whole (simply another file) | `changed` | +| gzip | `bad_reply` | `bad_reply` | +| expire_requests | `forbidden` | `expired` | +| expire_secs, 410 | `not_found` | `expired` | +| max_conns | whole | whole | + +Not seen without a checksum: a server that changes the bytes in the middle but keeps its size, ETag and date.