The request limits: a sliding window of an hour and one of a minute, each counting the
requests it has seen, as RateLimit-Reset is described ("the time when the oldest request
counted expires") by the adapter's reading of the API description. Rejected requests are not counted.
5use std::collections::VecDeque;
What a 429 reports: the window that was full, its limit, and the UNIX second it frees a slot.
The UNIX second the oldest counted request leaves the window (now, for an empty one).
34impl Limits {
Count one request, or say which window refuses it.
36 pub fn take(&mut self, now_ms: u64, hour: u32, minute: u32) -> Result<(), Refused> { 37 prune(&mut self.hour, now_ms, HOUR_MS); 38 prune(&mut self.minute, now_ms, MINUTE_MS); 39 if self.minute.len() >= minute as usize { 40 return Err(Refused { limit: minute, reset_s: reset_s(&self.minute, now_ms, MINUTE_MS) }); 41 } 42 if self.hour.len() >= hour as usize { 43 return Err(Refused { limit: hour, reset_s: reset_s(&self.hour, now_ms, HOUR_MS) }); 44 } 45 self.hour.push_back(now_ms); 46 self.minute.push_back(now_ms); 47 Ok(()) 48 }
RateLimit-Limit, -Remaining and -Reset of the hourly window, which is the one the headers report.
58#[cfg(test)] 59mod tests { 60 use super::*; 61 62 #[test] 63 fn the_minute_window_refuses_first_and_frees_a_slot_a_minute_after_the_oldest() { 64 let mut l = Limits::default(); 65 for i in 0..3 { 66 assert_eq!(l.take(1_000 + i, 100, 3), Ok(())); 67 } 68 assert_eq!(l.take(5_000, 100, 3), Err(Refused { limit: 3, reset_s: 61 })); 69 assert_eq!(l.take(61_000, 100, 3), Ok(())); 70 } 71 72 #[test] 73 fn the_hour_window_counts_and_reports_what_is_left() { 74 let mut l = Limits::default(); 75 assert_eq!(l.headers(0, 5), (5, 5, 0)); 76 l.take(0, 5, 100).unwrap(); 77 l.take(10_000, 5, 100).unwrap(); 78 assert_eq!(l.headers(10_000, 5), (5, 3, 3600)); 79 for t in [20_000, 30_000, 40_000] { 80 l.take(t, 5, 100).unwrap(); 81 } 82 assert_eq!(l.take(50_000, 5, 100), Err(Refused { limit: 5, reset_s: 3600 })); 83 assert_eq!(l.headers(3_600_000, 5).1, 1, "the oldest left the window"); 84 } 85}