netforge 0.1.0

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,
}

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,
            }),
        }
    }

    /// 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 snapshot. Updates the window cursor.
    ///
    /// First call after construction always returns 0 (no prior window).
    /// Subsequent calls return `(total - last_total) / elapsed_secs`.
    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(),
        };
        let delta_packets = total.saturating_sub(window.last_total);
        let elapsed = now.duration_since(window.last_at).as_secs_f64();
        let primed = window.primed;
        window.last_total = total;
        window.last_at = now;
        window.primed = true;
        if !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.
            return 0;
        }
        if elapsed <= 0.0 {
            return 0;
        }
        let pps = (delta_packets as f64) / elapsed;
        if !pps.is_finite() || pps < 0.0 {
            0
        } else {
            pps as u64
        }
    }
}

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 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();
        }
        assert_eq!(t.total(), 8_000);
        // Snapshot should at least be > 0 (8000 packets in <1s)
        let pps = t.snapshot_pps();
        assert!(pps > 0);
    }
}