misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
Engine tests: pause/resume, the event log and the overlap check no longer depend on timing (#123) (#135)
Ahmed Nefzaoui570375501271
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3595834a..192a4c2b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -235,6 +235,11 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see### Changed+- **Developers: two engine tests no longer fail now and then**+ ([#123](https://github.com/anefzaoui/misterdownloadmanager/issues/123)): the pause-and-resume+ and event-log tests no longer depend on how fast the machine is. The lab server can hold a+ byte back until a test lets it go (`stall_at`), and a test can wait until every request it+ made is in the server's log.- **Torrents behind a proxy open no UDP socket toward the network**: UDP trackers were alreadyleft out there; now their client stays on this computer too.- **Developers: tests no longer make Windows Firewall ask about them.** The torrent tests anddiff --git a/ROADMAP.md b/ROADMAP.mdindex cdbee818..954387de 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -13,6 +13,8 @@ Everything below ships together, in one release.### Done+- ✅ Two engine tests that failed now and then on busy machines are reliable+ ([#123](https://github.com/anefzaoui/misterdownloadmanager/issues/123))- ✅ Numbers are grouped and pointed the interface language's way (German `10.200`, `1,50 MB`)([#128](https://github.com/anefzaoui/misterdownloadmanager/issues/128))- ✅ The extension's button lists the media the tab has loaded (HLS and DASH streams, video anddiff --git a/crates/engine/tests/e2e.rs b/crates/engine/tests/e2e.rsindex 4ecc893f..e77e80cb 100644--- a/crates/engine/tests/e2e.rs+++ b/crates/engine/tests/e2e.rs@@ -4,6 +4,9 @@use mdm_engine::{Destination, Download, Options, Request};use mdm_labserver::{Config, Faults, LabServer, LogEntry, content};+/// How long a test waits for the lab server's log to take in every request (`settled`).+const SETTLE: std::time::Duration = std::time::Duration::from_secs(20);+async fn server(faults: &str) -> LabServer {LabServer::start(Config {faults: Faults::parse(faults).unwrap(),@@ -223,7 +226,11 @@ async fn a_wrong_checksum_fails_and_keeps_the_data() {#[tokio::test]async fn the_event_log_tells_what_happened() {- let s = server("rate=8M&drop_after=300K&drop_every=3").await;+ // Every response is cut after 300 KiB, so a retry is certain (#123). Cutting only every+ // third request left it to timing: on a busy machine that request could be a part under+ // 300 KiB, be taken over before it got there, or be cut after its part was already done,+ // and the download then had nothing to retry.+ let s = server("rate=8M&drop_after=300K").await;let dir = tempfile::tempdir().unwrap();let req = Request {url: s.url("/gen/4M/log.bin?seed=29").parse().unwrap(),@@ -468,8 +475,17 @@ async fn tiny_file_is_not_split() {assert_eq!(log.iter().filter(|e| e.bytes_sent > 0).count(), 1);}-/// Start a slow download, cancel it once some data is on disk; returns (dir, state file).+/// Start a download, cancel it once some data is on disk; returns (dir, state file). The server+/// holds the byte at 4 MiB back meanwhile, so the download can't finish before it is stopped+/// however busy the machine (#123: on a slow CI runner the whole file could arrive before the+/// stop). On return the server's faults are as before and every request of the stopped+/// download is in its log.async fn paused(s: &LabServer, path: &str) -> (tempfile::TempDir, std::path::PathBuf) {+ let faults = s.faults();+ s.set_faults(Faults {+ stall_at: Some(4 << 20),+ ..faults.clone()+ });let dir = tempfile::tempdir().unwrap();let req = Request {url: s.url(path).parse().unwrap(),@@ -482,12 +498,12 @@ async fn paused(s: &LabServer, path: &str) -> (tempfile::TempDir, std::path::Pat};let dl = Download::start(req, opts);// Wait for the real condition (not a fixed time: a busy machine is slower): the probe is- // done and some data is on disk.+ // done and a MiB is in (the server holds back only what follows its stall point).let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);let file = loop {tokio::time::sleep(std::time::Duration::from_millis(50)).await;let snap = dl.snapshot();- if let Some(f) = snap.file.filter(|_| snap.downloaded > 0) {+ if let Some(f) = snap.file.filter(|_| snap.downloaded >= 1 << 20) {break f;}assert!(@@ -495,12 +511,39 @@ async fn paused(s: &LabServer, path: &str) -> (tempfile::TempDir, std::path::Pat"the download never started");};- tokio::time::sleep(std::time::Duration::from_millis(300)).await;dl.cancel();- assert!(matches!(dl.wait().await, Err(mdm_engine::Error::Cancelled)));+ let stopped = dl.wait().await;+ assert!(+ matches!(stopped, Err(mdm_engine::Error::Cancelled)),+ "{:?}",+ stopped.map(|o| o.size)+ );+ // The held-back responses go on (into connections the download closed), and end.+ s.set_faults(faults);+ tokio::time::timeout(SETTLE, s.settled())+ .await+ .expect("the stopped download's requests end");(dir, mdm_engine::state::state_path(&file))}+/// Bytes of `range` (a `Range` header, `bytes=a-b`; none: the whole file) that the saved+/// segments say were already on disk: outside every segment's part still to fetch.+fn on_disk(range: Option<&str>, saved: &mdm_engine::state::ResumeState) -> u64 {+ let (from, to) = match range.and_then(|r| r.strip_prefix("bytes=")?.split_once('-')) {+ Some((a, b)) => (+ a.parse::<u64>().unwrap(),+ b.parse::<u64>().map_or(saved.size, |b| b + 1),+ ),+ None => (0, saved.size),+ };+ let to_fetch: u64 = saved+ .segments+ .iter()+ .map(|g| to.min(g.end).saturating_sub(from.max(g.cursor)))+ .sum();+ (to - from) - to_fetch+}+#[tokio::test]async fn pause_and_resume_continues_where_it_stopped() {let s = server("rate=1M").await;@@ -511,9 +554,7 @@ async fn pause_and_resume_continues_where_it_stopped() {before > 0 && before < 8 << 20,"partial progress saved: {before}");- // The server logs a request when its response body is dropped, which trails the cancel:- // let the paused phase's entries land before clearing, so only the resume is counted.- tokio::time::sleep(std::time::Duration::from_millis(500)).await;+ // Every request of the stopped download is in the log (`paused`): only the resume's follow.s.clear_log();let out = Download::resume(state.clone(), Default::default(), fast_opts())@@ -526,12 +567,23 @@ async fn pause_and_resume_continues_where_it_stopped() {content::fill(7, 0, &mut want);assert!(data == want, "content mismatch after resume");assert!(!state.exists(), "state file removed on completion");- tokio::time::sleep(std::time::Duration::from_millis(300)).await;- let refetched: u64 = s.log().iter().map(|e| e.bytes_sent).sum();- assert!(- refetched <= (8 << 20) - before + (1 << 20),- "resume re-downloaded too much: {refetched} after {before}"- );+ tokio::time::timeout(SETTLE, s.settled())+ .await+ .expect("the resume's requests end");+ // Nothing that was on disk is asked for again, but for the few bytes before each part that+ // a connection re-reads to check the file is the same (verify_overlap). How much of the+ // rest comes twice depends on timing (a part split while its bytes are on the way), so a+ // total would be flaky on a busy machine (#123).+ let overlap = fast_opts().verify_overlap;+ for e in s.log() {+ assert!(+ on_disk(e.range.as_deref(), &saved) <= overlap,+ "the resume asked again for data it had: {:?} ({} on disk)",+ e.range,+ on_disk(e.range.as_deref(), &saved)+ );+ }+ assert!(!s.log().is_empty());assert!(s.log().iter().all(|e| e.if_range.is_some()),"resume validates with If-Range"@@ -593,9 +645,18 @@ async fn resume_overlap_check_detects_changed_data() {let (_dir, state) = paused_without_validator(&s, "/gen/8M/c.bin?seed=12").await;// Make the data on disk differ from the server's just before every resume point, as if// the file had changed on the server since.- let saved = mdm_engine::state::ResumeState::load(&state).unwrap();+ let mut saved = mdm_engine::state::ResumeState::load(&state).unwrap();let part = mdm_engine::naming::part_path(&saved.dest);let mut bytes = std::fs::read(&part).unwrap();+ // Every part with data resumes inside it: a finished one is saved as half done (its data is+ // on disk all the same). Which parts are under way when the download stops depends on the+ // machine's speed (#123: on a busy one only the first connection had any).+ for seg in &mut saved.segments {+ if seg.cursor == seg.end && seg.end - seg.start > 4096 {+ seg.cursor = seg.start + (seg.end - seg.start) / 2;+ }+ }+ std::fs::write(&state, serde_json::to_vec(&saved).unwrap()).unwrap();let mut flipped = 0;for seg in &saved.segments {if seg.cursor > seg.start && seg.cursor < seg.end {diff --git a/crates/labserver/src/faults.rs b/crates/labserver/src/faults.rsindex f3019656..4fa9ee31 100644--- a/crates/labserver/src/faults.rs+++ b/crates/labserver/src/faults.rs@@ -49,6 +49,11 @@ pub struct Faults {/// (HEAD and ranges included) gets 410 Gone.#[serde(deserialize_with = "flag_opt")]pub once: Option<bool>,+ /// Never send the file's byte at this offset: a response that reaches it stops there and+ /// waits until the server's faults no longer say so ([`crate::LabServer::set_faults`]; a+ /// URL's own value is never lifted). A download can't finish meanwhile, only be stopped.+ #[serde(deserialize_with = "size_opt")]+ pub stall_at: Option<u64>,}impl Faults {@@ -79,6 +84,7 @@ impl Faults {.clone().or(self.require_referer.clone()),once: over.once.or(self.once),+ stall_at: over.stall_at.or(self.stall_at),}}}diff --git a/crates/labserver/src/server.rs b/crates/labserver/src/server.rsindex e7b2a653..89922958 100644--- a/crates/labserver/src/server.rs+++ b/crates/labserver/src/server.rs@@ -25,7 +25,7 @@ use std::collections::{HashMap, HashSet};use std::io;use std::net::{IpAddr, SocketAddr};use std::sync::atomic::{AtomicU64, Ordering};-use std::sync::{Arc, Mutex};+use std::sync::{Arc, Mutex, RwLock};use std::time::{Duration, Instant, UNIX_EPOCH};use axum::body::{Body, HttpBody};@@ -40,6 +40,7 @@ use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};use serde::{Deserialize, Serialize};use sha2::{Digest, Sha256};use tokio::net::TcpListener;+use tokio::sync::Notify;use tokio::task::JoinHandle;use crate::content;@@ -96,6 +97,47 @@ pub struct LogEntry {pub outcome: String,pub rate: Option<u64>,pub drop_at: Option<u64>,+ /// Counts the request as in flight until its entry is logged ([`LabServer::settled`]).+ #[serde(skip)]+ #[doc(hidden)]+ pub in_flight: InFlight,+}++/// A request begun and not logged yet: one of the server's in-flight count while it lives (a+/// request dropped before it is logged counts out too). A copy doesn't count.+#[derive(Default)]+pub struct InFlight(Option<Arc<Pending>>);++impl Clone for InFlight {+ fn clone(&self) -> Self {+ InFlight(None)+ }+}++impl std::fmt::Debug for InFlight {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(if self.0.is_some() {+ "InFlight"+ } else {+ "Logged"+ })+ }+}++impl Drop for InFlight {+ fn drop(&mut self) {+ if let Some(p) = self.0.take() {+ p.count.fetch_sub(1, Ordering::SeqCst);+ p.changed.notify_waiters();+ }+ }+}++/// How many requests are in flight, and a wake-up when that changes.+#[derive(Default)]+pub struct Pending {+ count: AtomicU64,+ changed: Notify,}pub type LogSink = Arc<dyn Fn(&LogEntry) + Send + Sync>;@@ -125,7 +167,12 @@ impl Default for Config {}pub(crate) struct Shared {- faults: Faults,+ /// The server's faults ([`LabServer::set_faults`] changes them; a URL's own override them).+ faults: RwLock<Faults>,+ /// Woken when `faults` change (a stalled response checks whether it may go on).+ faults_changed: Notify,+ /// Requests begun and not logged yet.+ pending: Arc<Pending>,/// `Config::rss_dir`.pub(crate) rss_dir: Option<std::path::PathBuf>,started: Instant,@@ -149,6 +196,23 @@ impl Shared {self.started.elapsed().as_millis() as u64}+ fn faults(&self) -> Faults {+ self.faults.read().unwrap().clone()+ }++ /// Resolves once the server's faults leave the byte at `at` to be sent.+ async fn unstalled(&self, at: u64) {+ loop {+ let changed = self.faults_changed.notified();+ tokio::pin!(changed);+ changed.as_mut().enable();+ if self.faults.read().unwrap().stall_at != Some(at) {+ return;+ }+ changed.await;+ }+ }+/// The log entry of a request that starts now; `body` is the request's body.pub(crate) fn begin(&self,@@ -166,6 +230,7 @@ impl Shared {*c};let has_body = !body.is_empty() || !matches!(*method, Method::GET | Method::HEAD);+ self.pending.count.fetch_add(1, Ordering::SeqCst);LogEntry {req: self.seq.fetch_add(1, Ordering::SeqCst) + 1,peer,@@ -194,6 +259,7 @@ impl Shared {outcome: String::new(),rate: None,drop_at: None,+ in_flight: InFlight(Some(self.pending.clone())),}}@@ -201,10 +267,13 @@ impl Shared {entry.status = status;entry.outcome = outcome.to_owned();entry.t_end_ms = self.ms();+ // In flight until it is in the log, so `settled` finds it there.+ let in_flight = std::mem::take(&mut entry.in_flight);if let Some(sink) = &self.on_log {sink(&entry);}self.log.lock().unwrap().push(entry);+ drop(in_flight);}}@@ -220,7 +289,9 @@ impl LabServer {let listener = TcpListener::bind(cfg.bind).await?;let addr = listener.local_addr()?;let shared = Arc::new(Shared {- faults: cfg.faults,+ faults: RwLock::new(cfg.faults),+ faults_changed: Notify::new(),+ pending: Arc::default(),rss_dir: cfg.rss_dir,started: Instant::now(),requests: AtomicU64::new(0),@@ -303,6 +374,34 @@ impl LabServer {self.shared.log.lock().unwrap().clear();}+ /// Resolves once every request begun so far is in the log. A response is logged when its+ /// body is dropped, which can trail the client: after a download is stopped, the server+ /// sees its connections close only as it next writes to them.+ pub async fn settled(&self) {+ let pending = &self.shared.pending;+ loop {+ let changed = pending.changed.notified();+ tokio::pin!(changed);+ changed.as_mut().enable();+ if pending.count.load(Ordering::SeqCst) == 0 {+ return;+ }+ changed.await;+ }+ }++ /// The server-wide faults (`--faults`, [`Config::faults`]).+ pub fn faults(&self) -> Faults {+ self.shared.faults()+ }++ /// Change the server-wide faults for the requests from now on, and lift a `stall_at` that+ /// responses are waiting at.+ pub fn set_faults(&self, faults: Faults) {+ *self.shared.faults.write().unwrap() = faults;+ self.shared.faults_changed.notify_waiters();+ }+/// Resolves when the server task ends (only on error; runs until dropped otherwise).pub async fn wait(&mut self) {let _ = (&mut self.task).await;@@ -333,6 +432,8 @@ GET|HEAD /gen/{size}[/{name}]?seed=N&<file params>&<faults> size: 12345, 64K,rate=SIZE slow_every=N slow_rate=SIZE max_conns=N drop_after=SIZE drop_every=Nfail_every=N fail_first=N no_range=1 no_range_every=N html=1 etag_change_every=Netag=weak|per-request|none latency_ms=N+ stall_at=SIZE never send the file's byte at that offset: a response stops there and waits+ (until the server's faults change, from a test; a URL's own value stays)require_cookie=NAME=VALUE|NAME 403 unless the Cookie header has itrequire_referer=PREFIX 403 unless the Referer starts with PREFIX (%-encode ? & =)once=1 a one-time link: the first request for this path and query is served, every@@ -775,7 +876,7 @@ pub(crate) async fn serve(shared.record(entry, 403, "expired");return (StatusCode::FORBIDDEN, "link expired\n").into_response();}- let f = shared.faults.overridden_by(&q.faults);+ let f = shared.faults().overridden_by(&q.faults);if let Some(want) = &f.require_cookie&& !has_cookie(entry.cookie.as_deref(), want)@@ -929,6 +1030,9 @@ pub(crate) async fn serve(end,rate,drop_at,+ // A URL's own stall stays; the server's is lifted with `set_faults`.+ stall_at: f.stall_at.filter(|at| (start..end).contains(at)),+ stall_lifts: q.faults.stall_at.is_none(),started: Instant::now(),sent: 0,dropped: false,@@ -1059,6 +1163,9 @@ struct Transfer {end: u64,rate: Option<u64>,drop_at: Option<u64>,+ /// The file offset this response stops at (`stall_at`), and whether `set_faults` can lift it.+ stall_at: Option<u64>,+ stall_lifts: bool,started: Instant,sent: u64,dropped: bool,@@ -1078,7 +1185,18 @@ impl Transfer {t.dropped = true;return Some((Err(io::Error::other("fault: drop_after")), t));}+ if let Some(at) = t.stall_at.filter(|at| t.pos >= *at) {+ if t.stall_lifts {+ t.shared.unstalled(at).await;+ } else {+ std::future::pending::<()>().await;+ }+ t.stall_at = None;+ }let mut n = CHUNK.min(t.end - t.pos);+ if let Some(at) = t.stall_at {+ n = n.min(at - t.pos);+ }if let Some(r) = t.rate.filter(|r| *r > 0) {n = n.min((r / 20).max(1024));let due = Duration::from_secs_f64((t.sent + n) as f64 / r as f64);diff --git a/crates/labserver/tests/http.rs b/crates/labserver/tests/http.rsindex 778920eb..07e62f14 100644--- a/crates/labserver/tests/http.rs+++ b/crates/labserver/tests/http.rs@@ -651,3 +651,40 @@ async fn help_lists_the_routes() {assert!(help.contains(word), "{word}");}}++/// `stall_at` (#123): a response stops at that byte and goes on once the server's faults are+/// changed; a request that starts past it isn't held; `settled` waits for every request's entry.+#[tokio::test]+async fn a_stall_holds_a_byte_back_until_lifted() {+ let s = server("stall_at=64K").await;+ let mut r = reqwest::get(s.url("/gen/256K/s.bin?seed=5")).await.unwrap();+ let mut got = Vec::new();+ while got.len() < 64 * 1024 {+ got.extend_from_slice(&r.chunk().await.unwrap().unwrap());+ }+ assert_eq!(got.len(), 64 * 1024, "nothing past the stall");+ // Held: no byte comes while the stall stands.+ let more = tokio::time::timeout(Duration::from_millis(300), r.chunk()).await;+ assert!(more.is_err(), "the stall let bytes through");+ // Past the stall point, a range is served at once.+ let tail = reqwest::Client::new()+ .get(s.url("/gen/256K/s.bin?seed=5"))+ .header("Range", "bytes=131072-")+ .send()+ .await+ .unwrap()+ .bytes()+ .await+ .unwrap();+ assert_eq!(tail, expected(5, 128 * 1024, 128 * 1024));+ s.set_faults(Faults::default());+ while let Some(c) = r.chunk().await.unwrap() {+ got.extend_from_slice(&c);+ }+ assert_eq!(got, expected(5, 0, 256 * 1024));+ tokio::time::timeout(Duration::from_secs(20), s.settled())+ .await+ .expect("every request is logged");+ assert_eq!(s.log().len(), 2);+ assert!(s.log().iter().all(|e| e.outcome == "complete"));+}