From 376ba9299591b58bf6e26142f568ffa4c2845323 Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 07:28:34 -0600 Subject: [PATCH] S019: limiter, modes and priority shares Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + Plans/04 Control/S019-limiter-priority.md | 14 +- Plans/INDEX.md | 2 +- crates/core/Cargo.toml | 1 + crates/core/src/error.rs | 2 + crates/core/src/host.rs | 196 +++++++- crates/core/src/http/download.rs | 2 + crates/core/src/http/fetch.rs | 77 ++- crates/core/src/http/mod.rs | 38 +- crates/core/src/http/monitor.rs | 15 +- crates/core/src/http/parts.rs | 37 +- crates/core/src/lib.rs | 1 + crates/core/src/limit/mod.rs | 241 ++++++++++ crates/core/src/limit/shares.rs | 228 +++++++++ crates/core/src/manager/actor.rs | 36 +- crates/core/src/manager/mod.rs | 5 +- crates/core/src/manager/pick.rs | 13 +- crates/core/src/relink/mod.rs | 2 +- crates/core/src/settings.rs | 26 ++ crates/core/src/site.rs | 3 +- crates/core/tests/http.rs | 1 - crates/core/tests/limit.rs | 545 ++++++++++++++++++++++ docs/DECISIONS.md | 3 + docs/PROGRESS.md | 12 + 24 files changed, 1443 insertions(+), 58 deletions(-) create mode 100644 crates/core/src/limit/mod.rs create mode 100644 crates/core/src/limit/shares.rs create mode 100644 crates/core/tests/limit.rs diff --git a/Cargo.lock b/Cargo.lock index 7895f25..b25d0ad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2223,6 +2223,7 @@ name = "medlar-core" version = "0.1.0" dependencies = [ "arc-swap", + "bytes", "chrono", "dirs", "fastrand", diff --git a/Plans/04 Control/S019-limiter-priority.md b/Plans/04 Control/S019-limiter-priority.md index 3a62d5e..87e5fb5 100644 --- a/Plans/04 Control/S019-limiter-priority.md +++ b/Plans/04 Control/S019-limiter-priority.md @@ -11,13 +11,13 @@ FEATURES 2.1, 2.2, 2.3. - docs/FEATURES.md §2 ## Steps -- [ ] Hierarchical token buckets (total, queue, host, download) with a virtual clock for tests -- [ ] Weighted fair sharing by priority for bandwidth and connections; unused share flows to others; no starvation of the lowest -- [ ] "Only this one" mode that pauses the rest and restores them -- [ ] Three editable modes plus snail, switched live without reconnecting -- [ ] Small reads under low limits so speed stays even; limit accuracy within 5 % from 10 KB/s to 1 GB/s -- [ ] Socket receive pressure so a limit really slows the sender -- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S019: …`, push +- [x] Hierarchical token buckets (total, queue, host, download) with a virtual clock for tests +- [x] Weighted fair sharing by priority for bandwidth and connections; unused share flows to others; no starvation of the lowest +- [x] "Only this one" mode that pauses the rest and restores them +- [x] Three editable modes plus snail, switched live without reconnecting +- [x] Small reads under low limits so speed stays even; limit accuracy within 5 % from 10 KB/s to 1 GB/s +- [x] Socket receive pressure so a limit really slows the sender +- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S019: …`, push ## End criteria - `nice cargo test -j 2 -p medlar-core --test limit` green: accuracy, shares 1:2:4, live change under 500 ms, overhead under 3 % at full speed diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 23035a1..de30a75 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -33,7 +33,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H ## 04 Control -- [ ] [S019](04%20Control/S019-limiter-priority.md) Limiter, modes and priority shares +- [x] [S019](04%20Control/S019-limiter-priority.md) Limiter, modes and priority shares - [ ] [S020](04%20Control/S020-auto-limit-quota.md) Automatic limiter, quota and metered lines - [ ] [S021](04%20Control/S021-queues-schedule-power.md) Queues, scheduler and power actions - [ ] [S022](04%20Control/S022-control-screens.md) Control screens diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 098e2e7..08b063f 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -7,6 +7,7 @@ description = "Medlar's engine, store and settings" [dependencies] arc-swap = "1.9.5" +bytes = "1.10" chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } dirs = "6" futures-lite = "2.6" diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index fe69d7e..4c607c2 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -186,6 +186,7 @@ impl Failure { E::Link => ErrorKind::BadLink, E::Net(e) if tls_error(e).is_some() => return Failure::because(ErrorKind::Tls, tls_why(tls_error(e)), place), E::Net(e) => of_net(e), + E::Idle => ErrorKind::Timeout, E::Tls(_) => ErrorKind::Tls, E::Proxy(None) => return Failure::because(ErrorKind::Proxy, Some("error.proxy.setting"), place), E::Proxy(Some(e)) if proxy_login(e) => return Failure::because(ErrorKind::Login, Some("error.login.proxy"), place), @@ -348,6 +349,7 @@ mod tests { (http::Error::Page, ErrorKind::WrongContent), (http::Error::NoResume, ErrorKind::NoResume), (http::Error::Link, ErrorKind::BadLink), + (http::Error::Idle, ErrorKind::Timeout), ]; for (e, kind) in all { let failure = Failure::of(&e, here()); diff --git a/crates/core/src/host.rs b/crates/core/src/host.rs index 9b33d57..265b555 100644 --- a/crates/core/src/host.rs +++ b/crates/core/src/host.rs @@ -42,11 +42,27 @@ struct Inner { next: u64, open: BTreeMap, hosts: HashMap, + members: BTreeMap, + /// The cap of each host when the places were shared out. None: something changed since. + shared: Option>, +} + +/// A download that uses connections. +#[derive(Debug)] +struct Want { + host: String, + weight: f64, + /// As many as it would use now. + wanted: u32, + /// As many as it may have, next to the others. + share: u32, } #[derive(Debug)] struct Open { host: String, + /// None in tests. + member: Option, revoked: bool, } @@ -63,6 +79,49 @@ struct Host { bucket: Option<(f64, Instant)>, } +/// A download's claim to its share of the connections, as long as it lives. +#[derive(Debug)] +pub struct Member { + hosts: Arc, + id: u64, + host: String, +} + +impl Member { + /// Takes a place for a connection, if there is one now. `wanted` is how many it would use in all. + pub fn open(&self, wanted: u32, weight: f64, now: Instant) -> Option { + self.wants(wanted, weight); + self.hosts.take(&self.host, Some(self.id), now) + } + + /// Others get what it doesn't use. + pub fn wants(&self, wanted: u32, weight: f64) { + let mut i = self.hosts.inner.lock().unwrap(); + let me = i.members.get_mut(&self.id).expect("it lives"); + if (me.wanted, me.weight) == (wanted, weight) { + return; + } + (me.wanted, me.weight) = (wanted, weight); + i.shared = None; + // Not told when it wants more: that frees no place, and `open` says whom to ask for one. + let moved = i.share(Instant::now()); + drop(i); + if moved { + self.hosts.changed.send_replace(()); + } + } +} + +impl Drop for Member { + fn drop(&mut self) { + let mut i = self.hosts.inner.lock().unwrap_or_else(|e| e.into_inner()); + i.members.remove(&self.id); + i.shared = None; + drop(i); + self.hosts.changed.send_replace(()); + } +} + /// One connection. Gives its place back when dropped. #[derive(Debug)] pub struct Permit { @@ -105,6 +164,62 @@ impl Inner { } } + /// Connections of a member that may stay. + fn has(&self, member: u64) -> u32 { + self.open.values().filter(|o| o.member == Some(member) && !o.revoked).count() as u32 + } + + /// Shares the places out by weight. Nobody gets more than he wants, and everybody gets one before anybody gets two. Marks + /// connections that have to end for it, newest first, and says whether there are any. + fn share(&mut self, now: Instant) -> bool { + let caps: HashMap = self.members.values().map(|m| (m.host.clone(), self.cap(&m.host, now))).collect(); + if self.shared.as_ref() == Some(&caps) { + return false; + } + let total = self.caps.total.max(1); + let mut left = caps.clone(); + self.members.values_mut().for_each(|m| m.share = 0); + for _ in 0..total { + let behind = |m: &Want| f64::from(m.share) / m.weight; + let wants = self.members.values_mut().filter(|m| m.share < m.wanted && left[&m.host] > 0); + let Some(m) = wants.min_by(|a, b| behind(a).total_cmp(&behind(b)).then(b.weight.total_cmp(&a.weight))) else { break }; + m.share += 1; + *left.get_mut(&m.host).expect("all hosts are in it") -= 1; + } + self.shared = Some(caps.clone()); + + let mut moved = false; + let mut free: HashMap<&str, i64> = caps.iter().map(|(h, cap)| (h.as_str(), i64::from(*cap))).collect(); + let mut free_total = i64::from(total); + for o in self.open.values().filter(|o| !o.revoked) { + free_total -= 1; + free.entry(&o.host).and_modify(|n| *n -= 1); + } + for (id, m) in &self.members { + let missing = i64::from(m.share) - i64::from(self.has(*id)); + free_total -= missing.max(0); + free.entry(&m.host).and_modify(|n| *n -= missing.max(0)); + } + let mut free: Vec<(Option, i64)> = free.into_iter().map(|(h, n)| (Some(h.to_string()), n)).collect(); + let hosts: i64 = free.iter().map(|(_, n)| (-n).max(0)).sum(); + // What ends for a host counts for all. + free.push((None, free_total + hosts)); + for (host, n) in free { + for _ in n..0 { + moved |= self.give_up(host.as_deref()); + } + } + moved + } + + /// Ends the newest connection of those who have more than their share. + fn give_up(&mut self, host: Option<&str>) -> bool { + let over: Vec = self.members.iter().filter(|(id, m)| self.has(**id) > m.share).map(|(id, _)| *id).collect(); + let theirs = |o: &&mut Open| !o.revoked && o.member.is_some_and(|m| over.contains(&m)) && host.is_none_or(|h| o.host == h); + let newest = self.open.values_mut().rev().find(theirs); + newest.map(|o| o.revoked = true).is_some() + } + /// Marks the newest connections over the caps. fn revoke(&mut self, now: Instant) { let caps: HashMap = self.open.values().map(|o| (o.host.clone(), self.cap(&o.host, now))).collect(); @@ -122,13 +237,28 @@ impl Inner { impl Hosts { pub fn new(caps: Caps) -> Arc { - let inner = Inner { caps, next: 0, open: BTreeMap::new(), hosts: HashMap::new() }; + let inner = Inner { caps, next: 0, open: BTreeMap::new(), hosts: HashMap::new(), members: BTreeMap::new(), shared: None }; Arc::new(Hosts { inner: Mutex::new(inner), changed: watch::Sender::new(()) }) } - /// Takes a place for a connection, if there is one now. - pub fn open(self: &Arc, host: &str, now: Instant) -> Option { + pub fn join(self: &Arc, host: &str) -> Member { let mut i = self.inner.lock().unwrap(); + let id = i.next; + i.next += 1; + i.members.insert(id, Want { host: host.into(), weight: 1.0, wanted: 0, share: 0 }); + i.shared = None; + drop(i); + Member { hosts: self.clone(), id, host: host.into() } + } + + fn take(self: &Arc, host: &str, member: Option, now: Instant) -> Option { + let mut i = self.inner.lock().unwrap(); + if i.share(now) { + self.changed.send_replace(()); + } + if member.is_some_and(|m| i.has(m) >= i.members[&m].share) { + return None; + } let (count, cap, caps) = (i.count(host), i.cap(host, now), i.caps); if i.open.len() as u32 >= caps.total.max(1) || count >= cap { return None; @@ -150,7 +280,7 @@ impl Hosts { h.bucket = Some((has - 1.0, now)); let id = i.next; i.next += 1; - i.open.insert(id, Open { host: host.into(), revoked: false }); + i.open.insert(id, Open { host: host.into(), member, revoked: false }); drop(i); Some(Permit { hosts: self.clone(), id }) } @@ -194,7 +324,10 @@ impl Hosts { fn change(&self, what: impl FnOnce(&mut Inner)) { let mut i = self.inner.lock().unwrap(); what(&mut i); - i.revoke(Instant::now()); + let now = Instant::now(); + i.shared = None; + i.share(now); + i.revoke(now); drop(i); self.changed.send_replace(()); } @@ -221,6 +354,12 @@ pub fn remember(store: &Store, host: &str, connections: u32, now: Time) -> store mod tests { use super::*; + impl Hosts { + fn open(self: &Arc, host: &str, now: Instant) -> Option { + self.take(host, None, now) + } + } + const FREE: Caps = Caps { total: 5, per_host: 3, burst: 100, per_second: 100.0 }; #[test] @@ -289,4 +428,51 @@ mod tests { assert_eq!(key(&Url::parse("https://H.example/f").unwrap()), "h.example"); assert_eq!(key(&Url::parse("http://h:8080/f").unwrap()), "h:8080"); } + + #[test] + fn places_are_shared_by_weight() { + let (hosts, now) = (Hosts::new(Caps { total: 64, per_host: 14, burst: 1000, per_second: 1000.0 }), Instant::now()); + let (a, b, c) = (hosts.join("h"), hosts.join("h"), hosts.join("h")); + let fill = |m: &Member, wanted, weight| std::iter::from_fn(|| m.open(wanted, weight, now)).collect::>(); + let stay = |p: &mut Vec| { + p.retain(|p| !p.revoked()); + p.len() + }; + let mut pa = fill(&a, 20, 1.0); + assert_eq!(pa.len(), 14, "alone"); + assert!(fill(&b, 20, 2.0).is_empty(), "no place yet"); + assert_eq!(stay(&mut pa), 5); + let mut pb = fill(&b, 20, 2.0); + assert_eq!(pb.len(), 9); + assert!(fill(&c, 20, 4.0).is_empty()); + assert_eq!((stay(&mut pa), stay(&mut pb)), (2, 4)); + let mut pc = fill(&c, 20, 4.0); + assert_eq!(pc.len(), 8); + assert!(a.open(20, 1.0, now).is_none() && b.open(20, 2.0, now).is_none()); + assert_eq!((stay(&mut pa), stay(&mut pb), stay(&mut pc)), (2, 4, 8), "nothing moves without a reason"); + // What one can't use is for the others. + pc.truncate(3); + c.wants(3, 4.0); + pb.extend(fill(&b, 20, 2.0)); + pa.extend(fill(&a, 20, 1.0)); + assert_eq!((stay(&mut pa), stay(&mut pb), stay(&mut pc)), (4, 7, 3)); + // Never without any. + hosts.set_host_cap("h", Some(3)); + assert_eq!((stay(&mut pa), stay(&mut pb), stay(&mut pc)), (1, 1, 1)); + hosts.set_host_cap("h", None); + drop(pc); + drop(c); + pb.extend(fill(&b, 20, 2.0)); + assert_eq!((pb.len(), hosts.open_to("h")), (9, 10)); + } + + #[test] + fn places_of_all_hosts_are_shared_too() { + let (hosts, now) = (Hosts::new(Caps { total: 6, per_host: 5, burst: 100, per_second: 100.0 }), Instant::now()); + let (a, b) = (hosts.join("a"), hosts.join("b")); + let pa: Vec<_> = std::iter::from_fn(|| a.open(9, 4.0, now)).collect(); + let pb: Vec<_> = std::iter::from_fn(|| b.open(9, 4.0, now)).collect(); + assert_eq!((pa.len(), pb.len()), (5, 1)); + assert_eq!(pa.iter().filter(|p| p.revoked()).count(), 2); + } } diff --git a/crates/core/src/http/download.rs b/crates/core/src/http/download.rs index c54c885..fe7a2f2 100644 --- a/crates/core/src/http/download.rs +++ b/crates/core/src/http/download.rs @@ -6,6 +6,7 @@ use super::*; use crate::adapt::{self, Timing}; use crate::disk::{PartialFile, blocking}; use crate::host::{self, Hosts}; +use crate::limit::Group; use crate::model::{self, Part, Task, TaskId}; use crate::part::LivePart; use crate::segment::Rules; @@ -105,6 +106,7 @@ pub async fn download(shared: &Shared, id: TaskId, source: Source, options: &Opt let asked = host.clone(); let known = job.run(move |s| Ok(s.host(&asked)?)).await?.unwrap_or_default(); shared.hosts.set_host_cap(&host, link.source.max_connections().or(known.max_connections)); + monitor.flow().put_limited(Group::Host(host.clone()), link.source.speed_limit().or(known.speed_limit)); let start = host::tolerated(&known, model::now()).unwrap_or(adapt::START); let mut run = Run::new(shared, link, file.clone(), parts, body, host.clone(), start, task.max_parts, options, monitor); let result = run.go(&job, &mut stop).await; diff --git a/crates/core/src/http/fetch.rs b/crates/core/src/http/fetch.rs index 32a01eb..d31ece9 100644 --- a/crates/core/src/http/fetch.rs +++ b/crates/core/src/http/fetch.rs @@ -3,7 +3,9 @@ use super::probe::check_length; use super::*; use crate::disk::PartialFile; +use crate::limit::Flow; use crate::part::LivePart; +use bytes::Bytes; use std::time::Instant; /// Finished bytes read again and compared when a part goes on. @@ -25,7 +27,19 @@ pub struct Link { /// Fills `part` until it is whole, `stop` turns true or something breaks. Whatever arrived is written before it returns, so stop /// it instead of dropping it. Without ranges the part must be untouched; `body` is the reply to use, if there is one already. -pub async fn fetch(link: &Link, part: &LivePart, file: &PartialFile, body: Option, mut stop: Stop) -> Result<()> { +pub async fn fetch(link: &Link, part: &LivePart, file: &PartialFile, body: Option, stop: Stop) -> Result<()> { + fetch_within(link, part, file, body, &Flow::free(), stop).await +} + +/// The same within limits of speed. +pub(super) async fn fetch_within( + link: &Link, + part: &LivePart, + file: &PartialFile, + body: Option, + flow: &Flow, + mut stop: Stop, +) -> Result<()> { if part.finished() { return Ok(()); } @@ -40,11 +54,17 @@ pub async fn fetch(link: &Link, part: &LivePart, file: &PartialFile, body: Optio part.begin(); let mut buf = Vec::with_capacity(BUFFER); let mut flushed = Instant::now(); + // What came while the limits held the bytes before it. + let mut ahead = None; loop { - let chunk = tokio::select! { - biased; - _ = stopped(&mut stop) => Err(Error::Stopped), - chunk = response.chunk() => chunk.map_err(|e| broken(e, part, link)), + let chunk = match ahead.take() { + Some(Err(_)) if *stop.borrow() => Err(Error::Stopped), + Some(chunk) => chunk, + None => tokio::select! { + biased; + _ = stopped(&mut stop) => Err(Error::Stopped), + chunk = next(&mut response, part, link) => chunk, + }, }; match chunk { Ok(Some(mut chunk)) => { @@ -53,15 +73,33 @@ pub async fn fetch(link: &Link, part: &LivePart, file: &PartialFile, body: Optio return Err(Error::Changed); } known.drain(..old.len()); - buf.extend_from_slice(&chunk); - part.arrive(chunk.len() as u64); - let whole = part.remaining().is_some_and(|left| buf.len() as u64 >= left); - if whole || buf.len() >= BUFFER || flushed.elapsed() >= FLUSH_EVERY { - buf = flush(part, file, buf).await?; - flushed = Instant::now(); - } - if part.finished() { - return Ok(()); + // Piece by piece, as fast as the limits have it. One chunk is read ahead, so that the sender has room again before + // all is used up. + let mut rest = &chunk[..]; + while !rest.is_empty() { + let take = flow.take(rest.len() as u64); + tokio::pin!(take); + let n = loop { + tokio::select! { + biased; + _ = stopped(&mut stop) => break None, + n = &mut take => break Some(n as usize), + chunk = next(&mut response, part, link), if ahead.is_none() => ahead = Some(chunk), + } + }; + // It is here already, so a stop doesn't throw it away. + let (piece, later) = rest.split_at(n.unwrap_or(rest.len())); + rest = later; + buf.extend_from_slice(piece); + part.arrive(piece.len() as u64); + let whole = part.remaining().is_some_and(|left| buf.len() as u64 >= left); + if whole || n.is_none() || buf.len() >= BUFFER || flushed.elapsed() >= FLUSH_EVERY { + buf = flush(part, file, buf).await?; + flushed = Instant::now(); + } + if part.finished() { + return Ok(()); + } } } Ok(None) => { @@ -84,8 +122,9 @@ fn expected(part: &LivePart, link: &Link) -> Option { p.end.map(|end| end - p.start).or(link.version.size) } -fn broken(e: reqwest::Error, part: &LivePart, link: &Link) -> Error { - if e.is_timeout() { e.into() } else { Error::Cut { got: part.get().done, expected: expected(part, link) } } +async fn next(response: &mut Response, part: &LivePart, link: &Link) -> Result> { + let cut = |e: reqwest::Error| if e.is_timeout() { e.into() } else { Error::Cut { got: part.get().done, expected: expected(part, link) } }; + link.client.wait(async { response.chunk().await.map_err(cut) }).await } async fn flush(part: &LivePart, file: &PartialFile, buf: Vec) -> Result> { @@ -169,16 +208,16 @@ pub async fn compare(link: &Link, file: &PartialFile, at: u64, len: u64, stop: & /// Whether the server has `known` at `at`. pub async fn same_bytes(link: &Link, known: &[u8], at: u64, stop: &mut Stop) -> Result { let len = known.len() as u64; - same_body(send_range(link, at, Some(at + len), stop).await?, known, stop).await + same_body(&link.client, send_range(link, at, Some(at + len), stop).await?, known, stop).await } /// Whether the body begins with `known`. -pub(crate) async fn same_body(mut response: Response, known: &[u8], stop: &mut Stop) -> Result { +pub(crate) async fn same_body(client: &Client, mut response: Response, known: &[u8], stop: &mut Stop) -> Result { let mut rest = known; while !rest.is_empty() { let chunk = tokio::select! { _ = stopped(stop) => return Err(Error::Stopped), - chunk = response.chunk() => chunk?, + chunk = client.wait(response.chunk()) => chunk?, }; let Some(chunk) = chunk else { return Err(Error::Cut { got: (known.len() - rest.len()) as u64, expected: Some(known.len() as u64) }); diff --git a/crates/core/src/http/mod.rs b/crates/core/src/http/mod.rs index 172fe9b..6dd2582 100644 --- a/crates/core/src/http/mod.rs +++ b/crates/core/src/http/mod.rs @@ -19,7 +19,7 @@ use crate::site::{Access, same_site}; use crate::tls::Trust; use crate::{disk, redact, store}; use reqwest::header::{self, HeaderMap, HeaderName, HeaderValue}; -pub(crate) use reqwest::{Client, Response}; +pub(crate) use reqwest::Response; use reqwest::{RequestBuilder, StatusCode, redirect}; use std::sync::{Arc, Once}; use std::time::Duration; @@ -35,6 +35,8 @@ pub enum Error { Link, /// No connection, no answer in time, or a broken one. Never holds the link. Net(reqwest::Error), + /// Nothing came for `ClientOptions::idle_timeout`. + Idle, /// The proxy can't be reached or refuses. None: its setting makes no sense. Proxy(Option), /// TLS can't be set up here. @@ -104,6 +106,28 @@ impl Default for ClientOptions { } } +/// Doesn't wait forever for an answer or the next piece of it. +#[derive(Debug, Clone)] +pub struct Client { + inner: reqwest::Client, + idle: Duration, +} + +impl Client { + pub(crate) fn get(&self, url: Url) -> RequestBuilder { + self.inner.get(url) + } + + /// The time counts while it is waited for only: limits may hold back what came before for longer. reqwest's own timeout goes + /// on meanwhile. + pub(crate) async fn wait>(&self, what: impl Future>) -> Result { + match tokio::time::timeout(self.idle, what).await { + Ok(result) => result.map_err(Into::into), + Err(_) => Err(Error::Idle), + } + } +} + pub fn client(options: &ClientOptions) -> Result { client_with(options, &trust(options)?, None) } @@ -117,7 +141,7 @@ pub(crate) fn client_with(options: &ClientOptions, trust: &Arc, proxy: Op static TLS: Once = Once::new(); // Fails only when one is installed already, which is fine. TLS.call_once(|| drop(rustls::crypto::ring::default_provider().install_default())); - let mut builder = Client::builder() + let mut builder = reqwest::Client::builder() .user_agent(concat!("Medlar/", env!("CARGO_PKG_VERSION"))) .http1_only() // Each hop has its own headers and its own way. @@ -128,12 +152,11 @@ pub(crate) fn client_with(options: &ClientOptions, trust: &Arc, proxy: Op // Reused at once or not at all: idle ones count against what a host stands. .pool_idle_timeout(Duration::from_millis(500)) .connect_timeout(options.connect_timeout) - .read_timeout(options.idle_timeout) .tls_backend_preconfigured(trust.config(Arc::new(rustls::crypto::ring::default_provider()))?); if let Some(proxy) = proxy { builder = builder.proxy(reqwest::Proxy::all(proxy)?); } - Ok(builder.build()?) + Ok(Client { inner: builder.build()?, idle: options.idle_timeout }) } /// A link and the headers that go with it. @@ -173,6 +196,11 @@ impl Source { self.access.as_ref()?.rules(&self.url).max_connections } + /// The user's limit for all that comes from this site. + pub(crate) fn speed_limit(&self) -> Option { + self.access.as_ref()?.rules(&self.url).speed_limit + } + /// The same source at the link its redirects led to. What was given for one site stays with it. pub fn at(&self, url: &Url) -> Source { let mut headers = self.headers.clone(); @@ -205,7 +233,7 @@ impl Source { }; let response = match &here.access { Some(access) => access.send(&here.url, &here.headers, request).await?, - None => request(client, &here.headers).send().await?, + None => client.wait(request(client, &here.headers).send()).await?, }; match redirect(&response)? { Some(next) => here = here.at(&next), diff --git a/crates/core/src/http/monitor.rs b/crates/core/src/http/monitor.rs index 7035f59..8c670b1 100644 --- a/crates/core/src/http/monitor.rs +++ b/crates/core/src/http/monitor.rs @@ -1,5 +1,6 @@ //! What others see of a running download, and its cap on connections. +use crate::limit::Flow; use crate::part::LivePart; use std::sync::{Arc, Mutex}; use tokio::sync::{broadcast, watch}; @@ -64,12 +65,22 @@ pub struct Monitor { cap: watch::Sender, events: broadcast::Sender, state: Mutex<(Snapshot, Vec>)>, + flow: Arc, } impl Monitor { - /// With a cap on connections. + /// With a cap on connections, and no limit of speed. pub fn new(cap: u32) -> Monitor { - Monitor { cap: watch::Sender::new(cap), events: broadcast::Sender::new(1024), state: Mutex::default() } + Monitor::with_flow(cap, Flow::free()) + } + + pub fn with_flow(cap: u32, flow: Flow) -> Monitor { + Monitor { cap: watch::Sender::new(cap), events: broadcast::Sender::new(1024), state: Mutex::default(), flow: Arc::new(flow) } + } + + /// The limits that count for it. + pub fn flow(&self) -> &Arc { + &self.flow } /// Takes effect at once, up and down. diff --git a/crates/core/src/http/parts.rs b/crates/core/src/http/parts.rs index 91a12f6..f7d3766 100644 --- a/crates/core/src/http/parts.rs +++ b/crates/core/src/http/parts.rs @@ -1,11 +1,12 @@ //! The parts of one download while it runs: which connection works on what. use super::download::Job; +use super::fetch::fetch_within; use super::monitor::{Monitor, PartEvent, PartId, PartState, PartView, Snapshot}; use super::*; use crate::adapt::Adapt; use crate::disk::PartialFile; -use crate::host::{Hosts, Permit}; +use crate::host::{Hosts, Member, Permit}; use crate::model::Part; use crate::part::LivePart; use crate::segment::{self, Pick, View}; @@ -24,6 +25,9 @@ pub(super) struct Run<'a> { body: Option, host: String, hosts: Arc, + member: Member, + /// Its speed had a limit, so it says nothing about the host. + limited: bool, max_parts: Option, options: &'a Options, monitor: &'a Monitor, @@ -94,7 +98,7 @@ enum Weight { fn weigh(e: &Error) -> Weight { match e { Error::Status { code: 429 | 503, .. } => Weight::Refused { again: true }, - Error::Status { code: 408 | 425 | 500..=599, .. } | Error::Cut { .. } => Weight::Broken, + Error::Status { code: 408 | 425 | 500..=599, .. } | Error::Cut { .. } | Error::Idle => Weight::Broken, Error::Status { .. } | Error::RangeIgnored => Weight::Refused { again: false }, Error::Net(e) if e.is_redirect() || e.is_builder() => Weight::Fatal, Error::Proxy(Some(_)) => Weight::Broken, @@ -123,8 +127,10 @@ impl<'a> Run<'a> { link: Arc::new(link), file, body, + member: shared.hosts.join(&host), host, hosts: shared.hosts.clone(), + limited: false, max_parts, options, monitor, @@ -160,7 +166,10 @@ impl<'a> Run<'a> { let mut saving = JoinSet::new(); loop { if self.failed.is_none() { - self.adapt.set_cap(cap.borrow_and_update().min(self.max_parts.unwrap_or(u32::MAX))); + let flow = self.monitor.flow(); + self.limited |= flow.limited(); + let cap = *cap.borrow_and_update(); + self.adapt.set_cap(cap.min(self.max_parts.unwrap_or(u32::MAX)).min(flow.connections())); self.schedule(Instant::now()); } self.publish(); @@ -198,7 +207,7 @@ impl<'a> Run<'a> { /// The parts, and the number of connections to remember for the host. Lets go of the file. pub(super) fn end(self) -> (Vec>, Option) { - (self.live(), self.adapt.learned().filter(|_| self.link.ranges)) + (self.live(), self.adapt.learned().filter(|_| self.link.ranges && !self.limited)) } fn live(&self) -> Vec> { @@ -232,7 +241,7 @@ impl<'a> Run<'a> { // One part without resume: no cuts, no second connection. let i = self.slots.iter().position(|s| !s.part.finished()); if let Some(i) = i.filter(|i| self.slots[*i].worker.is_none()) - && let Some(permit) = self.hosts.open(&self.host, now) + && let Some(permit) = self.member.open(1, self.monitor.flow().weight(), now) { self.begin(i, permit, now); } @@ -251,6 +260,9 @@ impl<'a> Run<'a> { slowest.map(Slot::send_away); } self.drop_stalled(now); + let weight = self.monitor.flow().weight(); + // How many it could use. + let mut use_of = self.wanted(); while self.running() < self.wanted() { let views: Vec = self.slots.iter().map(|s| view(s, now)).collect(); // A part that waits after a failure keeps its place, or the others would be cut for connections that fail too. @@ -258,10 +270,11 @@ impl<'a> Run<'a> { let full = self.running() + waiting >= self.wanted(); let pick = segment::next(&views, &self.options.rules).filter(|p| !full || matches!(p, Pick::Take(_))); let Some(pick) = pick else { + use_of = self.running() + waiting; self.drop_crawling(&views, now); break; }; - let Some(permit) = self.hosts.open(&self.host, now) else { break }; + let Some(permit) = self.member.open(self.wanted(), weight, now) else { break }; match pick { Pick::Take(i) => self.begin(i, permit, now), Pick::Split { part, at } => { @@ -277,6 +290,7 @@ impl<'a> Run<'a> { } } } + self.member.wants(use_of, weight); } /// A connection that brings nothing is replaced. One that never did only while others do: the server may be slow to answer. @@ -291,6 +305,10 @@ impl<'a> Run<'a> { /// There is a connection to spare and nothing left to cut: the slowest part gets another one. fn drop_crawling(&mut self, views: &[View], now: Instant) { + // Within limits the slow ones only wait for their turn. + if self.monitor.flow().limited() { + return; + } // One at a time. if self.slots.iter().any(|s| s.worker.as_ref().is_some_and(|w| w.leaving)) { return; @@ -317,7 +335,8 @@ impl<'a> Run<'a> { s.worker = Some(Worker { stop, permit, leaving: false, first, seen: first, quiet_since: now, delivers: None, speed: None }); (s.used, s.rest_until) = (true, None); let (id, link, part, file, body) = (s.id, self.link.clone(), s.part.clone(), self.file.clone(), self.body.take()); - self.workers.spawn(async move { (id, fetch(&link, &part, &file, body, stopping).await) }); + let flow = self.monitor.flow().clone(); + self.workers.spawn(async move { (id, fetch_within(&link, &part, &file, body, &flow, stopping).await) }); } fn ended(&mut self, id: PartId, result: Result<()>, now: Instant) { @@ -437,7 +456,9 @@ impl<'a> Run<'a> { } let delivering = self.delivering(); self.worked = self.worked.max(delivering); - self.adapt.tick(now, self.running(), delivering, self.received); + // While limits decide the speed, connections prove nothing. + let running = if self.monitor.flow().held() { 0 } else { self.running() }; + self.adapt.tick(now, running, delivering, self.received); } fn publish(&mut self) { diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index e3a67c7..400d949 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -9,6 +9,7 @@ pub mod error; pub mod events; pub mod host; pub mod http; +pub mod limit; pub mod logging; pub mod manager; pub mod model; diff --git a/crates/core/src/limit/mod.rs b/crates/core/src/limit/mod.rs new file mode 100644 index 0000000..c94bbf2 --- /dev/null +++ b/crates/core/src/limit/mod.rs @@ -0,0 +1,241 @@ +//! Speed limits, changed while downloads run, and what each download gets of them. +//! +//! One `Limiter` per program, one `Flow` per download. Whoever takes bytes off the network asks its flow first and doesn't read on +//! before it got them: the socket fills up and the sender slows down. + +mod shares; + +pub use shares::{Group, Shares}; + +use crate::model::Priority; +use shares::FlowId; +use std::collections::HashMap; +use std::fmt; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Instant; +use tokio::sync::{Notify, oneshot}; + +/// Below this many bytes per second a connection is asleep for so long that servers hang up. +const PER_CONNECTION: f64 = 8192.0; + +impl Priority { + /// Its share next to others, of bytes and of connections. + pub fn weight(self) -> f64 { + match self { + Priority::Lowest => 1.0, + Priority::Low => 2.0, + Priority::Normal => 4.0, + Priority::High => 8.0, + Priority::Highest => 16.0, + // Next to it are only those that can't be paused. + Priority::Only => 256.0, + } + } +} + +pub struct Limiter { + state: Mutex, + /// There is something to do before `State::wake`. + sooner: Notify, +} + +struct State { + shares: Shares>, + /// What each flow reads without the lock. + flows: HashMap>, + /// The task that wakes up for those who wait is there. + driven: bool, + /// When it wakes up; None if it has not looked yet. + wake: Option, +} + +struct View { + limited: AtomicBool, + /// Someone had to wait. + held: AtomicBool, + weight: AtomicU64, +} + +impl fmt::Debug for Limiter { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("Limiter") + } +} + +impl Limiter { + pub fn new() -> Arc { + let state = State { shares: Shares::default(), flows: HashMap::new(), driven: false, wake: None }; + Arc::new(Limiter { state: Mutex::new(state), sooner: Notify::new() }) + } + + /// Bytes per second; None or 0 for no limit. Counts at once. + pub fn set(&self, group: &Group, rate: Option) { + self.change(|s, now| s.set(group, rate, now)); + } + + pub fn flow(self: &Arc, priority: Priority) -> Flow { + let weight = priority.weight(); + let view = Arc::new(View { limited: AtomicBool::new(false), held: AtomicBool::new(false), weight: AtomicU64::new(weight.to_bits()) }); + let mut s = self.state.lock().unwrap(); + let id = s.shares.join(weight); + s.flows.insert(id, view.clone()); + s.see(); + drop(s); + Flow { limiter: self.clone(), id, view } + } + + fn change(&self, what: impl FnOnce(&mut Shares>, Instant)) { + let mut s = self.state.lock().unwrap(); + what(&mut s.shares, Instant::now()); + s.see(); + drop(s); + self.sooner.notify_one(); + } +} + +impl State { + fn see(&mut self) { + for id in self.shares.ids() { + self.flows[&id].limited.store(self.shares.rate(id).is_some(), Ordering::Relaxed); + } + } + + /// When to look again. + fn run(&mut self, now: Instant) -> Option { + let wait = self.shares.run(now, |who, n| who.send(n).is_ok()); + wait.map(|wait| now + wait) + } +} + +/// What one download has to do with the limits. +pub struct Flow { + limiter: Arc, + id: FlowId, + view: Arc, +} + +impl fmt::Debug for Flow { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Flow({})", self.id) + } +} + +impl Flow { + /// On its own, without limits. + pub fn free() -> Flow { + Limiter::new().flow(Priority::Normal) + } + + /// Its own limit. + pub fn set(&self, rate: Option) { + self.limiter.change(|s, now| s.set_own(self.id, rate, now)); + } + + /// Counts for this queue or host from now on. + pub fn put(&self, group: Group) { + self.limiter.change(|s, _| s.put(self.id, group)); + } + + /// The same, with the limit it has. + pub fn put_limited(&self, group: Group, rate: Option) { + self.limiter.set(&group, rate); + self.put(group); + } + + pub fn set_priority(&self, priority: Priority) { + let weight = priority.weight(); + self.view.weight.store(weight.to_bits(), Ordering::Relaxed); + self.limiter.change(|s, _| s.set_weight(self.id, weight)); + } + + pub fn weight(&self) -> f64 { + f64::from_bits(self.view.weight.load(Ordering::Relaxed)) + } + + pub fn limited(&self) -> bool { + self.view.limited.load(Ordering::Relaxed) + } + + /// Whether limits held it back since the last question. + pub fn held(&self) -> bool { + self.view.held.swap(false, Ordering::Relaxed) + } + + /// Connections that its limits have work for. + pub fn connections(&self) -> u32 { + if !self.limited() { + return u32::MAX; + } + let rate = self.limiter.state.lock().unwrap().shares.rate(self.id); + rate.map_or(u32::MAX, |r| (r / PER_CONNECTION).max(1.0) as u32) + } + + /// Waits until some of `most` bytes may be used, and says how many. Dropping it takes nothing. + pub async fn take(&self, most: u64) -> u64 { + if !self.limited() || most == 0 { + return most; + } + let (answer, mut given) = oneshot::channel(); + { + let mut s = self.limiter.state.lock().unwrap(); + let now = Instant::now(); + s.shares.ask(self.id, answer, most); + let next = s.run(now); + if let Ok(n) = given.try_recv() { + return n; + } + self.view.held.store(true, Ordering::Relaxed); + if !s.driven { + (s.driven, s.wake) = (true, None); + tokio::spawn(drive(self.limiter.clone())); + } else if let (Some(next), Some(wake)) = (next, s.wake) + && next < wake + { + self.limiter.sooner.notify_one(); + } + } + // Fails only when the runtime ends. + given.await.unwrap_or(most) + } +} + +impl Drop for Flow { + fn drop(&mut self) { + let mut s = self.limiter.state.lock().unwrap_or_else(|e| e.into_inner()); + s.shares.leave(self.id); + s.flows.remove(&self.id); + } +} + +/// Wakes up for those who wait, while there are any. +async fn drive(limiter: Arc) { + struct Driving(Arc, bool); + // When its runtime ends. + impl Drop for Driving { + fn drop(&mut self) { + if self.1 { + self.0.state.lock().unwrap_or_else(|e| e.into_inner()).driven = false; + } + } + } + let mut driving = Driving(limiter, true); + let limiter = &driving.0; + loop { + let next = { + let mut s = limiter.state.lock().unwrap(); + s.wake = s.run(Instant::now()); + if s.wake.is_none() { + // Under the lock, so that the next one to wait starts another. + s.driven = false; + } + s.wake + }; + let Some(next) = next else { break }; + tokio::select! { + _ = tokio::time::sleep_until(next.into()) => {} + _ = limiter.sooner.notified() => {} + } + } + driving.1 = false; +} diff --git a/crates/core/src/limit/shares.rs b/crates/core/src/limit/shares.rs new file mode 100644 index 0000000..616f3d6 --- /dev/null +++ b/crates/core/src/limit/shares.rs @@ -0,0 +1,228 @@ +//! Who may take how many bytes now. Decides only: the time is given. +//! +//! Buckets in a tree: everything, the queue, the host, the download. Bytes are taken from all buckets on the way. Of the +//! downloads whose buckets hold something, the one that is furthest behind its share goes first, so what one doesn't use is there +//! for the others. + +use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::time::{Duration, Instant}; + +/// What a bucket holds at most: what may be made up for after a late wake-up. +const BURST: f64 = 0.1; +/// Bytes given at once, in seconds of the tightest limit. +const PIECE: f64 = 0.02; +const MIN_PIECE: f64 = 1024.0; + +pub type FlowId = u64; + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum Group { + Total, + Queue(i64), + /// See `host::key`. + Host(String), +} + +#[derive(Debug, Default)] +struct Bucket { + /// Bytes per second. + rate: Option, + /// Below zero when the last one took more than was there. + tokens: f64, + at: Option, +} + +impl Bucket { + fn fill(&mut self, now: Instant) { + let Some(rate) = self.rate else { return }; + let dt = now.saturating_duration_since(self.at.unwrap_or(now)).as_secs_f64(); + self.tokens = (self.tokens + dt * rate).min(rate * BURST); + self.at = Some(self.at.map_or(now, |at| at.max(now))); + } + + /// Whether that is another one. + fn set(&mut self, rate: Option, now: Instant) -> bool { + self.fill(now); + let rate = rate.filter(|r| *r > 0).map(|r| r as f64); + if rate == self.rate { + return false; + } + // A debt at the old speed could take ages to pay at the new one. + self.tokens = rate.map_or(0.0, |r| self.tokens.clamp(-r * BURST, r * BURST)); + (self.rate, self.at) = (rate, Some(now)); + true + } + + /// Until there is something in it. + fn wait(&self) -> f64 { + match self.rate { + Some(rate) if self.tokens < 1.0 => (1.0 - self.tokens) / rate, + _ => 0.0, + } + } +} + +/// One that waits for bytes. +#[derive(Debug)] +struct Ask { + who: T, + most: u64, +} + +#[derive(Debug)] +struct Flow { + weight: f64, + own: Bucket, + queue: Option, + host: Option, + asks: VecDeque>, + /// Where it stands, in shares: what it took by its weight. Below the others' when its own limits hold it back. + at: f64, + /// `Shares::stand` when it had nothing more to ask for. + idle_at: f64, +} + +#[derive(Debug)] +pub struct Shares { + /// The first is for everything. + buckets: Vec, + groups: HashMap, + flows: BTreeMap>, + next: FlowId, + /// Where the one furthest ahead stands. + stand: f64, +} + +impl Default for Shares { + fn default() -> Shares { + let groups = HashMap::from([(Group::Total, 0)]); + Shares { buckets: vec![Bucket::default()], groups, flows: BTreeMap::new(), next: 0, stand: 0.0 } + } +} + +impl Shares { + pub fn join(&mut self, weight: f64) -> FlowId { + self.next += 1; + let (at, idle_at) = (self.stand, self.stand); + let flow = Flow { weight, own: Bucket::default(), queue: None, host: None, asks: VecDeque::new(), at, idle_at }; + self.flows.insert(self.next, flow); + self.even(); + self.next + } + + pub fn leave(&mut self, id: FlowId) { + self.flows.remove(&id); + } + + pub fn set_weight(&mut self, id: FlowId, weight: f64) { + self.flow(id).weight = weight; + self.even(); + } + + /// Counts for a queue or a host from now on. + pub fn put(&mut self, id: FlowId, group: Group) { + let bucket = self.bucket(&group); + let flow = self.flow(id); + match group { + Group::Total => {} + Group::Queue(_) => flow.queue = Some(bucket), + Group::Host(_) => flow.host = Some(bucket), + } + self.even(); + } + + /// Bytes per second; None or 0 for no limit. + pub fn set(&mut self, group: &Group, rate: Option, now: Instant) { + let i = self.bucket(group); + if self.buckets[i].set(rate, now) { + self.even(); + } + } + + /// Of one download. + pub fn set_own(&mut self, id: FlowId, rate: Option, now: Instant) { + if self.flow(id).own.set(rate, now) { + self.even(); + } + } + + /// Those who were held back don't get all they missed when that ends. + fn even(&mut self) { + self.flows.values_mut().for_each(|f| f.at = f.at.max(self.stand)); + } + + /// The tightest limit that counts for it. + pub fn rate(&self, id: FlowId) -> Option { + let flow = &self.flows[&id]; + self.path(flow).filter_map(|b| b.rate).min_by(f64::total_cmp) + } + + pub fn ids(&self) -> impl Iterator { + self.flows.keys().copied() + } + + /// Wants up to `most` bytes, after its other asks. + pub fn ask(&mut self, id: FlowId, who: T, most: u64) { + let stand = self.stand; + let flow = self.flow(id); + if flow.asks.is_empty() { + // What the others took meanwhile is not held for it. + flow.at = (flow.at + (stand - flow.idle_at).max(0.0)).min(flow.at.max(stand)); + } + flow.asks.push_back(Ask { who, most }); + } + + /// Gives all that can be given now. `give` says whether the one who asked is still there. The time until there is more, if + /// anyone waits. + pub fn run(&mut self, now: Instant, mut give: impl FnMut(T, u64) -> bool) -> Option { + self.buckets.iter_mut().for_each(|b| b.fill(now)); + self.flows.values_mut().for_each(|f| f.own.fill(now)); + loop { + let mut best: Option<(FlowId, f64)> = None; + let mut soonest = f64::INFINITY; + for (id, flow) in self.flows.iter().filter(|(_, f)| !f.asks.is_empty()) { + let wait = self.path(flow).map(Bucket::wait).fold(0.0, f64::max); + if wait > 0.0 { + soonest = soonest.min(wait); + } else if best.is_none_or(|(_, at)| flow.at < at) { + best = Some((*id, flow.at)); + } + } + let Some((id, at)) = best else { + return soonest.is_finite().then(|| Duration::from_secs_f64(soonest)); + }; + let piece = self.rate(id).map_or(u64::MAX, |r| (r * PIECE).max(MIN_PIECE) as u64); + let flow = self.flow(id); + let ask = flow.asks.pop_front().expect("only those that ask"); + let n = ask.most.min(piece); + if give(ask.who, n) { + flow.at += n as f64 / flow.weight; + flow.own.tokens -= n as f64; + let groups = [Some(0), flow.queue, flow.host]; + for i in groups.into_iter().flatten() { + self.buckets[i].tokens -= n as f64; + } + self.stand = self.stand.max(at); + } + self.flow(id).idle_at = self.stand; + } + } + + fn flow(&mut self, id: FlowId) -> &mut Flow { + self.flows.get_mut(&id).expect("it has not left") + } + + fn bucket(&mut self, group: &Group) -> usize { + if let Some(i) = self.groups.get(group) { + return *i; + } + self.buckets.push(Bucket::default()); + self.groups.insert(group.clone(), self.buckets.len() - 1); + self.buckets.len() - 1 + } + + fn path<'a>(&'a self, flow: &'a Flow) -> impl Iterator { + let groups = [Some(0), flow.queue, flow.host]; + groups.into_iter().flatten().map(|i| &self.buckets[i]).chain([&flow.own]) + } +} diff --git a/crates/core/src/manager/actor.rs b/crates/core/src/manager/actor.rs index 6ddd69e..20bfdc4 100644 --- a/crates/core/src/manager/actor.rs +++ b/crates/core/src/manager/actor.rs @@ -10,6 +10,7 @@ use crate::adopt::Found; use crate::error::{Failure, Place, Retry}; use crate::events::Event; use crate::http::{self, Monitor, PartState, PartView, Source, download, safe_name}; +use crate::limit::Group; use crate::model::*; use crate::net_state::{self, Network}; use crate::recover::sleep::{self, Sleep}; @@ -99,6 +100,8 @@ struct Entry { todo: VecDeque<(Todo, Option)>, /// Counts up with each start; 0 for never. forced: u64, + /// See `Candidate`. + interrupted: u64, size: Option, downloaded: u64, parts: Arc<[PartView]>, @@ -125,6 +128,7 @@ impl Entry { fails: 0, todo: VecDeque::new(), forced: 0, + interrupted: 0, size: None, downloaded: 0, parts: Arc::new([]), @@ -240,6 +244,7 @@ pub struct Actor { answers: Vec<(Answer, Result)>, last_position: f64, forces: u64, + choices: u64, meter: Meter, second: u64, born: Instant, @@ -277,6 +282,7 @@ impl Actor { answers: vec![], last_position: 0.0, forces: 0, + choices: 0, meter: Meter::default(), second: 0, born: Instant::now(), @@ -436,6 +442,7 @@ impl Actor { let hosts = &self.config.shared.hosts; let caps = host::Caps { total: unlimited(limits.max_connections), per_host: unlimited(limits.connections_per_host), ..hosts.caps() }; hosts.set_caps(caps); + self.config.limiter.set(&Group::Total, Some(limits.speed)); for id in &self.runs { if let Some(Work::Run(run)) = &self.entries[id].work { run.monitor.set_cap(unlimited(limits.parts_per_download)); @@ -817,6 +824,11 @@ impl Actor { if e.task.state == State::Running { (e.size, e.downloaded) = (size, downloaded); } + if let Some(Work::Run(run)) = &e.work { + run.monitor.flow().set_priority(e.task.priority); + run.monitor.flow().put(Group::Queue(e.task.queue)); + run.monitor.flow().set(e.task.speed_limit); + } self.choose = true; Ok(()) } @@ -837,6 +849,9 @@ impl Actor { let task = Arc::make_mut(&mut e.task); (task.state, task.error, task.finished_at) = (to, error, finished); e.hold = None; + if to != State::Queued { + e.interrupted = 0; + } self.held.remove(&id); self.happened.push(Event::State { id, from, to }); self.choose = true; @@ -869,7 +884,12 @@ impl Actor { fn choose(&mut self) { let queues: HashMap = match self.store.queues() { - Ok(queues) => queues.into_iter().map(|q| (q.id, q.position)).collect(), + Ok(queues) => { + for q in &queues { + self.config.limiter.set(&Group::Queue(q.id), q.speed_limit); + } + queues.into_iter().map(|q| (q.id, q.position)).collect() + } Err(e) => { log::error!("queues not read: {e}"); HashMap::new() @@ -888,6 +908,7 @@ impl Actor { priority: e.task.priority, forced: e.forced, running: e.task.state == State::Running, + interrupted: e.interrupted, pinned: e.resumable == Some(false) && e.downloaded > 0, order: (queues.get(&e.task.queue).copied().unwrap_or_default(), e.task.position), }); @@ -900,11 +921,15 @@ impl Actor { let running = self.runs.iter().filter(|id| &*self.entries[id].host == host).count() as u32; cap.min(running.max(1)) }; - let picked = pick(candidates.collect(), unlimited(self.config.limits.max_active) as usize, host_cap); + // One without any connection would wait for nothing. + let max = unlimited(self.config.limits.max_active).min(unlimited(self.config.limits.max_connections)); + let picked = pick(candidates.collect(), max as usize, host_cap); let chosen: BTreeSet = picked.iter().copied().collect(); + self.choices += 1; for id in self.runs.clone() { - if !chosen.contains(&id) { + if !chosen.contains(&id) && self.entries[&id].task.state == State::Running { self.suspend(id); + self.entry(id).interrupted = self.choices; } } for id in picked { @@ -929,7 +954,10 @@ impl Actor { return self.failed(id, &Why::Http(e)); } let (stop, stopped) = watch::channel(false); - let monitor = Arc::new(Monitor::new(unlimited(self.config.limits.parts_per_download))); + let flow = self.config.limiter.flow(task.priority); + flow.put(Group::Queue(task.queue)); + flow.set(task.speed_limit); + let monitor = Arc::new(Monitor::with_flow(unlimited(self.config.limits.parts_per_download), flow)); let run = Run { stop, monitor: monitor.clone(), since: Instant::now(), received: 0, known: false, had: self.entries[&id].downloaded }; let (shared, options, to) = (self.config.shared.clone(), self.config.options.clone(), self.to.clone()); let sites = self.config.sites.clone(); diff --git a/crates/core/src/manager/mod.rs b/crates/core/src/manager/mod.rs index fb9be33..acbc018 100644 --- a/crates/core/src/manager/mod.rs +++ b/crates/core/src/manager/mod.rs @@ -13,6 +13,7 @@ use crate::adopt::Found; use crate::error::Failure; use crate::events::Event; use crate::http::{Options, Shared}; +use crate::limit::Limiter; use crate::model::{Task, TaskId}; use crate::net_state::Network; use crate::recover::Recovery; @@ -171,6 +172,7 @@ pub struct Config { pub sites: Option>, pub options: Options, pub limits: Limits, + pub limiter: Arc, pub bin: Bin, pub recovery: Recovery, /// How long a removal can be undone. @@ -186,6 +188,7 @@ impl Config { sites: None, options: Options::default(), limits, + limiter: Limiter::new(), bin: Bin::default(), recovery: Recovery::default(), undo: Duration::from_secs(60), @@ -255,7 +258,7 @@ impl Manager { Reply(reply) } - /// Takes effect at once, also on running downloads. 0 is no limit. The speed is not its business. + /// Takes effect at once, also on running downloads. 0 is no limit. Connections that may stay go on as they are. pub fn set_limits(&self, limits: Limits) { let _ = self.to.send(Msg::Limits(limits)); } diff --git a/crates/core/src/manager/pick.rs b/crates/core/src/manager/pick.rs index c0982ca..aca0495 100644 --- a/crates/core/src/manager/pick.rs +++ b/crates/core/src/manager/pick.rs @@ -13,6 +13,8 @@ pub struct Candidate<'a> { /// When the user asked to start it now; 0 for never. The latest goes first. pub forced: u64, pub running: bool, + /// It ran until it had to give way, the one with the highest number last; 0 for never. + pub interrupted: u64, /// Stopping it would throw away what it has. pub pinned: bool, /// Place of its queue, and its place there. @@ -20,14 +22,14 @@ pub struct Candidate<'a> { } /// At most `max` of them, and no more of one host than it takes connections. Running ones give way to a higher priority or -/// a forced start, never to a better place, and pinned ones never. +/// a forced start, never to a better place, and pinned ones never. Those that gave way go on before others. pub fn pick(mut candidates: Vec, max: usize, mut host_cap: impl FnMut(&str) -> u32) -> Vec { let pinned = |c: &Candidate| c.running && c.pinned; if candidates.iter().any(|c| c.priority == Priority::Only) { candidates.retain(|c| c.priority == Priority::Only || pinned(c)); } candidates.sort_by(|a, b| { - let rank = |c: &Candidate| (Reverse(pinned(c)), Reverse(c.forced), Reverse(c.priority as u8), Reverse(c.running)); + let rank = |c: &Candidate| (Reverse(pinned(c)), Reverse(c.forced), Reverse(c.priority as u8), Reverse(c.running), Reverse(c.interrupted)); let order = |c: &Candidate, d: &Candidate| c.order.0.total_cmp(&d.order.0).then(c.order.1.total_cmp(&d.order.1)); rank(a).cmp(&rank(b)).then_with(|| order(a, b)).then(a.id.cmp(&b.id)) }); @@ -51,7 +53,7 @@ mod tests { use super::*; fn c(id: TaskId) -> Candidate<'static> { - Candidate { id, host: "h", priority: Priority::Normal, forced: 0, running: false, pinned: false, order: (0.0, id as f64) } + Candidate { id, host: "h", priority: Priority::Normal, forced: 0, running: false, interrupted: 0, pinned: false, order: (0.0, id as f64) } } fn picked(candidates: &[Candidate], max: usize) -> Vec { @@ -76,8 +78,13 @@ mod tests { #[test] fn running_ones_keep_their_place() { let mut all = vec![c(1), c(2), c(3)]; + all[2].interrupted = 1; + assert_eq!(picked(&all, 1), [3]); + all[1].interrupted = 2; + assert_eq!(picked(&all, 9), [2, 3, 1]); all[2].running = true; assert_eq!(picked(&all, 1), [3]); + all[1].interrupted = 0; all[0].priority = Priority::High; assert_eq!(picked(&all, 1), [1]); all[2].pinned = true; diff --git a/crates/core/src/relink/mod.rs b/crates/core/src/relink/mod.rs index 918a615..2d178fc 100644 --- a/crates/core/src/relink/mod.rs +++ b/crates/core/src/relink/mod.rs @@ -177,7 +177,7 @@ pub async fn check(client: &Client, task: &Task, parts: &[Part], link: NewLink, let head = whole.first().filter(|r| r.start == 0).map(|r| r.end.min(ALL)).unwrap_or(0); let known = read(&file, 0..head).await?; let same = match body { - Some(body) => same_body(body, &known, stop).await?, + Some(body) => same_body(client, body, &known, stop).await?, None => true, }; checked.compared = head; diff --git a/crates/core/src/settings.rs b/crates/core/src/settings.rs index c1656bb..dc17ac5 100644 --- a/crates/core/src/settings.rs +++ b/crates/core/src/settings.rs @@ -18,6 +18,8 @@ pub struct Settings { pub download_folder: String, /// The speed mode in use. pub mode: Mode, + /// The mode that comes back when snail is turned off. + pub before_snail: Mode, pub low: Limits, pub medium: Limits, pub high: Limits, @@ -122,6 +124,7 @@ impl Default for Settings { language: String::new(), download_folder: String::new(), mode: Mode::High, + before_snail: Mode::High, low: Limits::new(256 * 1024, 2, 8, 4, 4), medium: Limits::new(1024 * 1024, 3, 24, 8, 8), high: Limits::default(), @@ -199,6 +202,7 @@ impl Settings { fs::rename(tmp, path) } + /// Of the mode in use. pub fn limits(&self) -> Limits { match self.mode { Mode::Low => self.low, @@ -207,6 +211,28 @@ impl Settings { Mode::Snail => self.snail, } } + + /// To edit a mode. + pub fn limits_of(&mut self, mode: Mode) -> &mut Limits { + match mode { + Mode::Low => &mut self.low, + Mode::Medium => &mut self.medium, + Mode::High => &mut self.high, + Mode::Snail => &mut self.snail, + } + } + + /// Snail on, or back to the mode before it. + pub fn toggle_snail(&mut self) { + if self.mode == Mode::Snail { + self.mode = self.before_snail; + } else { + (self.before_snail, self.mode) = (self.mode, Mode::Snail); + } + if self.mode == Mode::Snail && self.before_snail == Mode::Snail { + self.before_snail = Mode::High; + } + } } fn set_aside(path: &Path) -> Option { diff --git a/crates/core/src/site.rs b/crates/core/src/site.rs index 8343ad8..10aec3f 100644 --- a/crates/core/src/site.rs +++ b/crates/core/src/site.rs @@ -349,7 +349,8 @@ impl Access { } } } - let response = request.send().await.map_err(|e| failed(e, proxied))?; + let answer = async { request.send().await.map_err(|e| failed(e, proxied)) }; + let response = client.wait(answer).await?; let mut inner = self.inner.lock().unwrap(); for value in response.headers().get_all(SET_COOKIE).iter().filter_map(|v| v.to_str().ok()) { inner.jar.set(response.url(), value, chrono::Utc::now()); diff --git a/crates/core/tests/http.rs b/crates/core/tests/http.rs index bd0160c..b35fcf6 100644 --- a/crates/core/tests/http.rs +++ b/crates/core/tests/http.rs @@ -8,7 +8,6 @@ use medlar_core::part::LivePart; use medlar_core::segment::Rules; use medlar_core::store::Store; use medlar_testserver::{Faults, TestServer, expected}; -use reqwest::Client; use sha2::{Digest, Sha256}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; diff --git a/crates/core/tests/limit.rs b/crates/core/tests/limit.rs new file mode 100644 index 0000000..8d911e0 --- /dev/null +++ b/crates/core/tests/limit.rs @@ -0,0 +1,545 @@ +//! Limits of speed: how exact they are, who gets what of them, and that they change while downloads run. + +use medlar_core::host::{self, Caps, Hosts}; +use medlar_core::http::{ClientOptions, Options, Shared, client}; +use medlar_core::limit::{Flow, Group, Limiter, Shares}; +use medlar_core::manager::*; +use medlar_core::model::*; +use medlar_core::segment::Rules; +use medlar_core::settings::{Limits, Mode, Settings}; +use medlar_core::snapshot::Snapshot; +use medlar_core::store::Store; +use medlar_testserver::{Faults, TestServer, expected}; +use std::io::{BufRead, BufReader, Write}; +use std::net::TcpListener; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; +use tokio::time::sleep; + +const KB: u64 = 1000; +const MB: u64 = 1000 * KB; +const GB: u64 = 1000 * MB; + +/// Speeds are measured: one test at a time. +static ALONE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +fn ms(n: u64) -> Duration { + Duration::from_millis(n) +} + +fn near(got: f64, wanted: f64, off: f64) -> bool { + (got - wanted).abs() <= wanted * off +} + +// With a clock of its own. + +struct Sim { + shares: Shares, + now: Instant, + /// Connections that have nothing to wait for. + idle: Vec, + chunk: u64, +} + +impl Sim { + fn new() -> Sim { + Sim { shares: Shares::default(), now: Instant::now(), idle: vec![], chunk: 0 } + } + + fn limit(&mut self, group: Group, rate: u64) { + self.shares.set(&group, Some(rate), self.now); + } + + /// A download with as many connections, each of which always has `chunk` bytes. + fn flow(&mut self, priority: Priority, connections: u64, chunk: u64) -> u64 { + let id = self.shares.join(priority.weight()); + self.chunk = chunk; + self.idle.extend((0..connections).map(|_| id)); + id + } + + /// Bytes per second of each, and the longest anyone waited. The clock wakes up late, by up to `late`. + fn run(&mut self, secs: f64, late: Duration, ids: &[u64]) -> (Vec, Duration) { + let mut random = fastrand::Rng::with_seed(7); + let (from, mut got, mut last) = (self.now, vec![0; ids.len()], vec![self.now; ids.len()]); + let mut longest = Duration::ZERO; + while (self.now - from).as_secs_f64() < secs { + for id in self.idle.drain(..) { + self.shares.ask(id, id, self.chunk); + } + let mut given = vec![]; + let wait = self.shares.run(self.now, |id, n| { + given.push((id, n)); + true + }); + for (id, n) in given { + if let Some(i) = ids.iter().position(|i| *i == id) { + got[i] += n; + longest = longest.max(self.now - last[i]); + last[i] = self.now; + } + self.idle.push(id); + } + if self.idle.is_empty() { + // Timers count in milliseconds. + let wait = wait.expect("they wait").max(ms(1)); + self.now += wait + late.mul_f64(random.f64()); + } + } + let secs = (self.now - from).as_secs_f64(); + (got.iter().map(|n| *n as f64 / secs).collect(), longest) + } +} + +#[test] +fn exact_from_slow_to_fast() { + for (rate, late) in [10 * KB, 100 * KB, MB, 10 * MB, 100 * MB, GB].into_iter().flat_map(|r| [(r, ms(0)), (r, ms(60))]) { + for connections in [1, 16] { + let mut sim = Sim::new(); + sim.limit(Group::Total, rate); + let one = sim.flow(Priority::Normal, connections, 400 * KB); + let (got, longest) = sim.run(10.0, late, &[one]); + assert!(near(got[0], rate as f64, 0.02), "{rate}: {}", got[0]); + assert!(longest <= ms(125) + late, "{rate}: nothing for {longest:?}"); + } + } +} + +#[test] +fn the_tightest_limit_counts() { + let mut sim = Sim::new(); + sim.limit(Group::Total, 1000 * KB); + sim.limit(Group::Queue(1), 600 * KB); + sim.limit(Group::Host("h".into()), 300 * KB); + let ids: Vec = (0..4).map(|_| sim.flow(Priority::Normal, 2, 64 * KB)).collect(); + // 0 and 1 are from one host, 0 has a limit of its own, 0 to 2 are in one queue. 3 is free to take the rest. + sim.shares.put(ids[0], Group::Host("h".into())); + sim.shares.put(ids[1], Group::Host("h".into())); + ids[..3].iter().for_each(|id| sim.shares.put(*id, Group::Queue(1))); + sim.shares.set_own(ids[0], Some(100 * KB), sim.now); + let (got, _) = sim.run(10.0, ms(5), &ids); + for (got, wanted) in got.iter().zip([100.0, 200.0, 300.0, 400.0]) { + assert!(near(*got, wanted * 1000.0, 0.05), "{got} {wanted}"); + } + // Without the one of the host, the queue is shared evenly. + sim.limit(Group::Host("h".into()), 0); + let (got, _) = sim.run(10.0, ms(5), &ids); + for (got, wanted) in got.iter().zip([100.0, 250.0, 250.0, 400.0]) { + assert!(near(*got, wanted * 1000.0, 0.05), "{got} {wanted}"); + } + // In another queue, it only has to share with all. + sim.shares.put(ids[2], Group::Queue(2)); + sim.limit(Group::Queue(1), 100 * KB); + let (got, _) = sim.run(10.0, ms(5), &ids); + assert!(near(got[0] + got[1], 100e3, 0.05) && near(got[2], 450e3, 0.05) && near(got[3], 450e3, 0.05), "{got:?}"); +} + +#[test] +fn shares_follow_priority() { + use Priority::*; + for (rate, connections) in [(100 * KB, [1, 1, 1]), (10 * MB, [8, 1, 3]), (100 * MB, [1, 8, 16])] { + let mut sim = Sim::new(); + sim.limit(Group::Total, rate); + let ids: Vec = [Low, Normal, High].iter().zip(connections).map(|(p, n)| sim.flow(*p, n, 400 * KB)).collect(); + let (got, _) = sim.run(20.0, ms(5), &ids); + for (got, share) in got.iter().zip([1.0, 2.0, 4.0]) { + assert!(near(*got, rate as f64 * share / 7.0, 0.05), "{got} {share}"); + } + // Takes effect at once, and what one leaves is for the others. + sim.shares.set_weight(ids[0], High.weight()); + sim.idle.retain(|id| *id != ids[1]); + sim.shares.leave(ids[1]); + let (got, _) = sim.run(5.0, ms(5), &ids); + assert!(near(got[0], rate as f64 / 2.0, 0.05) && near(got[2], rate as f64 / 2.0, 0.05), "{got:?}"); + } +} + +#[test] +fn the_lowest_is_never_left_out_and_nobody_saves_up() { + let mut sim = Sim::new(); + sim.limit(Group::Total, 100 * KB); + let mut ids = vec![sim.flow(Priority::Lowest, 1, 64 * KB)]; + ids.extend((0..5).map(|_| sim.flow(Priority::Highest, 8, 64 * KB))); + let (got, longest) = sim.run(30.0, ms(5), &ids); + assert!(near(got[0], 100e3 / 81.0, 0.1), "{got:?}"); + assert!(longest < ms(2500), "{longest:?}"); + // One that was held back for long gets its share when it is let go, not all it missed. + let mut sim = Sim::new(); + sim.limit(Group::Total, 100 * KB); + let ids: Vec = (0..2).map(|_| sim.flow(Priority::Normal, 2, 64 * KB)).collect(); + sim.shares.set_own(ids[0], Some(1000), sim.now); + sim.run(60.0, ms(5), &ids); + sim.shares.set_own(ids[0], None, sim.now); + let (got, _) = sim.run(2.0, ms(5), &ids); + assert!(near(got[1], 50e3, 0.1), "{got:?}"); +} + +#[test] +fn no_debts_after_a_change() { + let mut sim = Sim::new(); + sim.limit(Group::Total, GB); + let one = sim.flow(Priority::Normal, 16, 400 * KB); + sim.run(1.0, ms(5), &[one]); + sim.limit(Group::Total, 10 * KB); + let (got, longest) = sim.run(2.0, ms(0), &[one]); + assert!(near(got[0], 10e3, 0.1) && longest < ms(350), "{got:?} {longest:?}"); + sim.limit(Group::Total, 10 * MB); + let (got, _) = sim.run(0.5, ms(0), &[one]); + assert!(near(got[0], 10e6, 0.1), "{got:?}"); +} + +// With the real clock. + +/// Takes for so long and says how fast it was. +async fn pull(flow: Arc, chunk: u64, time: Duration) -> f64 { + let (from, mut got) = (Instant::now(), 0); + while from.elapsed() < time { + got += flow.take(chunk).await; + } + got as f64 / from.elapsed().as_secs_f64() +} + +#[tokio::test(flavor = "multi_thread")] +async fn exact_with_the_real_clock() { + let _alone = ALONE.lock().await; + for (rate, connections) in [(10 * KB, 1), (MB, 8), (100 * MB, 8), (GB, 16)] { + let limiter = Limiter::new(); + limiter.set(&Group::Total, Some(rate)); + let flow = Arc::new(limiter.flow(Priority::Normal)); + let pulls: Vec<_> = (0..connections).map(|_| tokio::spawn(pull(flow.clone(), 64 * KB, ms(2500)))).collect(); + let mut got = 0.0; + for p in pulls { + got += p.await.unwrap(); + } + println!("limit {rate}: {got:.0}"); + assert!(near(got, rate as f64, 0.05), "{rate}: {got}"); + } +} + +#[tokio::test] +async fn giving_up_takes_nothing_and_a_change_wakes_those_who_wait() { + let _alone = ALONE.lock().await; + let limiter = Limiter::new(); + limiter.set(&Group::Total, Some(10)); + let flow = Arc::new(limiter.flow(Priority::Normal)); + while tokio::time::timeout(ms(150), flow.take(5000)).await.is_ok() {} + let waiting = tokio::spawn({ + let flow = flow.clone(); + async move { flow.take(5000).await } + }); + sleep(ms(50)).await; + assert!(!waiting.is_finished()); + limiter.set(&Group::Total, None); + let got = tokio::time::timeout(ms(200), waiting).await.expect("woken").unwrap(); + assert_eq!((got, flow.limited(), flow.connections()), (5000, false, u32::MAX)); + limiter.set(&Group::Total, Some(100 * KB)); + assert!(flow.limited() && flow.held() && !flow.held()); + assert_eq!(flow.connections(), 12); + assert!(Flow::free().take(GB).await == GB); +} + +// With downloads. + +const LIMITS: Limits = Limits { speed: 0, max_active: 8, max_connections: 32, parts_per_download: 4, connections_per_host: 16 }; + +struct Bench { + server: TestServer, + dir: tempfile::TempDir, + store: Arc, + limiter: Arc, + manager: Manager, +} + +impl Bench { + async fn new(limits: Limits) -> Bench { + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(Store::open(&dir.path().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 mut config = Config::new(Shared { client, store: store.clone(), hosts }, limits); + config.options = Options { rules: Rules { min: 64 * 1024, align: 4096, min_time: ms(50) }, tick: ms(25), ..Options::default() }; + (config.bin, config.tick) = (Bin::at(dir.path().join("Trash")), ms(20)); + let limiter = config.limiter.clone(); + Bench { server: TestServer::start().await, dir, store, limiter, manager: Manager::open(config).unwrap() } + } + + async fn add(&self, path: &str, edit: impl FnOnce(&mut Task)) -> TaskId { + let mut task = Task { url: self.server.url(path), folder: self.dir.path().join("files"), ..Task::default() }; + edit(&mut task); + self.manager.send(Command::Add(Box::new(task))).await.unwrap() + } + + async fn edit(&self, id: TaskId, edit: impl FnOnce(&mut Task) + Send + 'static) { + self.manager.send(Command::Edit { id, edit: Box::new(edit) }).await.unwrap(); + } + + fn received(&self, id: TaskId) -> u64 { + self.manager.snapshot().get(id).unwrap().counters.received + } + + async fn until(&self, what: &str, is: impl Fn(&Snapshot) -> bool) { + let end = Instant::now() + Duration::from_secs(20); + while !is(&self.manager.snapshot()) { + let states: Vec<_> = self.manager.snapshot().iter().map(|v| (v.id(), v.state(), v.task.error.clone())).collect(); + assert!(Instant::now() < end, "never {what}: {states:?}"); + sleep(ms(5)).await; + } + } + + async fn until_bytes(&self, ids: &[TaskId]) { + self.until("bytes", |s| ids.iter().all(|id| s.get(*id).unwrap().counters.received > 0)).await; + } + + /// Bytes per second of each, for so long. + async fn speeds(&self, ids: &[TaskId], time: Duration) -> Vec { + let before: Vec = ids.iter().map(|id| self.received(*id)).collect(); + let from = Instant::now(); + sleep(time).await; + let secs = from.elapsed().as_secs_f64(); + ids.iter().zip(before).map(|(id, b)| (self.received(*id) - b) as f64 / secs).collect() + } + + fn states(&self) -> Vec { + self.manager.snapshot().iter().map(|v| v.state()).collect() + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn downloads_keep_to_limits_and_shares() { + let _alone = ALONE.lock().await; + let b = Bench::new(Limits { speed: 1400 * KB, ..LIMITS }).await; + let mut ids = vec![]; + for (seed, priority) in [(1, Priority::Low), (2, Priority::Normal), (3, Priority::High)] { + ids.push(b.add(&TestServer::data_path(seed, 64 * MB), |t| t.priority = priority).await); + } + b.until_bytes(&ids).await; + sleep(ms(1000)).await; + let got = b.speeds(&ids, ms(4000)).await; + println!("shares of 1400 KB/s: {got:.0?}"); + assert!(near(got.iter().sum(), 1400e3, 0.05), "{got:?}"); + for (got, share) in got.iter().zip([1.0, 2.0, 4.0]) { + assert!(near(*got, 200e3 * share, 0.1), "{got} {share}"); + } + // A limit of its own and a new priority, while it runs. + b.edit(ids[2], |t| t.speed_limit = Some(200 * KB)).await; + b.edit(ids[0], |t| t.priority = Priority::Normal).await; + sleep(ms(500)).await; + let got = b.speeds(&ids, ms(3000)).await; + println!("then: {got:.0?}"); + for (got, wanted) in got.iter().zip([600e3, 600e3, 200e3]) { + assert!(near(*got, wanted, 0.1), "{got} {wanted}"); + } + // Limits of the queue and of the host. + let queues = b.store.queues().unwrap(); + let queue = Queue { speed_limit: Some(300 * KB), ..queues[0].clone() }; + b.store.save_queue(queue).unwrap(); + b.manager.set_limits(Limits { speed: 1400 * KB, ..LIMITS }); + sleep(ms(500)).await; + let got = b.speeds(&ids, ms(2000)).await; + assert!(near(got.iter().sum(), 300e3, 0.1), "{got:?}"); + b.limiter.set(&Group::Host(host::key(&b.server.url("/").parse().unwrap())), Some(100 * KB)); + sleep(ms(500)).await; + let got = b.speeds(&ids, ms(2000)).await; + assert!(near(got.iter().sum(), 100e3, 0.1), "{got:?}"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn slow_is_even_and_stays_connected() { + let _alone = ALONE.lock().await; + let b = Bench::new(Limits { speed: 10 * KB, ..LIMITS }).await; + let id = b.add(&TestServer::data_path(1, 8 * MB), |_| {}).await; + b.until_bytes(&[id]).await; + sleep(ms(500)).await; + let before = b.server.log().len(); + // A second at a time, longer together than servers and this client wait without a byte. + let mut all = 0.0; + for _ in 0..4 { + let got = b.speeds(&[id], ms(1000)).await[0]; + println!("{got:.0}"); + assert!(near(got, 10e3, 0.2), "{got}"); + all += got / 4.0; + } + assert!(near(all, 10e3, 0.05), "{all}"); + assert_eq!(b.server.log().len(), before); + // The rest at full speed, and it is the right file. + b.manager.set_limits(LIMITS); + b.until("done", |s| s.get(id).unwrap().state() == State::Done).await; + let task = b.store.task(id).unwrap(); + assert!(std::fs::read(task.folder.join(&task.name)).unwrap() == expected(1, 0, 8 * MB as usize)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn modes_change_live_without_reconnecting() { + let _alone = ALONE.lock().await; + let mut settings = Settings::default(); + for (mode, speed) in [(Mode::Low, 100 * KB), (Mode::Medium, MB), (Mode::High, 3 * MB), (Mode::Snail, 32 * KB)] { + *settings.limits_of(mode) = Limits { speed, parts_per_download: 2, ..LIMITS }; + } + let b = Bench::new(settings.limits()).await; + let id = b.add(&TestServer::data_path(1, 200 * MB), |_| {}).await; + b.until_bytes(&[id]).await; + b.until("both", |s| s.get(id).unwrap().connections == 2).await; + // Its request has to get there. + sleep(ms(300)).await; + let before = b.server.log().len(); + for mode in [Mode::Low, Mode::High, Mode::Medium, Mode::High, Mode::Snail, Mode::Medium] { + if mode == Mode::Snail { + settings.toggle_snail(); + assert_eq!(settings.mode, Mode::Snail); + } else if settings.mode == Mode::Snail { + settings.toggle_snail(); + assert_eq!(settings.mode, Mode::High); + settings.mode = mode; + } else { + settings.mode = mode; + } + b.manager.set_limits(settings.limits()); + sleep(ms(400)).await; + let (speed, time) = (settings.limits().speed as f64, if mode == Mode::Snail { 1500 } else { 600 }); + let got = b.speeds(&[id], ms(time)).await[0]; + println!("{mode:?} {speed}: {got:.0}"); + assert!(near(got, speed, 0.1), "{mode:?}: {got}"); + } + assert_eq!(b.server.log().len(), before); +} + +/// Serves one file and counts what it could write, while it writes. The test server counts at the end. +fn counting(len: u64) -> (String, Arc) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}/big.bin", listener.local_addr().unwrap()); + let sent = Arc::new(AtomicU64::new(0)); + let count = sent.clone(); + std::thread::spawn(move || { + for mut io in listener.incoming().map_while(|r| r.ok()) { + let count = count.clone(); + std::thread::spawn(move || { + let (mut first, mut last) = (0, len - 1); + for line in BufReader::new(io.try_clone().unwrap()).lines().map_while(|r| r.ok()).take_while(|l| !l.is_empty()) { + if let Some(range) = line.to_ascii_lowercase().strip_prefix("range: bytes=") { + let (from, to) = range.split_once('-').unwrap(); + (first, last) = (from.parse().unwrap(), to.parse().unwrap_or(len - 1)); + } + } + let head = format!( + "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes {first}-{last}/{len}\r\nContent-Length: {}\r\nETag: \"a\"\r\n\r\n", + last + 1 - first + ); + let mut ok = io.write_all(head.as_bytes()).is_ok(); + let mut left = last + 1 - first; + while ok && left > 0 { + let n = left.min(16384); + ok = io.write_all(&[7; 16384][..n as usize]).is_ok(); + count.fetch_add(n, Ordering::Relaxed); + left -= n; + } + }); + } + }); + (url, sent) +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_sender_really_slows_down() { + let _alone = ALONE.lock().await; + let limits = Limits { speed: 500 * KB, parts_per_download: 1, ..LIMITS }; + let b = Bench::new(limits).await; + let (url, sent) = counting(200 * MB); + let sent = || sent.load(Ordering::Relaxed); + let id = b.add("/", |t| t.url = url).await; + b.until_bytes(&[id]).await; + sleep(ms(1000)).await; + let ahead = sent().saturating_sub(b.received(id)); + println!("sent ahead: {ahead}"); + assert!(ahead > 0 && ahead < 8 * MB, "{ahead}"); + // Faster for a moment, then slow again: what is on its way may come, no more. + b.manager.set_limits(Limits { speed: 100 * MB, ..limits }); + sleep(ms(300)).await; + b.manager.set_limits(limits); + sleep(ms(500)).await; + let before = sent(); + sleep(ms(4000)).await; + let more = sent() - before; + println!("sent in four seconds: {more}"); + assert!(more < 6 * MB, "{more}"); + assert_eq!(b.manager.snapshot().get(id).unwrap().connections, 1); +} + +#[tokio::test(flavor = "multi_thread")] +async fn only_this_one_pauses_the_rest_and_brings_them_back() { + let _alone = ALONE.lock().await; + use State::{Paused, Queued, Running}; + let b = Bench::new(Limits { max_active: 2, speed: 400 * KB, ..LIMITS }).await; + let mut ids = vec![]; + for seed in 0..5 { + ids.push(b.add(&TestServer::data_path(seed, 64 * MB), |_| {}).await); + } + // Those that run are not the first in line. + b.manager.send(Command::Start(ids[3])).await.unwrap(); + b.manager.send(Command::Start(ids[2])).await.unwrap(); + b.until_bytes(&ids[2..4]).await; + assert_eq!(b.states(), [Queued, Queued, Running, Running, Queued]); + b.edit(ids[4], |t| t.priority = Priority::Only).await; + b.until_bytes(&ids[4..]).await; + assert_eq!(b.states(), [Queued, Queued, Queued, Queued, Running]); + let got = b.speeds(&ids, ms(2000)).await; + assert!(near(got[4], 400e3, 0.1) && got[..4].iter().sum::() < 1.0, "{got:?}"); + // One the user pauses meanwhile doesn't come back. + b.manager.send(Command::Pause(ids[3])).await.unwrap(); + b.edit(ids[4], |t| t.priority = Priority::Normal).await; + b.until("back", |s| s.get(ids[2]).unwrap().state() == Running).await; + assert_eq!(b.states(), [Queued, Queued, Running, Paused, Running]); + // The end of it brings the others back as well. + let small = b.add(&TestServer::data_path(9, 200 * KB), |t| t.priority = Priority::Only).await; + b.until("alone", |s| s.get(small).unwrap().state() == Running && s.totals.running == 1).await; + b.until("the end", |s| s.get(small).unwrap().state() == State::Done && s.totals.running == 2).await; + assert_eq!(b.states()[..5], [Queued, Queued, Running, Paused, Running]); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_host_shares_its_connections() { + let _alone = ALONE.lock().await; + let b = Bench::new(Limits { connections_per_host: 7, parts_per_download: 16, ..LIMITS }).await; + let mut ids = vec![]; + for (seed, priority) in [(1, Priority::Low), (2, Priority::Normal), (3, Priority::High)] { + let path = TestServer::data_path(seed, 32 * MB); + b.server.set_faults(&path, Faults { throttle_conn: Some(100 * KB), ..Faults::default() }); + ids.push(b.add(&path, |t| t.priority = priority).await); + // The first one could have them all. + if seed == 1 { + b.until("all of them", |s| s.get(ids[0]).unwrap().connections == 7).await; + } + } + b.until("their shares", |s| ids.iter().map(|id| s.get(*id).unwrap().connections).eq([1, 2, 4])).await; + let requests = b.server.log().len(); + sleep(ms(1500)).await; + assert_eq!(b.server.log().len(), requests, "they stay as they are"); + b.manager.send(Command::Pause(ids[2])).await.unwrap(); + b.until("the rest", |s| ids[..2].iter().map(|id| s.get(*id).unwrap().connections).sum::() == 7).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn costs_next_to_nothing_at_full_speed() { + let _alone = ALONE.lock().await; + const CHUNK: u64 = 64 * KB; + const LEN: u64 = 128 * MB; + let b = Bench::new(Limits { parts_per_download: 4, ..LIMITS }).await; + let from = Instant::now(); + let id = b.add(&TestServer::data_path(1, LEN), |_| {}).await; + b.until("done", |s| s.get(id).unwrap().state() == State::Done).await; + let download = from.elapsed().as_secs_f64() / (LEN / CHUNK) as f64; + // Limited, but never held up. + let limiter = Limiter::new(); + limiter.set(&Group::Total, Some(100_000 * GB)); + let flow = limiter.flow(Priority::Normal); + let mut best = f64::INFINITY; + for _ in 0..5 { + let from = Instant::now(); + for _ in 0..2000 { + assert!(flow.take(CHUNK).await > 0); + } + best = best.min(from.elapsed().as_secs_f64() / 2000.0); + } + println!("per chunk: download {:.1} µs, limit {:.2} µs", download * 1e6, best * 1e6); + assert!(best < download * 0.03, "{best} of {download}"); +} diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 47d288b..d64d3bd 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -42,3 +42,6 @@ - D-040 — 2026-11-25 — Rows have fixed heights and places worked out at once; motion is an offset that springs back (FLIP, `list::flow`). Nothing moves for over 30 changes, for 0.5 s after the keyboard, or when the width changes. New numbers alone patch rows in place. — 10,000 rows, 1.1 and 9.8 at once. — 03, 04 - D-041 — 2026-11-25 — A row is dragged by its handle only, and only in queue order within its heading; a drag anywhere else is the lasso. Dropping gives it the neighbours' queue and a position between theirs. — Full-width rows leave no empty ground for a lasso. — 03, 04 - D-042 — 2026-11-25 — Removing never asks: Del keeps files, Shift+Del bins them, both undone from the toast. Status in the rail is one of six; queue, tag, type, host and day narrow it further and show as chips. — Undo is better than a question. — 03, 05 +- D-043 — 2026-11-25 — Weights lowest to highest: 1, 2, 4, 8, 16. Under a limit, bytes go to the download furthest behind its weighted share; without one, only connections are shared by weight. A host's connections (and all together) go by weight among the downloads that can use them, each gets one before any gets two, and the newest ones over a share are ended. Never more downloads run than connections exist. — No starvation, nothing unused — 04 +- D-044 — 2026-11-25 — Bytes are limited after the read: pieces of 20 ms (at least 1 KiB), one chunk read ahead, then the socket is left full. reqwest gives no way to a smaller socket buffer. Under 8 KiB/s per connection fewer are used; while a limit holds a download back, connection counts are not tried out or remembered, and slow ones not replaced. The idle timeout is Medlar's own and counts only while bytes are waited for. — reqwest's counts while a limit holds bytes, too — 02, 04 +- D-045 — 2026-11-25 — "Only this one" is a priority: the rest go back in line and come back first when it ends or is changed, those stopped last before others (not across a restart). Snail is a fourth mode; `before_snail` is the one to go back to. — Nothing of the others is changed, so nothing has to be restored — 04, 07 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index a031fec..a255c12 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -117,6 +117,18 @@ Not done: the exception shows a fingerprint only (no issuer or dates); proxies t Seen: until fixed, a test's `dbus-daemon --session` started real services from the system's list (gnome-keyring's starter found the running one and ended; portal, gvfs). No secret was read or written, nothing was left over. `auth.rs` has a bus without services; `recover.rs` still has the old one, but asks for no such names. Boxes were ticked together at the end, against rule 3. Fixed after review: `matrix` (max_conns) was flaky, also at 49f6e5d (2 of 10 under load): parts that started together and were all refused didn't count as too many, so every retry began with two again. Now the host stands fewer for a while (Retry-After and three windows), test `two_refused_at_once_come_back_as_one`; the test's `max_wait` is above the server's 1 s pause, as in real use. 12 of 12 under load. +## S019 — Limiter, modes and priority shares (2026-11-25) +Done: `core::limit` (`Limiter`, `Flow`, `Shares`), shares of connections in `host` (`Member`), hooks in `http`, `manager`, `settings`. Choices: D-043 to D-045. +Verified: `nice cargo test -j 2 -p medlar-core --test limit` green (14); the other core tests and clippy too, on this commit's tree. +Numbers (debug build): 10 KB/s to 1 GB/s within 4 %; three downloads 1:2:4 at 1400 KB/s → 200, 400, 800 KB/s ± 2 %; a change is exact after 400 ms, same connections; limit 1 % of the time of a 64 kB chunk; at 500 KB/s the sender is ≤ 6 MB ahead. +Outside the plan's files: `http::Client` is Medlar's own (reqwest's read timeout ran on while a limit held bytes, and cut slow downloads off every 30 s); `http::Error::Idle`; `error`, `site`, `relink` follow. New crate: `bytes` (was in the tree). +- `Config.limiter` (keep a clone) `.set(&Group::{Total, Queue(id), Host(host::key)}, Some(bytes per second))`: live, None or 0 is no limit. `manager.set_limits(settings.limits())` sets the total, so S020's automatic limiter must give `set_limits` its value or be a new group. +- A queue's limit comes from the store and is read whenever the manager chooses, so after editing a queue make it choose (`set_limits` does). A host's comes from its site rule, else its `HostProfile`, when a download of it starts: after an edit call `limiter.set` too. A download's and its priority: `Command::Edit`. +- Modes: `settings.mode`, `limits_of(mode)` to edit, `toggle_snail()`, then `set_limits`. Only this one: `Command::Edit` with `Priority::Only`, back with any other. +- Other protocols: `monitor.flow().take(n).await` before using up to n bytes read; don't drop what a stop leaves. Connections: `hosts.join(host)`, `member.open(wanted, weight, now)`, `member.wants(n, weight)`. +Not done: priorities change bytes only under a limit or through connections. A connection closed by a mode keeps the up to two chunks it has (≤ 800 kB at once, not charged). Uploads (none yet). Not tried on the real line. +Seen: boxes 1 to 6 were ticked together when their tests first passed. + ## S015 — Main window and list (2026-11-25) Done: `bridge`, `views::{main, list, rail, bar}`; the app opens store, engine (`Bus::System`) and settings log. Outside the plan's files: `lib.rs`, shots, `impl FromIterator> for Snapshot`. Choices: D-040 to D-042. Verified: `nice cargo test -j 2 -p medlar --test main` green (20, one with the real engine), all medlar tests, clippy; shots at 480, 900, 1600, 3440 px light and dark, hover, selected, empty, nothing found, failed; hidden release run: 3 real downloads done, a 404 with its fix, context menu, idle 0.2 % CPU over 5 s. 10,000 rows, release, CPU of the thread: scrolling 95 % 1.4 ms, with running downloads 1.8, when tasks change 3.6; the first frame of a list 16 ms, once.