1use std::{
4 sync::{Arc, Mutex},
5 time::Duration,
6};
7
8use tokio::time::Instant;
9
10#[doc(hidden)]
15#[derive(Debug, Clone, Default)]
16pub struct SharedCell<T>(Arc<Mutex<T>>);
17
18impl<T: Clone> SharedCell<T> {
19 pub fn update(&self, f: impl FnOnce(&mut T)) {
21 f(&mut self.0.lock().expect("poisoned"));
22 }
23
24 #[must_use]
26 pub fn get(&self) -> T {
27 self.0.lock().expect("poisoned").clone()
28 }
29}
30
31const RATE_WINDOW: Duration = Duration::from_secs(1);
36
37#[derive(Debug)]
42pub struct RateMeter {
43 window: Duration,
44 started: Instant,
45 events: u32,
46 amount: u64,
47}
48
49impl Default for RateMeter {
50 fn default() -> Self {
51 Self::over(RATE_WINDOW)
52 }
53}
54
55impl RateMeter {
56 #[must_use]
58 pub fn over(window: Duration) -> Self {
59 Self::starting(window, Instant::now())
60 }
61
62 fn starting(window: Duration, started: Instant) -> Self {
64 Self {
65 window,
66 started,
67 events: 0,
68 amount: 0,
69 }
70 }
71
72 #[must_use]
77 pub fn tick(&mut self, amount: u64) -> Option<Rates> {
78 self.tick_at(amount, Instant::now())
79 }
80
81 fn tick_at(&mut self, amount: u64, now: Instant) -> Option<Rates> {
83 let elapsed = now.duration_since(self.started);
84 if elapsed >= self.window * Rates::CURRENT_FOR {
85 *self = Self::starting(self.window, now);
90 return None;
91 }
92 self.events += 1;
93 self.amount += amount;
94 if elapsed < self.window {
95 return None;
96 }
97 let seconds = elapsed.as_secs_f64();
98 let rates = Rates {
99 events: f64::from(self.events) / seconds,
100 amount: self.amount as f64 / seconds,
101 at: now,
102 window: self.window,
103 };
104 *self = Self::starting(self.window, now);
107 Some(rates)
108 }
109}
110
111#[derive(Debug, Clone, Copy, PartialEq)]
113pub struct Rates {
114 pub events: f64,
116 pub amount: f64,
118 at: Instant,
120 window: Duration,
122}
123
124impl Rates {
125 const CURRENT_FOR: u32 = 2;
133
134 #[must_use]
139 pub fn is_current(&self) -> bool {
140 self.is_current_at(Instant::now())
141 }
142
143 fn is_current_at(&self, now: Instant) -> bool {
145 now.duration_since(self.at) < self.window * Self::CURRENT_FOR
146 }
147}
148
149#[derive(Debug, Default)]
151pub struct Smoothed(Option<f64>);
152
153impl Smoothed {
154 const ALPHA: f64 = 0.2;
156
157 pub fn record(&mut self, sample: Duration) -> Duration {
159 let value = sample.as_secs_f64();
160 let smoothed = match self.0 {
161 Some(previous) => Self::ALPHA * value + (1.0 - Self::ALPHA) * previous,
162 None => value,
163 };
164 self.0 = Some(smoothed);
165 Duration::from_secs_f64(smoothed)
166 }
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172
173 fn drive(offset: impl Fn(u32) -> Duration) -> f64 {
175 let start = Instant::now();
176 let mut meter = RateMeter::starting(RATE_WINDOW, start);
177 (0..40)
178 .find_map(|event| meter.tick_at(0, start + offset(event)))
179 .expect("the offsets span the window")
180 .events
181 }
182
183 #[test]
185 fn a_burst_reads_the_same_as_an_even_stream() {
186 let bursty = drive(|event| Duration::from_millis(350) * (event / 10));
187 let even = drive(|event| Duration::from_millis(35) * event);
188 assert!((bursty - even).abs() < 0.5, "{bursty} against {even}");
189 assert!((28.0..32.0).contains(&bursty), "{bursty}");
190 }
191
192 #[test]
193 fn the_amount_is_a_rate_too() {
194 let start = Instant::now();
195 let mut meter = RateMeter::starting(RATE_WINDOW, start);
196 for tick in 0..30u32 {
198 let rate = meter.tick_at(2_500, start + Duration::from_millis(33) * tick);
199 assert_eq!(rate, None, "the window closed early at event {tick}");
200 }
201 let bytes = meter
203 .tick_at(2_500, start + Duration::from_secs(1))
204 .expect("a second has passed")
205 .amount;
206 assert!((77_000.0..78_000.0).contains(&bytes), "{bytes}");
207 }
208
209 #[test]
211 fn rates_go_stale_once_events_stop() {
212 let start = Instant::now();
213 let mut meter = RateMeter::starting(RATE_WINDOW, start);
214 let mut last = None;
215 for event in 1..=60u32 {
217 let now = start + Duration::from_millis(50) * event;
218 if let Some(rates) = meter.tick_at(0, now) {
219 last = Some(rates);
220 }
221 let rates = last.filter(|rates| rates.is_current_at(now));
222 if now >= start + RATE_WINDOW {
223 let rates = rates.expect("a running stream has a rate");
224 assert!((19.0..21.0).contains(&rates.events), "{}", rates.events);
225 }
226 }
227 let rates = last.expect("the stream closed windows");
228 let stopped = start + Duration::from_secs(3);
229 assert!(rates.is_current_at(stopped + RATE_WINDOW));
230 assert!(!rates.is_current_at(stopped + RATE_WINDOW * 2));
231
232 let resumed = stopped + Duration::from_secs(5);
235 let rates = (0..=40u32)
236 .find_map(|event| meter.tick_at(0, resumed + Duration::from_millis(50) * event))
237 .expect("the resumed stream closes a window");
238 assert_eq!(rates.at, resumed + RATE_WINDOW);
239 assert!((19.0..21.0).contains(&rates.events), "{}", rates.events);
240 }
241
242 #[test]
243 fn smoothing_starts_at_the_first_sample() {
244 let mut smoothed = Smoothed::default();
245 assert_eq!(
246 smoothed.record(Duration::from_millis(10)),
247 Duration::from_millis(10)
248 );
249 let next = smoothed.record(Duration::from_millis(20));
250 assert!(next > Duration::from_millis(10) && next < Duration::from_millis(20));
251 }
252}