//! Scan engine: drives vendored asic-rs over the configured subnets and //! streams MinerRow snapshots to the UI thread via a std channel. use crate::model::{MinerCaps, MinerRow}; use asic_rs::core::data::firmware::FirmwareImage; use asic_rs::core::traits::miner::Miner; use futures_util::StreamExt; use measurements::Power; use std::collections::HashSet; use std::net::Ipv4Addr; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{channel, Receiver}; use std::sync::Arc; pub enum ScanMsg { /// A new scan started: `total` addresses to probe, and the exact set of /// target IPs (as strings) so the UI can drop miners no longer in range. Started { total: usize, targets: HashSet }, /// Progress update: `done` of `total` addresses probed; `ip` is the most /// recently probed address (activity indicator). Progress { done: usize, total: usize, ip: String }, /// A miner was identified. Row(MinerRow), /// The scan finished (label is informational). Done(String), /// The scan could not run. Failed(String), } pub const CONFIG_DIR: &str = ".config/alkane-toolkit"; pub const RANGES_FILE: &str = "scan-ranges.txt"; pub const AUTO_FILE: &str = "auto-rescan-secs.txt"; pub const DEFAULT_RANGE: &str = "10.255.1.0/24"; /// Default seconds between automatic rescans. pub const DEFAULT_AUTO_SECS: u64 = 300; /// Load the auto-rescan interval in seconds (0 = disabled). pub fn load_auto_secs() -> u64 { std::fs::read_to_string(config_path(AUTO_FILE)) .ok() .and_then(|s| s.trim().parse().ok()) .unwrap_or(DEFAULT_AUTO_SECS) } /// Save the auto-rescan interval in seconds. pub fn save_auto_secs(secs: u64) -> std::io::Result<()> { let p = config_path(AUTO_FILE); if let Some(dir) = p.parent() { std::fs::create_dir_all(dir)?; } std::fs::write(p, secs.to_string()) } pub fn config_path(file: &str) -> PathBuf { let home = std::env::var("HOME").unwrap_or_else(|_| ".".into()); PathBuf::from(home).join(CONFIG_DIR).join(file) } pub fn load_ranges() -> Vec { let p = config_path(RANGES_FILE); if let Ok(s) = std::fs::read_to_string(&p) { let v: Vec = s .lines() .map(|l| l.trim().to_string()) .filter(|l| !l.is_empty() && !l.starts_with('#')) .collect(); if !v.is_empty() { return v; } } vec![DEFAULT_RANGE.to_string()] } pub fn save_ranges(ranges: &[String]) -> std::io::Result<()> { let p = config_path(RANGES_FILE); if let Some(dir) = p.parent() { std::fs::create_dir_all(dir)?; } std::fs::write(p, ranges.join("\n") + "\n") } /// Parse "a.b.c.d/p" (also accepts a bare address as /32). pub fn parse_cidr(s: &str) -> Option<(Ipv4Addr, u8)> { let s = s.trim(); match s.split_once('/') { Some((addr, prefix)) => { let addr: Ipv4Addr = addr.parse().ok()?; let prefix: u8 = prefix.parse().ok()?; if prefix > 32 { return None; } Some((addr, prefix)) } None => Some((s.parse().ok()?, 32)), } } /// Upper bound on how many addresses a single line (or the whole target set) /// may expand to, so a stray `10.0.0.0/8` can't allocate gigabytes / freeze the /// app. A million addresses is already far more than any real miner LAN. pub const MAX_ADDRS: u64 = 1_000_000; /// Parse one scan-range line into its address list. Accepts: /// - CIDR: `10.253.1.0/24` /// - single IP: `10.253.1.5` /// - full range: `10.253.1.3-10.253.1.234` (inclusive) /// - short range: `10.253.1.3-234` (end = same /24, last octet) pub fn parse_line(line: &str) -> Result, String> { let line = line.trim(); if line.is_empty() { return Ok(Vec::new()); } if let Some((_a, _p)) = line.split_once('/') { let (addr, prefix) = parse_cidr(line).ok_or_else(|| format!("bad CIDR: {line}"))?; let base = u32::from(addr) & prefix_mask(prefix); let count = 1u64 << (32 - prefix as u32); if count > MAX_ADDRS { return Err(format!("CIDR too large (> {MAX_ADDRS} addresses): {line}")); } return Ok((0..count).map(|i| Ipv4Addr::from(base + i as u32)).collect()); } // Per-octet ranges: each of the four octets may be a single number or an // inclusive `a-b` range, e.g. "10.1-9.1.1-255" scans the cartesian product // (the 9 /24s: 10.1.1.x .. 10.9.1.x). This also subsumes a plain single // address and a bare last-octet range like "10.253.1.3-234". let parts: Vec<&str> = line.split('.').collect(); if parts.len() == 4 && parts.iter().all(|p| is_octet_spec(p)) { let r: Vec<(u8, u8)> = parts.iter().map(|p| parse_octet_spec(p)).collect::>()?; let count: u64 = r.iter().map(|(lo, hi)| (*hi as u64 - *lo as u64 + 1)).product(); if count > MAX_ADDRS { return Err(format!("range too large (> {MAX_ADDRS} addresses): {line}")); } let mut out = Vec::with_capacity(count as usize); for a in r[0].0..=r[0].1 { for b in r[1].0..=r[1].1 { for c in r[2].0..=r[2].1 { for d in r[3].0..=r[3].1 { out.push(Ipv4Addr::new(a, b, c, d)); } } } } return Ok(out); } // Full A-B range across two dotted addresses (e.g. "10.0.0.1-10.7.255.254"), // which the per-octet form above cannot express. if let Some((start_s, end_s)) = line.split_once('-') { let start: Ipv4Addr = start_s .trim() .parse() .map_err(|_| format!("bad start address: {start_s}"))?; let end_s = end_s.trim(); // full end address, or a bare last-octet sharing the start's /24 let end: Ipv4Addr = if end_s.contains('.') { end_s.parse().map_err(|_| format!("bad end address: {end_s}"))? } else { let o: u8 = end_s.parse().map_err(|_| format!("bad range end: {end_s}"))?; let s = start.octets(); Ipv4Addr::new(s[0], s[1], s[2], o) }; let (s, e) = (u32::from(start), u32::from(end)); if s > e { return Err(format!("range start after end: {line}")); } if (e - s) as u64 >= MAX_ADDRS { return Err(format!("range too large (> {MAX_ADDRS} addresses): {line}")); } return Ok((s..=e).map(Ipv4Addr::from).collect()); } // single address let addr: Ipv4Addr = line.parse().map_err(|_| format!("bad address: {line}"))?; Ok(vec![addr]) } /// Parse one octet spec: `"n"` -> `(n, n)`, or `"a-b"` -> `(a, b)` inclusive /// (rejecting `a > b`). Used by the per-octet range form in `parse_line`. fn parse_octet_spec(s: &str) -> Result<(u8, u8), String> { let s = s.trim(); if let Some((lo, hi)) = s.split_once('-') { let lo: u8 = lo.trim().parse().map_err(|_| format!("bad octet range: {s}"))?; let hi: u8 = hi.trim().parse().map_err(|_| format!("bad octet range: {s}"))?; if lo > hi { return Err(format!("octet range start after end: {s}")); } Ok((lo, hi)) } else { let n: u8 = s.parse().map_err(|_| format!("bad octet: {s}"))?; Ok((n, n)) } } fn is_octet_spec(s: &str) -> bool { parse_octet_spec(s).is_ok() } fn prefix_mask(prefix: u8) -> u32 { if prefix == 0 { 0 } else { u32::MAX << (32 - prefix as u32) } } /// Parse and de-duplicate all scan-range lines into a sorted target list. pub fn parse_targets(lines: &[String]) -> Result, String> { let mut set = std::collections::BTreeSet::new(); for line in lines { for ip in parse_line(line)? { set.insert(u32::from(ip)); } if set.len() as u64 > MAX_ADDRS { return Err(format!("too many addresses across ranges (> {MAX_ADDRS})")); } } Ok(set.into_iter().map(Ipv4Addr::from).collect()) } /// Validate scan-range lines; returns an error message if any line is bad or /// the set is empty. pub fn validate_ranges(lines: &[String]) -> Result<(), String> { let ips = parse_targets(lines)?; if ips.is_empty() { return Err("no addresses in the given ranges".into()); } Ok(()) } /// Aggregate a sorted, de-duplicated address list into the minimal set of CIDR /// blocks that cover exactly those addresses (used to load the asic-rs factory). fn targets_to_cidrs(ips: &[Ipv4Addr]) -> Vec<(Ipv4Addr, u8)> { let mut out = Vec::new(); let vals: Vec = ips.iter().map(|ip| u32::from(*ip)).collect(); let mut i = 0usize; while i < vals.len() { // extend a contiguous run [start, end] let start = vals[i]; let mut end = start; while i + 1 < vals.len() && vals[i + 1] == end + 1 { end = vals[i + 1]; i += 1; } out.extend(range_to_cidrs(start, end)); i += 1; } out } /// Cover the inclusive [start, end] u32 range with aligned CIDR blocks. fn range_to_cidrs(start: u32, end: u32) -> Vec<(Ipv4Addr, u8)> { let mut cidrs = Vec::new(); let mut cur = start as u64; let end = end as u64; while cur <= end { let align = if cur == 0 { 32 } else { (cur as u32).trailing_zeros() }; let mut bits = align.min(32); let remaining = end - cur + 1; while bits > 0 && (1u64 << bits) > remaining { bits -= 1; } cidrs.push((Ipv4Addr::from(cur as u32), (32 - bits) as u8)); cur += 1u64 << bits; } cidrs } /// Env var that swaps the live network scan for the built-in bench-fleet /// fixtures. Set it to render/test the UI offline and deterministically. pub const FAKE_SCAN_ENV: &str = "ALKANE_FAKE_SCAN"; /// True when the app should feed fixtures instead of scanning the network. pub fn fake_scan_enabled() -> bool { std::env::var_os(FAKE_SCAN_ENV).is_some() } /// Spawn the scan thread. It parses the range lines into an exact target set, /// tells the UI which addresses are in range (so out-of-range miners can be /// dropped), then streams identified miners plus progress updates. In fake-scan /// mode it streams the bench-fleet fixtures instead, needing no network. /// /// The returned [`ScanHandle`] carries the message stream plus a cancel flag the /// background thread checks each iteration, so Stop / re-scan can end a scan /// promptly instead of leaving a thread probing dead hosts (each probe waits out /// an asic-rs per-host timeout). pub struct ScanHandle { pub rx: Receiver, cancel: Arc, } impl ScanHandle { /// Signal the scan thread to stop at its next loop iteration. Idempotent; /// dropping the handle's `rx` alone does NOT stop the thread. pub fn stop(&self) { self.cancel.store(true, Ordering::Relaxed); } } pub fn start_scan(lines: Vec) -> ScanHandle { let (tx, rx) = channel(); let cancel = Arc::new(AtomicBool::new(false)); if fake_scan_enabled() { let thread_cancel = cancel.clone(); let err_tx = tx.clone(); let res = std::thread::Builder::new().name("fake-scan".into()).spawn(move || { let rows = crate::fixtures::bench_fleet(); let targets: HashSet = rows.iter().map(|r| r.ip.clone()).collect(); let total = rows.len(); let _ = tx.send(ScanMsg::Started { total, targets }); for (i, row) in rows.into_iter().enumerate() { if thread_cancel.load(Ordering::Relaxed) { return; } if tx.send(ScanMsg::Row(row)).is_err() { return; } let _ = tx.send(ScanMsg::Progress { done: i + 1, total, ip: String::new() }); } let _ = tx.send(ScanMsg::Done("fixtures".into())); }); if let Err(e) = res { let _ = err_tx.send(ScanMsg::Failed(format!("spawn fake-scan thread: {e}"))); } return ScanHandle { rx, cancel }; } // Resolve the target addresses up front so we can report total + membership. let targets = match parse_targets(&lines) { Ok(t) if !t.is_empty() => t, Ok(_) => { let _ = tx.send(ScanMsg::Failed("no addresses in the given ranges".into())); return ScanHandle { rx, cancel }; } Err(e) => { let _ = tx.send(ScanMsg::Failed(e)); return ScanHandle { rx, cancel }; } }; let total = targets.len(); let target_set: HashSet = targets.iter().map(|ip| ip.to_string()).collect(); let _ = tx.send(ScanMsg::Started { total, targets: target_set }); let cidrs = targets_to_cidrs(&targets); let thread_cancel = cancel.clone(); let err_tx = tx.clone(); let res = std::thread::Builder::new().name("asic-rs-scan".into()).spawn(move || { let rt = match tokio::runtime::Runtime::new() { Ok(rt) => rt, Err(e) => { let _ = tx.send(ScanMsg::Failed(format!("tokio runtime: {e}"))); return; } }; rt.block_on(async move { let mut factory = crate::credentials::configured_factory(); for (ip, prefix) in &cidrs { factory = match factory.with_subnet(&format!("{ip}/{prefix}")) { Ok(f) => f, Err(e) => { let _ = tx.send(ScanMsg::Failed(format!("{ip}/{prefix}: {e}"))); return; } }; } // scan_stream_with_ip yields one item per probed address, so we // get accurate progress plus the responders. let mut stream = factory.scan_stream_with_ip(); let mut done = 0usize; let step = (total / 100).max(1); // throttle progress messages while let Some((ip, miner)) = stream.next().await { if thread_cancel.load(Ordering::Relaxed) { return; // Stop / re-scan requested } done += 1; // Only surface a row for an address that actually has a miner // behind it. A non-responding address is not shown -- we never // fabricate a phantom "offline" row for an empty IP; a miner is // reported as "not hashing" only when it responds and we can see // it is not mining. if let Some(m) = miner { let row = to_row(&*m).await; if tx.send(ScanMsg::Row(row)).is_err() { return; // UI gone } } if done % step == 0 || done == total { let _ = tx.send(ScanMsg::Progress { done, total, ip: ip.to_string() }); } } let _ = tx.send(ScanMsg::Done(format!("{total} addresses"))); }); }); if let Err(e) = res { let _ = err_tx.send(ScanMsg::Failed(format!("spawn scan thread: {e}"))); } ScanHandle { rx, cancel } } /// Flatten a miner's structured messages into concise display lines for the /// Errors column's hover tooltip (the column cell itself shows only the count). /// Only actionable messages (Error + Warning) are kept -- Info is dropped as /// noise. Each line is just "message (component)" (no repetitive "[Error]" /// prefix), duplicates are collapsed, and errors sort before warnings. fn summarize_messages(messages: &[asic_rs::core::data::message::MinerMessage]) -> Vec { use asic_rs::core::data::message::MessageSeverity; let mut ranked: Vec<(u8, String)> = messages .iter() .filter_map(|m| { let rank = match m.severity { MessageSeverity::Error => 0u8, MessageSeverity::Warning => 1, MessageSeverity::Info => return None, // informational, not an error/warning }; let text = m.message.trim(); if text.is_empty() { return None; } let line = match m.component.as_ref().map(|c| c.to_string()) { Some(c) if !c.trim().is_empty() => format!("{text} ({})", c.trim()), _ => text.to_string(), }; Some((rank, line)) }) .collect(); // Stable sort keeps discovery order within a severity; errors before warnings. ranked.sort_by_key(|(r, _)| *r); // Collapse exact duplicates (asic-rs sometimes repeats the same fault per board). let mut seen = HashSet::new(); ranked.retain(|(_, s)| seen.insert(s.clone())); ranked.into_iter().map(|(_, s)| s).collect() } async fn to_row(miner: &dyn Miner) -> MinerRow { let data = miner.get_data().await; let hashrate_ths = data .hashrate .as_ref() .map(|h| h.clone().as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash).value) .unwrap_or(0.0); let expected_ths = data .expected_hashrate .as_ref() .map(|h| h.clone().as_unit(asic_rs::core::data::hashrate::HashRateUnit::TeraHash).value) .unwrap_or(0.0); let power_w = data.wattage.as_ref().map(|p| p.as_watts()).unwrap_or(0.0); let chip_temp_c = data .average_temperature .as_ref() .map(|t| t.as_celsius()) .unwrap_or(0.0); // Per-hashboard chip temperature (hottest chip per board, falling back to // the board/PCB temp), for the "77 / 64 / 74" Chip-temp cell. let board_temps: Vec = data .hashboards .iter() .filter_map(|b| { b.outlet_chip_temperature .as_ref() .or(b.board_temperature.as_ref()) .map(|t| t.as_celsius()) }) .filter(|&t| t > 0.0) .collect(); let fan_rpms: Vec = data .fans .iter() .map(|f| f.rpm.as_ref().map(|r| r.as_rpm()).unwrap_or(0.0)) .collect(); let worker = data .pools .iter() .flat_map(|g| g.pools.iter()) .find(|p| p.active == Some(true)) .or_else(|| data.pools.iter().flat_map(|g| g.pools.iter()).next()) .and_then(|p| p.user.clone()) .unwrap_or_default(); let active_pool = data .pools .iter() .flat_map(|g| g.pools.iter()) .find(|p| p.active == Some(true)) .or_else(|| data.pools.iter().flat_map(|g| g.pools.iter()).next()); let pool_url = active_pool .and_then(|p| p.url.as_ref().map(|u| u.to_string())) .unwrap_or_default(); // Each configured pool's (url, worker), in order, across all pool groups. let pools: Vec<(String, String)> = data .pools .iter() .flat_map(|g| g.pools.iter()) .map(|p| { ( p.url.as_ref().map(|u| u.to_string()).unwrap_or_default(), p.user.clone().unwrap_or_default(), ) }) .collect(); // Firmware family (coloured column) and version go in separate columns now. let firmware = data.device_info.firmware.clone(); let fw_version = data.firmware_version.clone().unwrap_or_default(); // Split asic-rs's compact make/model identifiers into the human-facing // Brand / Model / Submodel the table shows (see crate::naming). asic-rs hands // us "Antminer"/"S19KPro"; we render brand "Antminer", model "S19k Pro". let make = data.device_info.make.clone(); let model_id = data.device_info.model.clone(); let brand = crate::naming::brand(&make); let model = crate::naming::clean_model(&make, &model_id); let submodel = crate::naming::submodel(&make, &model_id); let raw_board = data.control_board_version.as_ref().map(|c| c.to_string()).unwrap_or_default(); let control_board = crate::naming::control_board_code(&make, &raw_board, &model); let cpu = crate::naming::control_board_cpu(&make, &raw_board, &model); let board_code = crate::naming::control_board_board(&make, &raw_board, &model); let fluid_temp_c = data.fluid_temperature.as_ref().map(|t| t.as_celsius()).unwrap_or(0.0); let outlet_temp_c = data .outlet_fluid_temperature .as_ref() .map(|t| t.as_celsius()) .unwrap_or(0.0); let psu_fan_rpm = data .psu_fans .iter() .filter_map(|f| f.rpm.as_ref().map(|r| r.as_rpm())) .fold(0.0f64, f64::max); let algorithm = data.hashrate.as_ref().map(|h| h.algo.to_string()).unwrap_or_default(); let is_mining = data.is_mining; let slow = crate::model::is_slow(is_mining, hashrate_ths, expected_ths); let operating_state = data.operating_state.as_ref().map(|s| s.to_string()).unwrap_or_default(); let paused = crate::model::is_paused(&operating_state, is_mining); // asic-rs advertises supports_set_power_limit=true unconditionally for whole // firmware families, VNish included -- where, per operator guidance, the // power-limit control should not be offered (round-9 #3). Mask it off for // VNish; Braiins and the rest keep asic-rs's answer. let power_limit = miner.supports_set_power_limit() && !data.device_info.firmware.eq_ignore_ascii_case("VNish"); // Probe what this miner supports being told to do (sync, no extra I/O). let caps = MinerCaps { fault_light: miner.supports_set_fault_light(), restart: miner.supports_restart(), pause: miner.supports_pause(), resume: miner.supports_resume(), power_limit, tuning: miner.supports_set_tuning_percent(), firmware_flash: miner.supports_upgrade_firmware(), }; // PIC vs noPIC is not reported over the network by asic-rs; best-effort // heuristic from the model string, else unknown (true detection needs an // on-board SSH/I2C probe -- a separate feature). let pic_present = if model.to_lowercase().contains("nopic") { Some(false) } else { None }; // Access: locked/view-only when the miner exposes no writable control at // all, otherwise unlocked. Inferred from capabilities (asic-rs has no direct // lock-state field). let write_locked = Some(!caps.any_control()); let errors = summarize_messages(&data.messages); MinerRow { ip: data.ip.to_string(), selected: false, caps, algorithm, pic_present, write_locked, errors, model, brand, submodel, mac: data.mac.map(|m| m.to_string()).unwrap_or_default(), hostname: data.hostname.clone().unwrap_or_default(), serial: data.serial_number.clone().unwrap_or_default(), firmware, fw_version, api_version: data.api_version.clone().unwrap_or_default(), control_board, cpu, board_code, hashrate_ths, expected_ths, efficiency: data.efficiency.unwrap_or(0.0), power_w, tuning_percent: data.tuning_percent, chip_temp_c, board_temps, fluid_temp_c, outlet_temp_c, fan_rpms, psu_fan_rpm, fan_count: (!data.fans.is_empty()).then_some(data.fans.len() as u32), expected_fans: data.expected_fans.map(|v| v as u32), total_chips: data.total_chips.map(|v| v as u32), expected_chips: data.expected_chips.map(|v| v as u32), hashboards: (!data.hashboards.is_empty()).then_some(data.hashboards.len() as u32), expected_hashboards: data.expected_hashboards.map(|v| v as u32), worker, pool_url, pools, best_share: data.best_share, session_best_share: data.session_best_share, uptime_secs: data.uptime.map(|d| d.as_secs()).unwrap_or(0), light_flashing: data.light_flashing, operating_state, is_mining, slow, paused, } } /// A one-shot configuration action applied to a set of miners from the /// right-click menu. #[derive(Debug, Clone)] pub enum ConfigAction { FaultLight(bool), Restart, Pause, Resume, PowerLimit(f64), // watts TuningPercent(u8), } impl ConfigAction { /// Short label for status text and summaries. pub fn label(&self) -> String { match self { ConfigAction::FaultLight(true) => "flash lights on".into(), ConfigAction::FaultLight(false) => "flash lights off".into(), ConfigAction::Restart => "restart".into(), ConfigAction::Pause => "pause".into(), ConfigAction::Resume => "resume".into(), ConfigAction::PowerLimit(w) => format!("power limit {w:.0} W"), ConfigAction::TuningPercent(p) => format!("tuning {p}%"), } } } /// Progress/results from a running config action. pub enum ActionMsg { Started { total: usize }, Result { ip: String, ok: bool, detail: String }, Done { ok: usize, total: usize }, } /// A running config action; `stop` cancels the remaining miners. pub struct ActionHandle { pub rx: Receiver, cancel: Arc, } impl ActionHandle { pub fn stop(&self) { self.cancel.store(true, Ordering::Relaxed); } } async fn apply_action(miner: &dyn Miner, action: &ConfigAction) -> Result { let result = match action { ConfigAction::FaultLight(on) => miner.set_fault_light(*on).await, ConfigAction::Restart => miner.restart().await, ConfigAction::Pause => miner.pause(None).await, ConfigAction::Resume => miner.resume(None).await, ConfigAction::PowerLimit(w) => miner.set_power_limit(Power::from_watts(*w)).await, ConfigAction::TuningPercent(p) => miner.set_tuning_percent(*p).await, }; result.map_err(|e| e.to_string()) } /// Apply `action` to each miner in `ips` on a background thread: re-discover the /// miner (asic-rs `scan_miner`), run the setter, and report per-IP results. In /// fake-scan mode it reports simulated successes so the flow works offline. pub fn start_config_action(ips: Vec, action: ConfigAction) -> ActionHandle { let (tx, rx) = channel(); let cancel = Arc::new(AtomicBool::new(false)); let total = ips.len(); let _ = tx.send(ActionMsg::Started { total }); if fake_scan_enabled() { let err_tx = tx.clone(); let thread_cancel = cancel.clone(); let res = std::thread::Builder::new().name("fake-action".into()).spawn(move || { let mut ok = 0usize; for ip in ips { if thread_cancel.load(Ordering::Relaxed) { break; } let _ = tx.send(ActionMsg::Result { ip, ok: true, detail: "simulated".into() }); ok += 1; } let _ = tx.send(ActionMsg::Done { ok, total }); }); if res.is_err() { let _ = err_tx.send(ActionMsg::Done { ok: 0, total }); } return ActionHandle { rx, cancel }; } let thread_cancel = cancel.clone(); let err_tx = tx.clone(); let res = std::thread::Builder::new().name("config-action".into()).spawn(move || { // A single-threaded runtime: the loop applies to one miner at a time, so // a worker-per-CPU pool would be wasted. let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() { Ok(rt) => rt, Err(_) => { let _ = tx.send(ActionMsg::Done { ok: 0, total }); return; } }; rt.block_on(async move { let factory = crate::credentials::configured_factory(); let mut ok = 0usize; for ip_s in ips { if thread_cancel.load(Ordering::Relaxed) { break; } let (success, detail) = match ip_s.parse::() { Err(_) => (false, "bad IP".to_string()), Ok(ip) => match factory.scan_miner(ip).await { Ok(Some(miner)) => match apply_action(&*miner, &action).await { Ok(true) => (true, "ok".to_string()), Ok(false) => (false, "refused".to_string()), Err(e) => (false, format!("{e}")), }, Ok(None) => (false, "no miner at IP".to_string()), Err(e) => (false, format!("{e}")), }, }; if success { ok += 1; } if tx.send(ActionMsg::Result { ip: ip_s, ok: success, detail }).is_err() { return; // UI gone } } let _ = tx.send(ActionMsg::Done { ok, total }); }); }); if res.is_err() { let _ = err_tx.send(ActionMsg::Done { ok: 0, total }); } ActionHandle { rx, cancel } } /// Progress/results from a background refresh of a specific, already-known /// set of miners (re-poll on a timer or after a right-click "Refresh" action, /// as opposed to `start_scan`'s full subnet sweep). pub enum RefreshMsg { Started { total: usize }, /// A miner's telemetry was re-read successfully. Row(MinerRow), /// A miner could not be reached or re-identified. Failed { ip: String, detail: String }, Done { ok: usize, total: usize }, } /// A running refresh; `stop` cancels the remaining miners. pub struct RefreshHandle { pub rx: Receiver, cancel: Arc, } impl RefreshHandle { pub fn stop(&self) { self.cancel.store(true, Ordering::Relaxed); } } /// Re-poll a specific list of already-known miner IPs on a background thread: /// re-discover each one (asic-rs `scan_miner`) and report its fresh row. In /// fake-scan mode it reports the matching bench-fleet fixture row per IP. pub fn start_refresh(ips: Vec) -> RefreshHandle { let (tx, rx) = channel(); let cancel = Arc::new(AtomicBool::new(false)); let total = ips.len(); let _ = tx.send(RefreshMsg::Started { total }); if fake_scan_enabled() { let err_tx = tx.clone(); let thread_cancel = cancel.clone(); let res = std::thread::Builder::new().name("fake-refresh".into()).spawn(move || { let fleet = crate::fixtures::bench_fleet(); let mut ok = 0usize; for ip in ips { if thread_cancel.load(Ordering::Relaxed) { break; } match fleet.iter().find(|r| r.ip == ip) { Some(row) => { if tx.send(RefreshMsg::Row(row.clone())).is_err() { return; // UI gone } ok += 1; } None => { if tx.send(RefreshMsg::Failed { ip, detail: "offline".into() }).is_err() { return; } } } } let _ = tx.send(RefreshMsg::Done { ok, total }); }); if res.is_err() { let _ = err_tx.send(RefreshMsg::Done { ok: 0, total }); } return RefreshHandle { rx, cancel }; } let thread_cancel = cancel.clone(); let err_tx = tx.clone(); let res = std::thread::Builder::new().name("miner-refresh".into()).spawn(move || { // A single-threaded runtime: the loop applies to one miner at a time, so // a worker-per-CPU pool would be wasted. let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() { Ok(rt) => rt, Err(_) => { let _ = tx.send(RefreshMsg::Done { ok: 0, total }); return; } }; rt.block_on(async move { let factory = crate::credentials::configured_factory(); let mut ok = 0usize; for ip_s in ips { if thread_cancel.load(Ordering::Relaxed) { break; } let msg = match ip_s.parse::() { Err(_) => RefreshMsg::Failed { ip: ip_s, detail: "bad IP".to_string() }, Ok(ip) => match factory.scan_miner(ip).await { Ok(Some(miner)) => { ok += 1; RefreshMsg::Row(to_row(&*miner).await) } Ok(None) => RefreshMsg::Failed { ip: ip_s, detail: "offline".to_string() }, Err(e) => RefreshMsg::Failed { ip: ip_s, detail: format!("{e}") }, }, }; if tx.send(msg).is_err() { return; // UI gone } } let _ = tx.send(RefreshMsg::Done { ok, total }); }); }); if res.is_err() { let _ = err_tx.send(RefreshMsg::Done { ok: 0, total }); } RefreshHandle { rx, cancel } } /// Prepare (if the backend supports it) then upload a firmware image to one /// miner. Never interrupted once started: `start_firmware_flash_action` only /// checks its cancel flag between miners, not while this is running. async fn flash_one(miner: &dyn Miner, image: &FirmwareImage) -> Result { let image = if miner.supports_prepare_firmware() { miner.prepare_firmware(image.clone()).await.map_err(|e| e.to_string())? } else { image.clone() }; miner.upgrade_firmware(image).await.map_err(|e| e.to_string()) } /// Flash `image` to each miner in `ips` on a background thread: re-discover the /// miner (asic-rs `scan_miner`), then prepare (if supported) and upload the /// firmware, reporting per-IP results. Backends that don't implement firmware /// upgrade report "unsupported" rather than attempting anything. The cancel /// flag is only checked between miners: a flash in progress always runs to /// completion instead of being interrupted mid-upload. In fake-scan mode it /// reports simulated successes so the flow works offline. pub fn start_firmware_flash_action(ips: Vec, image: FirmwareImage) -> ActionHandle { let (tx, rx) = channel(); let cancel = Arc::new(AtomicBool::new(false)); let total = ips.len(); let _ = tx.send(ActionMsg::Started { total }); if fake_scan_enabled() { let err_tx = tx.clone(); let thread_cancel = cancel.clone(); let res = std::thread::Builder::new().name("fake-firmware-flash".into()).spawn(move || { let mut ok = 0usize; for ip in ips { if thread_cancel.load(Ordering::Relaxed) { break; } let _ = tx.send(ActionMsg::Result { ip, ok: true, detail: "simulated".into() }); ok += 1; } let _ = tx.send(ActionMsg::Done { ok, total }); }); if res.is_err() { let _ = err_tx.send(ActionMsg::Done { ok: 0, total }); } return ActionHandle { rx, cancel }; } let thread_cancel = cancel.clone(); let err_tx = tx.clone(); let res = std::thread::Builder::new().name("firmware-flash".into()).spawn(move || { // A single-threaded runtime: flashes run one miner at a time by // design (see the cancel-between-miners note above). let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() { Ok(rt) => rt, Err(_) => { let _ = tx.send(ActionMsg::Done { ok: 0, total }); return; } }; rt.block_on(async move { let factory = crate::credentials::configured_factory(); let mut ok = 0usize; for ip_s in ips { if thread_cancel.load(Ordering::Relaxed) { break; } let (success, detail) = match ip_s.parse::() { Err(_) => (false, "bad IP".to_string()), Ok(ip) => match factory.scan_miner(ip).await { Ok(Some(miner)) => { if !miner.supports_upgrade_firmware() { (false, "unsupported".to_string()) } else { match flash_one(&*miner, &image).await { Ok(true) => (true, "ok".to_string()), Ok(false) => (false, "refused".to_string()), Err(e) => (false, format!("{e}")), } } } Ok(None) => (false, "no miner at IP".to_string()), Err(e) => (false, format!("{e}")), }, }; if success { ok += 1; } if tx.send(ActionMsg::Result { ip: ip_s, ok: success, detail }).is_err() { return; // UI gone } } let _ = tx.send(ActionMsg::Done { ok, total }); }); }); if res.is_err() { let _ = err_tx.send(ActionMsg::Done { ok: 0, total }); } ActionHandle { rx, cancel } } /// Progress/results from a background SSH PIC probe of specific miners. pub enum PicProbeMsg { Started { total: usize }, /// One miner's PIC result: `pic` = Some(true/false)/None (indeterminate), /// or `error` set on an SSH/connection failure. Result { ip: String, pic: Option, error: Option }, Done { total: usize }, } /// A running PIC probe; `stop` cancels the remaining miners. pub struct PicProbeHandle { pub rx: Receiver, cancel: Arc, } impl PicProbeHandle { pub fn stop(&self) { self.cancel.store(true, Ordering::Relaxed); } } /// Probe the PIC state of `targets` (ip + control-board string) over SSH on a /// background thread, one miner at a time (each is a slow SSH round trip). In /// fake-scan mode it reports simulated results without touching the network. pub fn start_pic_probe( targets: Vec<(String, String)>, creds: crate::pic_probe::SshCreds, ) -> PicProbeHandle { let (tx, rx) = channel(); let cancel = Arc::new(AtomicBool::new(false)); let total = targets.len(); let _ = tx.send(PicProbeMsg::Started { total }); if fake_scan_enabled() { let err_tx = tx.clone(); let thread_cancel = cancel.clone(); let res = std::thread::Builder::new().name("fake-pic-probe".into()).spawn(move || { for (ip, cb) in targets { if thread_cancel.load(Ordering::Relaxed) { break; } // Deterministic demo: Antminer S21 (CVITek) noPIC, other // Antminers PIC, WhatsMiner indeterminate. let pic = if cb.to_lowercase().contains("cvitek") { Some(false) } else if !cb.is_empty() { Some(true) } else { None }; let _ = tx.send(PicProbeMsg::Result { ip, pic, error: None }); } let _ = tx.send(PicProbeMsg::Done { total }); }); if res.is_err() { let _ = err_tx.send(PicProbeMsg::Done { total }); } return PicProbeHandle { rx, cancel }; } let thread_cancel = cancel.clone(); let err_tx = tx.clone(); let res = std::thread::Builder::new().name("pic-probe".into()).spawn(move || { for (ip, cb) in targets { if thread_cancel.load(Ordering::Relaxed) { break; } let (pic, error) = match crate::pic_probe::probe_pic(&ip, &cb, &creds) { Ok(v) => (v, None), Err(e) => (None, Some(e)), }; if tx.send(PicProbeMsg::Result { ip, pic, error }).is_err() { return; // UI gone } } let _ = tx.send(PicProbeMsg::Done { total }); }); if res.is_err() { let _ = err_tx.send(PicProbeMsg::Done { total }); } PicProbeHandle { rx, cancel } } /// Progress/results from a background access (lock-state) probe. pub enum AccessProbeMsg { Started { total: usize }, /// `locked` = Some(true) locked/view-only, Some(false) unlocked/writable, /// None indeterminate; `error` set only when the probe couldn't run. Result { ip: String, locked: Option, error: Option }, Done { total: usize }, } /// A running access probe; `stop` cancels the remaining miners. pub struct AccessProbeHandle { pub rx: Receiver, cancel: Arc, } impl AccessProbeHandle { pub fn stop(&self) { self.cancel.store(true, Ordering::Relaxed); } } /// Probe the access/lock state of `targets` (ip + firmware string) over the web /// API with `creds` (user, pass), on a background thread. A digest-auth GET is /// fast, but we still run one miner at a time with cancel-between. Fake-scan mode /// returns deterministic demo results. pub fn start_access_probe( targets: Vec<(String, String)>, creds: (String, String), ) -> AccessProbeHandle { let (tx, rx) = channel(); let cancel = Arc::new(AtomicBool::new(false)); let total = targets.len(); let _ = tx.send(AccessProbeMsg::Started { total }); let (user, pass) = creds; if fake_scan_enabled() { let err_tx = tx.clone(); let thread_cancel = cancel.clone(); let res = std::thread::Builder::new().name("fake-access-probe".into()).spawn(move || { for (ip, _fw) in targets { if thread_cancel.load(Ordering::Relaxed) { break; } // Demo: the WardenOS-dev unit (.115) is locked, others unlocked. let locked = Some(ip.ends_with(".115")); let _ = tx.send(AccessProbeMsg::Result { ip, locked, error: None }); } let _ = tx.send(AccessProbeMsg::Done { total }); }); if res.is_err() { let _ = err_tx.send(AccessProbeMsg::Done { total }); } return AccessProbeHandle { rx, cancel }; } let thread_cancel = cancel.clone(); let err_tx = tx.clone(); let res = std::thread::Builder::new().name("access-probe".into()).spawn(move || { for (ip, fw) in targets { if thread_cancel.load(Ordering::Relaxed) { break; } let (locked, error) = match crate::access_probe::probe_access(&ip, &fw, &user, &pass) { Ok(v) => (v, None), Err(e) => (None, Some(e)), }; if tx.send(AccessProbeMsg::Result { ip, locked, error }).is_err() { return; // UI gone } } let _ = tx.send(AccessProbeMsg::Done { total }); }); if res.is_err() { let _ = err_tx.send(AccessProbeMsg::Done { total }); } AccessProbeHandle { rx, cancel } } #[cfg(test)] mod tests { use super::*; #[test] fn parse_cidr_line() { let ips = parse_line("10.253.1.0/30").unwrap(); assert_eq!(ips.len(), 4); assert_eq!(ips[0], Ipv4Addr::new(10, 253, 1, 0)); assert_eq!(ips[3], Ipv4Addr::new(10, 253, 1, 3)); } #[test] fn parse_single_ip() { let ips = parse_line("10.253.1.5").unwrap(); assert_eq!(ips, vec![Ipv4Addr::new(10, 253, 1, 5)]); } #[test] fn parse_full_range() { let ips = parse_line("10.253.1.3-10.253.1.234").unwrap(); assert_eq!(ips.len(), 232); assert_eq!(ips[0], Ipv4Addr::new(10, 253, 1, 3)); assert_eq!(*ips.last().unwrap(), Ipv4Addr::new(10, 253, 1, 234)); } #[test] fn parse_short_range() { let ips = parse_line("10.253.1.3-234").unwrap(); assert_eq!(ips.len(), 232); assert_eq!(*ips.last().unwrap(), Ipv4Addr::new(10, 253, 1, 234)); } #[test] fn parse_per_octet_ranges() { // The user's example: 9 /24s (octet2 1..9), each with .1.1-255. let ips = parse_line("10.1-9.1.1-255").unwrap(); assert_eq!(ips.len(), 9 * 255, "9 /24 ranges of 255 addresses each"); assert_eq!(ips[0], Ipv4Addr::new(10, 1, 1, 1), "ascending, first combo"); assert_eq!(*ips.last().unwrap(), Ipv4Addr::new(10, 9, 1, 255)); // Ordered by octet: the second address is .1.1.2, the 256th is .2.1.1. assert_eq!(ips[1], Ipv4Addr::new(10, 1, 1, 2)); assert_eq!(ips[255], Ipv4Addr::new(10, 2, 1, 1)); // Ranges in more than one octet. let ips = parse_line("192.168.0-1.10-12").unwrap(); assert_eq!(ips.len(), 2 * 3); assert_eq!(ips[0], Ipv4Addr::new(192, 168, 0, 10)); assert_eq!(*ips.last().unwrap(), Ipv4Addr::new(192, 168, 1, 12)); // A single address still works through the per-octet path. assert_eq!(parse_line("10.0.0.5").unwrap(), vec![Ipv4Addr::new(10, 0, 0, 5)]); // Reversed octet range is an error. assert!(parse_line("10.9-1.1.1").is_err()); // Out-of-range octet falls through and is reported. assert!(parse_line("10.1.1.999").is_err()); } #[test] fn parse_cross_octet_range() { let ips = parse_line("10.253.1.250-10.253.2.5").unwrap(); assert_eq!(ips.len(), 12); // .250..=.255 (6) + 2.0..=2.5 (6) assert_eq!(ips[0], Ipv4Addr::new(10, 253, 1, 250)); assert_eq!(*ips.last().unwrap(), Ipv4Addr::new(10, 253, 2, 5)); } #[test] fn parse_rejects_reversed_range() { assert!(parse_line("10.0.0.10-10.0.0.1").is_err()); assert!(parse_line("not-an-ip").is_err()); } #[test] fn parse_rejects_oversized_cidr_and_range() { // a /8 (16.7M) and /0 must be rejected, not allocated assert!(parse_line("10.0.0.0/8").is_err()); assert!(parse_line("0.0.0.0/0").is_err()); // a large full range too assert!(parse_line("10.0.0.0-10.99.0.0").is_err()); // a /16 (65k) is fine assert!(parse_line("10.1.0.0/16").is_ok()); } #[test] fn targets_dedup_and_sort() { let lines = vec!["10.0.0.5".to_string(), "10.0.0.1-10.0.0.3".to_string(), "10.0.0.2".to_string()]; let t = parse_targets(&lines).unwrap(); assert_eq!(t, vec![ Ipv4Addr::new(10, 0, 0, 1), Ipv4Addr::new(10, 0, 0, 2), Ipv4Addr::new(10, 0, 0, 3), Ipv4Addr::new(10, 0, 0, 5), ]); } #[test] fn cidr_aggregation_round_trips() { // a /24 must aggregate back to exactly one /24 block let ips = parse_line("10.9.8.0/24").unwrap(); let cidrs = targets_to_cidrs(&ips); assert_eq!(cidrs, vec![(Ipv4Addr::new(10, 9, 8, 0), 24)]); // an arbitrary range's blocks must cover exactly the same address set let ips = parse_line("10.0.0.3-10.0.0.20").unwrap(); let cidrs = targets_to_cidrs(&ips); let mut covered = Vec::new(); for (base, prefix) in cidrs { let n = 1u32 << (32 - prefix as u32); let b = u32::from(base); covered.extend((0..n).map(|i| Ipv4Addr::from(b + i))); } covered.sort(); assert_eq!(covered, ips); } // ---- harness-driven additions (coverage) ---- #[test] fn parse_cidr_bare_and_rejections() { assert_eq!(parse_cidr("10.1.2.3"), Some((Ipv4Addr::new(10, 1, 2, 3), 32))); assert_eq!(parse_cidr("10.0.0.1/24"), Some((Ipv4Addr::new(10, 0, 0, 1), 24))); assert_eq!(parse_cidr("10.0.0.1/33"), None); assert_eq!(parse_cidr("10.0.0.1/abc"), None); assert_eq!(parse_cidr("bad/24"), None); } #[test] fn prefix_mask_boundaries() { assert_eq!(prefix_mask(0), 0); assert_eq!(prefix_mask(24), 0xFFFF_FF00); assert_eq!(prefix_mask(32), u32::MAX); } #[test] fn parse_line_single_host_cidr_slash_32() { assert_eq!(parse_line("10.1.2.3/32").unwrap(), vec![Ipv4Addr::new(10, 1, 2, 3)]); } #[test] fn parse_line_empty_and_whitespace() { assert_eq!(parse_line("").unwrap(), Vec::::new()); assert_eq!(parse_line(" ").unwrap(), Vec::::new()); } #[test] fn parse_line_short_range_single_address_and_reversed() { assert_eq!(parse_line("10.253.1.5-5").unwrap(), vec![Ipv4Addr::new(10, 253, 1, 5)]); // short form whose end octet precedes the start is an inverted range. assert!(parse_line("10.253.1.200-50").is_err()); assert!(parse_line("10.253.1.3-300").is_err()); // 300 is not a u8 } #[test] fn parse_targets_aggregate_cap_and_errors() { // Each /13 (524288) is under the cap; together they exceed 1,000,000. let over = parse_targets(&["10.0.0.0/13".into(), "11.0.0.0/13".into()]); assert!(over.is_err(), "aggregate over MAX_ADDRS must be rejected"); // One bad line among good ones propagates. assert!(parse_targets(&["10.0.0.1".into(), "not-an-ip".into()]).is_err()); // Empty input is an empty (Ok) set. assert!(parse_targets(&[]).unwrap().is_empty()); } #[test] fn validate_ranges_empty_ok_and_bad() { assert!(validate_ranges(&[]).is_err()); // no addresses assert!(validate_ranges(&["10.0.0.0/30".into()]).is_ok()); assert!(validate_ranges(&["garbage".into()]).is_err()); } #[test] fn targets_to_cidrs_splits_noncontiguous_runs() { let cidrs = targets_to_cidrs(&[Ipv4Addr::new(10, 0, 0, 5), Ipv4Addr::new(10, 0, 0, 10)]); assert_eq!(cidrs, vec![(Ipv4Addr::new(10, 0, 0, 5), 32), (Ipv4Addr::new(10, 0, 0, 10), 32)]); } #[test] fn auto_secs_round_trip_and_defaults() { // config_path() reads $HOME; point it at a private temp dir. HOME is // process-global, so this stays one test and restores HOME afterward. let prev = std::env::var_os("HOME"); let dir = std::env::temp_dir().join(format!("alkane-test-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); std::env::set_var("HOME", &dir); assert_eq!(load_auto_secs(), DEFAULT_AUTO_SECS, "missing file -> default"); save_auto_secs(150).unwrap(); assert_eq!(load_auto_secs(), 150, "round-trip"); std::fs::write(config_path(AUTO_FILE), "not-a-number").unwrap(); assert_eq!(load_auto_secs(), DEFAULT_AUTO_SECS, "malformed -> default"); std::fs::write(config_path(AUTO_FILE), " 42 \n").unwrap(); assert_eq!(load_auto_secs(), 42, "whitespace tolerated"); match prev { Some(v) => std::env::set_var("HOME", v), None => std::env::remove_var("HOME"), } let _ = std::fs::remove_dir_all(&dir); } // ---- microbenchmarks (perf-regression gates; run with --ignored) ---- #[test] #[ignore] fn bench_parse_line_near_max_addrs() { use std::time::Instant; let start = Ipv4Addr::new(10, 0, 0, 0); let end = Ipv4Addr::from(u32::from(start) + (MAX_ADDRS as u32 - 2)); let line = format!("{start}-{end}"); let iters = 5u32; let t = Instant::now(); let mut sink = 0usize; for _ in 0..iters { sink += parse_line(&line).unwrap().len(); } let per = t.elapsed() / iters; println!("bench_parse_line_near_max_addrs: {sink} addrs, {:?}/op", per); assert!(per.as_millis() < 400, "parse_line near MAX_ADDRS regressed: {per:?}/op"); } #[test] #[ignore] fn bench_parse_targets_many_ranges_near_cap() { use std::time::Instant; let mut lines = Vec::new(); let mut total = 0u64; let mut b = 0u32; while total + 65536 < MAX_ADDRS && b < 200 { lines.push(format!("10.{b}.0.0/16")); total += 65536; b += 1; } let iters = 5u32; let t = Instant::now(); let mut sink = 0usize; for _ in 0..iters { sink += parse_targets(&lines).unwrap().len(); } let per = t.elapsed() / iters; println!("bench_parse_targets_many_ranges_near_cap: {} lines, {sink} addrs, {:?}/op", lines.len(), per); assert!(per.as_millis() < 800, "parse_targets regressed: {per:?}/op"); } #[test] #[ignore] fn bench_targets_to_cidrs_large_range() { use std::time::Instant; let ips = parse_line("10.0.0.1-10.7.255.254").unwrap(); // ~524k addrs, odd start let iters = 20u32; let t = Instant::now(); let mut sink = 0usize; for _ in 0..iters { sink += targets_to_cidrs(&ips).len(); } let per = t.elapsed() / iters; println!("bench_targets_to_cidrs_large_range: {} addrs -> {sink} cidrs, {:?}/op", ips.len(), per); assert!(per.as_millis() < 200, "targets_to_cidrs regressed: {per:?}/op"); } /// Exercise the round-6 background actions through their fake-scan branch: /// offline-row emission (start_scan), per-IP refresh (start_refresh), /// firmware flash (start_firmware_flash_action), and that a cancelled run /// still terminates. ALKANE_FAKE_SCAN is process-global, but no other test /// calls these functions, so setting it here only affects this one /// (sequential) test; all fake-mode assertions live in a single #[test] so /// they never race each other over the env var. #[test] fn fake_mode_background_actions() { use std::sync::mpsc::RecvTimeoutError; use std::time::Duration; let deadline = Duration::from_secs(5); std::env::set_var(FAKE_SCAN_ENV, "1"); // start_scan (fake): streams exactly the bench-fleet fixtures, one Row // per fixture, and no fabricated rows for empty addresses. { let h = start_scan(vec!["10.255.1.0/30".into()]); let mut rows = Vec::new(); let mut total = 0usize; loop { match h.rx.recv_timeout(deadline) { Ok(ScanMsg::Started { total: t, .. }) => total = t, Ok(ScanMsg::Row(r)) => rows.push(r), Ok(ScanMsg::Done(_)) => break, Ok(_) => {} Err(RecvTimeoutError::Timeout) => panic!("fake start_scan hung"), Err(RecvTimeoutError::Disconnected) => break, } } let fleet = crate::fixtures::bench_fleet(); assert_eq!(rows.len(), fleet.len(), "one Row per fixture, no phantom offline rows"); assert_eq!(total, fleet.len()); assert!(rows.iter().all(|r| r.status() != "offline"), "no 'offline' status exists"); } // start_refresh: a known fixture IP re-reads as a Row, an unknown IP is // reported Failed{offline}, and the run ends with Done{ok:1,total:2}. { let known = "10.255.1.112".to_string(); // an S17 in bench_fleet let unknown = "10.0.0.250".to_string(); let h = start_refresh(vec![known.clone(), unknown.clone()]); let (mut rows, mut failed, mut done) = (0usize, 0usize, None); loop { match h.rx.recv_timeout(deadline) { Ok(RefreshMsg::Started { .. }) => {} Ok(RefreshMsg::Row(r)) => { assert_eq!(r.ip, known); rows += 1; } Ok(RefreshMsg::Failed { ip, detail }) => { assert_eq!(ip, unknown); assert_eq!(detail, "offline"); failed += 1; } Ok(RefreshMsg::Done { ok, total }) => { done = Some((ok, total)); break; } Err(RecvTimeoutError::Timeout) => panic!("fake start_refresh hung"), Err(RecvTimeoutError::Disconnected) => break, } } assert_eq!(rows, 1); assert_eq!(failed, 1); assert_eq!(done, Some((1, 2))); } // start_firmware_flash_action: fake mode reports one simulated success // per IP and a matching Done summary. { let image = FirmwareImage::new("fw.bin".to_string(), vec![0u8; 8]); let h = start_firmware_flash_action( vec!["10.255.1.166".into(), "10.255.1.149".into()], image, ); let (mut results, mut done) = (0usize, None); loop { match h.rx.recv_timeout(deadline) { Ok(ActionMsg::Started { .. }) => {} Ok(ActionMsg::Result { ok, detail, .. }) => { assert!(ok); assert_eq!(detail, "simulated"); results += 1; } Ok(ActionMsg::Done { ok, total }) => { done = Some((ok, total)); break; } Err(RecvTimeoutError::Timeout) => panic!("fake flash hung"), Err(RecvTimeoutError::Disconnected) => break, } } assert_eq!(results, 2); assert_eq!(done, Some((2, 2))); } // Cancellation contract: stopping a run still delivers a terminal Done // rather than hanging (the fake branches now honour the cancel flag). { let big: Vec = (0..200).map(|i| format!("10.9.0.{}", i % 256)).collect(); let h = start_refresh(big); h.stop(); let mut saw_done = false; loop { match h.rx.recv_timeout(deadline) { Ok(RefreshMsg::Done { .. }) => { saw_done = true; break; } Ok(_) => {} Err(_) => break, } } assert!(saw_done, "a cancelled fake refresh must still emit Done, not hang"); } std::env::remove_var(FAKE_SCAN_ENV); } }