Skip to content

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

Speed limiter: a raised or removed limit applies to the waits already started (#621) (#637)

Ahmed Nefzaoui39be735d19df
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2d77d0e8..12e374d5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,7 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- Raising a speed limit, or turning it off, applies at once: to a download's own limit (its progress window's **Speed Limiter** tab), the limit for one file and the limit for all downloads together. A connection already waiting its turn under the old limit sat out the wait the old limit gave it, many seconds at a low limit, before the new speed showed; it now counts what is left at the new limit, and ends its wait as soon as there is no limit ([#621](https://github.com/anefzaoui/misterdownloadmanager/issues/621)).
- **Download video**: a sound-only choice (MP3, Opus, FLAC, the original sound) saves in the Music category's folder and is listed under Music, as a playlist downloaded as sound only does; choosing a video again goes back to the Video folder. A folder you typed or picked in **Save to** stays as it is ([#611](https://github.com/anefzaoui/misterdownloadmanager/issues/611)).
- **Options → Save to**: changing the **General** category's default download directory now moves the default folders of all other categories without their own folder (`Video`, `Music`, `Torrents`, etc.) under it, instead of leaving them under the system's `Downloads` folder ([#556](https://github.com/anefzaoui/misterdownloadmanager/issues/556)). **Add torrent** also starts with the **Torrents** category's folder from the moment it opens (so **Save to** no longer flips when a magnet link's metadata arrives) and remembers a changed folder when **Change folder for this category on last selected** is ticked ([#550](https://github.com/anefzaoui/misterdownloadmanager/issues/550)).
- Windows: dragging a finished file out of **Download complete** (the grip at its bottom right) no longer holds up MDM's windows for as long as the drag lasts, or for as long as the program it is dropped on takes to answer: the drag now runs beside the window, as file dialogs already do ([#561](https://github.com/anefzaoui/misterdownloadmanager/issues/561)).
diff --git a/ROADMAP.md b/ROADMAP.md
index cc9d6f52..5fffe7cf 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -501,6 +501,8 @@ Bug fixes from the first days of 0.5.0, a Safari extension, and more file types.
These ship in the next version.
+- ✅ A speed limit raised or turned off applies at once, to the connections already waiting
+ under the old one too ([#621](https://github.com/anefzaoui/misterdownloadmanager/issues/621))
- ✅ The build and release workflows: each job gets only the permissions it needs, and every
action and release tool is pinned to an exact version
- ✅ A freeze on a slow disk, the data folder looked up on every tick
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index b894137c..9f034e08 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -65,6 +65,8 @@ mdm-labserver.workspace = true
proptest.workspace = true
serde_json.workspace = true
tempfile.workspace = true
+# The limiter's tests run on Tokio's paused clock (src/limiter.rs, #621).
+tokio = { workspace = true, features = ["test-util"] }
[lints]
workspace = true
diff --git a/crates/engine/src/limiter.rs b/crates/engine/src/limiter.rs
index 60d6c1f0..4180b01d 100644
--- a/crates/engine/src/limiter.rs
+++ b/crates/engine/src/limiter.rs
@@ -1,20 +1,28 @@
//! Per-download speed limiter (IDM: "Maximum download speed for one file", notes/ENGINE.md §4).
//! A token bucket shared by all of a download's connections; the limit can change while the
-//! download runs. Throttling the socket reads makes TCP slow the server down.
+//! download runs, and a new limit applies to the waits already started too (#621). Throttling
+//! the socket reads makes TCP slow the server down.
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
-use std::time::{Duration, Instant};
+use std::time::Duration;
+
+use tokio::sync::Notify;
+// Tokio's clock: the system's, except in tests that pause it.
+use tokio::time::Instant;
/// Bytes per second; 0 = unlimited. One per download, and optionally one shared by all of them
/// (the global cap, `Options::global`).
#[derive(Debug)]
pub struct Limiter {
+ /// Changed under the bucket's lock, read without it by [`Limiter::get`].
rate: AtomicU64,
bucket: Mutex<Bucket>,
/// Every byte that went through it (less what was given back), limited or not: what the
/// downloads under it took, for the global cap's split with torrents.
taken: AtomicU64,
+ /// Wakes the waits when the limit changes, so they count what is left at the new rate.
+ changed: Notify,
}
#[derive(Debug)]
@@ -22,6 +30,31 @@ struct Bucket {
/// Bytes that may be read right now (may go negative: debt to wait off).
tokens: f64,
last: Instant,
+ /// The budget earned since the limiter was made, bytes, at whatever the rate was each
+ /// moment: a wait ends when this reaches its mark, so a new rate applies to the rest of it.
+ earned: f64,
+ /// Goes up each time the limit is removed: the debt is forgiven then, and every wait from
+ /// before ends, even if a limit is set again before that wait looks.
+ era: u64,
+}
+
+impl Bucket {
+ /// Add what `rate` earned since the last time.
+ fn refill(&mut self, rate: u64, now: Instant) {
+ let earned = now.saturating_duration_since(self.last).as_secs_f64() * rate as f64;
+ self.last = now;
+ if rate > 0 {
+ self.earned += earned;
+ self.tokens = (self.tokens + earned).min(rate as f64 * BURST_SECS);
+ }
+ }
+}
+
+/// Where a wait ends: once the bucket has earned `at` bytes, in the same `era`.
+#[derive(Debug)]
+struct Mark {
+ at: f64,
+ era: u64,
}
/// Burst allowance: up to one second's budget accumulates while no connection is reading (e.g.
@@ -35,8 +68,11 @@ impl Limiter {
bucket: Mutex::new(Bucket {
tokens: 0.0,
last: Instant::now(),
+ earned: 0.0,
+ era: 0,
}),
taken: AtomicU64::new(0),
+ changed: Notify::new(),
}
}
@@ -45,33 +81,62 @@ impl Limiter {
self.taken.load(Ordering::Relaxed)
}
+ /// A new limit (None = unlimited), for the waits already started too: they wake and wait
+ /// only for what is left of their debt at the new rate, and end at once without a limit.
pub fn set(&self, rate: Option<u64>) {
- self.rate.store(rate.unwrap_or(0), Ordering::Relaxed);
+ let rate = rate.unwrap_or(0);
+ {
+ let mut b = self.bucket.lock().unwrap();
+ let old = self.rate.load(Ordering::Relaxed);
+ if old == rate {
+ return;
+ }
+ // What the old rate earned until now.
+ b.refill(old, Instant::now());
+ if rate == 0 {
+ // No limit: the debt is forgiven (a limit set later starts afresh).
+ b.tokens = 0.0;
+ b.era += 1;
+ }
+ self.rate.store(rate, Ordering::Relaxed);
+ }
+ self.changed.notify_waiters();
}
pub fn get(&self) -> Option<u64> {
Some(self.rate.load(Ordering::Relaxed)).filter(|r| *r > 0)
}
- /// Account for `n` received bytes; returns how long the caller should wait first.
- fn take(&self, n: u64) -> Duration {
+ /// Account for `n` received bytes; where the caller's wait ends, if it must wait.
+ fn take(&self, n: u64) -> Option<Mark> {
self.taken.fetch_add(n, Ordering::Relaxed);
+ if self.rate.load(Ordering::Relaxed) == 0 {
+ return None;
+ }
+ let mut b = self.bucket.lock().unwrap();
let rate = self.rate.load(Ordering::Relaxed);
if rate == 0 {
- return Duration::ZERO;
+ return None;
}
- let rate = rate as f64;
- let mut b = self.bucket.lock().unwrap();
- let now = Instant::now();
- let elapsed = now.duration_since(b.last).as_secs_f64();
- b.last = now;
- b.tokens = (b.tokens + elapsed * rate).min(rate * BURST_SECS);
+ b.refill(rate, Instant::now());
b.tokens -= n as f64;
- if b.tokens >= 0.0 {
- Duration::ZERO
- } else {
- Duration::from_secs_f64(-b.tokens / rate)
+ (b.tokens < 0.0).then(|| Mark {
+ at: b.earned - b.tokens,
+ era: b.era,
+ })
+ }
+
+ /// How much longer the wait ending at `mark` lasts at the rate now; None once it is over.
+ fn left(&self, mark: &Mark) -> Option<Duration> {
+ let mut b = self.bucket.lock().unwrap();
+ let rate = self.rate.load(Ordering::Relaxed);
+ if rate == 0 || b.era != mark.era {
+ return None;
}
+ b.refill(rate, Instant::now());
+ let owed = mark.at - b.earned;
+ // Under a byte is paid (the float's rounding would only add waits of nothing).
+ (owed >= 1.0).then(|| Duration::from_secs_f64(owed / rate as f64))
}
/// Give back budget for `n` bytes that were paid for but not kept.
@@ -90,11 +155,19 @@ impl Limiter {
}
}
- /// Wait until `n` more bytes fit under the limit.
+ /// Wait until `n` more bytes fit under the limit: the limit at each moment of the wait, not
+ /// only the one when it started (#621).
pub async fn acquire(&self, n: u64) {
- let wait = self.take(n);
- if !wait.is_zero() {
- tokio::time::sleep(wait).await;
+ let Some(mark) = self.take(n) else { return };
+ loop {
+ let mut changed = std::pin::pin!(self.changed.notified());
+ // Listening before counting: a change from here on wakes this wait.
+ changed.as_mut().enable();
+ let Some(wait) = self.left(&mark) else { return };
+ tokio::select! {
+ () = tokio::time::sleep(wait) => {}
+ () = changed => {}
+ }
}
}
}
@@ -135,4 +208,96 @@ mod tests {
l.refund(200);
assert_eq!(l.taken(), 1300, "limited or not, less what was given back");
}
+
+ /// #621, the reporter's witness: a wait that has started ends as soon as the limit is
+ /// raised or removed, not at the deadline the old limit set (64 s here).
+ #[tokio::test(start_paused = true)]
+ async fn a_new_limit_applies_to_a_wait_already_started() {
+ use std::future::Future;
+ use std::task::{Context, Poll, Waker};
+ for new_rate in [None, Some(1024 * 1024)] {
+ let limiter = Limiter::new(Some(1024));
+ let mut pending = Box::pin(limiter.acquire(64 * 1024));
+ let mut cx = Context::from_waker(Waker::noop());
+ assert!(pending.as_mut().poll(&mut cx).is_pending());
+ limiter.set(new_rate);
+ assert_eq!(limiter.get(), new_rate);
+ tokio::time::advance(Duration::from_secs(1)).await;
+ assert!(
+ matches!(pending.as_mut().poll(&mut cx), Poll::Ready(())),
+ "still waiting after the limit went to {new_rate:?}"
+ );
+ }
+ }
+
+ /// The time from `t` to now, to the millisecond (Tokio's paused clock).
+ fn ms_since(t: Instant) -> u128 {
+ t.elapsed().as_millis()
+ }
+
+ /// Two waits under one limit share it, before and after it changes: what each still owes
+ /// is counted at the new rate, in turn.
+ #[tokio::test(start_paused = true)]
+ async fn waits_count_what_is_left_at_the_new_rate() {
+ let l = Limiter::new(Some(1024));
+ let t = Instant::now();
+ let l = &l;
+ let wait = |n| async move {
+ l.acquire(n).await;
+ ms_since(t)
+ };
+ // 1 KB each at 1 KB/s: at 1 s and 2 s. At 0.5 s the limit doubles: the first has 512
+ // bytes left (0.25 s more), the second 1536 (0.75 s).
+ let (a, b, ()) = tokio::join!(wait(1024), wait(1024), async {
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ l.set(Some(2048));
+ });
+ assert!((750..760).contains(&a), "{a} ms");
+ assert!((1250..1260).contains(&b), "{b} ms");
+ // Halved: 2 KB at 2 KB/s, and at 0.5 s 1 KB left at 1 KB/s.
+ let t = Instant::now();
+ let (a, ()) = tokio::join!(
+ async {
+ l.acquire(2048).await;
+ ms_since(t)
+ },
+ async {
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ l.set(Some(1024));
+ }
+ );
+ assert!((1500..1510).contains(&a), "{a} ms");
+ }
+
+ /// Without a limit the debt is gone: a limit set again starts afresh, and a wait from
+ /// before ends even when the limit came back before it looked.
+ #[tokio::test(start_paused = true)]
+ async fn removing_the_limit_forgives_the_debt() {
+ use std::future::Future;
+ use std::task::{Context, Waker};
+ let l = Limiter::new(Some(1024));
+ let mut owed = Box::pin(l.acquire(64 * 1024));
+ let mut cx = Context::from_waker(Waker::noop());
+ assert!(owed.as_mut().poll(&mut cx).is_pending());
+ l.set(None);
+ l.set(Some(1024));
+ assert!(owed.as_mut().poll(&mut cx).is_ready());
+ let t = Instant::now();
+ l.acquire(1024).await;
+ assert!((1000..1010).contains(&ms_since(t)), "{} ms", ms_since(t));
+ }
+
+ /// The same limit again changes nothing (the app sets the global cap's every frame).
+ #[tokio::test(start_paused = true)]
+ async fn the_same_limit_again_changes_nothing() {
+ let l = Limiter::new(Some(1024));
+ let t = Instant::now();
+ tokio::join!(l.acquire(2048), async {
+ for _ in 0..10 {
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ l.set(Some(1024));
+ }
+ });
+ assert!((2000..2010).contains(&ms_since(t)), "{} ms", ms_since(t));
+ }
}
diff --git a/crates/engine/tests/e2e.rs b/crates/engine/tests/e2e.rs
index eb94e34d..c3b3b400 100644
--- a/crates/engine/tests/e2e.rs
+++ b/crates/engine/tests/e2e.rs
@@ -1499,6 +1499,61 @@ async fn stop_is_prompt_under_a_low_limit() {
);
}
+/// #621: a limit raised or removed while connections wait under the old one applies to those
+/// waits at once. Here they wait at 256 bytes/s, where a chunk owes half a minute (the wait used
+/// to be sat out: 1 MiB took 29 s after the limit went up), then the limit goes away (the global
+/// cap) or up four million times (this download's).
+#[tokio::test]
+async fn a_raised_limit_wakes_the_connections_waiting() {
+ let s = server("").await;
+ for (seed, global) in [(44u64, true), (43, false)] {
+ let dir = tempfile::tempdir().unwrap();
+ let req = Request {
+ url: s
+ .url(&format!("/gen/1M/raised.bin?seed={seed}"))
+ .parse()
+ .unwrap(),
+ headers: Default::default(),
+ dest: Destination::Dir(dir.path().to_owned()),
+ };
+ let cap = std::sync::Arc::new(mdm_engine::limiter::Limiter::new(Some(256)));
+ let opts = Options {
+ speed_limit: (!global).then_some(256),
+ global: global.then(|| cap.clone()),
+ ..fast_opts()
+ };
+ let dl = Download::start(req, opts);
+ // Long enough for the connections to be waiting their turn.
+ tokio::time::sleep(std::time::Duration::from_secs(2)).await;
+ let before = dl.snapshot().downloaded;
+ let raised = std::time::Instant::now();
+ if global {
+ cap.set(None);
+ } else {
+ dl.set_speed_limit(Some(1 << 30));
+ }
+ let out = tokio::time::timeout(std::time::Duration::from_secs(60), dl.wait())
+ .await
+ .expect("still waiting a minute after the limit went up")
+ .expect("download succeeds");
+ let took = raised.elapsed();
+ println!("global: {global}, {before} bytes before, the rest in {took:?}");
+ assert_eq!(out.size, 1 << 20);
+ let mut want = vec![0; 1 << 20];
+ content::fill(seed, 0, &mut want);
+ assert!(
+ std::fs::read(&out.path).unwrap() == want,
+ "content mismatch"
+ );
+ // Unlimited, 1 MiB from this machine takes well under a second; the slack is for a
+ // busy one. The old waits took a minute.
+ assert!(
+ took < std::time::Duration::from_secs(10),
+ "global: {global}, took {took:?} after the limit went up"
+ );
+ }
+}
+
#[tokio::test]
async fn the_finished_file_can_take_the_servers_date() {
// Options → Downloads → "Set file creation date as provided by the server": the lab server