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
This commit is contained in:
1 parent
a26a94b5bb
commit
a031b5b9eb
2 files changed
+45
-45
No files matched your search
+25
-24
@@ -66,33 +66,34 @@ fn read_from_tab_pty(config: Arc<Config>, tab_id: TabId, mut reader: Box<dyn std
|
||||
break;
|
||||
}
|
||||
Ok(size) => {
|
||||
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<u32> = 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(())
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+20
-21
@@ -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<LeakyBucket>,
|
||||
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<u32, Duration> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user