//! 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, 8 * 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}"); }