Skip to main content

rns_net/common/
interface_stats.rs

1/// Maximum number of announce timestamps to keep per direction.
2pub const ANNOUNCE_SAMPLE_MAX: usize = 6;
3
4/// Traffic statistics for an interface.
5#[derive(Debug, Clone, Default)]
6pub struct InterfaceStats {
7    pub rxb: u64,
8    pub txb: u64,
9    pub rx_packets: u64,
10    pub tx_packets: u64,
11    pub started: f64,
12    /// Recent incoming announce timestamps (bounded).
13    pub ia_timestamps: Vec<f64>,
14    /// Recent outgoing announce timestamps (bounded).
15    pub oa_timestamps: Vec<f64>,
16}
17
18impl InterfaceStats {
19    /// Record an incoming announce timestamp.
20    pub fn record_incoming_announce(&mut self, now: f64) {
21        self.ia_timestamps.push(now);
22        if self.ia_timestamps.len() > ANNOUNCE_SAMPLE_MAX {
23            self.ia_timestamps.remove(0);
24        }
25    }
26
27    /// Record an outgoing announce timestamp.
28    pub fn record_outgoing_announce(&mut self, now: f64) {
29        self.oa_timestamps.push(now);
30        if self.oa_timestamps.len() > ANNOUNCE_SAMPLE_MAX {
31            self.oa_timestamps.remove(0);
32        }
33    }
34
35    /// Compute announce frequency (per second) from timestamps.
36    fn compute_frequency(timestamps: &[f64]) -> f64 {
37        if timestamps.len() < 2 {
38            return 0.0;
39        }
40        let span = timestamps[timestamps.len() - 1] - timestamps[0];
41        if span <= 0.0 {
42            return 0.0;
43        }
44        (timestamps.len() - 1) as f64 / span
45    }
46
47    /// Incoming announce frequency (per second).
48    pub fn incoming_announce_freq(&self) -> f64 {
49        Self::compute_frequency(&self.ia_timestamps)
50    }
51
52    /// Outgoing announce frequency (per second).
53    pub fn outgoing_announce_freq(&self) -> f64 {
54        Self::compute_frequency(&self.oa_timestamps)
55    }
56}