Skip to content

misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux

Engine tests: a refusal below the cap, the learned limit and a dead address wait for what they check (#136) (#196)

Ahmed Nefzaouid57ac1619171
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4b237110..80897507 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -272,6 +272,12 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Changed
+- **Developers: the engine tests no longer fail on a busy computer**
+ ([#136](https://github.com/anefzaoui/misterdownloadmanager/issues/136)). Three end-to-end tests
+ depended on timing: a refused connection coming back, the learned connection limit, and a dead
+ address (a server without ranges was fixed earlier). Each now waits for the state it checks. The lab server
+ can hold a connection slot for a test (`hold_slot`), and `settled()` now also means every
+ slot is free.
- **A smaller download** ([#158](https://github.com/anefzaoui/misterdownloadmanager/issues/158)):
the program is built for size, which takes the installer from 16.1 to 13.6 MB and the zips
from 19.3 to 15.6 MB, with the same features and the same download speed.
diff --git a/ROADMAP.md b/ROADMAP.md
index 7d1dc94f..50c3a433 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -22,6 +22,9 @@ Everything below ships together, in one release.
manual install as the fallback
- ✅ A minimized MDM keeps working: queues, the Scheduler, download limits, the kill switch and
saving the list no longer wait for the window to be restored
+- ✅ The engine tests that failed now and then on a busy computer (a refused connection coming
+ back, the learned connection limit, a dead address) wait for what they check, not for time
+ ([#136](https://github.com/anefzaoui/misterdownloadmanager/issues/136))
- ✅ HLS and DASH videos from the browser reach yt-dlp as their stream, by the button over the
video, the right-click menu (it did nothing in Firefox) and the media list
([#155](https://github.com/anefzaoui/misterdownloadmanager/issues/155))
diff --git a/crates/engine/tests/e2e.rs b/crates/engine/tests/e2e.rs
index f8350121..bca1fd54 100644
--- a/crates/engine/tests/e2e.rs
+++ b/crates/engine/tests/e2e.rs
@@ -40,8 +40,11 @@ async fn fetch(s: &LabServer, path: &str, seed: u64, opts: Options) -> (Vec<LogE
content::fill(seed, 0, &mut want);
assert!(data == want, "content mismatch");
assert_eq!(data.len() as u64, out.size);
- // The server logs a request when its response body is dropped, which can trail the client.
- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
+ // The server logs a request when its response body is dropped, which can trail the client:
+ // wait until every one is in the log (and its connection slot is free).
+ tokio::time::timeout(SETTLE, s.settled())
+ .await
+ .expect("every request ends");
(s.log(), out.size)
}
@@ -82,11 +85,14 @@ async fn connections_skip_a_dead_address() {
let s = server("").await;
let port = s.url("/").parse::<url::Url>().unwrap().port().unwrap();
// The host's first address never answers (TEST-NET-1); the second is the lab server.
+ // A connect timeout long enough that waiting on the dead address can't pass for a slow
+ // machine (#136): 60 s per address, against the 30 s the whole download is given.
let opts = Options {
hosts: vec![(
"mirror.test".into(),
vec!["192.0.2.1".parse().unwrap(), "127.0.0.1".parse().unwrap()],
)],
+ connect_timeout: std::time::Duration::from_secs(120),
..Options::default()
};
let dir = tempfile::tempdir().unwrap();
@@ -97,14 +103,16 @@ async fn connections_skip_a_dead_address() {
headers: Default::default(),
dest: Destination::Dir(dir.path().to_owned()),
};
- let started = std::time::Instant::now();
- let out = Download::start(req, opts).wait().await.expect("completes");
- // Without the race every connection would wait 15 s (half the 30 s connect timeout).
- assert!(
- started.elapsed() < std::time::Duration::from_secs(3),
- "took {:?}",
- started.elapsed()
- );
+ // Without the race every connection would wait 60 s on the dead address (half the connect
+ // timeout) before trying the next. A 3 s budget failed on a starved CPU, where 2 MiB alone
+ // can take longer (#136).
+ let out = tokio::time::timeout(
+ std::time::Duration::from_secs(30),
+ Download::start(req, opts).wait(),
+ )
+ .await
+ .expect("the connections waited for the dead address")
+ .expect("completes");
let mut want = vec![0; 2 << 20];
content::fill(19, 0, &mut want);
assert!(
@@ -155,18 +163,20 @@ async fn a_slow_download_does_not_rewrite_its_state_every_tick() {
#[tokio::test]
async fn a_global_cap_is_shared_by_all_downloads() {
let s = server("").await;
+ // Timed from the cap's start: its budget builds up from then on, however long the
+ // downloads take to start (a burst of up to a second's), so 2 MiB can't take less than 2 s.
+ let started = std::time::Instant::now();
let global = std::sync::Arc::new(mdm_engine::limiter::Limiter::new(Some(1 << 20)));
let opts = Options {
global: Some(global),
..fast_opts()
};
- let started = std::time::Instant::now();
let (a, b) = tokio::join!(
fetch(&s, "/gen/1M/a.bin?seed=25", 25, opts.clone()),
fetch(&s, "/gen/1M/b.bin?seed=26", 26, opts.clone()),
);
assert_eq!((a.1, b.1), (1 << 20, 1 << 20));
- // 2 MiB through one 1 MiB/s cap (fetch adds 0.3 s of its own per download).
+ // 2 MiB through one 1 MiB/s cap.
let took = started.elapsed();
assert!(
took >= std::time::Duration::from_millis(1700),
@@ -256,14 +266,46 @@ async fn the_event_log_tells_what_happened() {
#[tokio::test]
async fn a_host_connection_limit_is_learned_and_reused() {
- let s = server("rate=2M&max_conns=2").await;
+ // The cap is learned from the connections seen receiving at once when others are refused.
+ // On a starved CPU the first connection (the probe) could finish its part before the second
+ // had its first bytes, so only one was ever seen and the cap learned was 1 (#136). Now the
+ // byte at 256 KiB, inside the probe's part however the file is split, is held back until
+ // the cap is learned: the probe keeps receiving while the other connection fetches the rest.
+ let s = server("rate=2M&max_conns=2&stall_at=256K").await;
let limits = std::sync::Arc::new(mdm_engine::hosts::HostLimits::default());
let opts = Options {
host_limits: Some(limits.clone()),
..fast_opts()
};
- let (first, _) = fetch(&s, "/gen/4M/a.bin?seed=30", 30, opts.clone()).await;
- assert!(first.iter().any(|e| e.outcome == "fault:max_conns"));
+ let dir = tempfile::tempdir().unwrap();
+ let req = Request {
+ url: s.url("/gen/4M/a.bin?seed=30").parse().unwrap(),
+ headers: Default::default(),
+ dest: Destination::Dir(dir.path().to_owned()),
+ };
+ let dl = Download::start(req, opts.clone());
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
+ while limits.cap("127.0.0.1") != Some(2) {
+ assert!(
+ std::time::Instant::now() < deadline,
+ "the cap learned: {:?}",
+ limits.learned()
+ );
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+ s.set_faults(Faults::parse("rate=2M&max_conns=2").unwrap());
+ let out = dl.wait().await.expect("download succeeds");
+ let mut want = vec![0; 4 << 20];
+ content::fill(30, 0, &mut want);
+ assert!(
+ std::fs::read(&out.path).unwrap() == want,
+ "content mismatch"
+ );
+ // Every request of the first download has ended and given its slot back.
+ tokio::time::timeout(SETTLE, s.settled())
+ .await
+ .expect("every request ends");
+ assert!(s.log().iter().any(|e| e.outcome == "fault:max_conns"));
assert_eq!(limits.cap("127.0.0.1"), Some(2), "{:?}", limits.learned());
// The next download from the host opens only what it allows: nothing is refused.
s.clear_log();
@@ -282,21 +324,20 @@ async fn a_refusal_below_the_learned_cap_is_retried() {
// a connection of ours that just closed and the server hasn't noticed yet): the second
// connection is refused while only one works. It must come back once the slot frees, not
// leave the whole file to one connection (benchmark 2026-10-29).
- // The blocker holds its slot until our download has been refused (it stops at its byte
- // 12 MiB, held back by the server, until the faults change): on a busy machine it used to be
- // done before our second connection asked (#136). Our file is shorter, so it isn't held.
- let s = server("rate=2M&max_conns=2&stall_at=12M").await;
+ // The other client's slot is held by the test until our download has been refused (#136:
+ // a blocking request could end before our second connection asked). Our download can't
+ // finish meanwhile either: the server holds back its byte at 6 MiB until a second connection
+ // has joined, so on a starved CPU the first one can't fetch the whole file alone before it.
+ let s = server("rate=2M&max_conns=2&stall_at=6M").await;
+ let ip: std::net::IpAddr = "127.0.0.1".parse().unwrap();
let limits = std::sync::Arc::new(mdm_engine::hosts::HostLimits::default());
limits.refused("127.0.0.1", 2);
limits.refused("127.0.0.1", 2);
- let blocker = tokio::spawn(
- reqwest::get(s.url("/gen/16M/blocker.bin?seed=1&rate=0"))
- .await
- .unwrap()
- .bytes(),
- );
+ let blocker = s.hold_slot(ip);
let opts = Options {
host_limits: Some(limits),
+ // Room to come back after the slot frees, however slowly the test notices the refusal.
+ max_retries: 8,
..fast_opts()
};
let dir = tempfile::tempdir().unwrap();
@@ -318,7 +359,22 @@ async fn a_refusal_below_the_learned_cap_is_retried() {
);
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
- // The slot frees: a second connection can join.
+ // The slot frees: a second connection can join, and once it has the first may go on.
+ drop(blocker);
+ let receiving = |dl: &Download| {
+ dl.snapshot()
+ .connections
+ .iter()
+ .filter(|c| matches!(c.status, mdm_engine::download::ConnStatus::Receiving))
+ .count()
+ };
+ while receiving(&dl) < 2 {
+ assert!(
+ std::time::Instant::now() < deadline,
+ "no second connection joined"
+ );
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
s.set_faults(Faults::parse("rate=2M&max_conns=2").unwrap());
let out = dl.wait().await.expect("download succeeds");
let size = out.size;
@@ -328,7 +384,6 @@ async fn a_refusal_below_the_learned_cap_is_retried() {
std::fs::read(&out.path).unwrap() == want,
"content mismatch"
);
- blocker.await.unwrap().unwrap();
tokio::time::timeout(SETTLE, s.settled())
.await
.expect("every request ends");
diff --git a/crates/labserver/src/lib.rs b/crates/labserver/src/lib.rs
index 2363a788..181b7acf 100644
--- a/crates/labserver/src/lib.rs
+++ b/crates/labserver/src/lib.rs
@@ -12,4 +12,4 @@ mod server;
mod streams;
pub use faults::Faults;
-pub use server::{Config, HELP, LabServer, LogEntry, LogSink};
+pub use server::{Config, HELP, LabServer, LogEntry, LogSink, SlotHold};
diff --git a/crates/labserver/src/server.rs b/crates/labserver/src/server.rs
index 9343b188..94037ff1 100644
--- a/crates/labserver/src/server.rs
+++ b/crates/labserver/src/server.rs
@@ -390,9 +390,10 @@ 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.
+ /// Resolves once every request begun so far is in the log, and has given back its
+ /// `max_conns` slot. 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 {
@@ -406,6 +407,18 @@ impl LabServer {
}
}
+ /// Take one of `ip`'s `max_conns` slots, as another client's response would, until the
+ /// guard is dropped: a test holds a slot for exactly as long as it needs.
+ pub fn hold_slot(&self, ip: IpAddr) -> SlotHold {
+ *self.shared.active.lock().unwrap().entry(ip).or_insert(0) += 1;
+ SlotHold {
+ _slot: ActiveSlot {
+ shared: self.shared.clone(),
+ ip,
+ },
+ }
+ }
+
/// The server-wide faults (`--faults`, [`Config::faults`]).
pub fn faults(&self) -> Faults {
self.shared.faults()
@@ -647,6 +660,11 @@ fn header_str(h: &HeaderMap, name: header::HeaderName) -> Option<String> {
h.get(name).and_then(|v| v.to_str().ok()).map(str::to_owned)
}
+/// A `max_conns` slot held by a test ([`LabServer::hold_slot`]), given back when dropped.
+pub struct SlotHold {
+ _slot: ActiveSlot,
+}
+
/// Releases a client's concurrent-response slot (for `max_conns`) when dropped.
struct ActiveSlot {
shared: Arc<Shared>,
@@ -959,6 +977,7 @@ pub(crate) async fn serve(
if f.once == Some(true) {
let key = format!("{}?{query}", entry.path);
if !shared.used_once.lock().unwrap().insert(key) {
+ drop(slot);
shared.record(entry, 410, "fault:once");
return (StatusCode::GONE, "this link was already used\n").into_response();
}
@@ -991,6 +1010,7 @@ pub(crate) async fn serve(
Ok(v) if v.len() == 1 => range = Some((*v[0].start(), *v[0].end() + 1)),
Ok(_) => {}
Err(_) => {
+ drop(slot);
shared.record(entry, 416, "error");
let mut resp = StatusCode::RANGE_NOT_SATISFIABLE.into_response();
resp.headers_mut().insert(
@@ -1066,7 +1086,7 @@ pub(crate) async fn serve(
started: Instant::now(),
sent: 0,
dropped: false,
- _slot: slot,
+ slot: Some(slot),
};
builder
.body(Body::from_stream(transfer.into_stream()))
@@ -1199,7 +1219,8 @@ struct Transfer {
started: Instant,
sent: u64,
dropped: bool,
- _slot: ActiveSlot,
+ /// Given back before the request is logged, so `settled` means every slot is free.
+ slot: Option<ActiveSlot>,
}
impl Transfer {
@@ -1246,6 +1267,7 @@ impl Transfer {
impl Drop for Transfer {
fn drop(&mut self) {
+ self.slot.take();
if let Some(mut entry) = self.entry.take() {
entry.bytes_sent = self.sent;
let outcome = if self.dropped {