Skip to main content

rustnet_core/network/
process_activity.rs

1//! Process traffic accounting over active and retained historic connections.
2//!
3//! Connection rows are intentionally short lived, but security-relevant
4//! traffic often needs to remain visible after a socket and its owning process
5//! have exited. [`ProcessActivityTracker`] streams the connection tracker's
6//! existing active and bounded historic rows into compact one-second and
7//! rolling-window metrics for user interfaces and exporters.
8
9use crate::network::types::{Connection, ConnectionKey};
10use std::collections::{BTreeSet, HashMap, VecDeque};
11use std::net::SocketAddr;
12use std::time::{Duration, SystemTime};
13
14const UNKNOWN_NAME: &str = "Unknown";
15const OTHER_NAME: &str = "Other";
16
17/// Bounds for retained process accounting.
18#[derive(Debug, Clone)]
19pub(crate) struct ProcessActivityConfig {
20    /// Maximum number of historic process buckets represented in one sample.
21    /// Additional identities are folded into attributed/unattributed `Other`
22    /// buckets. Active identities are always represented individually.
23    pub max_completed_processes: usize,
24    /// Maximum number of unique destinations reported per process. When this
25    /// is exceeded, the visible count is rendered with a `+` suffix. Top peers
26    /// are still selected from every destination in the transient sample.
27    pub max_destinations_per_process: usize,
28    /// Rolling traffic window used by the activity UI.
29    pub window: Duration,
30}
31
32impl Default for ProcessActivityConfig {
33    fn default() -> Self {
34        Self {
35            max_completed_processes: 4096,
36            max_destinations_per_process: 256,
37            window: Duration::from_secs(60),
38        }
39    }
40}
41
42/// Stable identity used to aggregate connections into process rows.
43#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
44pub struct ProcessIdentity {
45    pub pid: Option<u32>,
46    pub name: String,
47    pub attributed: bool,
48}
49
50impl ProcessIdentity {
51    fn from_connection(conn: &Connection) -> Self {
52        let attributed = conn.pid.is_some() || conn.process_name.is_some();
53        Self {
54            pid: conn.pid,
55            name: conn
56                .process_name
57                .clone()
58                .unwrap_or_else(|| UNKNOWN_NAME.to_string()),
59            attributed,
60        }
61    }
62
63    fn overflow(attributed: bool) -> Self {
64        Self {
65            pid: None,
66            name: if attributed {
67                OTHER_NAME.to_string()
68            } else {
69                UNKNOWN_NAME.to_string()
70            },
71            attributed,
72        }
73    }
74
75    pub fn display_name(&self) -> String {
76        match self.pid {
77            Some(pid) => format!("{} ({pid})", self.name),
78            None => self.name.clone(),
79        }
80    }
81}
82
83/// Traffic attributed to one remote socket for a process.
84#[derive(Debug, Clone)]
85pub struct DestinationActivity {
86    pub remote_addr: SocketAddr,
87    pub label: Option<String>,
88    pub tx_bytes: u64,
89    pub rx_bytes: u64,
90    pub connections: u64,
91}
92
93impl DestinationActivity {
94    pub fn display_name(&self) -> String {
95        self.label
96            .as_ref()
97            .map(|label| format!("{label}:{}", self.remote_addr.port()))
98            .unwrap_or_else(|| self.remote_addr.to_string())
99    }
100}
101
102/// Aggregated retained and rolling metrics for one process identity.
103#[derive(Debug, Clone)]
104pub struct ProcessActivity {
105    pub identity: ProcessIdentity,
106    pub current_tx_bps: f64,
107    pub current_rx_bps: f64,
108    pub window_tx_bytes: u64,
109    pub window_rx_bytes: u64,
110    pub peak_tx_bps: f64,
111    pub peak_rx_bps: f64,
112    pub retained_tx_bytes: u64,
113    pub retained_rx_bytes: u64,
114    pub active_connections: usize,
115    pub total_connections: u64,
116    pub unique_destinations: usize,
117    pub destinations_truncated: bool,
118    pub top_tx_destination: Option<DestinationActivity>,
119    pub top_rx_destination: Option<DestinationActivity>,
120    pub window_tx_share: f64,
121    pub window_rx_share: f64,
122    pub retained_tx_share: f64,
123    pub retained_rx_share: f64,
124}
125
126/// Immutable point-in-time process activity view.
127#[derive(Debug, Clone)]
128pub struct ProcessActivitySnapshot {
129    pub processes: Vec<ProcessActivity>,
130    pub current_tx_bps: f64,
131    pub current_rx_bps: f64,
132    pub window_tx_bytes: u64,
133    pub window_rx_bytes: u64,
134    pub retained_tx_bytes: u64,
135    pub retained_rx_bytes: u64,
136    pub attributed_tx_bytes: u64,
137    pub attributed_rx_bytes: u64,
138}
139
140impl Default for ProcessActivitySnapshot {
141    fn default() -> Self {
142        Self {
143            processes: Vec::new(),
144            current_tx_bps: 0.0,
145            current_rx_bps: 0.0,
146            window_tx_bytes: 0,
147            window_rx_bytes: 0,
148            retained_tx_bytes: 0,
149            retained_rx_bytes: 0,
150            attributed_tx_bytes: 0,
151            attributed_rx_bytes: 0,
152        }
153    }
154}
155
156impl ProcessActivitySnapshot {
157    pub fn tx_attribution_pct(&self) -> f64 {
158        percentage(
159            self.attributed_tx_bytes as f64,
160            self.retained_tx_bytes as f64,
161        )
162    }
163
164    pub fn rx_attribution_pct(&self) -> f64 {
165        percentage(
166            self.attributed_rx_bytes as f64,
167            self.retained_rx_bytes as f64,
168        )
169    }
170}
171
172#[derive(Debug, Clone)]
173struct FlowActivity {
174    identity: ProcessIdentity,
175    bytes_sent: u64,
176    bytes_received: u64,
177    remote_addr: SocketAddr,
178    remote_label: Option<String>,
179}
180
181impl FlowActivity {
182    fn from_connection(conn: &Connection) -> Self {
183        Self {
184            identity: ProcessIdentity::from_connection(conn),
185            bytes_sent: conn.bytes_sent,
186            bytes_received: conn.bytes_received,
187            remote_addr: conn.remote_addr,
188            remote_label: destination_label(conn),
189        }
190    }
191}
192
193/// Fixed-size identity used to detect byte growth without retaining a second
194/// copy of each full connection. Creation time distinguishes historic flows
195/// that reused the same protocol and socket tuple.
196#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
197struct FlowIdentity {
198    key: ConnectionKey,
199    created_nanos: u128,
200}
201
202impl FlowIdentity {
203    fn from_connection(conn: &Connection) -> Self {
204        Self {
205            key: ConnectionKey::new(conn.protocol, conn.local_addr, conn.remote_addr),
206            created_nanos: conn
207                .created_at
208                .duration_since(SystemTime::UNIX_EPOCH)
209                .unwrap_or_default()
210                .as_nanos(),
211        }
212    }
213}
214
215#[derive(Debug, Clone, Copy)]
216struct FlowCounters {
217    tx_bytes: u64,
218    rx_bytes: u64,
219    observed_generation: u64,
220}
221
222#[derive(Debug, Clone, Copy, Default)]
223struct TrafficDelta {
224    tx_bytes: u64,
225    rx_bytes: u64,
226}
227
228impl TrafficDelta {
229    fn add(&mut self, other: Self) {
230        self.tx_bytes = self.tx_bytes.saturating_add(other.tx_bytes);
231        self.rx_bytes = self.rx_bytes.saturating_add(other.rx_bytes);
232    }
233}
234
235#[derive(Debug, Clone)]
236struct ProcessAccumulator {
237    tx_bytes: u64,
238    rx_bytes: u64,
239    active_connections: usize,
240    completed_connections: u64,
241    destinations: HashMap<SocketAddr, DestinationActivity>,
242}
243
244impl ProcessAccumulator {
245    fn new() -> Self {
246        Self {
247            tx_bytes: 0,
248            rx_bytes: 0,
249            active_connections: 0,
250            completed_connections: 0,
251            destinations: HashMap::new(),
252        }
253    }
254
255    fn add_flow(&mut self, flow: &FlowActivity, completed: bool) {
256        self.tx_bytes = self.tx_bytes.saturating_add(flow.bytes_sent);
257        self.rx_bytes = self.rx_bytes.saturating_add(flow.bytes_received);
258        if completed {
259            self.completed_connections = self.completed_connections.saturating_add(1);
260        } else {
261            self.active_connections = self.active_connections.saturating_add(1);
262        }
263        self.add_destination(flow);
264    }
265
266    fn add_destination(&mut self, flow: &FlowActivity) {
267        if let Some(destination) = self.destinations.get_mut(&flow.remote_addr) {
268            destination.tx_bytes = destination.tx_bytes.saturating_add(flow.bytes_sent);
269            destination.rx_bytes = destination.rx_bytes.saturating_add(flow.bytes_received);
270            destination.connections = destination.connections.saturating_add(1);
271            if destination.label.is_none() {
272                destination.label.clone_from(&flow.remote_label);
273            }
274            return;
275        }
276
277        self.destinations.insert(
278            flow.remote_addr,
279            DestinationActivity {
280                remote_addr: flow.remote_addr,
281                label: flow.remote_label.clone(),
282                tx_bytes: flow.bytes_sent,
283                rx_bytes: flow.bytes_received,
284                connections: 1,
285            },
286        );
287    }
288}
289
290#[derive(Debug, Clone, Copy)]
291struct ProcessSample {
292    timestamp: SystemTime,
293    tx_bytes: u64,
294    rx_bytes: u64,
295}
296
297#[derive(Debug, Default)]
298struct ProcessHistory {
299    samples: VecDeque<ProcessSample>,
300    cumulative_tx_bytes: u64,
301    cumulative_rx_bytes: u64,
302    current_tx_bps: f64,
303    current_rx_bps: f64,
304    peak_tx_bps: f64,
305    peak_rx_bps: f64,
306}
307
308impl ProcessHistory {
309    fn sample(
310        &mut self,
311        now: SystemTime,
312        tx_delta: u64,
313        rx_delta: u64,
314        window: Duration,
315        active: bool,
316    ) {
317        if self.samples.is_empty() {
318            // Monotonic counters begin at the first retained observation. A
319            // zero baseline at the same instant includes the first observed
320            // bytes in the rolling window without inventing a current rate.
321            self.samples.push_back(ProcessSample {
322                timestamp: now,
323                tx_bytes: self.cumulative_tx_bytes,
324                rx_bytes: self.cumulative_rx_bytes,
325            });
326        }
327
328        self.cumulative_tx_bytes = self.cumulative_tx_bytes.saturating_add(tx_delta);
329        self.cumulative_rx_bytes = self.cumulative_rx_bytes.saturating_add(rx_delta);
330        let tx_bytes = self.cumulative_tx_bytes;
331        let rx_bytes = self.cumulative_rx_bytes;
332
333        let unchanged = self
334            .samples
335            .back()
336            .is_some_and(|sample| sample.tx_bytes == tx_bytes && sample.rx_bytes == rx_bytes);
337        if !active && unchanged {
338            self.current_tx_bps = 0.0;
339            self.current_rx_bps = 0.0;
340            self.prune(now, window, false);
341            return;
342        }
343
344        if let Some(previous) = self.samples.back().copied() {
345            let elapsed = now
346                .duration_since(previous.timestamp)
347                .unwrap_or_default()
348                .as_secs_f64();
349            if elapsed > 0.0 {
350                self.current_tx_bps = tx_bytes.saturating_sub(previous.tx_bytes) as f64 / elapsed;
351                self.current_rx_bps = rx_bytes.saturating_sub(previous.rx_bytes) as f64 / elapsed;
352                self.peak_tx_bps = self.peak_tx_bps.max(self.current_tx_bps);
353                self.peak_rx_bps = self.peak_rx_bps.max(self.current_rx_bps);
354            }
355        }
356
357        self.samples.push_back(ProcessSample {
358            timestamp: now,
359            tx_bytes,
360            rx_bytes,
361        });
362
363        self.prune(now, window, active);
364    }
365
366    fn prune(&mut self, now: SystemTime, window: Duration, active: bool) {
367        while self.samples.len() > 2
368            && self.samples.get(1).is_some_and(|sample| {
369                now.duration_since(sample.timestamp).unwrap_or_default() >= window
370            })
371        {
372            self.samples.pop_front();
373        }
374
375        if !active
376            && self.samples.back().is_some_and(|sample| {
377                now.duration_since(sample.timestamp).unwrap_or_default() >= window
378            })
379            && let Some(last) = self.samples.back().copied()
380        {
381            self.samples.clear();
382            self.samples.push_back(last);
383        }
384    }
385
386    fn window_bytes(&self, now: SystemTime, window: Duration) -> (u64, u64) {
387        if self.samples.back().is_some_and(|sample| {
388            now.duration_since(sample.timestamp).unwrap_or_default() >= window
389        }) {
390            return (0, 0);
391        }
392        match (self.samples.front(), self.samples.back()) {
393            (Some(first), Some(last)) => (
394                last.tx_bytes.saturating_sub(first.tx_bytes),
395                last.rx_bytes.saturating_sub(first.rx_bytes),
396            ),
397            _ => (0, 0),
398        }
399    }
400}
401
402fn observe_flow_delta(
403    flow_counters: &mut HashMap<FlowIdentity, FlowCounters>,
404    conn: &Connection,
405    generation: u64,
406) -> TrafficDelta {
407    let identity = FlowIdentity::from_connection(conn);
408    match flow_counters.entry(identity) {
409        std::collections::hash_map::Entry::Occupied(mut entry) => {
410            let counters = entry.get_mut();
411            let delta = TrafficDelta {
412                tx_bytes: conn.bytes_sent.saturating_sub(counters.tx_bytes),
413                rx_bytes: conn.bytes_received.saturating_sub(counters.rx_bytes),
414            };
415            counters.tx_bytes = conn.bytes_sent;
416            counters.rx_bytes = conn.bytes_received;
417            counters.observed_generation = generation;
418            delta
419        }
420        std::collections::hash_map::Entry::Vacant(entry) => {
421            entry.insert(FlowCounters {
422                tx_bytes: conn.bytes_sent,
423                rx_bytes: conn.bytes_received,
424                observed_generation: generation,
425            });
426            TrafficDelta {
427                tx_bytes: conn.bytes_sent,
428                rx_bytes: conn.bytes_received,
429            }
430        }
431    }
432}
433
434/// Process traffic view derived from active and retained historic connections.
435pub struct ProcessActivityTracker {
436    config: ProcessActivityConfig,
437    sample: HashMap<ProcessIdentity, ProcessAccumulator>,
438    flow_counters: HashMap<FlowIdentity, FlowCounters>,
439    sample_generation: u64,
440    histories: HashMap<ProcessIdentity, ProcessHistory>,
441    snapshot: ProcessActivitySnapshot,
442}
443
444impl ProcessActivityTracker {
445    pub fn new() -> Self {
446        Self::with_config(ProcessActivityConfig::default())
447    }
448
449    pub(crate) fn with_config(config: ProcessActivityConfig) -> Self {
450        Self {
451            config,
452            sample: HashMap::new(),
453            flow_counters: HashMap::new(),
454            sample_generation: 0,
455            histories: HashMap::new(),
456            snapshot: ProcessActivitySnapshot::default(),
457        }
458    }
459
460    /// Stream active and historic sources into one sample without cloning
461    /// their full [`Connection`] values.
462    ///
463    /// The historic callback is replayed once to choose a deterministic,
464    /// bounded set of completed process identities and once to aggregate it.
465    /// Callers must therefore provide stable sources for the duration of this
466    /// synchronous method.
467    pub fn observe_sources<A, H>(
468        &mut self,
469        now: SystemTime,
470        mut feed_active: A,
471        mut feed_historic: H,
472    ) where
473        A: FnMut(&mut dyn FnMut(&Connection)),
474        H: FnMut(&mut dyn FnMut(&Connection)),
475    {
476        self.sample.clear();
477        self.sample_generation = self.sample_generation.wrapping_add(1);
478        let generation = self.sample_generation;
479        let max_processes = self.config.max_completed_processes;
480        let mut traffic_deltas: HashMap<ProcessIdentity, TrafficDelta> = HashMap::new();
481
482        {
483            let sample = &mut self.sample;
484            let flow_counters = &mut self.flow_counters;
485            let mut observe = |conn: &Connection| {
486                let flow = FlowActivity::from_connection(conn);
487                let identity = flow.identity.clone();
488                sample
489                    .entry(identity.clone())
490                    .or_insert_with(ProcessAccumulator::new)
491                    .add_flow(&flow, false);
492                traffic_deltas
493                    .entry(identity)
494                    .or_default()
495                    .add(observe_flow_delta(flow_counters, conn, generation));
496            };
497            feed_active(&mut observe);
498        }
499
500        let mut completed_identities = BTreeSet::new();
501        {
502            let active = &self.sample;
503            let mut select = |conn: &Connection| {
504                let identity = ProcessIdentity::from_connection(conn);
505                if active.contains_key(&identity) {
506                    return;
507                }
508                completed_identities.insert(identity);
509                if completed_identities.len() > max_processes {
510                    completed_identities.pop_last();
511                }
512            };
513            feed_historic(&mut select);
514        }
515
516        {
517            let sample = &mut self.sample;
518            let flow_counters = &mut self.flow_counters;
519            let mut observe = |conn: &Connection| {
520                let flow = FlowActivity::from_connection(conn);
521                let identity = if sample.contains_key(&flow.identity)
522                    || completed_identities.contains(&flow.identity)
523                {
524                    flow.identity.clone()
525                } else {
526                    ProcessIdentity::overflow(flow.identity.attributed)
527                };
528                sample
529                    .entry(identity.clone())
530                    .or_insert_with(ProcessAccumulator::new)
531                    .add_flow(&flow, true);
532                traffic_deltas
533                    .entry(identity)
534                    .or_default()
535                    .add(observe_flow_delta(flow_counters, conn, generation));
536            };
537            feed_historic(&mut observe);
538        }
539
540        self.flow_counters
541            .retain(|_, counters| counters.observed_generation == generation);
542        self.rebuild_snapshot(now, &traffic_deltas);
543        self.sample.clear();
544    }
545
546    pub fn snapshot(&self) -> ProcessActivitySnapshot {
547        self.snapshot.clone()
548    }
549
550    pub fn clear(&mut self) {
551        self.sample.clear();
552        self.flow_counters.clear();
553        self.sample_generation = 0;
554        self.histories.clear();
555        self.snapshot = ProcessActivitySnapshot::default();
556    }
557
558    fn rebuild_snapshot(
559        &mut self,
560        now: SystemTime,
561        traffic_deltas: &HashMap<ProcessIdentity, TrafficDelta>,
562    ) {
563        self.histories
564            .retain(|identity, _| self.sample.contains_key(identity));
565
566        for (identity, aggregate) in &self.sample {
567            let is_new = !self.histories.contains_key(identity);
568            let delta = traffic_deltas.get(identity).copied().unwrap_or_default();
569            let (tx_delta, rx_delta) = if is_new {
570                (aggregate.tx_bytes, aggregate.rx_bytes)
571            } else {
572                (delta.tx_bytes, delta.rx_bytes)
573            };
574            self.histories.entry(identity.clone()).or_default().sample(
575                now,
576                tx_delta,
577                rx_delta,
578                self.config.window,
579                aggregate.active_connections > 0,
580            );
581        }
582
583        let mut processes = Vec::with_capacity(self.sample.len());
584        for (identity, aggregate) in &self.sample {
585            let history = self.histories.entry(identity.clone()).or_default();
586            let (window_tx_bytes, window_rx_bytes) = history.window_bytes(now, self.config.window);
587            let destination_count = aggregate.destinations.len();
588            let top_tx_destination = aggregate
589                .destinations
590                .values()
591                .max_by(|a, b| {
592                    a.tx_bytes
593                        .cmp(&b.tx_bytes)
594                        .then_with(|| a.remote_addr.cmp(&b.remote_addr))
595                })
596                .cloned();
597            let top_rx_destination = aggregate
598                .destinations
599                .values()
600                .max_by(|a, b| {
601                    a.rx_bytes
602                        .cmp(&b.rx_bytes)
603                        .then_with(|| a.remote_addr.cmp(&b.remote_addr))
604                })
605                .cloned();
606            processes.push(ProcessActivity {
607                identity: identity.clone(),
608                current_tx_bps: history.current_tx_bps,
609                current_rx_bps: history.current_rx_bps,
610                window_tx_bytes,
611                window_rx_bytes,
612                peak_tx_bps: history.peak_tx_bps,
613                peak_rx_bps: history.peak_rx_bps,
614                retained_tx_bytes: aggregate.tx_bytes,
615                retained_rx_bytes: aggregate.rx_bytes,
616                active_connections: aggregate.active_connections,
617                total_connections: aggregate
618                    .completed_connections
619                    .saturating_add(aggregate.active_connections as u64),
620                unique_destinations: destination_count
621                    .min(self.config.max_destinations_per_process),
622                destinations_truncated: destination_count
623                    > self.config.max_destinations_per_process,
624                top_tx_destination,
625                top_rx_destination,
626                window_tx_share: 0.0,
627                window_rx_share: 0.0,
628                retained_tx_share: 0.0,
629                retained_rx_share: 0.0,
630            });
631        }
632
633        let current_tx_bps = processes.iter().map(|p| p.current_tx_bps).sum();
634        let current_rx_bps = processes.iter().map(|p| p.current_rx_bps).sum();
635        let window_tx_bytes = processes.iter().map(|p| p.window_tx_bytes).sum();
636        let window_rx_bytes = processes.iter().map(|p| p.window_rx_bytes).sum();
637        let retained_tx_bytes = processes.iter().map(|p| p.retained_tx_bytes).sum();
638        let retained_rx_bytes = processes.iter().map(|p| p.retained_rx_bytes).sum();
639        let attributed_tx_bytes = processes
640            .iter()
641            .filter(|p| p.identity.attributed)
642            .map(|p| p.retained_tx_bytes)
643            .sum();
644        let attributed_rx_bytes = processes
645            .iter()
646            .filter(|p| p.identity.attributed)
647            .map(|p| p.retained_rx_bytes)
648            .sum();
649
650        for process in &mut processes {
651            process.window_tx_share =
652                percentage(process.window_tx_bytes as f64, window_tx_bytes as f64);
653            process.window_rx_share =
654                percentage(process.window_rx_bytes as f64, window_rx_bytes as f64);
655            process.retained_tx_share =
656                percentage(process.retained_tx_bytes as f64, retained_tx_bytes as f64);
657            process.retained_rx_share =
658                percentage(process.retained_rx_bytes as f64, retained_rx_bytes as f64);
659        }
660        processes.sort_by(|a, b| {
661            b.retained_tx_bytes
662                .cmp(&a.retained_tx_bytes)
663                .then_with(|| a.identity.name.cmp(&b.identity.name))
664                .then_with(|| a.identity.pid.cmp(&b.identity.pid))
665        });
666
667        self.snapshot = ProcessActivitySnapshot {
668            processes,
669            current_tx_bps,
670            current_rx_bps,
671            window_tx_bytes,
672            window_rx_bytes,
673            retained_tx_bytes,
674            retained_rx_bytes,
675            attributed_tx_bytes,
676            attributed_rx_bytes,
677        };
678    }
679}
680
681impl Default for ProcessActivityTracker {
682    fn default() -> Self {
683        Self::new()
684    }
685}
686
687fn percentage(part: f64, total: f64) -> f64 {
688    if total > 0.0 {
689        (part / total * 100.0).clamp(0.0, 100.0)
690    } else {
691        0.0
692    }
693}
694
695fn destination_label(conn: &Connection) -> Option<String> {
696    let dpi = conn.dpi_info.as_ref()?;
697    dpi.application.hostname().map(str::to_string)
698}
699
700#[cfg(test)]
701mod tests {
702    use super::*;
703    use crate::network::types::{Protocol, ProtocolState, TcpState};
704    use std::net::{IpAddr, Ipv4Addr};
705
706    impl ProcessActivityTracker {
707        /// Test shorthand: feed one complete active-plus-historic connection
708        /// slice through [`observe_sources`](Self::observe_sources).
709        fn observe_connections(&mut self, connections: &[Connection], now: SystemTime) {
710            self.observe_sources(
711                now,
712                |observe| {
713                    for connection in connections.iter().filter(|conn| !conn.is_historic) {
714                        observe(connection);
715                    }
716                },
717                |observe| {
718                    for connection in connections.iter().filter(|conn| conn.is_historic) {
719                        observe(connection);
720                    }
721                },
722            );
723        }
724    }
725
726    fn connection(pid: Option<u32>, name: Option<&str>, remote_port: u16) -> Connection {
727        let mut conn = Connection::new(
728            Protocol::Tcp,
729            SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 40_000 + remote_port),
730            SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 10)), remote_port),
731            ProtocolState::Tcp(TcpState::Established),
732        );
733        conn.pid = pid;
734        conn.process_name = name.map(str::to_string);
735        conn
736    }
737
738    #[test]
739    fn aggregates_active_and_retained_historic_flows() {
740        let start = SystemTime::UNIX_EPOCH + Duration::from_secs(100);
741        let mut a = connection(Some(7), Some("uploader"), 443);
742        let mut b = connection(Some(7), Some("uploader"), 8443);
743        a.created_at = start;
744        b.created_at = start + Duration::from_millis(1);
745        a.bytes_sent = 800;
746        b.bytes_sent = 200;
747
748        let mut tracker = ProcessActivityTracker::new();
749        tracker.observe_connections(&[a.clone(), b.clone()], start + Duration::from_secs(1));
750        a.is_historic = true;
751        tracker.observe_connections(&[a, b], start + Duration::from_secs(2));
752
753        let snapshot = tracker.snapshot();
754        let process = &snapshot.processes[0];
755        assert_eq!(process.retained_tx_bytes, 1000);
756        assert_eq!(process.active_connections, 1);
757        assert_eq!(process.total_connections, 2);
758        assert_eq!(process.unique_destinations, 2);
759    }
760
761    #[test]
762    fn late_attribution_moves_active_bytes_out_of_unknown() {
763        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(200);
764        let mut conn = connection(None, None, 443);
765        conn.created_at = now;
766        conn.bytes_sent = 4096;
767
768        let mut tracker = ProcessActivityTracker::new();
769        tracker.observe_connections(&[conn.clone()], now + Duration::from_secs(1));
770        assert!(!tracker.snapshot().processes[0].identity.attributed);
771
772        conn.pid = Some(42);
773        conn.process_name = Some("agent-helper".to_string());
774        tracker.observe_connections(&[conn], now + Duration::from_secs(2));
775        let snapshot = tracker.snapshot();
776        assert_eq!(snapshot.processes.len(), 1);
777        assert_eq!(snapshot.processes[0].identity.pid, Some(42));
778        assert_eq!(snapshot.attributed_tx_bytes, 4096);
779    }
780
781    #[test]
782    fn repeated_historic_observations_are_idempotent() {
783        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(300);
784        let mut conn = connection(Some(9), Some("once"), 443);
785        conn.created_at = now;
786        conn.bytes_sent = 1234;
787        conn.is_historic = true;
788
789        let mut tracker = ProcessActivityTracker::new();
790        tracker.observe_connections(&[conn.clone()], now + Duration::from_secs(1));
791        tracker.observe_connections(&[conn], now + Duration::from_secs(2));
792
793        let process = &tracker.snapshot().processes[0];
794        assert_eq!(process.retained_tx_bytes, 1234);
795        assert_eq!(process.active_connections, 0);
796        assert_eq!(process.total_connections, 1);
797    }
798
799    #[test]
800    fn calculates_current_window_and_retained_shares() {
801        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(400);
802        let mut first = connection(Some(1), Some("first"), 443);
803        let mut second = connection(Some(2), Some("second"), 443);
804        first.created_at = now;
805        second.created_at = now + Duration::from_millis(1);
806
807        let mut tracker = ProcessActivityTracker::new();
808        tracker.observe_connections(
809            &[first.clone(), second.clone()],
810            now + Duration::from_secs(1),
811        );
812        first.bytes_sent = 750;
813        second.bytes_sent = 250;
814        first.bytes_received = 250;
815        second.bytes_received = 750;
816        tracker.observe_connections(&[first, second], now + Duration::from_secs(2));
817
818        let snapshot = tracker.snapshot();
819        let first = snapshot
820            .processes
821            .iter()
822            .find(|process| process.identity.name == "first")
823            .unwrap();
824        assert_eq!(snapshot.window_tx_bytes, 1000);
825        assert_eq!(snapshot.window_rx_bytes, 1000);
826        assert_eq!(first.current_tx_bps, 750.0);
827        assert_eq!(first.current_rx_bps, 250.0);
828        assert_eq!(first.peak_rx_bps, 250.0);
829        assert_eq!(first.window_tx_share, 75.0);
830        assert_eq!(first.window_rx_share, 25.0);
831        assert_eq!(first.retained_tx_share, 75.0);
832        assert_eq!(first.retained_rx_share, 25.0);
833    }
834
835    #[test]
836    fn first_observation_is_visible_in_the_window_without_a_fake_rate() {
837        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(500);
838        let mut conn = connection(Some(12), Some("quick-uploader"), 443);
839        conn.created_at = now;
840        conn.bytes_sent = 64 * 1024 * 1024;
841
842        let mut tracker = ProcessActivityTracker::new();
843        tracker.observe_connections(&[conn], now + Duration::from_secs(1));
844
845        let process = &tracker.snapshot().processes[0];
846        assert_eq!(process.window_tx_bytes, 64 * 1024 * 1024);
847        assert_eq!(process.current_tx_bps, 0.0);
848        assert_eq!(process.window_tx_share, 100.0);
849    }
850
851    #[test]
852    fn historic_eviction_preserves_new_traffic_in_both_directions() {
853        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(600);
854        let mut old = connection(Some(21), Some("worker"), 443);
855        let mut live = connection(Some(21), Some("worker"), 8443);
856        old.created_at = now;
857        live.created_at = now + Duration::from_millis(1);
858        old.bytes_sent = 10_000;
859        old.bytes_received = 100;
860        old.is_historic = true;
861
862        let mut tracker = ProcessActivityTracker::new();
863        tracker.observe_connections(&[old, live.clone()], now + Duration::from_secs(1));
864
865        live.bytes_sent = 100;
866        live.bytes_received = 300;
867        tracker.observe_connections(&[live.clone()], now + Duration::from_secs(2));
868        let after_eviction = &tracker.snapshot().processes[0];
869        assert_eq!(after_eviction.retained_tx_bytes, 100);
870        assert_eq!(after_eviction.retained_rx_bytes, 300);
871        assert_eq!(after_eviction.current_tx_bps, 100.0);
872        assert_eq!(after_eviction.current_rx_bps, 300.0);
873        assert_eq!(after_eviction.window_tx_bytes, 10_100);
874        assert_eq!(after_eviction.window_rx_bytes, 400);
875
876        live.bytes_sent = 300;
877        live.bytes_received = 500;
878        tracker.observe_connections(&[live], now + Duration::from_secs(3));
879        let resumed = &tracker.snapshot().processes[0];
880        assert_eq!(resumed.current_tx_bps, 200.0);
881        assert_eq!(resumed.current_rx_bps, 200.0);
882        assert_eq!(resumed.window_tx_bytes, 10_300);
883        assert_eq!(resumed.window_rx_bytes, 600);
884    }
885
886    #[test]
887    fn historic_eviction_does_not_reduce_a_larger_new_delta() {
888        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(650);
889        let mut old = connection(Some(22), Some("worker"), 443);
890        let mut live = connection(Some(22), Some("worker"), 8443);
891        old.created_at = now;
892        live.created_at = now + Duration::from_millis(1);
893        old.bytes_sent = 1_000;
894        old.is_historic = true;
895
896        let mut tracker = ProcessActivityTracker::new();
897        tracker.observe_connections(&[old, live.clone()], now + Duration::from_secs(1));
898
899        live.bytes_sent = 1_500;
900        tracker.observe_connections(&[live], now + Duration::from_secs(2));
901        let process = &tracker.snapshot().processes[0];
902        assert_eq!(process.retained_tx_bytes, 1_500);
903        assert_eq!(process.current_tx_bps, 1_500.0);
904        assert_eq!(process.window_tx_bytes, 2_500);
905    }
906
907    #[test]
908    fn full_connection_aggregation_is_transient() {
909        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(700);
910        let conn = connection(Some(33), Some("short-lived"), 443);
911        let mut tracker = ProcessActivityTracker::new();
912
913        tracker.observe_connections(&[conn], now);
914
915        assert!(tracker.sample.is_empty());
916        assert_eq!(tracker.snapshot().processes.len(), 1);
917        assert_eq!(tracker.histories.len(), 1);
918    }
919
920    #[test]
921    fn active_to_historic_transition_does_not_create_a_rate_spike() {
922        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(800);
923        let mut idle = connection(Some(44), Some("long-session"), 443);
924        let mut live = connection(Some(44), Some("long-session"), 8443);
925        idle.bytes_sent = 500 * 1024 * 1024;
926
927        let mut tracker = ProcessActivityTracker::new();
928        tracker.observe_connections(&[idle.clone(), live.clone()], now);
929
930        live.bytes_sent = 1024;
931        tracker.observe_connections(&[idle.clone(), live.clone()], now + Duration::from_secs(1));
932
933        idle.is_historic = true;
934        live.bytes_sent = 2048;
935        tracker.observe_connections(&[idle, live], now + Duration::from_secs(2));
936
937        let process = &tracker.snapshot().processes[0];
938        assert_eq!(process.current_tx_bps, 1024.0);
939        assert_eq!(process.peak_tx_bps, 1024.0);
940        assert_eq!(process.window_tx_bytes, 500 * 1024 * 1024 + 2048);
941    }
942
943    #[test]
944    fn completed_process_overflow_is_independent_of_source_order() {
945        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(900);
946        let mut connections: Vec<_> = (1..=4)
947            .map(|pid| {
948                let mut conn = connection(Some(pid), Some(&format!("process-{pid}")), 443);
949                conn.bytes_sent = u64::from(pid) * 100;
950                conn.is_historic = true;
951                conn
952            })
953            .collect();
954        let config = ProcessActivityConfig {
955            max_completed_processes: 2,
956            ..ProcessActivityConfig::default()
957        };
958        let mut tracker = ProcessActivityTracker::with_config(config);
959
960        tracker.observe_connections(&connections, now);
961        let first: Vec<_> = tracker
962            .snapshot()
963            .processes
964            .iter()
965            .map(|process| (process.identity.display_name(), process.retained_tx_bytes))
966            .collect();
967
968        connections.reverse();
969        tracker.observe_connections(&connections, now + Duration::from_secs(1));
970        let second: Vec<_> = tracker
971            .snapshot()
972            .processes
973            .iter()
974            .map(|process| (process.identity.display_name(), process.retained_tx_bytes))
975            .collect();
976
977        assert_eq!(second, first);
978        assert!(second.contains(&("process-1 (1)".to_string(), 100)));
979        assert!(second.contains(&("process-2 (2)".to_string(), 200)));
980        assert!(second.contains(&(OTHER_NAME.to_string(), 700)));
981        assert!(
982            tracker
983                .snapshot()
984                .processes
985                .iter()
986                .all(|process| process.current_tx_bps == 0.0)
987        );
988    }
989
990    #[test]
991    fn destination_cap_does_not_hide_the_highest_volume_peer() {
992        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000);
993        let mut low = connection(Some(55), Some("scanner"), 80);
994        let mut medium = connection(Some(55), Some("scanner"), 443);
995        let mut highest = connection(Some(55), Some("scanner"), 8443);
996        low.bytes_sent = 10;
997        medium.bytes_sent = 20;
998        highest.bytes_sent = 10_000;
999        low.bytes_received = 30;
1000        medium.bytes_received = 40;
1001        highest.bytes_received = 20_000;
1002
1003        let config = ProcessActivityConfig {
1004            max_destinations_per_process: 2,
1005            ..ProcessActivityConfig::default()
1006        };
1007        let mut tracker = ProcessActivityTracker::with_config(config);
1008        tracker.observe_connections(&[low, medium, highest], now);
1009
1010        let process = &tracker.snapshot().processes[0];
1011        assert_eq!(process.unique_destinations, 2);
1012        assert!(process.destinations_truncated);
1013        assert_eq!(
1014            process
1015                .top_tx_destination
1016                .as_ref()
1017                .map(|destination| destination.remote_addr.port()),
1018            Some(8443)
1019        );
1020        assert_eq!(
1021            process
1022                .top_rx_destination
1023                .as_ref()
1024                .map(|destination| destination.remote_addr.port()),
1025            Some(8443)
1026        );
1027    }
1028}