Factor shared scanner logic into scanners/common

The five scanners (ARP, SNMP, mDNS, SSDP, DHCP) duplicated their
persist-and-notify pipeline, device enrichment, and status state
machines across same-family files. Extract the shared logic so a change
lands in one place instead of three to five.

- scanners/common/pipeline.rs: single record_sighting() persist+notify
  path, replacing the per-scanner match blocks. ARP/SNMP now use the
  same merge rules as the passive scanners (keep a stored hostname,
  never overwrite a known IP with an empty one).
- scanners/common/enrichment.rs: build_device() for vendor/device-type
  lookup with the privacy-MAC service fallback.
- scanners/common/{active,passive}_status.rs: the two status state
  machines plus their tests, written once. Each scanner status.rs is now
  a thin wrapper over its own static.
- utils/network::format_mac(): replaces three identical copies.
- web_server/scanner_status.rs: Active/Passive response types and two
  handler helpers, replacing five near-identical structs+handlers. JSON
  field names are unchanged so the frontend is unaffected; only OpenAPI
  schema names change.

27 files changed, ~900 lines net removed. Build, clippy and all 113
tests (4 new) pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
rzuasti
2026-06-02 10:14:50 -04:00
co-authored by Claude Opus 4.8
parent 72dbbe5e9a
commit 5f7a1287a1
28 changed files with 692 additions and 1125 deletions
+7 -122
View File
@@ -1,141 +1,26 @@
use chrono::{DateTime, Duration, Utc};
use once_cell::sync::OnceCell;
use std::collections::HashMap;
use std::sync::Mutex;
/// A device counts as "seen" only if its most recent sighting falls within this
/// rolling window.
const RECENT_WINDOW_SECONDS: i64 = 3600;
use crate::scanners::common::passive_status::{PassiveSnapshot, PassiveStatus};
pub struct MdnsScannerStatus {
pub is_listening: bool,
pub listening_since: Option<DateTime<Utc>>,
/// Most recent sighting time per device MAC, used to count the distinct
/// devices seen within the last hour.
pub recent_sightings: HashMap<String, DateTime<Utc>>,
pub last_discovery_at: Option<DateTime<Utc>>,
}
#[derive(Clone)]
pub struct MdnsScannerStatusSnapshot {
pub is_listening: bool,
pub listening_since: Option<DateTime<Utc>>,
/// Distinct devices seen within the last hour.
pub devices_last_hour: u64,
pub last_discovery_at: Option<DateTime<Utc>>,
}
static STATUS: OnceCell<Mutex<MdnsScannerStatus>> = OnceCell::new();
static STATUS: OnceCell<Mutex<PassiveStatus>> = OnceCell::new();
pub fn init() {
STATUS
.set(Mutex::new(MdnsScannerStatus {
is_listening: false,
listening_since: None,
recent_sightings: HashMap::new(),
last_discovery_at: None,
}))
.ok();
STATUS.set(Mutex::new(PassiveStatus::new())).ok();
}
pub fn set_listening() {
if let Some(m) = STATUS.get() {
let mut s = m.lock().unwrap();
s.is_listening = true;
s.listening_since = Some(Utc::now());
m.lock().unwrap().set_listening();
}
}
pub fn record_discovery(mac: &str) {
if let Some(m) = STATUS.get() {
let now = Utc::now();
let mut s = m.lock().unwrap();
s.recent_sightings.insert(mac.to_string(), now);
s.last_discovery_at = Some(now);
m.lock().unwrap().record_discovery(mac);
}
}
pub fn get() -> Option<MdnsScannerStatusSnapshot> {
STATUS.get().map(|m| {
let mut s = m.lock().unwrap();
let cutoff = Utc::now() - Duration::seconds(RECENT_WINDOW_SECONDS);
s.recent_sightings.retain(|_, seen| *seen >= cutoff);
MdnsScannerStatusSnapshot {
is_listening: s.is_listening,
listening_since: s.listening_since,
devices_last_hour: s.recent_sightings.len() as u64,
last_discovery_at: s.last_discovery_at,
}
})
}
#[cfg(test)]
mod tests {
use super::*;
fn reset_for_test() {
if let Some(m) = STATUS.get() {
let mut s = m.lock().unwrap();
s.is_listening = false;
s.listening_since = None;
s.recent_sightings.clear();
s.last_discovery_at = None;
} else {
init();
}
}
#[test]
fn test_set_listening() {
reset_for_test();
set_listening();
let snapshot = get().unwrap();
assert!(snapshot.is_listening);
assert!(snapshot.listening_since.is_some());
}
#[test]
fn test_same_mac_counts_once() {
reset_for_test();
record_discovery("aa:bb:cc:dd:ee:ff");
record_discovery("aa:bb:cc:dd:ee:ff");
let snapshot = get().unwrap();
assert_eq!(snapshot.devices_last_hour, 1);
assert!(snapshot.last_discovery_at.is_some());
}
#[test]
fn test_distinct_macs_counted() {
reset_for_test();
record_discovery("aa:bb:cc:dd:ee:ff");
record_discovery("11:22:33:44:55:66");
let snapshot = get().unwrap();
assert_eq!(snapshot.devices_last_hour, 2);
}
#[test]
fn test_old_sighting_excluded() {
reset_for_test();
record_discovery("aa:bb:cc:dd:ee:ff");
// Backdate an entry beyond the window; it must not be counted.
if let Some(m) = STATUS.get() {
let mut s = m.lock().unwrap();
s.recent_sightings.insert(
"11:22:33:44:55:66".to_string(),
Utc::now() - Duration::seconds(RECENT_WINDOW_SECONDS + 60),
);
}
let snapshot = get().unwrap();
assert_eq!(snapshot.devices_last_hour, 1);
}
#[test]
fn test_initial_state() {
reset_for_test();
let snapshot = get().unwrap();
assert!(!snapshot.is_listening);
assert!(snapshot.listening_since.is_none());
assert_eq!(snapshot.devices_last_hour, 0);
assert!(snapshot.last_discovery_at.is_none());
}
pub fn get() -> Option<PassiveSnapshot> {
STATUS.get().map(|m| m.lock().unwrap().snapshot())
}