1use crate::network::tracker::HistoricKey;
10use crate::network::types::{Connection, ConnectionKey, UNKNOWN_PROCESS_NAME};
11use std::collections::{BTreeSet, HashMap, VecDeque};
12use std::net::SocketAddr;
13use std::time::{Duration, SystemTime};
14
15const OTHER_NAME: &str = "Other";
16
17pub const UNKNOWN_PROCESS_GROUP: &str = "<unknown>";
19
20pub fn process_group_label(conn: &Connection) -> &str {
25 match conn.process_name.as_deref() {
26 None | Some(UNKNOWN_PROCESS_NAME) => UNKNOWN_PROCESS_GROUP,
27 Some(name) => name,
28 }
29}
30
31#[derive(Debug, Clone)]
33pub(crate) struct ProcessActivityConfig {
34 pub max_completed_processes: usize,
38 pub max_destinations_per_process: usize,
42 pub window: Duration,
44}
45
46impl Default for ProcessActivityConfig {
47 fn default() -> Self {
48 Self {
49 max_completed_processes: 4096,
50 max_destinations_per_process: 256,
51 window: Duration::from_secs(60),
52 }
53 }
54}
55
56#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
58pub struct ProcessIdentity {
59 pub pid: Option<u32>,
60 pub name: String,
61 pub attributed: bool,
62}
63
64impl ProcessIdentity {
65 fn from_connection(conn: &Connection) -> Self {
66 let attributed = conn.pid.is_some() || conn.process_name.is_some();
67 Self {
68 pid: conn.pid,
69 name: conn
70 .process_name
71 .clone()
72 .unwrap_or_else(|| UNKNOWN_PROCESS_NAME.to_string()),
73 attributed,
74 }
75 }
76
77 fn overflow(attributed: bool) -> Self {
78 Self {
79 pid: None,
80 name: if attributed {
81 OTHER_NAME.to_string()
82 } else {
83 UNKNOWN_PROCESS_NAME.to_string()
84 },
85 attributed,
86 }
87 }
88
89 pub fn application_identity(&self) -> Self {
91 let unknown = self.name == UNKNOWN_PROCESS_NAME;
92 Self {
93 pid: None,
94 name: self.name.clone(),
95 attributed: !unknown && self.attributed,
96 }
97 }
98
99 pub fn connection_filter_query(&self) -> Option<String> {
102 if self.name == OTHER_NAME && self.pid.is_none() {
103 return None;
104 }
105 let name: String = self
106 .name
107 .chars()
108 .map(|ch| {
109 if ch.is_ascii_lowercase() || ch.is_ascii_digit() || matches!(ch, '_' | '-') {
110 ch.to_string()
111 } else {
112 format!("\\x{{{:x}}}", u32::from(ch))
113 }
114 })
115 .collect();
116 let mut query = format!("process:/^(?-i:{name})$/");
117 if let Some(pid) = self.pid {
118 query.push_str(&format!(" pid:{pid}"));
119 }
120 Some(query)
121 }
122
123 pub fn display_name(&self) -> String {
124 match self.pid {
125 Some(pid) => format!("{} ({pid})", self.name),
126 None => self.name.clone(),
127 }
128 }
129}
130
131#[derive(Debug, Clone)]
133pub struct DestinationActivity {
134 pub remote_addr: SocketAddr,
135 pub label: Option<String>,
136 pub tx_bytes: u64,
137 pub rx_bytes: u64,
138 pub connections: u64,
139}
140
141impl DestinationActivity {
142 pub fn display_name(&self) -> String {
143 self.label
144 .as_ref()
145 .map(|label| format!("{label}:{}", self.remote_addr.port()))
146 .unwrap_or_else(|| self.remote_addr.to_string())
147 }
148}
149
150#[derive(Debug, Clone)]
152pub struct ProcessActivity {
153 pub identity: ProcessIdentity,
154 pub current_tx_bps: f64,
155 pub current_rx_bps: f64,
156 pub average_tx_bps: f64,
157 pub average_rx_bps: f64,
158 pub window_tx_bytes: u64,
159 pub window_rx_bytes: u64,
160 pub peak_tx_bps: f64,
161 pub peak_rx_bps: f64,
162 pub retained_tx_bytes: u64,
163 pub retained_rx_bytes: u64,
164 pub active_connections: usize,
165 pub total_connections: u64,
166 pub unique_destinations: usize,
167 pub destinations_truncated: bool,
168 pub top_tx_destination: Option<DestinationActivity>,
169 pub top_rx_destination: Option<DestinationActivity>,
170 pub window_tx_share: f64,
171 pub window_rx_share: f64,
172 pub retained_tx_share: f64,
173 pub retained_rx_share: f64,
174}
175
176#[derive(Debug, Clone)]
178pub struct ProcessActivitySnapshot {
179 pub processes: Vec<ProcessActivity>,
180 pub applications: Vec<ProcessActivity>,
182 pub current_tx_bps: f64,
183 pub current_rx_bps: f64,
184 pub window_tx_bytes: u64,
185 pub window_rx_bytes: u64,
186 pub retained_tx_bytes: u64,
187 pub retained_rx_bytes: u64,
188 pub attributed_tx_bytes: u64,
189 pub attributed_rx_bytes: u64,
190}
191
192impl Default for ProcessActivitySnapshot {
193 fn default() -> Self {
194 Self {
195 processes: Vec::new(),
196 applications: Vec::new(),
197 current_tx_bps: 0.0,
198 current_rx_bps: 0.0,
199 window_tx_bytes: 0,
200 window_rx_bytes: 0,
201 retained_tx_bytes: 0,
202 retained_rx_bytes: 0,
203 attributed_tx_bytes: 0,
204 attributed_rx_bytes: 0,
205 }
206 }
207}
208
209impl ProcessActivitySnapshot {
210 pub fn tx_attribution_pct(&self) -> f64 {
211 percentage(
212 self.attributed_tx_bytes as f64,
213 self.retained_tx_bytes as f64,
214 )
215 }
216
217 pub fn rx_attribution_pct(&self) -> f64 {
218 percentage(
219 self.attributed_rx_bytes as f64,
220 self.retained_rx_bytes as f64,
221 )
222 }
223}
224
225#[derive(Debug, Clone)]
226struct FlowActivity {
227 identity: ProcessIdentity,
228 bytes_sent: u64,
229 bytes_received: u64,
230 remote_addr: SocketAddr,
231 remote_label: Option<String>,
232}
233
234impl FlowActivity {
235 fn from_connection(conn: &Connection) -> Self {
236 Self {
237 identity: ProcessIdentity::from_connection(conn),
238 bytes_sent: conn.bytes_sent,
239 bytes_received: conn.bytes_received,
240 remote_addr: conn.remote_addr,
241 remote_label: destination_label(conn),
242 }
243 }
244}
245
246fn flow_identity(conn: &Connection) -> HistoricKey {
251 HistoricKey::for_connection(ConnectionKey::from_connection(conn), conn)
252}
253
254#[derive(Debug, Clone, Copy)]
255struct FlowCounters {
256 tx_bytes: u64,
257 rx_bytes: u64,
258 observed_generation: u64,
259}
260
261#[derive(Debug, Clone, Copy, Default)]
262struct TrafficDelta {
263 tx_bytes: u64,
264 rx_bytes: u64,
265}
266
267impl TrafficDelta {
268 fn add(&mut self, other: Self) {
269 self.tx_bytes = self.tx_bytes.saturating_add(other.tx_bytes);
270 self.rx_bytes = self.rx_bytes.saturating_add(other.rx_bytes);
271 }
272}
273
274#[derive(Debug, Clone)]
275struct ProcessAccumulator {
276 tx_bytes: u64,
277 rx_bytes: u64,
278 active_connections: usize,
279 completed_connections: u64,
280 destinations: HashMap<SocketAddr, DestinationActivity>,
281}
282
283impl ProcessAccumulator {
284 fn new() -> Self {
285 Self {
286 tx_bytes: 0,
287 rx_bytes: 0,
288 active_connections: 0,
289 completed_connections: 0,
290 destinations: HashMap::new(),
291 }
292 }
293
294 fn merge(&mut self, other: &Self) {
295 self.tx_bytes = self.tx_bytes.saturating_add(other.tx_bytes);
296 self.rx_bytes = self.rx_bytes.saturating_add(other.rx_bytes);
297 self.active_connections = self
298 .active_connections
299 .saturating_add(other.active_connections);
300 self.completed_connections = self
301 .completed_connections
302 .saturating_add(other.completed_connections);
303 for (address, peer) in &other.destinations {
304 let combined =
305 self.destinations
306 .entry(*address)
307 .or_insert_with(|| DestinationActivity {
308 remote_addr: *address,
309 label: peer.label.clone(),
310 tx_bytes: 0,
311 rx_bytes: 0,
312 connections: 0,
313 });
314 combined.tx_bytes = combined.tx_bytes.saturating_add(peer.tx_bytes);
315 combined.rx_bytes = combined.rx_bytes.saturating_add(peer.rx_bytes);
316 combined.connections = combined.connections.saturating_add(peer.connections);
317 if combined.label.is_none() {
318 combined.label.clone_from(&peer.label);
319 }
320 }
321 }
322
323 fn top_peer(&self, transmit: bool) -> Option<DestinationActivity> {
324 self.destinations
325 .values()
326 .max_by(|a, b| {
327 let bytes = |peer: &DestinationActivity| {
328 if transmit {
329 peer.tx_bytes
330 } else {
331 peer.rx_bytes
332 }
333 };
334 bytes(a)
335 .cmp(&bytes(b))
336 .then_with(|| a.remote_addr.cmp(&b.remote_addr))
337 })
338 .cloned()
339 }
340
341 fn add_flow(&mut self, flow: &FlowActivity, completed: bool) {
342 self.tx_bytes = self.tx_bytes.saturating_add(flow.bytes_sent);
343 self.rx_bytes = self.rx_bytes.saturating_add(flow.bytes_received);
344 if completed {
345 self.completed_connections = self.completed_connections.saturating_add(1);
346 } else {
347 self.active_connections = self.active_connections.saturating_add(1);
348 }
349 self.add_destination(flow);
350 }
351
352 fn add_destination(&mut self, flow: &FlowActivity) {
353 if let Some(destination) = self.destinations.get_mut(&flow.remote_addr) {
354 destination.tx_bytes = destination.tx_bytes.saturating_add(flow.bytes_sent);
355 destination.rx_bytes = destination.rx_bytes.saturating_add(flow.bytes_received);
356 destination.connections = destination.connections.saturating_add(1);
357 if destination.label.is_none() {
358 destination.label.clone_from(&flow.remote_label);
359 }
360 return;
361 }
362
363 self.destinations.insert(
364 flow.remote_addr,
365 DestinationActivity {
366 remote_addr: flow.remote_addr,
367 label: flow.remote_label.clone(),
368 tx_bytes: flow.bytes_sent,
369 rx_bytes: flow.bytes_received,
370 connections: 1,
371 },
372 );
373 }
374}
375
376#[derive(Debug, Clone, Copy)]
377struct ProcessSample {
378 timestamp: SystemTime,
379 tx_bytes: u64,
380 rx_bytes: u64,
381}
382
383#[derive(Debug, Default)]
384struct ProcessHistory {
385 samples: VecDeque<ProcessSample>,
386 cumulative_tx_bytes: u64,
387 cumulative_rx_bytes: u64,
388 current_tx_bps: f64,
389 current_rx_bps: f64,
390 peak_tx_bps: f64,
391 peak_rx_bps: f64,
392}
393
394impl ProcessHistory {
395 fn sample(
396 &mut self,
397 now: SystemTime,
398 tx_delta: u64,
399 rx_delta: u64,
400 window: Duration,
401 active: bool,
402 ) {
403 if self.samples.is_empty() {
404 self.samples.push_back(ProcessSample {
408 timestamp: now,
409 tx_bytes: self.cumulative_tx_bytes,
410 rx_bytes: self.cumulative_rx_bytes,
411 });
412 }
413
414 self.cumulative_tx_bytes = self.cumulative_tx_bytes.saturating_add(tx_delta);
415 self.cumulative_rx_bytes = self.cumulative_rx_bytes.saturating_add(rx_delta);
416 let tx_bytes = self.cumulative_tx_bytes;
417 let rx_bytes = self.cumulative_rx_bytes;
418
419 let unchanged = self
420 .samples
421 .back()
422 .is_some_and(|sample| sample.tx_bytes == tx_bytes && sample.rx_bytes == rx_bytes);
423 if !active && unchanged {
424 self.current_tx_bps = 0.0;
425 self.current_rx_bps = 0.0;
426 self.prune(now, window, false);
427 return;
428 }
429
430 if let Some(previous) = self.samples.back().copied() {
431 let elapsed = now
432 .duration_since(previous.timestamp)
433 .unwrap_or_default()
434 .as_secs_f64();
435 if elapsed > 0.0 {
436 self.current_tx_bps = tx_bytes.saturating_sub(previous.tx_bytes) as f64 / elapsed;
437 self.current_rx_bps = rx_bytes.saturating_sub(previous.rx_bytes) as f64 / elapsed;
438 self.peak_tx_bps = self.peak_tx_bps.max(self.current_tx_bps);
439 self.peak_rx_bps = self.peak_rx_bps.max(self.current_rx_bps);
440 }
441 }
442
443 self.samples.push_back(ProcessSample {
444 timestamp: now,
445 tx_bytes,
446 rx_bytes,
447 });
448
449 self.prune(now, window, active);
450 }
451
452 fn prune(&mut self, now: SystemTime, window: Duration, active: bool) {
453 while self.samples.len() > 2
454 && self.samples.get(1).is_some_and(|sample| {
455 now.duration_since(sample.timestamp).unwrap_or_default() >= window
456 })
457 {
458 self.samples.pop_front();
459 }
460
461 if !active
462 && self.samples.back().is_some_and(|sample| {
463 now.duration_since(sample.timestamp).unwrap_or_default() >= window
464 })
465 && let Some(last) = self.samples.back().copied()
466 {
467 self.samples.clear();
468 self.samples.push_back(last);
469 }
470 }
471
472 fn recent_average(&self, now: SystemTime) -> (f64, f64) {
476 let Some(first) = self.samples.front() else {
477 return (0.0, 0.0);
478 };
479 let duration = now
480 .duration_since(first.timestamp)
481 .unwrap_or_default()
482 .as_secs_f64()
483 .min(2.0);
484 if duration <= 0.0 {
485 return (0.0, 0.0);
486 }
487 let mut rates = (0.0, 0.0);
488 for (older, newer) in self.samples.iter().zip(self.samples.iter().skip(1)).rev() {
489 let age = now
490 .duration_since(newer.timestamp)
491 .unwrap_or_default()
492 .as_secs_f64();
493 if age >= 2.0 {
494 break;
495 }
496 let elapsed = newer
497 .timestamp
498 .duration_since(older.timestamp)
499 .unwrap_or_default()
500 .as_secs_f64();
501 if elapsed > 0.0 {
502 let fraction = elapsed.min(2.0 - age) / elapsed;
503 rates.0 += newer.tx_bytes.saturating_sub(older.tx_bytes) as f64 * fraction;
504 rates.1 += newer.rx_bytes.saturating_sub(older.rx_bytes) as f64 * fraction;
505 }
506 }
507 (rates.0 / duration, rates.1 / duration)
508 }
509
510 fn window_bytes(&self, now: SystemTime, window: Duration) -> (u64, u64) {
511 if self.samples.back().is_some_and(|sample| {
512 now.duration_since(sample.timestamp).unwrap_or_default() >= window
513 }) {
514 return (0, 0);
515 }
516 match (self.samples.front(), self.samples.back()) {
517 (Some(first), Some(last)) => (
518 last.tx_bytes.saturating_sub(first.tx_bytes),
519 last.rx_bytes.saturating_sub(first.rx_bytes),
520 ),
521 _ => (0, 0),
522 }
523 }
524}
525
526fn observe_flow_delta(
527 flow_counters: &mut HashMap<HistoricKey, FlowCounters>,
528 conn: &Connection,
529 generation: u64,
530) -> TrafficDelta {
531 let identity = flow_identity(conn);
532 match flow_counters.entry(identity) {
533 std::collections::hash_map::Entry::Occupied(mut entry) => {
534 let counters = entry.get_mut();
535 let delta = TrafficDelta {
536 tx_bytes: conn.bytes_sent.saturating_sub(counters.tx_bytes),
537 rx_bytes: conn.bytes_received.saturating_sub(counters.rx_bytes),
538 };
539 counters.tx_bytes = conn.bytes_sent;
540 counters.rx_bytes = conn.bytes_received;
541 counters.observed_generation = generation;
542 delta
543 }
544 std::collections::hash_map::Entry::Vacant(entry) => {
545 entry.insert(FlowCounters {
546 tx_bytes: conn.bytes_sent,
547 rx_bytes: conn.bytes_received,
548 observed_generation: generation,
549 });
550 TrafficDelta {
551 tx_bytes: conn.bytes_sent,
552 rx_bytes: conn.bytes_received,
553 }
554 }
555 }
556}
557
558pub struct ProcessActivityTracker {
560 config: ProcessActivityConfig,
561 sample: HashMap<ProcessIdentity, ProcessAccumulator>,
562 flow_counters: HashMap<HistoricKey, FlowCounters>,
563 sample_generation: u64,
564 histories: HashMap<ProcessIdentity, ProcessHistory>,
565 application_peaks: HashMap<ProcessIdentity, (f64, f64)>,
566 snapshot: ProcessActivitySnapshot,
567}
568
569impl ProcessActivityTracker {
570 pub fn new() -> Self {
571 Self::with_config(ProcessActivityConfig::default())
572 }
573
574 pub(crate) fn with_config(config: ProcessActivityConfig) -> Self {
575 Self {
576 config,
577 sample: HashMap::new(),
578 flow_counters: HashMap::new(),
579 sample_generation: 0,
580 histories: HashMap::new(),
581 application_peaks: HashMap::new(),
582 snapshot: ProcessActivitySnapshot::default(),
583 }
584 }
585
586 pub fn observe_sources<A, H>(
594 &mut self,
595 now: SystemTime,
596 mut feed_active: A,
597 mut feed_historic: H,
598 ) where
599 A: FnMut(&mut dyn FnMut(&Connection)),
600 H: FnMut(&mut dyn FnMut(&Connection)),
601 {
602 self.sample.clear();
603 self.sample_generation = self.sample_generation.wrapping_add(1);
604 let generation = self.sample_generation;
605 let max_processes = self.config.max_completed_processes;
606 let mut traffic_deltas: HashMap<ProcessIdentity, TrafficDelta> = HashMap::new();
607
608 {
609 let sample = &mut self.sample;
610 let flow_counters = &mut self.flow_counters;
611 let mut observe = |conn: &Connection| {
612 let flow = FlowActivity::from_connection(conn);
613 let identity = flow.identity.clone();
614 sample
615 .entry(identity.clone())
616 .or_insert_with(ProcessAccumulator::new)
617 .add_flow(&flow, false);
618 traffic_deltas
619 .entry(identity)
620 .or_default()
621 .add(observe_flow_delta(flow_counters, conn, generation));
622 };
623 feed_active(&mut observe);
624 }
625
626 let mut completed_identities = BTreeSet::new();
627 {
628 let active = &self.sample;
629 let mut select = |conn: &Connection| {
630 let identity = ProcessIdentity::from_connection(conn);
631 if active.contains_key(&identity) {
632 return;
633 }
634 completed_identities.insert(identity);
635 if completed_identities.len() > max_processes {
636 completed_identities.pop_last();
637 }
638 };
639 feed_historic(&mut select);
640 }
641
642 {
643 let sample = &mut self.sample;
644 let flow_counters = &mut self.flow_counters;
645 let mut observe = |conn: &Connection| {
646 let flow = FlowActivity::from_connection(conn);
647 let identity = if sample.contains_key(&flow.identity)
648 || completed_identities.contains(&flow.identity)
649 {
650 flow.identity.clone()
651 } else {
652 ProcessIdentity::overflow(flow.identity.attributed)
653 };
654 sample
655 .entry(identity.clone())
656 .or_insert_with(ProcessAccumulator::new)
657 .add_flow(&flow, true);
658 traffic_deltas
659 .entry(identity)
660 .or_default()
661 .add(observe_flow_delta(flow_counters, conn, generation));
662 };
663 feed_historic(&mut observe);
664 }
665
666 self.flow_counters
667 .retain(|_, counters| counters.observed_generation == generation);
668 self.rebuild_snapshot(now, &traffic_deltas);
669 self.sample.clear();
670 }
671
672 pub fn snapshot(&self) -> ProcessActivitySnapshot {
673 self.snapshot.clone()
674 }
675
676 pub fn clear(&mut self) {
677 self.sample.clear();
678 self.flow_counters.clear();
679 self.sample_generation = 0;
680 self.histories.clear();
681 self.application_peaks.clear();
682 self.snapshot = ProcessActivitySnapshot::default();
683 }
684
685 fn rebuild_snapshot(
686 &mut self,
687 now: SystemTime,
688 traffic_deltas: &HashMap<ProcessIdentity, TrafficDelta>,
689 ) {
690 self.histories
691 .retain(|identity, _| self.sample.contains_key(identity));
692
693 for (identity, aggregate) in &self.sample {
694 let is_new = !self.histories.contains_key(identity);
695 let delta = traffic_deltas.get(identity).copied().unwrap_or_default();
696 let (tx_delta, rx_delta) = if is_new {
697 (aggregate.tx_bytes, aggregate.rx_bytes)
698 } else {
699 (delta.tx_bytes, delta.rx_bytes)
700 };
701 self.histories.entry(identity.clone()).or_default().sample(
702 now,
703 tx_delta,
704 rx_delta,
705 self.config.window,
706 aggregate.active_connections > 0,
707 );
708 }
709
710 let mut processes = Vec::with_capacity(self.sample.len());
711 for (identity, aggregate) in &self.sample {
712 let history = self.histories.entry(identity.clone()).or_default();
713 let (window_tx_bytes, window_rx_bytes) = history.window_bytes(now, self.config.window);
714 let destination_count = aggregate.destinations.len();
715 let top_tx_destination = aggregate.top_peer(true);
716 let top_rx_destination = aggregate.top_peer(false);
717 let (average_tx_bps, average_rx_bps) = history.recent_average(now);
718 processes.push(ProcessActivity {
719 identity: identity.clone(),
720 current_tx_bps: history.current_tx_bps,
721 current_rx_bps: history.current_rx_bps,
722 average_tx_bps,
723 average_rx_bps,
724 window_tx_bytes,
725 window_rx_bytes,
726 peak_tx_bps: history.peak_tx_bps,
727 peak_rx_bps: history.peak_rx_bps,
728 retained_tx_bytes: aggregate.tx_bytes,
729 retained_rx_bytes: aggregate.rx_bytes,
730 active_connections: aggregate.active_connections,
731 total_connections: aggregate
732 .completed_connections
733 .saturating_add(aggregate.active_connections as u64),
734 unique_destinations: destination_count
735 .min(self.config.max_destinations_per_process),
736 destinations_truncated: destination_count
737 > self.config.max_destinations_per_process,
738 top_tx_destination,
739 top_rx_destination,
740 window_tx_share: 0.0,
741 window_rx_share: 0.0,
742 retained_tx_share: 0.0,
743 retained_rx_share: 0.0,
744 });
745 }
746
747 let current_tx_bps = processes.iter().map(|p| p.current_tx_bps).sum();
748 let current_rx_bps = processes.iter().map(|p| p.current_rx_bps).sum();
749 let window_tx_bytes = processes.iter().map(|p| p.window_tx_bytes).sum();
750 let window_rx_bytes = processes.iter().map(|p| p.window_rx_bytes).sum();
751 let retained_tx_bytes = processes.iter().map(|p| p.retained_tx_bytes).sum();
752 let retained_rx_bytes = processes.iter().map(|p| p.retained_rx_bytes).sum();
753 let attributed_tx_bytes = processes
754 .iter()
755 .filter(|p| p.identity.attributed)
756 .map(|p| p.retained_tx_bytes)
757 .sum();
758 let attributed_rx_bytes = processes
759 .iter()
760 .filter(|p| p.identity.attributed)
761 .map(|p| p.retained_rx_bytes)
762 .sum();
763
764 for process in &mut processes {
765 process.window_tx_share =
766 percentage(process.window_tx_bytes as f64, window_tx_bytes as f64);
767 process.window_rx_share =
768 percentage(process.window_rx_bytes as f64, window_rx_bytes as f64);
769 process.retained_tx_share =
770 percentage(process.retained_tx_bytes as f64, retained_tx_bytes as f64);
771 process.retained_rx_share =
772 percentage(process.retained_rx_bytes as f64, retained_rx_bytes as f64);
773 }
774 processes.sort_by(|a, b| {
775 b.retained_tx_bytes
776 .cmp(&a.retained_tx_bytes)
777 .then_with(|| a.identity.name.cmp(&b.identity.name))
778 .then_with(|| a.identity.pid.cmp(&b.identity.pid))
779 });
780
781 let applications = self.application_totals(&processes);
782
783 self.snapshot = ProcessActivitySnapshot {
784 processes,
785 applications,
786 current_tx_bps,
787 current_rx_bps,
788 window_tx_bytes,
789 window_rx_bytes,
790 retained_tx_bytes,
791 retained_rx_bytes,
792 attributed_tx_bytes,
793 attributed_rx_bytes,
794 };
795 }
796
797 fn application_totals(&mut self, processes: &[ProcessActivity]) -> Vec<ProcessActivity> {
798 let mut groups: HashMap<ProcessIdentity, (ProcessActivity, ProcessAccumulator)> =
799 HashMap::new();
800 for process in processes {
801 let identity = process.identity.application_identity();
802 let aggregate = &self.sample[&process.identity];
803 match groups.entry(identity.clone()) {
804 std::collections::hash_map::Entry::Vacant(entry) => {
805 let mut summary = process.clone();
806 summary.identity = identity;
807 entry.insert((summary, aggregate.clone()));
808 }
809 std::collections::hash_map::Entry::Occupied(mut entry) => {
810 let (summary, combined) = entry.get_mut();
811 summary.current_tx_bps += process.current_tx_bps;
812 summary.current_rx_bps += process.current_rx_bps;
813 summary.average_tx_bps += process.average_tx_bps;
814 summary.average_rx_bps += process.average_rx_bps;
815 summary.window_tx_bytes = summary
816 .window_tx_bytes
817 .saturating_add(process.window_tx_bytes);
818 summary.window_rx_bytes = summary
819 .window_rx_bytes
820 .saturating_add(process.window_rx_bytes);
821 summary.window_tx_share += process.window_tx_share;
822 summary.window_rx_share += process.window_rx_share;
823 summary.retained_tx_share += process.retained_tx_share;
824 summary.retained_rx_share += process.retained_rx_share;
825 combined.merge(aggregate);
826 }
827 }
828 }
829 self.application_peaks
830 .retain(|identity, _| groups.contains_key(identity));
831 let mut applications = Vec::with_capacity(groups.len());
832 for (identity, (mut summary, aggregate)) in groups {
833 let peak = self.application_peaks.entry(identity).or_default();
834 peak.0 = peak.0.max(summary.current_tx_bps);
835 peak.1 = peak.1.max(summary.current_rx_bps);
836 summary.peak_tx_bps = peak.0;
837 summary.peak_rx_bps = peak.1;
838 summary.retained_tx_bytes = aggregate.tx_bytes;
839 summary.retained_rx_bytes = aggregate.rx_bytes;
840 summary.active_connections = aggregate.active_connections;
841 summary.total_connections = aggregate
842 .completed_connections
843 .saturating_add(aggregate.active_connections as u64);
844 summary.unique_destinations = aggregate
845 .destinations
846 .len()
847 .min(self.config.max_destinations_per_process);
848 summary.destinations_truncated =
849 aggregate.destinations.len() > self.config.max_destinations_per_process;
850 summary.top_tx_destination = aggregate.top_peer(true);
851 summary.top_rx_destination = aggregate.top_peer(false);
852 applications.push(summary);
853 }
854 applications.sort_by(|a, b| {
855 b.retained_tx_bytes
856 .cmp(&a.retained_tx_bytes)
857 .then_with(|| a.identity.cmp(&b.identity))
858 });
859 applications
860 }
861}
862
863impl Default for ProcessActivityTracker {
864 fn default() -> Self {
865 Self::new()
866 }
867}
868
869fn percentage(part: f64, total: f64) -> f64 {
870 if total > 0.0 {
871 (part / total * 100.0).clamp(0.0, 100.0)
872 } else {
873 0.0
874 }
875}
876
877fn destination_label(conn: &Connection) -> Option<String> {
878 let dpi = conn.dpi_info.as_ref()?;
879 dpi.application.hostname().map(str::to_string)
880}
881
882#[cfg(test)]
883mod tests {
884 use super::*;
885 use crate::network::types::{Protocol, ProtocolState, TcpState};
886 use std::net::{IpAddr, Ipv4Addr};
887
888 impl ProcessActivityTracker {
889 fn observe_connections(&mut self, connections: &[Connection], now: SystemTime) {
892 self.observe_sources(
893 now,
894 |observe| {
895 for connection in connections.iter().filter(|conn| !conn.is_historic) {
896 observe(connection);
897 }
898 },
899 |observe| {
900 for connection in connections.iter().filter(|conn| conn.is_historic) {
901 observe(connection);
902 }
903 },
904 );
905 }
906 }
907
908 fn connection(pid: Option<u32>, name: Option<&str>, remote_port: u16) -> Connection {
909 let mut conn = Connection::new(
910 Protocol::Tcp,
911 SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 40_000 + remote_port),
912 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 10)), remote_port),
913 ProtocolState::Tcp(TcpState::Established),
914 );
915 conn.pid = pid;
916 conn.process_name = name.map(str::to_string);
917 conn
918 }
919
920 #[test]
921 fn recent_average_preserves_bursts_and_expires_during_idle_time() {
922 let start = SystemTime::UNIX_EPOCH + Duration::from_secs(100);
923 let mut history = ProcessHistory::default();
924 let window = Duration::from_secs(60);
925 history.sample(start, 1_000_000, 2_000_000, window, true);
926 assert_eq!(history.recent_average(start), (0.0, 0.0));
927 history.sample(start + Duration::from_millis(500), 1000, 500, window, true);
928 assert_eq!(
929 history.recent_average(start + Duration::from_millis(500)),
930 (2000.0, 1000.0)
931 );
932 history.sample(start + Duration::from_secs(2), 0, 0, window, false);
933 assert_eq!(
934 history.recent_average(start + Duration::from_secs(2)),
935 (500.0, 250.0)
936 );
937 assert_eq!(
938 history.recent_average(start + Duration::from_millis(2250)),
939 (250.0, 125.0)
940 );
941 assert_eq!(
942 history.recent_average(start + Duration::from_secs(3)),
943 (0.0, 0.0)
944 );
945 }
946
947 #[test]
948 fn application_totals_merge_pids_and_deduplicate_peers_before_truncation() {
949 let now = SystemTime::UNIX_EPOCH + Duration::from_secs(100);
950 let mut flows: Vec<_> = [(1, 443, 100), (1, 8443, 90), (2, 9443, 100), (2, 8443, 90)]
951 .into_iter()
952 .enumerate()
953 .map(|(index, (pid, port, bytes))| {
954 let mut flow = connection(Some(pid), Some("gh"), port);
955 flow.local_addr.set_port(1000 + index as u16);
956 flow.bytes_sent = bytes;
957 flow.bytes_received = bytes * 2;
958 flow
959 })
960 .collect();
961 flows[0].is_historic = true;
962 let mut tracker = ProcessActivityTracker::with_config(ProcessActivityConfig {
963 max_destinations_per_process: 2,
964 ..Default::default()
965 });
966 tracker.observe_connections(&flows, now);
967 let snapshot = tracker.snapshot();
968 assert_eq!(snapshot.processes.len(), 2);
969 assert_eq!(snapshot.applications.len(), 1);
970 let app = &snapshot.applications[0];
971 assert_eq!(app.identity.name, "gh");
972 assert_eq!(app.identity.pid, None);
973 assert_eq!(app.retained_tx_bytes, 380);
974 assert_eq!(app.retained_rx_bytes, 760);
975 assert_eq!(app.active_connections, 3);
976 assert_eq!(app.total_connections, 4);
977 assert_eq!(app.unique_destinations, 2);
978 assert!(app.destinations_truncated);
979 assert_eq!(
980 app.top_tx_destination.as_ref().unwrap().remote_addr.port(),
981 8443
982 );
983 assert_eq!(app.top_tx_destination.as_ref().unwrap().tx_bytes, 180);
984 assert_eq!(app.top_rx_destination.as_ref().unwrap().rx_bytes, 360);
985 assert_eq!(app.window_tx_share, 100.0);
986 }
987
988 #[test]
989 fn application_peak_tracks_simultaneous_rates_and_survives_pid_turnover() {
990 let now = SystemTime::UNIX_EPOCH + Duration::from_secs(100);
991 let mut a = connection(Some(1), Some("gh"), 443);
992 let mut b = connection(Some(2), Some("gh"), 8443);
993 let mut tracker = ProcessActivityTracker::new();
994 tracker.observe_connections(&[a.clone(), b.clone()], now);
995 a.bytes_sent = 100;
996 tracker.observe_connections(&[a.clone(), b.clone()], now + Duration::from_secs(1));
997 b.bytes_sent = 100;
998 tracker.observe_connections(&[a.clone(), b.clone()], now + Duration::from_secs(2));
999 let snapshot = tracker.snapshot();
1000 assert_eq!(
1001 snapshot
1002 .processes
1003 .iter()
1004 .map(|p| p.peak_tx_bps)
1005 .sum::<f64>(),
1006 200.0
1007 );
1008 assert_eq!(snapshot.applications[0].peak_tx_bps, 100.0);
1009 a.bytes_sent += 100;
1010 b.bytes_sent += 100;
1011 tracker.observe_connections(&[a, b.clone()], now + Duration::from_secs(3));
1012 assert_eq!(tracker.snapshot().applications[0].peak_tx_bps, 200.0);
1013 tracker.observe_connections(&[b.clone()], now + Duration::from_secs(4));
1014 assert_eq!(tracker.snapshot().applications[0].peak_tx_bps, 200.0);
1015 tracker.clear();
1016 tracker.observe_connections(&[b], now + Duration::from_secs(5));
1017 assert_eq!(tracker.snapshot().applications[0].peak_tx_bps, 0.0);
1018 }
1019
1020 #[test]
1021 fn application_query_matches_exact_names_and_optional_pids() {
1022 use crate::network::filter::ConnectionFilter;
1023 for name in ["gh", "GH", "Code (Service)", "a/b.*[x]", "工具 App"] {
1024 let identity = ProcessIdentity {
1025 name: name.into(),
1026 pid: None,
1027 attributed: true,
1028 };
1029 let query = identity.connection_filter_query().unwrap();
1030 let filter = ConnectionFilter::parse(&query);
1031 assert!(
1032 filter.matches(&connection(Some(1), Some(name), 443)),
1033 "{query}"
1034 );
1035 assert!(!filter.matches(&connection(Some(1), Some(&format!("{name}-extra")), 443)));
1036 if name.to_lowercase() != name {
1037 assert!(!filter.matches(&connection(Some(1), Some(&name.to_lowercase()), 443)));
1038 }
1039 let mut identity = identity;
1040 identity.pid = Some(1);
1041 let filter = ConnectionFilter::parse(&identity.connection_filter_query().unwrap());
1042 assert!(filter.matches(&connection(Some(1), Some(name), 443)));
1043 assert!(!filter.matches(&connection(Some(10), Some(name), 443)));
1044 }
1045 let unknown = ProcessIdentity {
1046 name: UNKNOWN_PROCESS_NAME.into(),
1047 pid: None,
1048 attributed: false,
1049 };
1050 let filter = ConnectionFilter::parse(&unknown.connection_filter_query().unwrap());
1051 assert!(filter.matches(&connection(None, None, 443)));
1052 assert!(filter.matches(&connection(Some(1), Some(UNKNOWN_PROCESS_NAME), 443)));
1053 assert!(!ConnectionFilter::parse("pid:invalid").matches(&connection(None, None, 443)));
1054 }
1055
1056 #[test]
1057 fn process_group_label_folds_missing_and_placeholder_names() {
1058 let missing = connection(None, None, 80);
1059 let placeholder = connection(Some(7), Some(UNKNOWN_PROCESS_NAME), 443);
1060 let named = connection(Some(8), Some("curl"), 8443);
1061
1062 assert_eq!(process_group_label(&missing), UNKNOWN_PROCESS_GROUP);
1063 assert_eq!(process_group_label(&placeholder), UNKNOWN_PROCESS_GROUP);
1064 assert_eq!(process_group_label(&named), "curl");
1065 }
1066
1067 #[test]
1068 fn aggregates_active_and_retained_historic_flows() {
1069 let start = SystemTime::UNIX_EPOCH + Duration::from_secs(100);
1070 let mut a = connection(Some(7), Some("uploader"), 443);
1071 let mut b = connection(Some(7), Some("uploader"), 8443);
1072 a.created_at = start;
1073 b.created_at = start + Duration::from_millis(1);
1074 a.bytes_sent = 800;
1075 b.bytes_sent = 200;
1076
1077 let mut tracker = ProcessActivityTracker::new();
1078 tracker.observe_connections(&[a.clone(), b.clone()], start + Duration::from_secs(1));
1079 a.is_historic = true;
1080 tracker.observe_connections(&[a, b], start + Duration::from_secs(2));
1081
1082 let snapshot = tracker.snapshot();
1083 let process = &snapshot.processes[0];
1084 assert_eq!(process.retained_tx_bytes, 1000);
1085 assert_eq!(process.active_connections, 1);
1086 assert_eq!(process.total_connections, 2);
1087 assert_eq!(process.unique_destinations, 2);
1088 }
1089
1090 #[test]
1091 fn late_attribution_moves_active_bytes_out_of_unknown() {
1092 let now = SystemTime::UNIX_EPOCH + Duration::from_secs(200);
1093 let mut conn = connection(None, None, 443);
1094 conn.created_at = now;
1095 conn.bytes_sent = 4096;
1096
1097 let mut tracker = ProcessActivityTracker::new();
1098 tracker.observe_connections(&[conn.clone()], now + Duration::from_secs(1));
1099 assert!(!tracker.snapshot().processes[0].identity.attributed);
1100
1101 conn.pid = Some(42);
1102 conn.process_name = Some("agent-helper".to_string());
1103 tracker.observe_connections(&[conn], now + Duration::from_secs(2));
1104 let snapshot = tracker.snapshot();
1105 assert_eq!(snapshot.processes.len(), 1);
1106 assert_eq!(snapshot.processes[0].identity.pid, Some(42));
1107 assert_eq!(snapshot.attributed_tx_bytes, 4096);
1108 }
1109
1110 #[test]
1111 fn repeated_historic_observations_are_idempotent() {
1112 let now = SystemTime::UNIX_EPOCH + Duration::from_secs(300);
1113 let mut conn = connection(Some(9), Some("once"), 443);
1114 conn.created_at = now;
1115 conn.bytes_sent = 1234;
1116 conn.is_historic = true;
1117
1118 let mut tracker = ProcessActivityTracker::new();
1119 tracker.observe_connections(&[conn.clone()], now + Duration::from_secs(1));
1120 tracker.observe_connections(&[conn], now + Duration::from_secs(2));
1121
1122 let process = &tracker.snapshot().processes[0];
1123 assert_eq!(process.retained_tx_bytes, 1234);
1124 assert_eq!(process.active_connections, 0);
1125 assert_eq!(process.total_connections, 1);
1126 }
1127
1128 #[test]
1129 fn calculates_current_window_and_retained_shares() {
1130 let now = SystemTime::UNIX_EPOCH + Duration::from_secs(400);
1131 let mut first = connection(Some(1), Some("first"), 443);
1132 let mut second = connection(Some(2), Some("second"), 443);
1133 first.created_at = now;
1134 second.created_at = now + Duration::from_millis(1);
1135
1136 let mut tracker = ProcessActivityTracker::new();
1137 tracker.observe_connections(
1138 &[first.clone(), second.clone()],
1139 now + Duration::from_secs(1),
1140 );
1141 first.bytes_sent = 750;
1142 second.bytes_sent = 250;
1143 first.bytes_received = 250;
1144 second.bytes_received = 750;
1145 tracker.observe_connections(&[first, second], now + Duration::from_secs(2));
1146
1147 let snapshot = tracker.snapshot();
1148 let first = snapshot
1149 .processes
1150 .iter()
1151 .find(|process| process.identity.name == "first")
1152 .unwrap();
1153 assert_eq!(snapshot.window_tx_bytes, 1000);
1154 assert_eq!(snapshot.window_rx_bytes, 1000);
1155 assert_eq!(first.current_tx_bps, 750.0);
1156 assert_eq!(first.current_rx_bps, 250.0);
1157 assert_eq!(first.peak_rx_bps, 250.0);
1158 assert_eq!(first.window_tx_share, 75.0);
1159 assert_eq!(first.window_rx_share, 25.0);
1160 assert_eq!(first.retained_tx_share, 75.0);
1161 assert_eq!(first.retained_rx_share, 25.0);
1162 }
1163
1164 #[test]
1165 fn first_observation_is_visible_in_the_window_without_a_fake_rate() {
1166 let now = SystemTime::UNIX_EPOCH + Duration::from_secs(500);
1167 let mut conn = connection(Some(12), Some("quick-uploader"), 443);
1168 conn.created_at = now;
1169 conn.bytes_sent = 64 * 1024 * 1024;
1170
1171 let mut tracker = ProcessActivityTracker::new();
1172 tracker.observe_connections(&[conn], now + Duration::from_secs(1));
1173
1174 let process = &tracker.snapshot().processes[0];
1175 assert_eq!(process.window_tx_bytes, 64 * 1024 * 1024);
1176 assert_eq!(process.current_tx_bps, 0.0);
1177 assert_eq!(process.window_tx_share, 100.0);
1178 }
1179
1180 #[test]
1181 fn historic_eviction_preserves_new_traffic_in_both_directions() {
1182 let now = SystemTime::UNIX_EPOCH + Duration::from_secs(600);
1183 let mut old = connection(Some(21), Some("worker"), 443);
1184 let mut live = connection(Some(21), Some("worker"), 8443);
1185 old.created_at = now;
1186 live.created_at = now + Duration::from_millis(1);
1187 old.bytes_sent = 10_000;
1188 old.bytes_received = 100;
1189 old.is_historic = true;
1190
1191 let mut tracker = ProcessActivityTracker::new();
1192 tracker.observe_connections(&[old, live.clone()], now + Duration::from_secs(1));
1193
1194 live.bytes_sent = 100;
1195 live.bytes_received = 300;
1196 tracker.observe_connections(&[live.clone()], now + Duration::from_secs(2));
1197 let after_eviction = &tracker.snapshot().processes[0];
1198 assert_eq!(after_eviction.retained_tx_bytes, 100);
1199 assert_eq!(after_eviction.retained_rx_bytes, 300);
1200 assert_eq!(after_eviction.current_tx_bps, 100.0);
1201 assert_eq!(after_eviction.current_rx_bps, 300.0);
1202 assert_eq!(after_eviction.window_tx_bytes, 10_100);
1203 assert_eq!(after_eviction.window_rx_bytes, 400);
1204
1205 live.bytes_sent = 300;
1206 live.bytes_received = 500;
1207 tracker.observe_connections(&[live], now + Duration::from_secs(3));
1208 let resumed = &tracker.snapshot().processes[0];
1209 assert_eq!(resumed.current_tx_bps, 200.0);
1210 assert_eq!(resumed.current_rx_bps, 200.0);
1211 assert_eq!(resumed.window_tx_bytes, 10_300);
1212 assert_eq!(resumed.window_rx_bytes, 600);
1213 }
1214
1215 #[test]
1216 fn historic_eviction_does_not_reduce_a_larger_new_delta() {
1217 let now = SystemTime::UNIX_EPOCH + Duration::from_secs(650);
1218 let mut old = connection(Some(22), Some("worker"), 443);
1219 let mut live = connection(Some(22), Some("worker"), 8443);
1220 old.created_at = now;
1221 live.created_at = now + Duration::from_millis(1);
1222 old.bytes_sent = 1_000;
1223 old.is_historic = true;
1224
1225 let mut tracker = ProcessActivityTracker::new();
1226 tracker.observe_connections(&[old, live.clone()], now + Duration::from_secs(1));
1227
1228 live.bytes_sent = 1_500;
1229 tracker.observe_connections(&[live], now + Duration::from_secs(2));
1230 let process = &tracker.snapshot().processes[0];
1231 assert_eq!(process.retained_tx_bytes, 1_500);
1232 assert_eq!(process.current_tx_bps, 1_500.0);
1233 assert_eq!(process.window_tx_bytes, 2_500);
1234 }
1235
1236 #[test]
1237 fn full_connection_aggregation_is_transient() {
1238 let now = SystemTime::UNIX_EPOCH + Duration::from_secs(700);
1239 let conn = connection(Some(33), Some("short-lived"), 443);
1240 let mut tracker = ProcessActivityTracker::new();
1241
1242 tracker.observe_connections(&[conn], now);
1243
1244 assert!(tracker.sample.is_empty());
1245 assert_eq!(tracker.snapshot().processes.len(), 1);
1246 assert_eq!(tracker.histories.len(), 1);
1247 }
1248
1249 #[test]
1250 fn active_to_historic_transition_does_not_create_a_rate_spike() {
1251 let now = SystemTime::UNIX_EPOCH + Duration::from_secs(800);
1252 let mut idle = connection(Some(44), Some("long-session"), 443);
1253 let mut live = connection(Some(44), Some("long-session"), 8443);
1254 idle.bytes_sent = 500 * 1024 * 1024;
1255
1256 let mut tracker = ProcessActivityTracker::new();
1257 tracker.observe_connections(&[idle.clone(), live.clone()], now);
1258
1259 live.bytes_sent = 1024;
1260 tracker.observe_connections(&[idle.clone(), live.clone()], now + Duration::from_secs(1));
1261
1262 idle.is_historic = true;
1263 live.bytes_sent = 2048;
1264 tracker.observe_connections(&[idle, live], now + Duration::from_secs(2));
1265
1266 let process = &tracker.snapshot().processes[0];
1267 assert_eq!(process.current_tx_bps, 1024.0);
1268 assert_eq!(process.peak_tx_bps, 1024.0);
1269 assert_eq!(process.window_tx_bytes, 500 * 1024 * 1024 + 2048);
1270 }
1271
1272 #[test]
1273 fn completed_process_overflow_is_independent_of_source_order() {
1274 let now = SystemTime::UNIX_EPOCH + Duration::from_secs(900);
1275 let mut connections: Vec<_> = (1..=4)
1276 .map(|pid| {
1277 let mut conn = connection(Some(pid), Some(&format!("process-{pid}")), 443);
1278 conn.bytes_sent = u64::from(pid) * 100;
1279 conn.is_historic = true;
1280 conn
1281 })
1282 .collect();
1283 let config = ProcessActivityConfig {
1284 max_completed_processes: 2,
1285 ..ProcessActivityConfig::default()
1286 };
1287 let mut tracker = ProcessActivityTracker::with_config(config);
1288
1289 tracker.observe_connections(&connections, now);
1290 let first: Vec<_> = tracker
1291 .snapshot()
1292 .processes
1293 .iter()
1294 .map(|process| (process.identity.display_name(), process.retained_tx_bytes))
1295 .collect();
1296
1297 connections.reverse();
1298 tracker.observe_connections(&connections, now + Duration::from_secs(1));
1299 let second: Vec<_> = tracker
1300 .snapshot()
1301 .processes
1302 .iter()
1303 .map(|process| (process.identity.display_name(), process.retained_tx_bytes))
1304 .collect();
1305
1306 assert_eq!(second, first);
1307 assert!(second.contains(&("process-1 (1)".to_string(), 100)));
1308 assert!(second.contains(&("process-2 (2)".to_string(), 200)));
1309 assert!(second.contains(&(OTHER_NAME.to_string(), 700)));
1310 assert!(
1311 tracker
1312 .snapshot()
1313 .processes
1314 .iter()
1315 .all(|process| process.current_tx_bps == 0.0)
1316 );
1317 }
1318
1319 #[test]
1320 fn destination_cap_does_not_hide_the_highest_volume_peer() {
1321 let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000);
1322 let mut low = connection(Some(55), Some("scanner"), 80);
1323 let mut medium = connection(Some(55), Some("scanner"), 443);
1324 let mut highest = connection(Some(55), Some("scanner"), 8443);
1325 low.bytes_sent = 10;
1326 medium.bytes_sent = 20;
1327 highest.bytes_sent = 10_000;
1328 low.bytes_received = 30;
1329 medium.bytes_received = 40;
1330 highest.bytes_received = 20_000;
1331
1332 let config = ProcessActivityConfig {
1333 max_destinations_per_process: 2,
1334 ..ProcessActivityConfig::default()
1335 };
1336 let mut tracker = ProcessActivityTracker::with_config(config);
1337 tracker.observe_connections(&[low, medium, highest], now);
1338
1339 let process = &tracker.snapshot().processes[0];
1340 assert_eq!(process.unique_destinations, 2);
1341 assert!(process.destinations_truncated);
1342 assert_eq!(
1343 process
1344 .top_tx_destination
1345 .as_ref()
1346 .map(|destination| destination.remote_addr.port()),
1347 Some(8443)
1348 );
1349 assert_eq!(
1350 process
1351 .top_rx_destination
1352 .as_ref()
1353 .map(|destination| destination.remote_addr.port()),
1354 Some(8443)
1355 );
1356 }
1357}