Skip to main content

labstream_net/
health.rs

1//! Stream health snapshots and gap tracking for inlets and outlets.
2//!
3//! `docs/health.md` and `docs/roadmap.md` (step 11) specify each field.
4
5use std::collections::VecDeque;
6use std::sync::atomic::{AtomicU64, Ordering};
7
8/// Lock-free tracker of the most recent sample timestamp and local arrival time.
9///
10/// Updated once per read batch with two relaxed atomic stores; latency is
11/// computed only when [`crate::Inlet::health`] is called.
12#[derive(Debug)]
13pub(crate) struct LatencyProbe {
14    sample_ts_bits: AtomicU64,
15    arrival_local_bits: AtomicU64,
16}
17
18impl Default for LatencyProbe {
19    fn default() -> Self {
20        Self {
21            sample_ts_bits: AtomicU64::new(f64::NAN.to_bits()),
22            arrival_local_bits: AtomicU64::new(f64::NAN.to_bits()),
23        }
24    }
25}
26
27impl LatencyProbe {
28    pub(crate) fn record(&self, sample_ts: f64) {
29        if !sample_ts.is_finite() {
30            return;
31        }
32        let arrival = crate::clock();
33        self.sample_ts_bits
34            .store(sample_ts.to_bits(), Ordering::Relaxed);
35        self.arrival_local_bits
36            .store(arrival.to_bits(), Ordering::Relaxed);
37    }
38
39    pub(crate) fn measure(&self, clock_offset: Option<f64>) -> Option<f64> {
40        let offset = clock_offset?;
41        let sample_ts = f64::from_bits(self.sample_ts_bits.load(Ordering::Relaxed));
42        let arrival = f64::from_bits(self.arrival_local_bits.load(Ordering::Relaxed));
43        if sample_ts.is_finite() && arrival.is_finite() {
44            Some((arrival - (sample_ts + offset)).max(0.0))
45        } else {
46            None
47        }
48    }
49}
50
51/// Maximum number of gaps retained per ring so long streams use bounded memory.
52pub(crate) const MAX_GAPS: usize = 1024;
53
54/// Why a gap occurred in the sample stream.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum GapKind {
57    /// Samples never reached this inlet (outlet queue drop, network loss, or
58    /// dropout not covered by the resume history). Reported through `seq/1` or
59    /// `dgram/1`.
60    Lost,
61    /// Samples arrived at this inlet and were dropped because the inlet buffer
62    /// filled before the application pulled them.
63    Dropped,
64}
65
66/// One missing interval in a stream, given as a pair of timestamps.
67///
68/// `start` is the timestamp of the last sample before the gap (or the first
69/// dropped sample when nothing was read before it). `end` is the timestamp of
70/// the first sample after the gap. When `Post::CLOCK_SYNC` is enabled on the
71/// inlet and a clock offset exists, both timestamps are shifted to the local
72/// clock to match pulled samples.
73#[derive(Debug, Clone, Copy, PartialEq)]
74pub struct Gap {
75    /// Timestamp at the start of the gap.
76    pub start: f64,
77    /// Timestamp at the end of the gap (first sample after the missing block).
78    pub end: f64,
79    /// Number of missing samples in this gap.
80    pub count: u64,
81    /// Whether the gap came from network/outlet loss or inlet buffer overflow.
82    pub kind: GapKind,
83}
84
85/// Snapshot of the health of one [`crate::Inlet`].
86#[derive(Debug, Clone, Copy, PartialEq)]
87pub struct InletHealth {
88    /// Measured arrival latency of the most recent sample, in seconds
89    /// (`arrival_local - (sample_timestamp + clock_offset)`), or `None` before
90    /// the first sample arrives or before clock sync completes.
91    pub latency: Option<f64>,
92    /// Samples that never reached this inlet (`seq/1`), or `None` when the
93    /// source does not use `seq/1`.
94    pub lost: Option<u64>,
95    /// Samples dropped by this inlet's local buffer because the application
96    /// pulled too slowly.
97    pub dropped: u64,
98    /// Samples delivered from the outlet's `resume/1` history after a dropout,
99    /// or `None` when `resume/1` is not active.
100    pub resent: Option<u64>,
101    /// Round-trip time of the latest clock offset estimate, in seconds, or
102    /// `None` before the first burst completes.
103    pub clock_uncertainty: Option<f64>,
104    /// Estimated relative clock drift (`d(offset)/d(t_local)` in s/s) from the
105    /// opt-in drift model (`docs/roadmap.md`, step 17), or `None` before the
106    /// first burst completes.
107    pub clock_drift: Option<f64>,
108    /// Number of times the inlet rebuilt its connection.
109    pub recoveries: u64,
110    /// True while the inlet reader is attached to a source.
111    pub connected: bool,
112    /// True while samples arrive over UDP (`dgram/1`).
113    pub on_udp: bool,
114    /// True while samples arrive through shared memory (`shm/1`).
115    pub on_shm: bool,
116    /// True while wire compression (`comp/1`) is active on this connection.
117    pub compressed: bool,
118    /// True while negotiated encryption (`enc/1`) is active on this connection.
119    pub encrypted: bool,
120    /// Ratio `wire_bytes / raw_bytes` observed on this connection when
121    /// `comp/1` is active, or `None` when uncompressed or before data arrives.
122    pub compression_ratio: Option<f64>,
123    /// Number of samples currently waiting in the inlet buffer.
124    pub buffered: usize,
125    /// Capacity of the inlet buffer, in samples.
126    pub buffer_capacity: usize,
127    /// Number of gaps currently recorded on this inlet.
128    pub gap_count: usize,
129}
130
131/// Snapshot of one consumer queue on an [`crate::Outlet`].
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct ConsumerHealth {
134    /// Monotonic identifier assigned when the consumer connected.
135    pub id: u64,
136    /// Remote address of the consumer, when known.
137    pub peer: String,
138    /// Number of samples currently waiting in this consumer's queue.
139    pub fill: usize,
140    /// Maximum capacity of this consumer's queue, in samples. Zero for a
141    /// blocking outlet, which holds no queue.
142    pub capacity: usize,
143    /// Number of samples dropped from this consumer's queue because it filled.
144    pub dropped: u64,
145}
146
147/// Snapshot of the health of one [`crate::Outlet`].
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct OutletHealth {
150    /// Fill and drop state of each connected consumer queue.
151    pub consumers: Vec<ConsumerHealth>,
152    /// Number of samples currently held in the `resume/1` history.
153    pub history_len: usize,
154    /// Total number of samples pushed into this outlet since it opened.
155    pub pushed: u64,
156}
157
158/// Internal ring buffer that tracks [`GapKind::Lost`] intervals from `seq/1`
159/// and `dgram/1` delivery order.
160#[derive(Debug, Default)]
161pub(crate) struct GapTracker {
162    /// Timestamp of the last sample delivered on the current outlet run.
163    last_ts: Option<f64>,
164    /// Pending lost samples waiting for the next sample to close the interval.
165    pending_count: u64,
166    /// Start timestamp latched when `pending_count` first became non-zero.
167    pending_start: Option<f64>,
168    /// Completed gaps, bounded to [`MAX_GAPS`].
169    gaps: VecDeque<Gap>,
170}
171
172impl GapTracker {
173    pub(crate) fn new() -> Self {
174        Self::default()
175    }
176
177    /// Record that `delta` samples were lost before the next sample arrives.
178    pub(crate) fn record_lost(&mut self, delta: u64) {
179        if delta == 0 {
180            return;
181        }
182        if self.pending_count == 0 {
183            self.pending_start = self.last_ts;
184        }
185        self.pending_count = self.pending_count.saturating_add(delta);
186    }
187
188    /// Record one delivered sample at raw timestamp `ts`.
189    pub(crate) fn on_sample(&mut self, ts: f64) {
190        if self.pending_count > 0 {
191            let count = self.pending_count;
192            let start = self.pending_start.unwrap_or(ts);
193            self.pending_count = 0;
194            self.pending_start = None;
195            // Only record a real gap when a previous sample existed or start is finite.
196            if start.is_finite() && ts.is_finite() {
197                if self.gaps.len() >= MAX_GAPS {
198                    self.gaps.pop_front();
199                }
200                self.gaps.push_back(Gap {
201                    start,
202                    end: ts,
203                    count,
204                    kind: GapKind::Lost,
205                });
206            }
207        }
208        self.last_ts = Some(ts);
209    }
210
211    /// Record a contiguous batch of delivered samples.
212    pub(crate) fn on_batch(&mut self, first_ts: f64, last_ts: f64) {
213        self.on_sample(first_ts);
214        self.last_ts = Some(last_ts);
215    }
216
217    /// Reset the timestamp cursor when attaching to a new outlet run so
218    /// timestamps from two different clocks do not pair into a false gap.
219    pub(crate) fn reset_cursor(&mut self) {
220        self.last_ts = None;
221        self.pending_count = 0;
222        self.pending_start = None;
223    }
224
225    /// Number of recorded gaps.
226    pub(crate) fn len(&self) -> usize {
227        self.gaps.len()
228    }
229
230    /// Snapshot all recorded gaps, adding `shift` to each timestamp.
231    pub(crate) fn snapshot(&self, shift: f64) -> Vec<Gap> {
232        self.gaps
233            .iter()
234            .map(|g| Gap {
235                start: g.start + shift,
236                end: g.end + shift,
237                count: g.count,
238                kind: g.kind,
239            })
240            .collect()
241    }
242
243    /// Drain all recorded gaps, adding `shift` to each timestamp.
244    pub(crate) fn take(&mut self, shift: f64) -> Vec<Gap> {
245        self.gaps
246            .drain(..)
247            .map(|g| Gap {
248                start: g.start + shift,
249                end: g.end + shift,
250                count: g.count,
251                kind: g.kind,
252            })
253            .collect()
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260
261    #[test]
262    fn tracker_records_exact_timestamp_pair_and_coalesces_consecutive_losses() {
263        let mut t = GapTracker::new();
264        t.on_sample(10.0);
265        t.on_sample(10.5);
266        t.record_lost(3);
267        t.record_lost(2);
268        t.on_sample(13.0);
269
270        let gaps = t.snapshot(0.0);
271        assert_eq!(gaps.len(), 1);
272        assert_eq!(
273            gaps[0],
274            Gap {
275                start: 10.5,
276                end: 13.0,
277                count: 5,
278                kind: GapKind::Lost,
279            }
280        );
281
282        // Clock shift moves both endpoints by the same offset.
283        let shifted = t.take(100.0);
284        assert_eq!(shifted[0].start, 110.5);
285        assert_eq!(shifted[0].end, 113.0);
286        assert!(t.snapshot(0.0).is_empty());
287    }
288
289    #[test]
290    fn tracker_bounds_ring_size_and_resets_cursor_on_new_run() {
291        let mut t = GapTracker::new();
292        t.on_sample(0.0);
293        for i in 1..=(MAX_GAPS + 20) {
294            t.record_lost(1);
295            t.on_sample(i as f64);
296        }
297        assert_eq!(t.len(), MAX_GAPS);
298        let first = t.snapshot(0.0)[0];
299        assert_eq!(first.end, 21.0);
300
301        // Pending loss across a new outlet run does not pair old and new clocks.
302        t.record_lost(10);
303        t.reset_cursor();
304        t.on_sample(5000.0);
305        assert_eq!(t.len(), MAX_GAPS);
306    }
307}