Skip to main content

moq_ext_sources/
stats.rs

1//! Small helpers for the figures a broadcast and a player report.
2
3use std::{
4    sync::{Arc, Mutex},
5    time::Duration,
6};
7
8use tokio::time::Instant;
9
10/// A value one task writes and anyone snapshots.
11///
12/// Clones share the value.
13// Shared with moq-ext-publisher and moq-ext-player, not public API.
14#[doc(hidden)]
15#[derive(Debug, Clone, Default)]
16pub struct SharedCell<T>(Arc<Mutex<T>>);
17
18impl<T: Clone> SharedCell<T> {
19    /// Changes the value in place.
20    pub fn update(&self, f: impl FnOnce(&mut T)) {
21        f(&mut self.0.lock().expect("poisoned"));
22    }
23
24    /// Returns a copy of the value.
25    #[must_use]
26    pub fn get(&self) -> T {
27        self.0.lock().expect("poisoned").clone()
28    }
29}
30
31/// How long a [`RateMeter`] counts events before it reports.
32///
33/// Frame rates are quoted per second. A meter reports only when an event
34/// arrives, so a reader asks [`Rates::is_current`] whether a stream still runs.
35const RATE_WINDOW: Duration = Duration::from_secs(1);
36
37/// A counter of events that reports their rate once per window.
38///
39/// Owned by the one task that sees the events, so it needs no lock. It reads
40/// the clock through tokio, so a test with paused time drives it.
41#[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    /// Creates a meter that reports once per `window`.
57    #[must_use]
58    pub fn over(window: Duration) -> Self {
59        Self::starting(window, Instant::now())
60    }
61
62    /// Creates a meter whose window opened at `started`.
63    fn starting(window: Duration, started: Instant) -> Self {
64        Self {
65            window,
66            started,
67            events: 0,
68            amount: 0,
69        }
70    }
71
72    /// Counts one event carrying `amount`, such as bytes.
73    ///
74    /// Returns the rates when this event closes the window, and `None` before
75    /// that.
76    #[must_use]
77    pub fn tick(&mut self, amount: u64) -> Option<Rates> {
78        self.tick_at(amount, Instant::now())
79    }
80
81    /// Counts one event at `now`, as [`tick`](Self::tick) does.
82    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            // The stream paused for so long that the last reading went stale.
86            // Averaging over the pause would report a rate far below the one
87            // the stream resumes at, so this event opens a new window instead,
88            // as the event that closes a window does.
89            *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        // The window restarts at the reading, so time spent computing does not
105        // add up across windows.
106        *self = Self::starting(self.window, now);
107        Some(rates)
108    }
109}
110
111/// What a [`RateMeter`] counted over one window, per second.
112#[derive(Debug, Clone, Copy, PartialEq)]
113pub struct Rates {
114    /// Events per second.
115    pub events: f64,
116    /// The amount the events carried, per second.
117    pub amount: f64,
118    /// When the window closed.
119    at: Instant,
120    /// The meter's window.
121    window: Duration,
122}
123
124impl Rates {
125    /// How many windows a reading stays current for.
126    ///
127    /// A steady stream closes a window about once per window, and a stream
128    /// slower than one event per window closes one with every event. Two
129    /// windows without a reading mean at least one window without an event,
130    /// so a stream reads as running only while it sends faster than one event
131    /// per two windows.
132    const CURRENT_FOR: u32 = 2;
133
134    /// Returns whether the stream still runs, as far as these rates tell.
135    ///
136    /// The rates go stale once the meter closed no window for two windows. A
137    /// reader shows a stale rate as unknown, since the stream stopped.
138    #[must_use]
139    pub fn is_current(&self) -> bool {
140        self.is_current_at(Instant::now())
141    }
142
143    /// Returns whether the rates are current at `now`, as [`is_current`](Self::is_current) does.
144    fn is_current_at(&self, now: Instant) -> bool {
145        now.duration_since(self.at) < self.window * Self::CURRENT_FOR
146    }
147}
148
149/// An exponentially smoothed duration, for timings that jitter per call.
150#[derive(Debug, Default)]
151pub struct Smoothed(Option<f64>);
152
153impl Smoothed {
154    /// The weight of a new sample.
155    const ALPHA: f64 = 0.2;
156
157    /// Folds `sample` in and returns the smoothed value.
158    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    /// Runs forty events at offsets from `offset` and returns the first rate.
174    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    /// Bursty delivery reads the same rate as even delivery.
184    #[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        // Thirty events 33 ms apart stay inside the window.
197        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        // 31 events of 2500 bytes over one second.
202        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    /// Rates stay current while the stream runs and go stale once it stops.
210    #[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        // Three seconds at 20 events per second.
216        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        // After a five-second pause the stream resumes at 20 events per second.
233        // The first reading covers only the time since the resume.
234        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}