netforge 0.1.5

High-performance raw packet I/O engine with AF_XDP, sendmmsg, and pnet backends
Documentation
//! Rolling-window packets-per-second tracker for [`crate::engine::EngineStats`].
//!
//! Backends update lifetime totals via `record_tx` / `record_rx`. On each
//! [`PpsTracker::snapshot`] call the tracker computes the delta against the
//! previous call and divides by the elapsed wall-clock time, yielding an
//! instantaneous pps reading. Two-sample rolling window  -  minimal state,
//! lock-free hot path, single short critical section on snapshot.

use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Instant;

/// Lifetime + rolling-window tracker for a single TX/RX direction.
pub struct PpsTracker {
    total: AtomicU64,
    drops: AtomicU64,
    window: Mutex<Window>,
}

struct Window {
    last_total: u64,
    last_at: Instant,
    primed: bool,
    /// Rate computed at the most recent baseline advance. Returned verbatim for
    /// reads that land within `MIN_SAMPLE_SECS` of the last advance, so polling
    /// `stats()` twice in quick succession (or from two consumers) is
    /// side-effect-free rather than resetting the window and reporting 0.
    last_pps: u64,
}

impl PpsTracker {
    /// Create a fresh tracker with zero counters.
    #[must_use]
    pub fn new() -> Self {
        Self {
            total: AtomicU64::new(0),
            drops: AtomicU64::new(0),
            window: Mutex::new(Window {
                last_total: 0,
                last_at: Instant::now(),
                primed: false,
                last_pps: 0,
            }),
        }
    }

    /// Record `n` successful packets.
    #[inline]
    pub fn record(&self, n: u64) {
        self.total.fetch_add(n, Ordering::Relaxed);
    }

    /// Record `n` dropped packets.
    #[inline]
    pub fn record_drop(&self, n: u64) {
        self.drops.fetch_add(n, Ordering::Relaxed);
    }

    /// Lifetime packet total.
    #[inline]
    pub fn total(&self) -> u64 {
        self.total.load(Ordering::Relaxed)
    }

    /// Lifetime drop total.
    #[inline]
    pub fn drops(&self) -> u64 {
        self.drops.load(Ordering::Relaxed)
    }

    /// Compute pps since the previous baseline advance.
    ///
    /// First call after construction seeds the baseline and returns 0 (no prior
    /// window). A subsequent call spaced by at least `MIN_SAMPLE_SECS` returns
    /// `(total - last_total) / elapsed_secs` and advances the baseline.
    ///
    /// Reading is side-effect-free within a sample interval: a call landing
    /// within `MIN_SAMPLE_SECS` of the last advance returns the last computed
    /// rate WITHOUT touching the window. This is what makes it safe for
    /// `EngineStats`/`stats()` to be read more than once in quick succession (or
    /// by two consumers): the old code advanced the baseline on every call, so a
    /// rapid second read both reported a misleading 0 AND reset the reference
    /// point, corrupting the next real sample.
    pub fn snapshot_pps(&self) -> u64 {
        let now = Instant::now();
        let total = self.total();
        let mut window = match self.window.lock() {
            Ok(g) => g,
            Err(poisoned) => poisoned.into_inner(),
        };

        if !window.primed {
            // First call only seeds the baseline  -  there is no prior
            // reference point so any computed rate would be an artifact
            // of construction-to-snapshot timing, not workload pps.
            window.last_total = total;
            window.last_at = now;
            window.primed = true;
            return 0;
        }

        let elapsed = now.duration_since(window.last_at).as_secs_f64();

        // Minimum meaningful sample interval. A rate measured over a window
        // shorter than this carries no signal: it either divides a tiny packet
        // delta by a tiny interval (reporting an absurd multi-billion-pps spike)
        // or, for back-to-back reads, measures near-zero packets over the
        // function-call overhead itself. Either way we return the last computed
        // rate WITHOUT advancing the baseline, so:
        //   * a rapid re-read (two consumers, or one polling loop that reads
        //     `stats()` twice) is idempotent rather than reporting a spurious 0;
        //   * the baseline is not reset, so the next genuinely-spaced sample
        //     still measures real throughput from the correct reference point.
        // 1 ms comfortably exceeds any back-to-back read latency (microseconds)
        // while staying far below any real polling cadence.
        const MIN_SAMPLE_SECS: f64 = 1e-3;
        if elapsed < MIN_SAMPLE_SECS {
            return window.last_pps;
        }

        let delta_packets = total.saturating_sub(window.last_total);
        let pps_f = (delta_packets as f64) / elapsed;
        let pps = if pps_f.is_finite() && pps_f >= 0.0 {
            pps_f as u64
        } else {
            0
        };
        window.last_total = total;
        window.last_at = now;
        window.last_pps = pps;
        pps
    }
}

impl Default for PpsTracker {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;
    use std::time::Duration;

    #[test]
    fn first_snapshot_is_zero() {
        let t = PpsTracker::new();
        t.record(100);
        // No prior window; first call resets baseline and returns 0.
        assert_eq!(t.snapshot_pps(), 0);
    }

    #[test]
    fn second_snapshot_reports_rate() {
        let t = PpsTracker::new();
        t.snapshot_pps(); // baseline
        t.record(1000);
        thread::sleep(Duration::from_millis(50));
        let pps = t.snapshot_pps();
        // 1000 packets in ~50ms ≈ 20 000 pps. Allow generous slack for
        // CI scheduling jitter  -  anywhere in [5_000, 100_000] proves
        // the math, not a regression.
        assert!(
            (5_000..=100_000).contains(&pps),
            "expected ~20kpps, got {pps}"
        );
    }

    #[test]
    fn lifetime_total_and_drops_track() {
        let t = PpsTracker::new();
        t.record(7);
        t.record(3);
        t.record_drop(2);
        assert_eq!(t.total(), 10);
        assert_eq!(t.drops(), 2);
    }

    #[test]
    fn snapshot_idempotent_on_zero_delta() {
        let t = PpsTracker::new();
        t.snapshot_pps();
        let pps = t.snapshot_pps();
        assert_eq!(pps, 0);
    }

    #[test]
    fn rapid_reread_is_idempotent_and_does_not_corrupt_baseline() {
        let t = PpsTracker::new();
        t.snapshot_pps(); // prime the baseline
        t.record(1000);
        thread::sleep(Duration::from_millis(50));

        // First real read establishes a rate and advances the baseline.
        let first = t.snapshot_pps();
        assert!(first > 0, "first spaced read should report a rate, got {first}");

        // A second read landing immediately after (well within MIN_WINDOW_SECS)
        // must return the SAME cached rate  -  NOT 0  -  and must NOT advance the
        // baseline. Under the old code this returned 0 and reset last_at/last_total,
        // so this assertion discriminates the fix from the bug.
        let second = t.snapshot_pps();
        assert_eq!(
            second, first,
            "rapid re-read must be idempotent (cached rate), got {second} vs {first}"
        );

        // Because the rapid re-read did not corrupt the baseline, the next
        // genuinely-spaced sample still measures real throughput from the
        // correct reference point rather than from the poisoned instant.
        t.record(1000);
        thread::sleep(Duration::from_millis(50));
        let third = t.snapshot_pps();
        assert!(
            third > 0,
            "baseline must survive the rapid re-read so the next sample is real, got {third}"
        );
    }

    #[test]
    fn handles_concurrent_updates() {
        let t = std::sync::Arc::new(PpsTracker::new());
        t.snapshot_pps();
        let handles: Vec<_> = (0..8)
            .map(|_| {
                let t = std::sync::Arc::clone(&t);
                thread::spawn(move || {
                    for _ in 0..1_000 {
                        t.record(1);
                    }
                })
            })
            .collect();
        for h in handles {
            h.join().unwrap();
        }
        // Primary assertion: every concurrent record lands (no lost updates).
        assert_eq!(t.total(), 8_000);
        // Rate sanity: a snapshot taken after a real sample window (> the
        // MIN_SAMPLE_SECS floor) reports those 8000 packets as a positive rate.
        // The threads finish in well under a millisecond, so without the sleep
        // the final read would land inside the sample interval and return the
        // cached (zero) rate  -  correct by contract, but not what this test is
        // checking. The sleep gives it a genuine measurement window.
        thread::sleep(Duration::from_millis(3));
        let pps = t.snapshot_pps();
        assert!(pps > 0, "8000 packets over a real window should report a rate, got {pps}");
    }
}