S019: limiter, modes and priority shares
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
c0e4a365f5
commit
376ba92995
24 changed files with 1443 additions and 58 deletions
1
Cargo.lock
generated
1
Cargo.lock
generated
|
|
@ -2223,6 +2223,7 @@ name = "medlar-core"
|
|||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"dirs",
|
||||
"fastrand",
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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());
|
||||
|
|
|
|||
|
|
@ -42,11 +42,27 @@ struct Inner {
|
|||
next: u64,
|
||||
open: BTreeMap<u64, Open>,
|
||||
hosts: HashMap<String, Host>,
|
||||
members: BTreeMap<u64, Want>,
|
||||
/// The cap of each host when the places were shared out. None: something changed since.
|
||||
shared: Option<HashMap<String, u32>>,
|
||||
}
|
||||
|
||||
/// 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<u64>,
|
||||
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<Hosts>,
|
||||
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<Permit> {
|
||||
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<String, u32> = 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<String>, 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<u64> = 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<String, u32> = 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<Hosts> {
|
||||
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<Hosts>, host: &str, now: Instant) -> Option<Permit> {
|
||||
pub fn join(self: &Arc<Hosts>, 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<Hosts>, host: &str, member: Option<u64>, now: Instant) -> Option<Permit> {
|
||||
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<Hosts>, host: &str, now: Instant) -> Option<Permit> {
|
||||
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::<Vec<_>>();
|
||||
let stay = |p: &mut Vec<Permit>| {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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<Response>, mut stop: Stop) -> Result<()> {
|
||||
pub async fn fetch(link: &Link, part: &LivePart, file: &PartialFile, body: Option<Response>, 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<Response>,
|
||||
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<u64> {
|
|||
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<Option<Bytes>> {
|
||||
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<u8>) -> Result<Vec<u8>> {
|
||||
|
|
@ -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<bool> {
|
||||
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<bool> {
|
||||
pub(crate) async fn same_body(client: &Client, mut response: Response, known: &[u8], stop: &mut Stop) -> Result<bool> {
|
||||
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) });
|
||||
|
|
|
|||
|
|
@ -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<reqwest::Error>),
|
||||
/// 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<T, E: Into<Error>>(&self, what: impl Future<Output = std::result::Result<T, E>>) -> Result<T> {
|
||||
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> {
|
||||
client_with(options, &trust(options)?, None)
|
||||
}
|
||||
|
|
@ -117,7 +141,7 @@ pub(crate) fn client_with(options: &ClientOptions, trust: &Arc<Trust>, 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<Trust>, 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<u64> {
|
||||
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),
|
||||
|
|
|
|||
|
|
@ -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<u32>,
|
||||
events: broadcast::Sender<PartEvent>,
|
||||
state: Mutex<(Snapshot, Vec<Arc<LivePart>>)>,
|
||||
flow: Arc<Flow>,
|
||||
}
|
||||
|
||||
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<Flow> {
|
||||
&self.flow
|
||||
}
|
||||
|
||||
/// Takes effect at once, up and down.
|
||||
|
|
|
|||
|
|
@ -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<Response>,
|
||||
host: String,
|
||||
hosts: Arc<Hosts>,
|
||||
member: Member,
|
||||
/// Its speed had a limit, so it says nothing about the host.
|
||||
limited: bool,
|
||||
max_parts: Option<u32>,
|
||||
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<Arc<LivePart>>, Option<u32>) {
|
||||
(self.live(), self.adapt.learned().filter(|_| self.link.ranges))
|
||||
(self.live(), self.adapt.learned().filter(|_| self.link.ranges && !self.limited))
|
||||
}
|
||||
|
||||
fn live(&self) -> Vec<Arc<LivePart>> {
|
||||
|
|
@ -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<View> = 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) {
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
241
crates/core/src/limit/mod.rs
Normal file
241
crates/core/src/limit/mod.rs
Normal file
|
|
@ -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<State>,
|
||||
/// There is something to do before `State::wake`.
|
||||
sooner: Notify,
|
||||
}
|
||||
|
||||
struct State {
|
||||
shares: Shares<oneshot::Sender<u64>>,
|
||||
/// What each flow reads without the lock.
|
||||
flows: HashMap<FlowId, Arc<View>>,
|
||||
/// 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<Instant>,
|
||||
}
|
||||
|
||||
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<Limiter> {
|
||||
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<u64>) {
|
||||
self.change(|s, now| s.set(group, rate, now));
|
||||
}
|
||||
|
||||
pub fn flow(self: &Arc<Limiter>, 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<oneshot::Sender<u64>>, 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<Instant> {
|
||||
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<Limiter>,
|
||||
id: FlowId,
|
||||
view: Arc<View>,
|
||||
}
|
||||
|
||||
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<u64>) {
|
||||
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<u64>) {
|
||||
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<Limiter>) {
|
||||
struct Driving(Arc<Limiter>, 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;
|
||||
}
|
||||
228
crates/core/src/limit/shares.rs
Normal file
228
crates/core/src/limit/shares.rs
Normal file
|
|
@ -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<f64>,
|
||||
/// Below zero when the last one took more than was there.
|
||||
tokens: f64,
|
||||
at: Option<Instant>,
|
||||
}
|
||||
|
||||
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<u64>, 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<T> {
|
||||
who: T,
|
||||
most: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Flow<T> {
|
||||
weight: f64,
|
||||
own: Bucket,
|
||||
queue: Option<usize>,
|
||||
host: Option<usize>,
|
||||
asks: VecDeque<Ask<T>>,
|
||||
/// 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<T> {
|
||||
/// The first is for everything.
|
||||
buckets: Vec<Bucket>,
|
||||
groups: HashMap<Group, usize>,
|
||||
flows: BTreeMap<FlowId, Flow<T>>,
|
||||
next: FlowId,
|
||||
/// Where the one furthest ahead stands.
|
||||
stand: f64,
|
||||
}
|
||||
|
||||
impl<T> Default for Shares<T> {
|
||||
fn default() -> Shares<T> {
|
||||
let groups = HashMap::from([(Group::Total, 0)]);
|
||||
Shares { buckets: vec![Bucket::default()], groups, flows: BTreeMap::new(), next: 0, stand: 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Shares<T> {
|
||||
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<u64>, 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<u64>, 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<f64> {
|
||||
let flow = &self.flows[&id];
|
||||
self.path(flow).filter_map(|b| b.rate).min_by(f64::total_cmp)
|
||||
}
|
||||
|
||||
pub fn ids(&self) -> impl Iterator<Item = FlowId> {
|
||||
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<Duration> {
|
||||
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<T> {
|
||||
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<T>) -> impl Iterator<Item = &'a Bucket> {
|
||||
let groups = [Some(0), flow.queue, flow.host];
|
||||
groups.into_iter().flatten().map(|i| &self.buckets[i]).chain([&flow.own])
|
||||
}
|
||||
}
|
||||
|
|
@ -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<Answer>)>,
|
||||
/// Counts up with each start; 0 for never.
|
||||
forced: u64,
|
||||
/// See `Candidate`.
|
||||
interrupted: u64,
|
||||
size: Option<u64>,
|
||||
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<TaskId>)>,
|
||||
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<QueueId, f64> = 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<TaskId> = 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();
|
||||
|
|
|
|||
|
|
@ -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<Arc<Sites>>,
|
||||
pub options: Options,
|
||||
pub limits: Limits,
|
||||
pub limiter: Arc<Limiter>,
|
||||
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));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<Candidate>, max: usize, mut host_cap: impl FnMut(&str) -> u32) -> Vec<TaskId> {
|
||||
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<TaskId> {
|
||||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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<PathBuf> {
|
||||
|
|
|
|||
|
|
@ -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());
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue