Skip to main content

agentmux_srv_core/backend/
net_counters.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The machine's network byte counters for the telemetry tick (`sysinfo.rs`).
5//!
6//! The tick only needs the bytes sent and received, summed over the machine's real interfaces.
7//! `sysinfo::Networks::refresh` on Windows also looks up every adapter's MAC and IP addresses on
8//! each call (`GetAdaptersAddresses`), which srv never reads: about a tenth of an idle srv's CPU.
9//! On Windows this reads the counters from `GetIfTable2` directly, with the interface filter
10//! sysinfo applies; elsewhere it still uses sysinfo.
11
12/// One row of the interface table, reduced to what the filter and the sum need.
13#[cfg_attr(not(windows), allow(dead_code))]
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub struct IfRow {
16    /// The interface has a link speed, is connected and has a hardware address.
17    pub usable: bool,
18    /// The interface's GUID without its first field, which is how sysinfo groups software
19    /// interfaces (a virtual switch and its members) with the hardware one.
20    pub group: [u8; 12],
21    pub in_octets: u64,
22    pub out_octets: u64,
23}
24
25/// `(bytes sent, bytes received)` over the usable interfaces that are alone in their group,
26/// which is the set `sysinfo::Networks` keeps.
27#[cfg_attr(not(windows), allow(dead_code))]
28pub fn sum_rows(rows: &[IfRow]) -> (u64, u64) {
29    let mut groups = std::collections::HashMap::new();
30    for r in rows.iter().filter(|r| r.usable) {
31        *groups.entry(r.group).or_insert(0u32) += 1;
32    }
33    rows.iter()
34        .filter(|r| r.usable && groups[&r.group] == 1)
35        .fold((0, 0), |(sent, recv), r| (sent.saturating_add(r.out_octets), recv.saturating_add(r.in_octets)))
36}
37
38/// The totals after a read: those of `rows`, or the last good ones when the table could not be read
39/// (a zero would become the next tick's baseline and show as a spike of the whole lifetime count).
40#[cfg_attr(not(windows), allow(dead_code))]
41fn after_read(last: &mut (u64, u64), rows: Option<Vec<IfRow>>) -> (u64, u64) {
42    if let Some(rows) = rows {
43        *last = sum_rows(&rows);
44    }
45    *last
46}
47
48#[cfg(windows)]
49pub mod imp {
50    use super::{after_read, IfRow};
51    use windows_sys::Win32::NetworkManagement::IpHelper::{FreeMibTable, GetIfTable2, MIB_IF_TABLE2};
52    use windows_sys::Win32::NetworkManagement::Ndis::MediaConnectStateDisconnected;
53
54    pub struct NetCounters {
55        last: (u64, u64),
56    }
57
58    impl NetCounters {
59        pub fn new() -> Self {
60            let mut counters = NetCounters { last: (0, 0) };
61            counters.totals();
62            counters
63        }
64
65        /// `(bytes sent, bytes received)`; the last good ones when the table can't be read.
66        pub fn totals(&mut self) -> (u64, u64) {
67            after_read(&mut self.last, read_rows())
68        }
69    }
70
71    fn read_rows() -> Option<Vec<IfRow>> {
72        let mut table: *mut MIB_IF_TABLE2 = std::ptr::null_mut();
73        // SAFETY: on success `table` points at a table that lives until `FreeMibTable`; its
74        // `NumEntries` rows are read before that and copied out.
75        unsafe {
76            if GetIfTable2(&mut table) != 0 || table.is_null() {
77                return None;
78            }
79            let first = (*table).Table.as_ptr();
80            let rows = (0..(*table).NumEntries as usize)
81                .map(|i| {
82                    let r = &*first.add(i);
83                    let g = r.InterfaceGuid;
84                    let mut group = [0u8; 12];
85                    group[..2].copy_from_slice(&g.data2.to_le_bytes());
86                    group[2..4].copy_from_slice(&g.data3.to_le_bytes());
87                    group[4..].copy_from_slice(&g.data4);
88                    IfRow {
89                        usable: !(r.TransmitLinkSpeed == 0 && r.ReceiveLinkSpeed == 0)
90                            && r.MediaConnectState != MediaConnectStateDisconnected
91                            && r.PhysicalAddressLength != 0,
92                        group,
93                        in_octets: r.InOctets,
94                        out_octets: r.OutOctets,
95                    }
96                })
97                .collect();
98            FreeMibTable(table as _);
99            Some(rows)
100        }
101    }
102}
103
104#[cfg(not(windows))]
105pub mod imp {
106    pub struct NetCounters(sysinfo::Networks);
107
108    impl NetCounters {
109        pub fn new() -> Self {
110            NetCounters(sysinfo::Networks::new_with_refreshed_list())
111        }
112
113        /// `(bytes sent, bytes received)` since each interface appeared.
114        pub fn totals(&mut self) -> (u64, u64) {
115            self.0.refresh(true);
116            self.0.iter().fold((0, 0), |(sent, recv), (_, d)| (sent + d.total_transmitted(), recv + d.total_received()))
117        }
118    }
119}
120
121pub use imp::NetCounters;
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    fn row(group: u8, usable: bool, inb: u64, out: u64) -> IfRow {
128        IfRow { usable, group: [group; 12], in_octets: inb, out_octets: out }
129    }
130
131    #[test]
132    fn sums_the_usable_interfaces() {
133        let rows = [row(1, true, 100, 10), row(2, true, 200, 20)];
134        assert_eq!(sum_rows(&rows), (30, 300));
135    }
136
137    #[test]
138    fn leaves_out_unusable_interfaces() {
139        let rows = [row(1, true, 100, 10), row(2, false, 5_000, 500)];
140        assert_eq!(sum_rows(&rows), (10, 100));
141    }
142
143    #[test]
144    fn leaves_out_software_interfaces_that_share_a_hardware_guid() {
145        // two usable rows in one group (a virtual switch and its member) are both dropped, as sysinfo drops them
146        let rows = [row(1, true, 100, 10), row(1, true, 900, 90), row(2, true, 200, 20)];
147        assert_eq!(sum_rows(&rows), (20, 200));
148    }
149
150    #[test]
151    fn an_unusable_row_does_not_make_its_group_shared() {
152        let rows = [row(1, true, 100, 10), row(1, false, 900, 90)];
153        assert_eq!(sum_rows(&rows), (10, 100));
154    }
155
156    #[test]
157    fn a_failed_read_keeps_the_last_good_totals() {
158        let mut last = (0, 0);
159        assert_eq!(after_read(&mut last, Some(vec![row(1, true, 100, 10)])), (10, 100));
160        assert_eq!(after_read(&mut last, None), (10, 100));
161        assert_eq!(after_read(&mut last, Some(vec![row(1, true, 150, 12)])), (12, 150));
162    }
163
164    #[test]
165    fn no_interfaces_sum_to_zero() {
166        assert_eq!(sum_rows(&[]), (0, 0));
167    }
168
169    #[test]
170    fn the_live_table_is_readable_and_counts_never_go_backwards() {
171        let mut counters = NetCounters::new();
172        let (sent_a, recv_a) = counters.totals();
173        let (sent_b, recv_b) = counters.totals();
174        assert!(sent_b >= sent_a && recv_b >= recv_a, "{sent_a}/{recv_a} then {sent_b}/{recv_b}");
175    }
176}