Files
alkane-toolkit/crates/alkane-gui/src/scan.rs
T
noahandClaude Opus 4.8 eb08a9ef97 GUI: per-miner capabilities + live config write path (right-click actions)
Completes the right-click config menu (round-2 item 11): the menu now offers
real actions computed from the intersection of what every selected miner
supports, and applies them to the fleet over the network.

- Capability detection: to_row probes each miner's asic-rs supports_* methods
  (fault light, restart, pause, resume, power limit, tuning) at scan time and
  stores them in MinerRow.caps -- no extra network round-trip.
- Intersection: MinerCaps::intersect_all yields the actions common to the whole
  selection; the context menu offers only those (a mixed mining + idle selection
  shows just fault light + restart; an all-mining selection shows everything).
- Write path: scan::start_config_action runs on a background thread -- it
  re-discovers each selected miner with asic-rs scan_miner(ip), applies the
  setter, and reports per-IP results that drain into the status bar (running
  progress while applying, a pass/fail summary when done). Cancellable, and a
  new action cancels any in-flight one so two never overlap. In fake-scan mode
  it simulates success so the flow is exercisable offline.
- Actions: fault light on/off, pause, resume, restart apply immediately; set
  power limit and set tuning % open a small value-prompt dialog first. Factory
  reset, change password, and firmware upgrade are deliberately not exposed in a
  casual right-click.

Adds the `measurements` dependency (already in the lock, transitive via asic-rs)
for Power::from_watts.

Review fixes (one review pass):
- Restart / pause / resume now require a confirmation dialog (naming the count)
  so a misclick can't stop a producing fleet; fault light stays instant, and
  power/tuning are confirmed by their value entry.
- The action result is held on the status bar for a few ticks so a fleet
  action's outcome (including failures) isn't clobbered by the next timer tick.
- The action loop uses a current-thread tokio runtime (it applies to one miner
  at a time; a worker pool was wasted).
- The value prompt validates before closing: a bad value keeps the dialog and
  the captured selection so it can be corrected.
- The menu's "(N)" counts use the rows-backed selection, matching what is
  actually acted on.

Verified off-screen: capability intersection (mixed vs all-mining selections),
the value-prompt and confirmation nested modals (menu -> dialog) with no crash,
the end-to-end apply flow, 46 unit tests (incl. a caps-intersection test), and
the headless self-test.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-17 11:05:15 -06:00

839 lines
31 KiB
Rust

//! 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::MinerFactory;
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<String> },
/// 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<String> {
let p = config_path(RANGES_FILE);
if let Ok(s) = std::fs::read_to_string(&p) {
let v: Vec<String> = 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<Vec<Ipv4Addr>, 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());
}
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])
}
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<Vec<Ipv4Addr>, 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<u32> = 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<ScanMsg>,
cancel: Arc<AtomicBool>,
}
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<String>) -> 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<String> = 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<String> = 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 = MinerFactory::new();
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;
if let Some(miner) = miner {
let row = to_row(&*miner).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 }
}
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);
let fan_rpm = data
.fans
.iter()
.filter_map(|f| f.rpm.as_ref().map(|r| r.as_rpm()))
.fold(0.0f64, f64::max);
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();
let firmware = match (&data.device_info.firmware, &data.firmware_version) {
(fw, Some(v)) if !fw.is_empty() => format!("{fw} {v}"),
(fw, Some(v)) => format!("{fw}{v}"),
(fw, None) => fw.clone(),
};
let model = if data.device_info.make.is_empty() {
data.device_info.model.clone()
} else {
format!("{} {}", data.device_info.make, data.device_info.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 is_mining = data.is_mining;
let slow = crate::model::is_slow(is_mining, hashrate_ths, expected_ths);
// 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: miner.supports_set_power_limit(),
tuning: miner.supports_set_tuning_percent(),
};
MinerRow {
ip: data.ip.to_string(),
selected: false,
caps,
model,
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,
api_version: data.api_version.clone().unwrap_or_default(),
control_board: data.control_board_version.as_ref().map(|c| c.to_string()).unwrap_or_default(),
hashrate_ths,
expected_ths,
efficiency: data.efficiency.unwrap_or(0.0),
power_w,
tuning_percent: data.tuning_percent,
chip_temp_c,
fluid_temp_c,
outlet_temp_c,
fan_rpm,
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: data.operating_state.as_ref().map(|s| s.to_string()).unwrap_or_default(),
is_mining,
slow,
}
}
/// 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) => "fault light on".into(),
ConfigAction::FaultLight(false) => "fault light 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<ActionMsg>,
cancel: Arc<AtomicBool>,
}
impl ActionHandle {
pub fn stop(&self) {
self.cancel.store(true, Ordering::Relaxed);
}
}
async fn apply_action(miner: &dyn Miner, action: &ConfigAction) -> Result<bool, String> {
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<String>, 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 res = std::thread::Builder::new().name("fake-action".into()).spawn(move || {
let mut ok = 0usize;
for ip in ips {
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 = MinerFactory::new();
let mut ok = 0usize;
for ip_s in ips {
if thread_cancel.load(Ordering::Relaxed) {
break;
}
let (success, detail) = match ip_s.parse::<std::net::IpAddr>() {
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 }
}
#[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_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::<Ipv4Addr>::new());
assert_eq!(parse_line(" ").unwrap(), Vec::<Ipv4Addr>::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");
}
}