1use super::threshold::{AdaptiveThreshold, ThresholdTimeBase};
4use std::time::{Duration, Instant};
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
8pub enum Usage {
9 #[default]
11 Normal,
12 Over,
14 Under,
16}
17
18pub const DEFAULT_OVERUSE_TIME: Duration = Duration::from_millis(10);
23
24#[derive(Debug, Clone, Copy)]
36pub struct OveruseDetector {
37 threshold: AdaptiveThreshold,
38 overuse_time: Duration,
39 outside_since: Option<Instant>,
41 consecutive: u32,
43 previous_estimate_ms: f64,
45 usage: Usage,
46 time_base: ThresholdTimeBase,
47 last_arrival: Option<Duration>,
49}
50
51impl Default for OveruseDetector {
52 fn default() -> Self {
53 Self {
54 threshold: AdaptiveThreshold::new(),
55 overuse_time: DEFAULT_OVERUSE_TIME,
56 outside_since: None,
57 consecutive: 0,
58 previous_estimate_ms: 0.0,
59 usage: Usage::Normal,
60 time_base: ThresholdTimeBase::default(),
61 last_arrival: None,
62 }
63 }
64}
65
66impl OveruseDetector {
67 pub fn new() -> Self {
69 Self::default()
70 }
71
72 pub fn with_threshold_time_base(mut self, time_base: ThresholdTimeBase) -> Self {
74 self.time_base = time_base;
75 self
76 }
77
78 pub fn update_with_arrival(
81 &mut self,
82 now: Instant,
83 arrival: Duration,
84 estimate_ms: f64,
85 ) -> Usage {
86 let usage = self.classify(now, estimate_ms);
87 match self.time_base {
88 ThresholdTimeBase::Departure => {
89 self.threshold.update(now, estimate_ms);
90 }
91 ThresholdTimeBase::Arrival | ThresholdTimeBase::ArrivalCapped => {
92 if let Some(last) = self.last_arrival {
93 let step = arrival.saturating_sub(last);
94 let step = if self.time_base == ThresholdTimeBase::ArrivalCapped {
95 step.min(crate::gcc::threshold::MAX_STEP)
96 } else {
97 step
98 };
99 self.threshold.update_over(step, estimate_ms);
100 }
101 self.last_arrival = Some(arrival);
102 }
103 }
104 usage
105 }
106
107 pub fn usage(&self) -> Usage {
109 self.usage
110 }
111
112 pub fn threshold_ms(&self) -> f64 {
114 self.threshold.value_ms()
115 }
116
117 pub fn update(&mut self, now: Instant, estimate_ms: f64) -> Usage {
121 self.classify(now, estimate_ms);
122 self.threshold.update(now, estimate_ms);
126 self.usage
127 }
128
129 fn classify(&mut self, now: Instant, estimate_ms: f64) -> Usage {
130 let threshold_ms = self.threshold.value_ms();
131
132 self.usage = if estimate_ms > threshold_ms {
133 let since = *self.outside_since.get_or_insert(now);
136 self.consecutive += 1;
137
138 let long_enough = now.saturating_duration_since(since) >= self.overuse_time;
139 let still_growing = estimate_ms >= self.previous_estimate_ms;
140
141 if long_enough && still_growing && self.consecutive > 1 {
142 Usage::Over
143 } else {
144 self.usage
146 }
147 } else if estimate_ms < -threshold_ms {
148 self.outside_since = None;
149 self.consecutive = 0;
150 Usage::Under
151 } else {
152 self.outside_since = None;
153 self.consecutive = 0;
154 Usage::Normal
155 };
156
157 self.previous_estimate_ms = estimate_ms;
158 self.usage
159 }
160}
161
162#[cfg(test)]
163mod tests {
164 use super::*;
165
166 #[test]
168 fn a_quiet_path_reads_normal() {
169 let epoch = Instant::now();
170 let mut detector = OveruseDetector::new();
171
172 for step in 0..100u64 {
173 let usage = detector.update(epoch + Duration::from_millis(step * 20), 1.0);
174 assert_eq!(Usage::Normal, usage, "at step {step}");
175 }
176 }
177
178 #[test]
180 fn one_spike_is_not_overuse() {
181 let epoch = Instant::now();
182 let mut detector = OveruseDetector::new();
183
184 detector.update(epoch, 0.0);
185 let usage = detector.update(epoch + Duration::from_millis(20), 40.0);
186
187 assert_eq!(
188 Usage::Normal,
189 usage,
190 "a lone reading outside the threshold is noise, not congestion"
191 );
192 }
193
194 #[test]
196 fn a_sustained_growing_trend_is_overuse() {
197 let epoch = Instant::now();
198 let mut detector = OveruseDetector::new();
199
200 let mut usage = Usage::Normal;
201 for step in 0..10u64 {
202 usage = detector.update(
204 epoch + Duration::from_millis(step * 20),
205 20.0 + step as f64 * 2.0,
206 );
207 }
208
209 assert_eq!(
210 Usage::Over,
211 usage,
212 "a queue that keeps growing must eventually be declared"
213 );
214 }
215
216 #[test]
219 fn recovery_is_not_debounced() {
220 let epoch = Instant::now();
221 let mut detector = OveruseDetector::new();
222
223 let mut at = epoch;
224 for step in 0..10u64 {
225 at = epoch + Duration::from_millis(step * 20);
226 detector.update(at, 20.0 + step as f64 * 2.0);
227 }
228 assert_eq!(Usage::Over, detector.usage());
229
230 let usage = detector.update(at + Duration::from_millis(20), 0.0);
231 assert_eq!(
232 Usage::Normal,
233 usage,
234 "back inside the threshold must be believed at once"
235 );
236 }
237
238 #[test]
240 fn a_draining_queue_reads_under() {
241 let epoch = Instant::now();
242 let mut detector = OveruseDetector::new();
243
244 let usage = detector.update(epoch, -40.0);
245 assert_eq!(Usage::Under, usage);
246 }
247
248 #[test]
251 fn a_high_but_flat_trend_does_not_re_declare_overuse() {
252 let epoch = Instant::now();
253 let mut detector = OveruseDetector::new();
254
255 let mut at = epoch;
257 for step in 0..10u64 {
258 at = epoch + Duration::from_millis(step * 20);
259 detector.update(at, 20.0 + step as f64 * 2.0);
260 }
261 assert_eq!(Usage::Over, detector.usage());
262
263 for step in 0..200u64 {
265 at += Duration::from_millis(20);
266 detector.update(at, 1.0);
267 let _ = step;
268 }
269 assert_eq!(
270 Usage::Normal,
271 detector.usage(),
272 "a settled path must return to normal"
273 );
274 }
275
276 #[test]
280 fn a_trend_above_the_threshold_but_falling_is_not_overuse() {
281 let epoch = Instant::now();
282 let mut detector = OveruseDetector::new();
283 for step in 0..10u64 {
284 let usage =
285 detector.update(epoch + Duration::from_millis(step * 20), 40.0 - step as f64);
286 assert_eq!(Usage::Normal, usage, "at step {step}");
287 }
288 }
289
290 #[test]
293 fn overuse_needs_ten_milliseconds_outside_the_threshold() {
294 let epoch = Instant::now();
295 let mut detector = OveruseDetector::new();
296 assert_eq!(Usage::Normal, detector.update(epoch, 20.0));
297 assert_eq!(
298 Usage::Normal,
299 detector.update(epoch + Duration::from_millis(5), 21.0)
300 );
301 assert_eq!(
302 Usage::Normal,
303 detector.update(epoch + Duration::from_millis(9), 22.0)
304 );
305 assert_eq!(
306 Usage::Over,
307 detector.update(epoch + Duration::from_millis(10), 23.0)
308 );
309 }
310
311 #[test]
315 fn the_capped_arrival_time_base_steps_at_most_100_ms() {
316 let now = Instant::now();
317 let after = |time_base: ThresholdTimeBase, gap_ms: u64| {
318 let mut detector = OveruseDetector::new().with_threshold_time_base(time_base);
319 detector.update_with_arrival(now, Duration::ZERO, 1.0);
320 detector.update_with_arrival(now, Duration::from_millis(gap_ms), 1.0);
322 detector.threshold_ms()
323 };
324 let capped = ThresholdTimeBase::ArrivalCapped;
325 let draft = ThresholdTimeBase::Arrival;
326 assert_eq!(after(capped, 60), after(draft, 60));
328 assert!(after(capped, 60) < DEFAULT_THRESHOLD_FOR_TEST);
329 assert_eq!(after(capped, 400), after(capped, 100));
331 assert!(after(draft, 400) < after(capped, 400));
332 assert_eq!(
334 after(ThresholdTimeBase::Departure, 400),
335 DEFAULT_THRESHOLD_FOR_TEST
336 );
337 }
338
339 const DEFAULT_THRESHOLD_FOR_TEST: f64 = crate::gcc::threshold::DEFAULT_INITIAL_MS;
340 #[test]
347 fn the_drafts_threshold_adapts_over_the_uncapped_arrival_gap() {
348 let epoch = Instant::now();
349 let mut draft = OveruseDetector::new().with_threshold_time_base(ThresholdTimeBase::Arrival);
350 draft.update_with_arrival(epoch, Duration::ZERO, 20.0);
351 draft.update_with_arrival(
352 epoch + Duration::from_millis(1),
353 Duration::from_millis(300),
354 20.0,
355 );
356 assert!(
357 (draft.threshold_ms() - 35.0).abs() < 1e-9,
358 "{}",
359 draft.threshold_ms()
360 );
361
362 let mut default = OveruseDetector::new();
363 default.update_with_arrival(epoch, Duration::ZERO, 20.0);
364 default.update_with_arrival(
365 epoch + Duration::from_millis(1),
366 Duration::from_millis(300),
367 20.0,
368 );
369 assert!(
370 (default.threshold_ms() - 12.575).abs() < 1e-9,
371 "{}",
372 default.threshold_ms()
373 );
374 }
375}