Skip to main content

rustnet_core/network/
tracker.rs

1//! Live connection tracking.
2//!
3//! [`ConnectionTracker`] folds parsed packets into a long-lived, lifecycle-
4//! managed table of [`Connection`]s. It owns everything needed to turn a stream
5//! of [`ParsedPacket`]s into the same connection view the `rustnet` TUI shows —
6//! the active table, an archive of recently-closed ("historic") connections,
7//! RTT estimation from TCP SYN/SYN-ACK timing, QUIC connection-ID coalescing,
8//! and timeout-based cleanup — **without** any UI, capture, or process-lookup
9//! dependency.
10//!
11//! This is the piece that makes headless tools easy: pair a capture source with
12//! a parser, then feed each parsed packet to [`ConnectionTracker::ingest`] and
13//! periodically call [`ConnectionTracker::cleanup`]. A Prometheus exporter, a
14//! pcap post-processor, or a test harness can all reuse the exact connection
15//! semantics of the main application. Offline consumers replaying a saved trace
16//! should use [`ConnectionTracker::ingest_at`] with each packet's capture
17//! timestamp so connection lifetimes and timeouts follow trace time rather than
18//! the replay wall clock.
19//!
20//! ```no_run
21//! use rustnet_core::network::parser::PacketParser;
22//! use rustnet_core::network::tracker::ConnectionTracker;
23//! use std::time::SystemTime;
24//!
25//! let parser = PacketParser::new();
26//! let tracker = ConnectionTracker::new();
27//! # let frames: Vec<Vec<u8>> = Vec::new();
28//! for frame in frames {
29//!     if let Some(parsed) = parser.parse_packet(&frame) {
30//!         tracker.ingest(&parsed);
31//!     }
32//! }
33//! tracker.cleanup(SystemTime::now()); // expire idle/closed connections
34//! for conn in tracker.snapshot() {
35//!     println!("{} {} -> {}", conn.protocol, conn.local_addr, conn.remote_addr);
36//! }
37//! ```
38//!
39//! All methods take `&self` (the internal tables use interior mutability), so a
40//! single tracker can be wrapped in an [`std::sync::Arc`] and shared across a
41//! capture thread, a cleanup thread, and a reader thread.
42
43use crate::network::merge::{create_connection_from_packet, merge_packet_into_connection};
44use crate::network::parser::ParsedPacket;
45use crate::network::types::{ApplicationProtocol, Connection, ConnectionKey, Protocol, RttTracker};
46use dashmap::DashMap;
47use rustc_hash::FxBuildHasher;
48use std::collections::HashMap;
49use std::sync::Mutex;
50use std::sync::atomic::{AtomicUsize, Ordering};
51use std::time::{Duration, SystemTime};
52
53/// The active connection table: flow key -> connection.
54///
55/// Keys are compact `Copy` structs, and the map uses FxHash — with a small
56/// fixed-size key, hashing is a handful of multiplies instead of SipHash over
57/// a formatted string. (Hash-flooding resistance isn't needed here: the table
58/// is bounded by `max_connections` and keyed by addresses, not attacker-chosen
59/// bytes of arbitrary length.)
60pub type ConnectionMap = DashMap<ConnectionKey, Connection, FxBuildHasher>;
61
62/// The historic (recently-closed) connection table.
63pub type HistoricMap = DashMap<HistoricKey, Connection, FxBuildHasher>;
64
65/// Identity of an archived (closed) connection: the flow key plus the
66/// connection's creation time, so multiple closed connections that reused the
67/// same 4-tuple don't clobber each other. (Replaces the former
68/// `"<key>:<created_at_nanos>"` string suffix.)
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
70pub struct HistoricKey {
71    pub key: ConnectionKey,
72    pub created_nanos: u128,
73}
74
75impl std::fmt::Display for HistoricKey {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        write!(f, "{}:{}", self.key, self.created_nanos)
78    }
79}
80
81/// Tuning knobs for a [`ConnectionTracker`].
82#[derive(Debug, Clone)]
83pub struct TrackerConfig {
84    /// Maximum number of concurrent active connections. New connections beyond
85    /// this limit are dropped (existing ones still update) to bound memory
86    /// under port scans or connection floods.
87    pub max_connections: usize,
88    /// Maximum number of recently-closed ("historic") connections retained.
89    /// Oldest-closed entries are evicted first.
90    pub max_historic: usize,
91    /// Maximum number of QUIC connection-ID -> connection-key mappings kept for
92    /// coalescing migrated QUIC connections. Cleared wholesale when exceeded.
93    pub max_quic_mappings: usize,
94    /// Whether [`ConnectionTracker::cleanup`] archives removed connections into
95    /// the historic table. Headless tools that don't need a closed-connection
96    /// view can set this to `false` to save memory.
97    pub keep_historic: bool,
98}
99
100impl Default for TrackerConfig {
101    fn default() -> Self {
102        Self {
103            max_connections: 50_000,
104            max_historic: 5_000,
105            max_quic_mappings: 10_000,
106            keep_historic: true,
107        }
108    }
109}
110
111/// What happened when a packet was [`ingest`](ConnectionTracker::ingest)ed.
112///
113/// Returned so callers can layer their own concerns — global statistics,
114/// structured logging, DNS enrichment — on top of the core table update without
115/// the tracker needing to know about them.
116#[derive(Debug, Clone)]
117pub struct IngestOutcome {
118    /// The (possibly QUIC-coalesced) key under which the connection is stored.
119    /// `Copy`, and its `Display` form matches the historical string key
120    /// (`"TCP:1.2.3.4:80-TCP:5.6.7.8:443"`).
121    pub key: ConnectionKey,
122    /// `true` if this packet created a new connection entry.
123    pub created: bool,
124    /// `true` if the packet was dropped because `max_connections` was reached
125    /// (the connection did not already exist and was not inserted).
126    pub dropped: bool,
127    /// New TCP retransmissions detected by this packet.
128    pub retransmits: u64,
129    /// New out-of-order TCP segments detected by this packet.
130    pub out_of_order: u64,
131    /// New TCP fast-retransmits detected by this packet.
132    pub fast_retransmits: u64,
133    /// An RTT sample, if this packet was a TCP SYN-ACK that matched a prior SYN.
134    pub measured_rtt: Option<Duration>,
135}
136
137/// A live, lifecycle-managed table of network connections built from parsed
138/// packets. See the [module docs](self) for the intended usage.
139pub struct ConnectionTracker {
140    connections: ConnectionMap,
141    historic: HistoricMap,
142    rtt: Mutex<RttTracker>,
143    quic_map: Mutex<HashMap<String, ConnectionKey>>,
144    config: TrackerConfig,
145    /// Active-connection count maintained by `ingest_at`/`cleanup`/`clear`.
146    /// Lets the per-packet `max_connections` check be a single atomic load
147    /// instead of a `DashMap::len()` (which read-locks every shard) plus an
148    /// extra `contains_key` lookup. May transiently lag `connections.len()`
149    /// by a few entries under concurrent ingest near the limit — acceptable
150    /// for a flood-protection bound.
151    active_count: AtomicUsize,
152}
153
154impl ConnectionTracker {
155    /// Create a tracker with [default](TrackerConfig::default) configuration.
156    pub fn new() -> Self {
157        Self::with_config(TrackerConfig::default())
158    }
159
160    /// Create a tracker with custom [`TrackerConfig`].
161    pub fn with_config(config: TrackerConfig) -> Self {
162        Self {
163            connections: ConnectionMap::with_hasher(FxBuildHasher),
164            historic: HistoricMap::with_hasher(FxBuildHasher),
165            rtt: Mutex::new(RttTracker::new()),
166            quic_map: Mutex::new(HashMap::new()),
167            config,
168            active_count: AtomicUsize::new(0),
169        }
170    }
171
172    /// Fold a parsed packet into the connection table, creating or updating the
173    /// matching connection, timestamping the update with the current wall clock.
174    ///
175    /// This is the right call for live capture. Offline consumers replaying a
176    /// pcap should use [`ingest_at`](Self::ingest_at) and pass the packet's own
177    /// capture time so connection lifetimes and [`cleanup`](Self::cleanup)
178    /// timeouts reflect the trace rather than the replay wall clock.
179    pub fn ingest(&self, parsed: &ParsedPacket) -> IngestOutcome {
180        self.ingest_at(parsed, SystemTime::now())
181    }
182
183    /// Like [`ingest`](Self::ingest), but stamps the connection update with the
184    /// supplied `now` instead of the wall clock.
185    ///
186    /// Use this for deterministic offline processing (pcap replay, tests): pass
187    /// the packet's capture timestamp so `created_at`/`last_activity` and the
188    /// `cleanup` timeout sweep operate on trace time, not real time.
189    pub fn ingest_at(&self, parsed: &ParsedPacket, now: SystemTime) -> IngestOutcome {
190        let mut key = parsed.connection_key();
191
192        // Track RTT for TCP connections using SYN/SYN-ACK timing.
193        let mut measured_rtt: Option<Duration> = None;
194        if parsed.protocol == Protocol::Tcp
195            && let Some(tcp_header) = &parsed.tcp_header
196        {
197            if tcp_header.flags.syn && !tcp_header.flags.ack {
198                if let Ok(mut tracker) = self.rtt.lock() {
199                    tracker.record_syn(key);
200                }
201            } else if tcp_header.flags.syn
202                && tcp_header.flags.ack
203                && let Ok(mut tracker) = self.rtt.lock()
204            {
205                measured_rtt = tracker.record_syn_ack(&key);
206            }
207        }
208
209        // For QUIC packets, coalesce by connection ID so connection migration
210        // (address change) maps back to the original connection key.
211        if parsed.protocol == Protocol::Udp
212            && let Some(dpi_result) = &parsed.dpi_result
213            && let ApplicationProtocol::Quic(quic_info) = &dpi_result.application
214            && let Some(conn_id_hex) = &quic_info.connection_id_hex
215            && let Ok(mut mapping) = self.quic_map.lock()
216        {
217            if let Some(existing_key) = mapping.get(conn_id_hex) {
218                key = *existing_key;
219            } else {
220                // Prevent unbounded growth of QUIC connection-ID mappings.
221                if mapping.len() >= self.config.max_quic_mappings {
222                    mapping.clear();
223                }
224                mapping.insert(conn_id_hex.clone(), key);
225            }
226        }
227
228        // Prevent unbounded growth from port scans or connection floods. Only
229        // limit new connections; existing ones always get updated. The fast
230        // path is a single atomic load; only when at the cap do we pay a
231        // lookup to distinguish update-existing from drop-new. (Never call
232        // `len()` here or while holding an entry guard — it read-locks every
233        // shard.)
234        if self.active_count.load(Ordering::Relaxed) >= self.config.max_connections
235            && !self.connections.contains_key(&key)
236        {
237            return IngestOutcome {
238                key,
239                created: false,
240                dropped: true,
241                retransmits: 0,
242                out_of_order: 0,
243                fast_retransmits: 0,
244                measured_rtt,
245            };
246        }
247
248        let mut created = false;
249        let mut deltas = (0u64, 0u64, 0u64);
250        self.connections
251            .entry(key)
252            .and_modify(|conn| {
253                deltas = merge_packet_into_connection(conn, parsed, now);
254                if let Some(rtt) = measured_rtt
255                    && conn.initial_rtt.is_none()
256                {
257                    conn.initial_rtt = Some(rtt);
258                }
259            })
260            .or_insert_with(|| {
261                created = true;
262                let mut conn = create_connection_from_packet(parsed, now);
263                if let Some(rtt) = measured_rtt {
264                    conn.initial_rtt = Some(rtt);
265                }
266                conn
267            });
268        if created {
269            self.active_count.fetch_add(1, Ordering::Relaxed);
270        }
271
272        IngestOutcome {
273            key,
274            created,
275            dropped: false,
276            retransmits: deltas.0,
277            out_of_order: deltas.1,
278            fast_retransmits: deltas.2,
279            measured_rtt,
280        }
281    }
282
283    /// Remove connections whose protocol-aware timeout has elapsed as of `now`.
284    ///
285    /// Removed connections are archived into the historic table (when
286    /// [`keep_historic`](TrackerConfig::keep_historic) is set, subject to
287    /// [`max_historic`](TrackerConfig::max_historic) eviction) and their QUIC
288    /// mappings are dropped. Returns the removed connections (in their original,
289    /// pre-archive form) so callers can emit close events or export them.
290    pub fn cleanup(&self, now: SystemTime) -> Vec<Connection> {
291        let mut removed: Vec<Connection> = Vec::new();
292        let mut removed_keys: Vec<ConnectionKey> = Vec::new();
293        let mut to_archive: Vec<(HistoricKey, Connection)> = Vec::new();
294        let keep_historic = self.config.keep_historic;
295
296        self.connections.retain(|key, conn| {
297            let should_keep = !conn.should_cleanup(now);
298            if !should_keep {
299                removed_keys.push(*key);
300                removed.push(conn.clone());
301
302                // Archive a historic copy. The historic key includes created_at
303                // so multiple closed connections sharing a 4-tuple don't clobber
304                // each other. snapshot_clone: historic connections never refresh
305                // their rates, so don't pin the (potentially large) sample
306                // buffer in the archive.
307                if keep_historic {
308                    let mut historic = conn.snapshot_clone();
309                    historic.is_historic = true;
310                    historic.closed_at = Some(now);
311                    let historic_key = HistoricKey {
312                        key: *key,
313                        created_nanos: conn
314                            .created_at
315                            .duration_since(SystemTime::UNIX_EPOCH)
316                            .unwrap_or_default()
317                            .as_nanos(),
318                    };
319                    to_archive.push((historic_key, historic));
320                }
321            }
322            should_keep
323        });
324        if !removed.is_empty() {
325            self.active_count
326                .fetch_sub(removed.len(), Ordering::Relaxed);
327        }
328
329        if keep_historic {
330            for (key, conn) in to_archive {
331                self.historic.insert(key, conn);
332            }
333
334            // Enforce max_historic by evicting oldest-closed first.
335            if self.historic.len() > self.config.max_historic {
336                let mut entries: Vec<(HistoricKey, SystemTime)> = self
337                    .historic
338                    .iter()
339                    .map(|entry| {
340                        let closed = entry.value().closed_at.unwrap_or(entry.value().created_at);
341                        (*entry.key(), closed)
342                    })
343                    .collect();
344                entries.sort_by_key(|(_, closed)| *closed);
345                let to_remove = self.historic.len() - self.config.max_historic;
346                for (key, _) in entries.into_iter().take(to_remove) {
347                    self.historic.remove(&key);
348                }
349            }
350        }
351
352        // Clean up QUIC connection-ID mappings pointing at removed connections.
353        if !removed_keys.is_empty()
354            && let Ok(mut mapping) = self.quic_map.lock()
355        {
356            mapping.retain(|_, conn_key| !removed_keys.contains(conn_key));
357        }
358
359        removed
360    }
361
362    /// A point-in-time copy of the active connections.
363    ///
364    /// Note: this is a full clone, including each connection's rate-sample
365    /// buffer — the buffer is shared via `Arc`, so the *next* per-packet
366    /// update on a live connection pays a copy-on-write deep copy. Callers
367    /// that only need the cached `current_*_rate_bps` fields (any read-only
368    /// view) should prefer [`Connection::snapshot_clone`] over the entries of
369    /// [`connections`](Self::connections) to keep the packet path allocation-
370    /// free.
371    pub fn snapshot(&self) -> Vec<Connection> {
372        self.connections
373            .iter()
374            .map(|entry| entry.value().clone())
375            .collect()
376    }
377
378    /// A point-in-time copy of the historic (recently-closed) connections.
379    pub fn historic_snapshot(&self) -> Vec<Connection> {
380        self.historic
381            .iter()
382            .map(|entry| entry.value().clone())
383            .collect()
384    }
385
386    /// Number of active connections.
387    pub fn len(&self) -> usize {
388        self.connections.len()
389    }
390
391    /// `true` if there are no active connections.
392    pub fn is_empty(&self) -> bool {
393        self.connections.is_empty()
394    }
395
396    /// Number of historic (recently-closed) connections.
397    pub fn historic_len(&self) -> usize {
398        self.historic.len()
399    }
400
401    /// Drop all active and historic connections and reset RTT/QUIC state.
402    pub fn clear(&self) {
403        self.connections.clear();
404        self.active_count.store(0, Ordering::Relaxed);
405        self.historic.clear();
406        if let Ok(mut tracker) = self.rtt.lock() {
407            tracker.clear();
408        }
409        if let Ok(mut mapping) = self.quic_map.lock() {
410            mapping.clear();
411        }
412    }
413
414    /// The tracker's configuration.
415    pub fn config(&self) -> &TrackerConfig {
416        &self.config
417    }
418
419    /// Direct access to the active connection table.
420    ///
421    /// Use this for in-place enrichment (e.g. attaching process, DNS, or GeoIP
422    /// information via `iter_mut`) or custom reads. Lifecycle changes should go
423    /// through [`ingest`](Self::ingest) and [`cleanup`](Self::cleanup) so the
424    /// connection-count limit, RTT, and QUIC coalescing stay consistent —
425    /// inserting or removing entries directly desyncs the internal counter
426    /// backing the `max_connections` check.
427    pub fn connections(&self) -> &ConnectionMap {
428        &self.connections
429    }
430
431    /// Direct access to the historic (recently-closed) connection table.
432    pub fn historic(&self) -> &HistoricMap {
433        &self.historic
434    }
435
436    /// Average RTT (in milliseconds) over the last `window_secs` seconds of
437    /// SYN/SYN-ACK samples, consuming the samples in that window. `None` if no
438    /// samples are available.
439    pub fn take_average_rtt(&self, window_secs: u64) -> Option<f64> {
440        self.rtt
441            .lock()
442            .ok()
443            .and_then(|mut tracker| tracker.take_average_rtt(window_secs))
444    }
445}
446
447impl Default for ConnectionTracker {
448    fn default() -> Self {
449        Self::new()
450    }
451}
452
453#[cfg(test)]
454mod tests {
455    use super::*;
456    use crate::network::parser::PacketParser;
457
458    /// A minimal Ethernet+IPv4+UDP frame, parsed into a `ParsedPacket` so we can
459    /// exercise the tracker with a realistic input.
460    fn udp_frame(src_port: u16, dst_port: u16) -> Vec<u8> {
461        let mut f = Vec::new();
462        // Ethernet header: dst mac, src mac, ethertype IPv4 (0x0800)
463        f.extend_from_slice(&[0x02, 0, 0, 0, 0, 1]);
464        f.extend_from_slice(&[0x02, 0, 0, 0, 0, 2]);
465        f.extend_from_slice(&[0x08, 0x00]);
466        // IPv4 header (20 bytes)
467        let ip_total_len = (20 + 8u16).to_be_bytes(); // ip header + udp header
468        f.extend_from_slice(&[0x45, 0x00]);
469        f.extend_from_slice(&ip_total_len);
470        f.extend_from_slice(&[0, 0, 0, 0]); // id, flags/frag
471        f.push(64); // ttl
472        f.push(17); // protocol = UDP
473        f.extend_from_slice(&[0, 0]); // checksum
474        f.extend_from_slice(&[192, 168, 0, 1]); // src ip
475        f.extend_from_slice(&[192, 168, 0, 2]); // dst ip
476        // UDP header (8 bytes)
477        f.extend_from_slice(&src_port.to_be_bytes());
478        f.extend_from_slice(&dst_port.to_be_bytes());
479        f.extend_from_slice(&8u16.to_be_bytes()); // length
480        f.extend_from_slice(&[0, 0]); // checksum
481        f
482    }
483
484    fn parse(frame: &[u8]) -> ParsedPacket {
485        PacketParser::new()
486            .parse_packet(frame)
487            .expect("frame should parse")
488    }
489
490    #[test]
491    fn ingest_creates_then_updates() {
492        let tracker = ConnectionTracker::new();
493        let p = parse(&udp_frame(40000, 53));
494
495        let first = tracker.ingest(&p);
496        assert!(first.created, "first packet should create a connection");
497        assert!(!first.dropped);
498        assert_eq!(tracker.len(), 1);
499
500        let second = tracker.ingest(&p);
501        assert!(!second.created, "second packet should update, not create");
502        assert_eq!(second.key, first.key);
503        assert_eq!(tracker.len(), 1);
504    }
505
506    #[test]
507    fn distinct_flows_are_separate_connections() {
508        let tracker = ConnectionTracker::new();
509        tracker.ingest(&parse(&udp_frame(40000, 53)));
510        tracker.ingest(&parse(&udp_frame(40001, 53)));
511        assert_eq!(tracker.len(), 2);
512    }
513
514    #[test]
515    fn max_connections_limit_drops_new_only() {
516        let tracker = ConnectionTracker::with_config(TrackerConfig {
517            max_connections: 1,
518            ..TrackerConfig::default()
519        });
520        let a = tracker.ingest(&parse(&udp_frame(40000, 53)));
521        assert!(a.created && !a.dropped);
522
523        // A different flow can't be inserted (limit reached) and is dropped.
524        let b = tracker.ingest(&parse(&udp_frame(40001, 53)));
525        assert!(b.dropped, "new connection beyond the limit must be dropped");
526        assert!(!b.created);
527        assert_eq!(tracker.len(), 1);
528
529        // The existing flow still updates despite the limit.
530        let a2 = tracker.ingest(&parse(&udp_frame(40000, 53)));
531        assert!(!a2.dropped && !a2.created);
532    }
533
534    #[test]
535    fn connection_limit_recovers_after_cleanup() {
536        let tracker = ConnectionTracker::with_config(TrackerConfig {
537            max_connections: 1,
538            ..TrackerConfig::default()
539        });
540        assert!(tracker.ingest(&parse(&udp_frame(40000, 53))).created);
541        assert!(tracker.ingest(&parse(&udp_frame(40001, 53))).dropped);
542
543        // Expire everything; the limit accounting must follow the removals.
544        tracker.cleanup(SystemTime::now() + Duration::from_secs(86_400));
545        assert_eq!(tracker.len(), 0);
546
547        let c = tracker.ingest(&parse(&udp_frame(40002, 53)));
548        assert!(
549            c.created && !c.dropped,
550            "slot freed by cleanup must be reusable"
551        );
552        assert_eq!(tracker.len(), 1);
553    }
554
555    #[test]
556    fn connection_limit_recovers_after_clear() {
557        let tracker = ConnectionTracker::with_config(TrackerConfig {
558            max_connections: 1,
559            ..TrackerConfig::default()
560        });
561        assert!(tracker.ingest(&parse(&udp_frame(40000, 53))).created);
562        tracker.clear();
563        let b = tracker.ingest(&parse(&udp_frame(40001, 53)));
564        assert!(b.created && !b.dropped, "clear() must reset the limit");
565    }
566
567    #[test]
568    fn cleanup_archives_to_historic() {
569        let tracker = ConnectionTracker::new();
570        tracker.ingest(&parse(&udp_frame(40000, 53)));
571        assert_eq!(tracker.len(), 1);
572
573        // A far-future `now` forces every connection past its timeout.
574        let far_future = SystemTime::now() + Duration::from_secs(86_400);
575        let removed = tracker.cleanup(far_future);
576
577        assert_eq!(removed.len(), 1, "the idle connection should be removed");
578        assert!(!removed[0].is_historic, "returned form is the original");
579        assert_eq!(tracker.len(), 0);
580        assert_eq!(
581            tracker.historic_len(),
582            1,
583            "removed conn archived as historic"
584        );
585    }
586
587    #[test]
588    fn cleanup_without_keep_historic_skips_archive() {
589        let tracker = ConnectionTracker::with_config(TrackerConfig {
590            keep_historic: false,
591            ..TrackerConfig::default()
592        });
593        tracker.ingest(&parse(&udp_frame(40000, 53)));
594        let far_future = SystemTime::now() + Duration::from_secs(86_400);
595        let removed = tracker.cleanup(far_future);
596        assert_eq!(removed.len(), 1);
597        assert_eq!(tracker.historic_len(), 0, "historic disabled");
598    }
599
600    #[test]
601    fn ingest_at_uses_supplied_time_for_cleanup() {
602        // A packet ingested "in the past" must be eligible for cleanup at a
603        // `now` only slightly later than its supplied capture time — proving the
604        // tracker stamps the connection with the caller's time, not the wall
605        // clock. (Wall-clock stamping would make `created_at` ~= real now, so a
606        // cleanup at trace-time + a few minutes would NOT expire it.)
607        let tracker = ConnectionTracker::new();
608        let capture_time = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
609        tracker.ingest_at(&parse(&udp_frame(40000, 53)), capture_time);
610        assert_eq!(tracker.len(), 1);
611
612        // One day after the capture time the UDP flow is well past its timeout.
613        let removed = tracker.cleanup(capture_time + Duration::from_secs(86_400));
614        assert_eq!(
615            removed.len(),
616            1,
617            "flow stamped at capture time should expire"
618        );
619        assert_eq!(tracker.len(), 0);
620    }
621
622    #[test]
623    fn clear_empties_everything() {
624        let tracker = ConnectionTracker::new();
625        tracker.ingest(&parse(&udp_frame(40000, 53)));
626        tracker.cleanup(SystemTime::now() + Duration::from_secs(86_400));
627        assert_eq!(tracker.historic_len(), 1);
628        tracker.clear();
629        assert!(tracker.is_empty());
630        assert_eq!(tracker.historic_len(), 0);
631    }
632}