Skip to content

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

A server without ranges sends the file once, even under load (part of #136) (#160)

Ahmed Nefzaouib66d991e985c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 26d13d80..8c590d61 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -331,6 +331,12 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- **A server without ranges no longer sends the file twice**
+ ([#136](https://github.com/anefzaoui/misterdownloadmanager/issues/136)): when the extra
+ connections' answers came late (a busy computer), the download could finish and then start over
+ on one connection, fetching the whole file again. MDM now stops its other connections once every
+ byte is in, and a server that never said it takes ranges is known for one at its first full
+ answer (a CDN that says it does and misses a range now and then still gets several connections).
- **Screen readers reach every row of a list, not only those in view**
([#111](https://github.com/anefzaoui/misterdownloadmanager/issues/111)): a list's rows out of
view (the last qualities of Download video, a long playlist, the downloads) are there too,
diff --git a/ROADMAP.md b/ROADMAP.md
index 415ce55d..95a9b451 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -13,6 +13,8 @@ Everything below ships together, in one release.
### Done
+- ✅ A server that can't resume a download no longer gets the file downloaded twice on a busy
+ computer (part of [#136](https://github.com/anefzaoui/misterdownloadmanager/issues/136))
- ✅ Translators: a reviewed translation is never replaced by machine translation, and CI checks it;
Italian is the first catalog reviewed by a native speaker
([#150](https://github.com/anefzaoui/misterdownloadmanager/pull/150))
@@ -141,8 +143,6 @@ Everything below ships together, in one release.
icons all come from the chosen theme, and Base16 and pywal schemes can be imported
([#45](https://github.com/anefzaoui/misterdownloadmanager/issues/45))
- 🔄 A crash when a magnet link comes from Firefox ([#145](https://github.com/anefzaoui/misterdownloadmanager/issues/145))
-- 🔄 A server that can't resume a download no longer gets the file downloaded twice
- ([#136](https://github.com/anefzaoui/misterdownloadmanager/issues/136))
### Bugs being looked into
diff --git a/crates/engine/src/download.rs b/crates/engine/src/download.rs
index d91fecec..467cdb38 100644
--- a/crates/engine/src/download.rs
+++ b/crates/engine/src/download.rs
@@ -1,4 +1,4 @@
-//! One download: probe, parallel connections driven by the planner, positional writes, progress.
+//! One download: probe, parallel connections driven by the planner, positional writes, progress.
//!
//! The first connection is also the probe: a plain `GET` (no Range, as IDM does — D-007) that
//! keeps streaming from byte 0 while further connections split the file (notes/ENGINE.md §1).
@@ -1119,6 +1119,10 @@ struct Ctx {
cancel: CancellationToken,
/// `RANGES_*`: learned from the first range answer.
ranges: AtomicU8,
+ /// The first answer advertised ranges (`Accept-Ranges: bytes`, or a 206): a full answer to
+ /// a range request with the same ETag is then an edge that missed the range this time, not
+ /// a server without ranges (#136).
+ advertised: bool,
/// Further connections wait for a range answer (`range_answered`): a POST whose server
/// hasn't shown yet that it takes ranges (`Options::post`).
wait_for_ranges: bool,
@@ -1455,6 +1459,10 @@ async fn run_fresh(
} else {
RANGES_UNKNOWN
};
+ // The first answer says the server takes ranges (`Accept-Ranges: bytes`).
+ let advertised = ranges == RANGES_YES
+ || header_str(resp.headers(), header::ACCEPT_RANGES)
+ .is_some_and(|v| v.split(',').any(|t| t.trim().eq_ignore_ascii_case("bytes")));
let final_url = resp.url().clone();
shared.event(format!(
"Connected to {}{}: {}, size {}",
@@ -1542,6 +1550,7 @@ async fn run_fresh(
// download (which may still fall back to one connection).
cancel: cancel.child_token(),
ranges: AtomicU8::new(ranges),
+ advertised,
wait_for_ranges,
range_answered: Default::default(),
as_get,
@@ -1734,6 +1743,8 @@ async fn run_fresh_ftp(
shared: shared.clone(),
cancel: cancel.child_token(),
ranges: AtomicU8::new(ranges),
+ // FTP's REST is asked for, not advertised.
+ advertised: true,
wait_for_ranges: false,
range_answered: Default::default(),
as_get: AsGet::default(),
@@ -1892,6 +1903,7 @@ async fn run_resume(
cancel: cancel.child_token(),
// Ranges worked before: a 200 now is a changed file or a range-less edge.
ranges: AtomicU8::new(RANGES_YES),
+ advertised: true,
range_answered: Default::default(),
as_get,
web_page_ok,
@@ -2534,7 +2546,14 @@ async fn supervise(ctx: Arc<Ctx>, first: Option<Body>) -> Result<(), Error> {
Ok(()) => {}
}
let complete = ctx.shared.with_planner(|p| p.is_complete());
- if set.is_empty() && !complete {
+ // Every byte is in: the connections still asking (a retry under way, an answer late on
+ // a busy machine) have nothing left to fetch. Stopped now, a late answer can't start
+ // the download over (#136: a server without ranges sent the whole file twice).
+ if complete {
+ set.shutdown().await;
+ break;
+ }
+ if set.is_empty() {
if let Some(e) = last_err.take() {
return Err(e); // the last connection exhausted its retries
}
@@ -2802,7 +2821,14 @@ fn per_node_etag(ctx: &Ctx, sent: Option<&HeaderValue>, resp: &Response) -> bool
// Sent with an ETag (dates never start with a quote) — possibly one another connection has
// just dropped, so don't compare it with the current one.
let sent_etag = sent.is_some_and(|s| s.as_bytes().starts_with(b"\""));
+ // Another node's ETag differs from the one sent. The same ETag is that too only from a
+ // server that advertised ranges: one that didn't, answering in full, has no ranges (#136),
+ // and is told so at once rather than after a round of retries.
+ let theirs = header_str(resp.headers(), header::ETAG);
+ let other_node = ctx.advertised
+ || (theirs.is_some() && theirs.map(str::as_bytes) != sent.map(HeaderValue::as_bytes));
let same = sent_etag
+ && other_node
&& resp.content_length() == Some(ctx.size)
&& v.last_modified.is_some()
&& header_str(resp.headers(), header::LAST_MODIFIED) == v.last_modified.as_deref();
diff --git a/crates/engine/tests/e2e.rs b/crates/engine/tests/e2e.rs
index e77e80cb..f8350121 100644
--- a/crates/engine/tests/e2e.rs
+++ b/crates/engine/tests/e2e.rs
@@ -282,27 +282,57 @@ 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).
- let s = server("rate=2M&max_conns=2").await;
+ // 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;
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);
- // Margins both ways, for slow, busy machines: the blocker (1 MiB at 2 MB/s) holds its slot
- // for about half a second, long enough for our download to start into it (512 KiB was gone
- // first on CI runners); the file (8 MiB, 4 s on one connection) outlasts the retries'
- // growing waits, so a second connection can still join.
let blocker = tokio::spawn(
- reqwest::get(s.url("/gen/1M/blocker.bin?seed=1"))
+ reqwest::get(s.url("/gen/16M/blocker.bin?seed=1&rate=0"))
.await
.unwrap()
.bytes(),
);
- tokio::time::sleep(std::time::Duration::from_millis(50)).await;
let opts = Options {
host_limits: Some(limits),
..fast_opts()
};
- let (log, size) = fetch(&s, "/gen/8M/c.bin?seed=33", 33, opts).await;
+ let dir = tempfile::tempdir().unwrap();
+ let req = Request {
+ url: s.url("/gen/8M/c.bin?seed=33").parse().unwrap(),
+ headers: Default::default(),
+ dest: Destination::Dir(dir.path().to_owned()),
+ };
+ let dl = Download::start(req, opts);
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
+ while !s
+ .log()
+ .iter()
+ .any(|e| e.path.contains("c.bin") && e.outcome == "fault:max_conns")
+ {
+ assert!(
+ std::time::Instant::now() < deadline,
+ "the blocker held a slot"
+ );
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+ // The slot frees: a second connection can join.
+ s.set_faults(Faults::parse("rate=2M&max_conns=2").unwrap());
+ let out = dl.wait().await.expect("download succeeds");
+ let size = out.size;
+ let mut want = vec![0; 8 << 20];
+ content::fill(33, 0, &mut want);
+ assert!(
+ std::fs::read(&out.path).unwrap() == want,
+ "content mismatch"
+ );
blocker.await.unwrap().unwrap();
+ tokio::time::timeout(SETTLE, s.settled())
+ .await
+ .expect("every request ends");
+ let log = s.log();
assert_eq!(size, 8 << 20);
let ours: Vec<_> = log.iter().filter(|e| e.path.contains("c.bin")).collect();
assert!(
@@ -435,9 +465,38 @@ async fn respects_server_connection_limit() {
#[tokio::test]
async fn no_range_server_uses_one_connection() {
// Rate-limited: unlimited, the 200 sent to a range attempt can fit whole into the socket
- // buffers before the engine drops it, and the server logs it complete (macOS runners).
- let s = server("no_range=true&rate=8M").await;
- let (log, size) = fetch(&s, "/gen/3M?seed=4", 4, fast_opts()).await;
+ // buffers before the engine drops it, and the server logs it complete (macOS runners). The
+ // byte at 2 MiB is held back until the engine knows the server has no ranges, so the range
+ // attempts always come while the probe is still streaming, however busy the machine (#136).
+ let s = server("no_range=true&rate=8M&stall_at=2M").await;
+ let dir = tempfile::tempdir().unwrap();
+ let req = Request {
+ url: s.url("/gen/3M?seed=4").parse().unwrap(),
+ headers: Default::default(),
+ dest: Destination::Dir(dir.path().to_owned()),
+ };
+ let dl = Download::start(req, fast_opts());
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
+ while dl.snapshot().resumable != Some(false) {
+ assert!(
+ std::time::Instant::now() < deadline,
+ "never learned the server has no ranges"
+ );
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+ s.set_faults(Faults::parse("no_range=true&rate=8M").unwrap());
+ let out = dl.wait().await.expect("download succeeds");
+ let size = out.size;
+ let mut want = vec![0; 3 << 20];
+ content::fill(4, 0, &mut want);
+ assert!(
+ std::fs::read(&out.path).unwrap() == want,
+ "content mismatch"
+ );
+ tokio::time::timeout(SETTLE, s.settled())
+ .await
+ .expect("every request ends");
+ let log = s.log();
assert_eq!(size, 3 << 20);
// Like IDM (lab S6): range attempts get 200 and are dropped; the probe finishes alone.
let complete: Vec<_> = log.iter().filter(|e| e.outcome == "complete").collect();
@@ -457,6 +516,69 @@ async fn no_range_server_uses_one_connection() {
assert_eq!(complete[0].range, None, "the probe is a plain GET");
}
+/// Part of #136: a server without ranges sends the file once, even when the range attempts are
+/// answered after the probe's plain GET has run on (a busy machine): every part is taken by the
+/// probe, none is fetched again by a fresh start on one connection.
+#[tokio::test]
+async fn a_server_without_ranges_sends_the_file_once() {
+ // The probe takes about 375 ms; every range attempt is answered after 300 ms, so the first
+ // answers come while it runs and a retry's after it has ended.
+ let s = server("no_range=true&rate=8M&range_latency_ms=300").await;
+ let (log, size) = fetch(&s, "/gen/3M?seed=41", 41, fast_opts()).await;
+ assert_eq!(size, 3 << 20);
+ let sent: u64 = log.iter().map(|e| e.bytes_sent).sum();
+ let requests: Vec<_> = log
+ .iter()
+ .map(|e| (e.range.clone(), e.outcome.clone(), e.bytes_sent))
+ .collect();
+ // One plain GET, the probe: no start over on one connection. The bytes served beyond the
+ // file are what the server had written into the range attempts' sockets when the engine
+ // dropped them (a few hundred KiB on a busy machine); a second copy would double them.
+ assert_eq!(
+ log.iter().filter(|e| e.range.is_none()).count(),
+ 1,
+ "{requests:#?}"
+ );
+ assert!(
+ sent < 2 * size,
+ "{sent} bytes served for a {size}-byte file: {requests:#?}"
+ );
+ assert_eq!(
+ log.iter().filter(|e| e.outcome == "complete").count(),
+ 1,
+ "{requests:#?}"
+ );
+}
+
+/// A CDN whose edges sometimes ignore ranges, with the same file and the same ETag: a full
+/// answer to a range request is retried, and the download stays on several connections (#136:
+/// telling it from a server without ranges must not cost it its speed). `every` = 2: the very
+/// first range request is the one answered in full; 3: one in three.
+async fn a_cdn_ignoring_ranges_now_and_then(every: u32, seed: u64) {
+ let s = server(&format!("rate=2M&no_range_every={every}")).await;
+ let path = format!("/gen/8M/cdn.bin?seed={seed}");
+ let (log, size) = fetch(&s, &path, seed, fast_opts()).await;
+ assert_eq!(size, 8 << 20);
+ let ranged: Vec<LogEntry> = log.iter().filter(|e| e.status == 206).cloned().collect();
+ assert!(
+ max_concurrent(&ranged) >= 2,
+ "one connection only: {:?}",
+ log.iter()
+ .map(|e| (e.range.clone(), e.status, e.outcome.clone()))
+ .collect::<Vec<_>>()
+ );
+}
+
+#[tokio::test]
+async fn a_cdn_ignoring_the_first_range_stays_segmented() {
+ a_cdn_ignoring_ranges_now_and_then(2, 44).await;
+}
+
+#[tokio::test]
+async fn a_cdn_ignoring_one_range_in_three_stays_segmented() {
+ a_cdn_ignoring_ranges_now_and_then(3, 45).await;
+}
+
#[tokio::test]
async fn probe_is_a_plain_get() {
let s = server("rate=4M").await;
diff --git a/crates/labserver/src/faults.rs b/crates/labserver/src/faults.rs
index 4fa9ee31..08b9a16b 100644
--- a/crates/labserver/src/faults.rs
+++ b/crates/labserver/src/faults.rs
@@ -40,6 +40,9 @@ pub struct Faults {
pub etag: Option<String>,
/// Delay before sending response headers, ms.
pub latency_ms: Option<u64>,
+ /// Delay before answering a request that asks for a range, ms (on top of `latency_ms`): the
+ /// probe's plain GET runs ahead of the range attempts, as on a busy machine.
+ pub range_latency_ms: Option<u64>,
/// 403 unless the request's `Cookie` holds this pair (`sid=1`), or a cookie of this name
/// (`sid`): a file behind a session.
pub require_cookie: Option<String>,
@@ -78,6 +81,7 @@ impl Faults {
etag_change_every: over.etag_change_every.or(self.etag_change_every),
etag: over.etag.clone().or(self.etag.clone()),
latency_ms: over.latency_ms.or(self.latency_ms),
+ range_latency_ms: over.range_latency_ms.or(self.range_latency_ms),
require_cookie: over.require_cookie.clone().or(self.require_cookie.clone()),
require_referer: over
.require_referer
diff --git a/crates/labserver/src/server.rs b/crates/labserver/src/server.rs
index 427ac965..b44b4c2f 100644
--- a/crates/labserver/src/server.rs
+++ b/crates/labserver/src/server.rs
@@ -441,7 +441,7 @@ GET|HEAD /gen/{size}[/{name}]?seed=N&<file params>&<faults> size: 12345, 64K,
faults (also server-wide with --faults; per-URL values override):
rate=SIZE slow_every=N slow_rate=SIZE max_conns=N drop_after=SIZE drop_every=N
fail_every=N fail_first=N no_range=1 no_range_every=N html=1 etag_change_every=N
- etag=weak|per-request|none latency_ms=N
+ etag=weak|per-request|none latency_ms=N range_latency_ms=N (only requests with a Range)
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 it
@@ -908,6 +908,9 @@ pub(crate) async fn serve(
if let Some(ms) = f.latency_ms {
tokio::time::sleep(Duration::from_millis(ms)).await;
}
+ if let Some(ms) = f.range_latency_ms.filter(|_| entry.range.is_some()) {
+ tokio::time::sleep(Duration::from_millis(ms)).await;
+ }
if every(n, f.fail_every) {
shared.record(entry, 503, "fault:fail_every");
return StatusCode::SERVICE_UNAVAILABLE.into_response();