478 lines
18 KiB
Rust
478 lines
18 KiB
Rust
//! Connections to each host: how many are open, how many may be, and what hosts tolerated before.
|
|
|
|
use crate::model::{HostProfile, Time};
|
|
use crate::store::{self, Store};
|
|
use std::collections::{BTreeMap, HashMap};
|
|
use std::sync::{Arc, Mutex};
|
|
use std::time::{Duration, Instant};
|
|
use tokio::sync::watch;
|
|
use url::Url;
|
|
|
|
/// What a host tolerated is forgotten after this many milliseconds.
|
|
const REMEMBERED: Time = 7 * 24 * 3600 * 1000;
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
|
pub struct Caps {
|
|
pub total: u32,
|
|
pub per_host: u32,
|
|
/// New requests to one host: this many at once, then so many a second.
|
|
pub burst: u32,
|
|
pub per_second: f64,
|
|
}
|
|
|
|
impl Default for Caps {
|
|
fn default() -> Self {
|
|
Caps { total: 64, per_host: 16, burst: 16, per_second: 4.0 }
|
|
}
|
|
}
|
|
|
|
/// A host that turned connections away may count one that was closed for this long.
|
|
const LINGER: Duration = Duration::from_millis(300);
|
|
|
|
/// Shared by all downloads.
|
|
#[derive(Debug)]
|
|
pub struct Hosts {
|
|
inner: Mutex<Inner>,
|
|
changed: watch::Sender<()>,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
struct Inner {
|
|
caps: Caps,
|
|
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,
|
|
}
|
|
|
|
#[derive(Debug, Default)]
|
|
struct Host {
|
|
/// Set by the user.
|
|
cap: Option<u32>,
|
|
/// What it refused to go beyond, and until when that counts.
|
|
ceiling: Option<(u32, Instant)>,
|
|
rest_until: Option<Instant>,
|
|
/// When connections ended, while there is a ceiling.
|
|
closed: Vec<Instant>,
|
|
/// Requests in the bucket, as of then.
|
|
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 {
|
|
hosts: Arc<Hosts>,
|
|
id: u64,
|
|
}
|
|
|
|
impl Permit {
|
|
/// The caps went down: end this connection.
|
|
pub fn revoked(&self) -> bool {
|
|
self.hosts.inner.lock().unwrap().open[&self.id].revoked
|
|
}
|
|
}
|
|
|
|
impl Drop for Permit {
|
|
fn drop(&mut self) {
|
|
self.hosts.inner.lock().unwrap().close(self.id, Instant::now());
|
|
self.hosts.changed.send_replace(());
|
|
}
|
|
}
|
|
|
|
impl Inner {
|
|
fn count(&self, host: &str) -> u32 {
|
|
self.open.values().filter(|o| o.host == host).count() as u32
|
|
}
|
|
|
|
fn cap(&self, host: &str, now: Instant) -> u32 {
|
|
let known = self.hosts.get(host);
|
|
let own = known.and_then(|h| h.cap).unwrap_or(self.caps.per_host);
|
|
let ceiling = known.and_then(|h| h.ceiling).filter(|(_, until)| now < *until);
|
|
own.min(ceiling.map_or(u32::MAX, |c| c.0)).max(1)
|
|
}
|
|
|
|
fn close(&mut self, id: u64, now: Instant) {
|
|
let Some(o) = self.open.remove(&id) else { return };
|
|
if let Some(h) = self.hosts.get_mut(&o.host)
|
|
&& h.ceiling.is_some_and(|(_, until)| now < until)
|
|
{
|
|
h.closed.push(now);
|
|
}
|
|
}
|
|
|
|
/// 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();
|
|
let (total_cap, mut total, mut each) = (self.caps.total.max(1), 0, HashMap::new());
|
|
for o in self.open.values_mut().filter(|o| !o.revoked) {
|
|
let n: &mut u32 = each.entry(o.host.clone()).or_default();
|
|
o.revoked = total >= total_cap || *n >= caps[&o.host];
|
|
if !o.revoked {
|
|
total += 1;
|
|
*n += 1;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Hosts {
|
|
pub fn new(caps: Caps) -> Arc<Hosts> {
|
|
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(()) })
|
|
}
|
|
|
|
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;
|
|
}
|
|
let h = i.hosts.entry(host.into()).or_default();
|
|
h.closed.retain(|at| now < *at + LINGER);
|
|
if count + h.closed.len() as u32 >= cap {
|
|
return None;
|
|
}
|
|
if h.rest_until.is_some_and(|until| now < until) {
|
|
return None;
|
|
}
|
|
let burst = f64::from(caps.burst.max(1));
|
|
let (had, then) = h.bucket.unwrap_or((burst, now));
|
|
let has = (had + now.saturating_duration_since(then).as_secs_f64() * caps.per_second).min(burst);
|
|
if has < 1.0 {
|
|
return None;
|
|
}
|
|
h.bucket = Some((has - 1.0, now));
|
|
let id = i.next;
|
|
i.next += 1;
|
|
i.open.insert(id, Open { host: host.into(), member, revoked: false });
|
|
drop(i);
|
|
Some(Permit { hosts: self.clone(), id })
|
|
}
|
|
|
|
pub fn caps(&self) -> Caps {
|
|
self.inner.lock().unwrap().caps
|
|
}
|
|
|
|
pub fn set_caps(&self, caps: Caps) {
|
|
self.change(|i| i.caps = caps);
|
|
}
|
|
|
|
/// The user's cap for one host; None for the general one.
|
|
pub fn set_host_cap(&self, host: &str, cap: Option<u32>) {
|
|
self.change(|i| i.hosts.entry(host.into()).or_default().cap = cap);
|
|
}
|
|
|
|
/// The host turned one connection away while others work. Counts for all downloads, until then.
|
|
pub fn refused(&self, host: &str, until: Instant) {
|
|
let mut i = self.inner.lock().unwrap();
|
|
let ceiling = i.count(host).saturating_sub(1).max(1);
|
|
i.hosts.entry(host.into()).or_default().ceiling = Some((ceiling, until));
|
|
}
|
|
|
|
/// The host asked for a pause.
|
|
pub fn rest(&self, host: &str, until: Instant) {
|
|
let mut i = self.inner.lock().unwrap();
|
|
let rest = &mut i.hosts.entry(host.into()).or_default().rest_until;
|
|
*rest = (*rest).max(Some(until));
|
|
}
|
|
|
|
pub fn open_to(&self, host: &str) -> u32 {
|
|
self.inner.lock().unwrap().count(host)
|
|
}
|
|
|
|
/// Tells when a place may have become free or a connection must end.
|
|
pub(crate) fn watch(&self) -> watch::Receiver<()> {
|
|
self.changed.subscribe()
|
|
}
|
|
|
|
fn change(&self, what: impl FnOnce(&mut Inner)) {
|
|
let mut i = self.inner.lock().unwrap();
|
|
what(&mut i);
|
|
let now = Instant::now();
|
|
i.shared = None;
|
|
i.share(now);
|
|
i.revoke(now);
|
|
drop(i);
|
|
self.changed.send_replace(());
|
|
}
|
|
}
|
|
|
|
/// Name and port: what counts as one host.
|
|
pub fn key(url: &Url) -> String {
|
|
let name = url.host_str().unwrap_or_default().to_ascii_lowercase();
|
|
url.port().map_or(name.clone(), |port| format!("{name}:{port}"))
|
|
}
|
|
|
|
/// What the host tolerated, unless that is too long ago.
|
|
pub fn tolerated(profile: &HostProfile, now: Time) -> Option<u32> {
|
|
profile.good_connections.filter(|n| *n > 0 && now.saturating_sub(profile.seen_at) < REMEMBERED)
|
|
}
|
|
|
|
/// Blocks.
|
|
pub fn remember(store: &Store, host: &str, connections: u32, now: Time) -> store::Result<()> {
|
|
let known = store.host(host)?.unwrap_or_default();
|
|
store.save_host(HostProfile { host: host.into(), good_connections: Some(connections), seen_at: now, ..known })
|
|
}
|
|
|
|
#[cfg(test)]
|
|
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]
|
|
fn caps_hold_and_places_come_back() {
|
|
let (hosts, now) = (Hosts::new(FREE), Instant::now());
|
|
let mut a: Vec<_> = (0..4).filter_map(|_| hosts.open("a", now)).collect();
|
|
assert_eq!(a.len(), 3);
|
|
let b: Vec<_> = (0..4).filter_map(|_| hosts.open("b", now)).collect();
|
|
assert_eq!(b.len(), 2, "five in total");
|
|
a.pop();
|
|
assert!(hosts.open("a", now).is_some());
|
|
}
|
|
|
|
#[test]
|
|
fn lower_caps_revoke_the_newest() {
|
|
let (hosts, now) = (Hosts::new(FREE), Instant::now());
|
|
let a: Vec<_> = (0..3).filter_map(|_| hosts.open("a", now)).collect();
|
|
let b: Vec<_> = (0..2).filter_map(|_| hosts.open("b", now)).collect();
|
|
let revoked = |p: &[Permit]| p.iter().map(Permit::revoked).collect::<Vec<_>>();
|
|
hosts.set_host_cap("a", Some(2));
|
|
assert_eq!((revoked(&a), revoked(&b)), (vec![false, false, true], vec![false, false]));
|
|
hosts.set_caps(Caps { total: 3, ..FREE });
|
|
assert_eq!((revoked(&a), revoked(&b)), (vec![false, false, true], vec![false, true]));
|
|
assert!(hosts.open("c", now).is_none());
|
|
drop((a, b));
|
|
hosts.set_caps(FREE);
|
|
let a: Vec<_> = (0..3).filter_map(|_| hosts.open("a", now)).collect();
|
|
assert_eq!(a.len(), 2);
|
|
}
|
|
|
|
#[test]
|
|
fn refusals_rests_and_bursts() {
|
|
let (hosts, now) = (Hosts::new(FREE), Instant::now());
|
|
let one = hosts.open("a", now);
|
|
let two = hosts.open("a", now);
|
|
let later = now + Duration::from_secs(10);
|
|
hosts.refused("a", later);
|
|
drop(two);
|
|
assert!(hosts.open("a", now).is_none(), "one is what it stands");
|
|
drop(one);
|
|
assert!(hosts.open("a", now).is_none(), "it may not have noticed the end");
|
|
let one = hosts.open("a", Instant::now() + LINGER);
|
|
assert!(one.is_some());
|
|
assert!(hosts.open("a", later).is_some());
|
|
hosts.rest("b", later);
|
|
hosts.rest("b", now);
|
|
assert!(hosts.open("b", now).is_none() && hosts.open("b", later).is_some());
|
|
drop(one);
|
|
|
|
hosts.set_caps(Caps { burst: 2, per_second: 2.0, ..FREE });
|
|
let open = |at| (0..5).filter(|_| hosts.open("c", at).is_some()).count();
|
|
assert_eq!((open(now), open(now), open(now + Duration::from_millis(500)), open(later)), (2, 0, 1, 2));
|
|
}
|
|
|
|
#[test]
|
|
fn memory_expires() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let store = Store::open(&dir.path().join("m.db")).unwrap();
|
|
let known = HostProfile { host: "h".into(), max_connections: Some(9), seen_at: 1, ..HostProfile::default() };
|
|
store.save_host(known).unwrap();
|
|
remember(&store, "h", 6, 1000).unwrap();
|
|
let p = store.host("h").unwrap().unwrap();
|
|
assert_eq!((p.max_connections, tolerated(&p, 2000)), (Some(9), Some(6)));
|
|
assert_eq!(tolerated(&p, 1000 + REMEMBERED), None);
|
|
assert_eq!(tolerated(&HostProfile::default(), 0), None);
|
|
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);
|
|
}
|
|
}
|