From a031b5b9eb2ca06d57bbd389eac6d285990f5363 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Thu, 21 Nov 2019 14:28:09 -0800 Subject: [PATCH] improve the rate limiter when over the budget, this reduces to a trickle of 1 byte per appropriate sub-second interval. For example, if the limit is set to 100 bytes per second, we admit 1 byte every 10ms. Refs: https://github.com/wez/wezterm/issues/65 Refs: https://github.com/wez/wezterm/pull/67 --- src/mux/mod.rs | 49 +++++++++++++++++++++++++------------------------ src/ratelim.rs | 41 ++++++++++++++++++++--------------------- 2 files changed, 45 insertions(+), 45 deletions(-) diff --git a/src/mux/mod.rs b/src/mux/mod.rs index f3a438812..715f11bb3 100644 --- a/src/mux/mod.rs +++ b/src/mux/mod.rs @@ -66,33 +66,34 @@ fn read_from_tab_pty(config: Arc, tab_id: TabId, mut reader: Box { - for chunk in buf[..size].chunks(lim.capacity_per_second()) { - lim.blocking_admittance_check(chunk.len() as u32); - let data = chunk.to_vec(); - /* - match std::str::from_utf8(&data) { - Ok(s) => { - let chars: Vec = s.chars().map(|c| c as u32).collect(); - error!("read chars: {:x?}", chars); + let buf = &buf[..size]; + let mut pos = 0; + + while pos < size { + match lim.admit_check((size - pos) as u32) { + Ok(len) => { + let len = len as usize; + let data = buf[pos..pos + len].to_vec(); + pos += len; + Future::with_executor(executor(), move || { + let mux = Mux::get().unwrap(); + if let Some(tab) = mux.get_tab(tab_id) { + tab.advance_bytes( + &data, + &mut Host { + writer: &mut *tab.writer(), + }, + ); + mux.notify(MuxNotification::TabOutput(tab_id)); + } + Ok(()) + }); } - Err(e) => { - error!("couldn't convert to string: {:?}", e); + Err(delay) => { + log::trace!("RateLimiter: sleep for {:?}", delay); + std::thread::sleep(delay); } } - */ - Future::with_executor(executor(), move || { - let mux = Mux::get().unwrap(); - if let Some(tab) = mux.get_tab(tab_id) { - tab.advance_bytes( - &data, - &mut Host { - writer: &mut *tab.writer(), - }, - ); - mux.notify(MuxNotification::TabOutput(tab_id)); - } - Ok(()) - }); } } } diff --git a/src/ratelim.rs b/src/ratelim.rs index df1ddba96..7a5dfc995 100644 --- a/src/ratelim.rs +++ b/src/ratelim.rs @@ -1,9 +1,9 @@ use ratelimit_meter::algorithms::NonConformance; use ratelimit_meter::{DirectRateLimiter, LeakyBucket, NegativeMultiDecision}; +use std::time::{Duration, Instant}; pub struct RateLimiter { lim: DirectRateLimiter, - capacity_per_second: u32, } impl RateLimiter { @@ -13,7 +13,6 @@ impl RateLimiter { std::num::NonZeroU32::new(capacity_per_second) .expect("RateLimiter capacity to be non-zero"), ), - capacity_per_second, } } @@ -21,28 +20,28 @@ impl RateLimiter { self.lim.check_n(amount).is_ok() } - pub fn capacity_per_second(&self) -> usize { - self.capacity_per_second as usize - } - - pub fn blocking_admittance_check(&mut self, amount: u32) { + /// Attempt to admit up to `amount` number of items. + /// On success, returns the amount that were actually admitted, + /// which may be less than the requested amount. + /// If no items can be admitted immediately, returns a duration + /// of time after which the caller should retry to admit. + pub fn admit_check(&mut self, mut amount: u32) -> Result { loop { match self.lim.check_n(amount) { - Ok(_) => return, - Err(NegativeMultiDecision::BatchNonConforming(_, over)) => { - let duration = over.wait_time_from(std::time::Instant::now()); - log::trace!("RateLimiter: sleep for {:?}", duration); - std::thread::sleep(duration); + Ok(_) => return Ok(amount), + Err(NegativeMultiDecision::BatchNonConforming(_, over)) if amount == 1 => { + return Err(over.wait_time_from(Instant::now())); } - Err(NegativeMultiDecision::InsufficientCapacity(n)) => { - panic!( - "Programmer Error: you need to chunk the input \ - because you're trying to admit {} items at once \ - and this exceeds the maximum limit of {} per second", - n, self.capacity_per_second - ); - } - } + _ => {} + }; + + // try again with half the size. + // This isn't a perfectly efficient approach, especially + // with a very large input buffer size, but it is reasonable; + // we use a 32k buffer which means that in the worst case + // (where the buffer is 100% full), we'll take ~15 iterations + // to reach a decision of a single byte or a sleep delay. + amount = amount / 2; } } }