Compare commits

...
1 Commits
Author SHA1 Message Date
noahandClaude Opus 4.8 8e9c5e7105 GUI + CI: code-review-harness fixes, expanded tests, version-logic tests
Ran the code-review-harness (four parallel reviewers: correctness, reliability,
performance, test-coverage) over the GUI crate and fixed every Critical/High
finding, plus grew the test + microbenchmark suite that gates the pipeline.

Correctness / reliability fixes:
- IP column sorted lexically, not numerically. The default view is IP-ascending
  but Column::Ip fell through to the generic lowercase-string sort key, so
  10.255.1.10 sorted before 10.255.1.2 on every launch. Add a numeric IP sort
  key (u32, exact in f64) and switch view() to decorate-sort-undecorate so a
  sort key is computed once per row, not twice per comparison.
- Scans had no cancellation. Stop/Apply/Play only dropped the receiver, leaving
  the background thread probing dead hosts (each waits out an asic-rs timeout),
  and Play could spawn a second concurrent scan + tokio runtime. Add a
  ScanHandle with an Arc<AtomicBool> cancel flag the loop checks each iteration,
  a begin_scan() helper that stops the in-flight scan before starting a new one,
  and Stop now signals cancellation.
- Native column drag never rebuilt the control: column_reordered mutated
  view.order but skipped rebuild_table(), so the store's creation order diverged
  from display_columns() and cells rendered under the wrong headers on the next
  scan tick. Rebuild after applying the reorder.
- format_si rounding rolled a mantissa up to "1000" without advancing the SI
  prefix (999.9 W -> "1000 W", a 4-digit result). Round first, then roll over;
  [99.95,100) drops its decimal.
- start_scan used .expect() on thread spawn, which would panic across the wx FFI
  boundary; it now sends ScanMsg::Failed and returns the handle.

Tests / benchmarks (the pipeline's regression gate):
- Unit tests 24 -> 41: format_si/format_uptime boundaries, numeric IP sort,
  upsert-new-IP, Light three-state + pool-slot-out-of-range cells, filter
  AND/OR, reorder non-permutation guard; scan.rs parse_cidr/prefix_mask,
  single-host /32, empty/whitespace, short-range single/reversed, parse_targets
  aggregate cap + error propagation, validate_ranges, targets_to_cidrs
  non-contiguous, auto-rescan-secs round-trip.
- Microbenchmarks 2 -> 9: view default-sort, sort-by-each-column, filtered view,
  upsert cold-start, parse_line near MAX_ADDRS, parse_targets many ranges,
  targets_to_cidrs large range. Floors are 5-10x above local numbers.
- New ci/test-compute-version.sh: 9 cases for the X.Y.Z logic (first release,
  pre-bumped X, backend/UI bumps, docs-only no-op, major-wins-over-UI,
  backend-wins-over-UI, nested ci/ and thirdparty/wx-rs paths). Wired in as a
  fast-fail CI step.

CI: install libssl-dev + pkg-config (openssl-sys); add xauth so the headless
self-test actually launches under xvfb (was aborting on "xauth not found").

Deferred (documented in code-review-report.md, guarded by benches): Cow cells,
an ip->index map for upsert. Local: 41 tests + 9 benches + 9 shell tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-16 19:22:49 -06:00
6 changed files with 627 additions and 86 deletions
+6 -1
View File
@@ -21,6 +21,10 @@ jobs:
id: ver
run: bash ci/compute-version.sh | tee -a "$GITHUB_OUTPUT"
- name: Test version logic
if: steps.ver.outputs.release == 'true'
run: bash ci/test-compute-version.sh
- name: Install build dependencies
if: steps.ver.outputs.release == 'true'
run: |
@@ -73,7 +77,8 @@ jobs:
if: steps.ver.outputs.release == 'true'
continue-on-error: true
run: |
apt-get update -qq && apt-get install -y -qq --no-install-recommends xvfb dbus-x11 fonts-dejavu-core >/dev/null
apt-get update -qq && apt-get install -y -qq --no-install-recommends \
xvfb xauth dbus-x11 fonts-dejavu-core >/dev/null
BIN=target/release/alkane-toolkit
xvfb-run -a env GDK_BACKEND=x11 ALKANE_SELFTEST=1 "$BIN"
+2 -2
View File
@@ -1,3 +1,3 @@
/target
**/target
.claude/
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env bash
# Tests for ci/compute-version.sh (the X.Y.Z versioning logic). Each case builds
# a throwaway git repo in a scratch tmp dir (never inside this repo / the Ultron
# mount), lays out a scenario, runs compute-version.sh inside it, and asserts the
# emitted KEY=VALUE lines. Run: bash ci/test-compute-version.sh
set -euo pipefail
SCRIPT="$(cd "$(dirname "$0")" && pwd)/compute-version.sh"
[ -f "$SCRIPT" ] || { echo "cannot find compute-version.sh at $SCRIPT"; exit 2; }
pass=0
fail=0
# new_repo: fresh git repo in a scratch dir, echoes its path.
new_repo() {
local r
r="$(mktemp -d "${TMPDIR:-/tmp}/alkane-cv-XXXXXX")"
git -C "$r" init -q
git -C "$r" config user.email t@t
git -C "$r" config user.name t
echo "$r"
}
commit() { # commit <repo> <msg>
git -C "$1" add -A
git -C "$1" commit -q -m "$2"
}
# run_case: <name> <repo> then key=value expectations as remaining args.
run_case() {
local name="$1" repo="$2"; shift 2
local out get k v ok=1
out="$(cd "$repo" && bash "$SCRIPT")"
get() { echo "$out" | grep "^$1=" | cut -d= -f2-; }
for kv in "$@"; do
k="${kv%%=*}"; v="${kv#*=}"
if [ "$(get "$k")" != "$v" ]; then
echo "FAIL [$name]: expected $k=$v, got $k=$(get "$k")"
ok=0
fi
done
if [ "$ok" = 1 ]; then echo "PASS [$name]"; pass=$((pass + 1)); else fail=$((fail + 1)); fi
rm -rf "$repo"
}
# 1. First release, no tag, X=0 -> 0.1.0
R="$(new_repo)"; mkdir -p "$R/ci"; printf '0' > "$R/ci/version-x.txt"
printf 'x' > "$R/README.md"; commit "$R" init
run_case first_release "$R" version=0.1.0 tag=v0.1.0 bump=initial release=true last_tag=none
# 2. First release with a pre-bumped major (X=2, no tag) -> 2.0.0
R="$(new_repo)"; mkdir -p "$R/ci"; printf '2' > "$R/ci/version-x.txt"
printf 'x' > "$R/README.md"; commit "$R" init
run_case first_release_prebumped_x "$R" version=2.0.0 bump=initial release=true
# 3. Backend path change bumps Y
R="$(new_repo)"; mkdir -p "$R/ci" "$R/crates/alkane-gui/src"; printf '0' > "$R/ci/version-x.txt"
printf 'x' > "$R/README.md"; commit "$R" init; git -C "$R" tag v1.2.3
printf 'fn x(){}' > "$R/crates/alkane-gui/src/scan.rs"; commit "$R" backend
run_case backend_bump "$R" version=1.3.0 tag=v1.3.0 bump=backend release=true last_tag=v1.2.3
# 4. UI path change bumps Z
R="$(new_repo)"; mkdir -p "$R/ci" "$R/crates/alkane-gui/src"; printf '0' > "$R/ci/version-x.txt"
printf 'x' > "$R/README.md"; commit "$R" init; git -C "$R" tag v1.2.3
printf 'fn x(){}' > "$R/crates/alkane-gui/src/fixtures.rs"; commit "$R" ui
run_case ui_bump "$R" version=1.2.4 bump=ui release=true
# 5. Docs-only change -> no release
R="$(new_repo)"; mkdir -p "$R/ci"; printf '0' > "$R/ci/version-x.txt"
printf 'x' > "$R/README.md"; commit "$R" init; git -C "$R" tag v1.2.3
printf 'more docs' > "$R/README.md"; commit "$R" docs
run_case no_release_docs_only "$R" version=1.2.3 bump=none release=false
# 6. Manual major bump wins over a simultaneous UI change
R="$(new_repo)"; mkdir -p "$R/ci" "$R/crates/alkane-gui/src"; printf '0' > "$R/ci/version-x.txt"
printf 'x' > "$R/README.md"; commit "$R" init; git -C "$R" tag v1.2.3
printf '2' > "$R/ci/version-x.txt"; printf 'fn x(){}' > "$R/crates/alkane-gui/src/fixtures.rs"; commit "$R" bumpx
run_case manual_major_wins_over_ui "$R" version=2.0.0 bump=major release=true
# 7. Backend wins over UI when both change in the same diff
R="$(new_repo)"; mkdir -p "$R/ci" "$R/crates/alkane-gui/src"; printf '0' > "$R/ci/version-x.txt"
printf 'x' > "$R/README.md"; commit "$R" init; git -C "$R" tag v1.2.3
printf 'a' > "$R/crates/alkane-gui/src/scan.rs"
printf 'b' > "$R/crates/alkane-gui/src/fixtures.rs"; commit "$R" both
run_case backend_wins_over_ui "$R" version=1.3.0 bump=backend release=true
# 8. Nested ci/ path classified as backend (also covers editing compute-version.sh)
R="$(new_repo)"; mkdir -p "$R/ci"; printf '0' > "$R/ci/version-x.txt"
printf 'x' > "$R/README.md"; commit "$R" init; git -C "$R" tag v1.2.3
printf '# tweak' >> "$R/ci/compute-version.sh"; commit "$R" ci
run_case ci_nested_is_backend "$R" version=1.3.0 bump=backend release=true
# 9. Nested thirdparty/wx-rs path classified as UI
R="$(new_repo)"; mkdir -p "$R/ci" "$R/thirdparty/wx-rs/src/deep"; printf '0' > "$R/ci/version-x.txt"
printf 'x' > "$R/README.md"; commit "$R" init; git -C "$R" tag v1.2.3
printf 'x' > "$R/thirdparty/wx-rs/src/deep/nested.rs"; commit "$R" wx
run_case wx_rs_nested_is_ui "$R" version=1.2.4 bump=ui release=true
echo "----"
echo "compute-version tests: $pass passed, $fail failed"
[ "$fail" -eq 0 ]
+255 -10
View File
@@ -29,11 +29,19 @@ pub fn format_si(value_base: f64, unit: &str) -> String {
v /= 1000.0;
i += 1;
}
let num = if v >= 100.0 {
format!("{v:.0}")
} else {
format!("{v:.1}")
};
// Round first, then re-check the prefix. A mantissa that rounds up to 1000
// (e.g. 999.9 -> "1000") must roll over to the next prefix so the number
// never shows more than three integer digits; and a mantissa in [99.95,100)
// rounds to "100.0" and should drop its decimal (the >=100 branch's rule).
let render = |v: f64| if v >= 100.0 { format!("{v:.0}") } else { format!("{v:.1}") };
let mut num = render(v);
if (num == "1000" || num == "1000.0") && i < PREFIXES.len() - 1 {
v /= 1000.0;
i += 1;
num = render(v);
} else if num == "100.0" {
num = "100".to_string();
}
format!("{num} {}{unit}", PREFIXES[i])
}
@@ -57,6 +65,19 @@ pub fn format_uptime(secs: u64) -> String {
}
}
/// Pack a dotted-quad IPv4 string into a u32 for numeric ordering, so
/// "10.255.1.9" sorts before "10.255.1.10" (a plain string sort gets this
/// wrong). Anything unparseable sorts first (0).
fn ip_to_u32(s: &str) -> u32 {
let mut parts = s.split('.');
let mut acc = 0u32;
for _ in 0..4 {
let octet: u32 = parts.next().and_then(|p| p.trim().parse().ok()).unwrap_or(0);
acc = (acc << 8) | (octet & 0xff);
}
acc
}
/// One miner's telemetry snapshot, flattened from asic-rs `MinerData` into the
/// scalar fields the table can display. Absent metrics are `None` / empty /
/// 0.0 and render as a blank cell.
@@ -361,6 +382,8 @@ impl Column {
Column::TuningPercent => {
SortKey::Num(r.tuning_percent.map(|v| v as f64).unwrap_or(none))
}
// IP sorts numerically (u32 fits exactly in f64), not lexically.
Column::Ip => SortKey::Num(ip_to_u32(&r.ip) as f64),
_ => SortKey::Str(self.cell(r).to_lowercase()),
}
}
@@ -522,16 +545,21 @@ impl ViewState {
.filter(|&i| self.passes_filters(&rows[i]))
.collect();
if let Some((col, asc)) = self.sort {
idx.sort_by(|&a, &b| {
let ka = col.sort_key(&rows[a]);
let kb = col.sort_key(&rows[b]);
// Decorate-sort-undecorate: compute each row's sort key exactly once
// (a string key allocates), not twice per comparison.
let mut keyed: Vec<(SortKey, usize)> =
idx.iter().map(|&i| (col.sort_key(&rows[i]), i)).collect();
keyed.sort_by(|(ka, _), (kb, _)| {
let ord = match (ka, kb) {
(SortKey::Num(x), SortKey::Num(y)) => x.partial_cmp(&y).unwrap_or(std::cmp::Ordering::Equal),
(SortKey::Str(x), SortKey::Str(y)) => x.cmp(&y),
(SortKey::Num(x), SortKey::Num(y)) => {
x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal)
}
(SortKey::Str(x), SortKey::Str(y)) => x.cmp(y),
_ => std::cmp::Ordering::Equal,
};
if asc { ord } else { ord.reverse() }
});
idx = keyed.into_iter().map(|(_, i)| i).collect();
}
idx
}
@@ -812,4 +840,221 @@ mod tests {
assert!(r.selected, "selection preserved across upsert");
assert_eq!(r.hashrate_ths, 12.3, "data updated");
}
// ---- harness-driven additions (correctness + coverage) ----
#[test]
fn format_si_handles_zero_negative_and_nonfinite() {
assert_eq!(format_si(0.0, "W"), "0 W");
assert_eq!(format_si(-5.0, "W"), "0 W");
assert_eq!(format_si(f64::NAN, "W"), "0 W");
assert_eq!(format_si(f64::INFINITY, "H/s"), "0 H/s");
}
#[test]
fn format_si_rolls_over_at_rounding_boundary() {
// A mantissa that rounds up to 1000 must advance the prefix, never print
// a 4-digit number (spec: at most 2 digits + 1 decimal after the prefix).
assert_eq!(format_si(999.9, "W"), "1.0 kW");
assert_eq!(format_si(999_990.0, "W"), "1.0 MW");
assert_eq!(format_si(1000.0, "W"), "1.0 kW");
// [99.95, 100) rounds to 100 and drops the decimal (>=100 rule).
assert_eq!(format_si(99.95, "W"), "100 W");
assert_eq!(format_si(45.6, "W"), "45.6 W");
assert_eq!(format_si(250.0, "W"), "250 W");
}
#[test]
fn format_uptime_boundaries() {
assert_eq!(format_uptime(0), "");
assert_eq!(format_uptime(59), "59s");
assert_eq!(format_uptime(60), "1m");
assert_eq!(format_uptime(3599), "59m");
assert_eq!(format_uptime(3600), "1h 0m");
assert_eq!(format_uptime(86_399), "23h 59m");
assert_eq!(format_uptime(86_400), "1d 0h");
assert_eq!(format_uptime(90_061), "1d 1h");
}
#[test]
fn ip_column_sorts_numerically() {
// A plain string sort puts "10.255.1.10" before "10.255.1.2"; the IP
// column must order by numeric value instead.
let rows = vec![
MinerRow { ip: "10.255.1.10".into(), ..Default::default() },
MinerRow { ip: "10.255.1.2".into(), ..Default::default() },
MinerRow { ip: "10.255.1.112".into(), ..Default::default() },
MinerRow { ip: "10.255.1.9".into(), ..Default::default() },
];
let idx = ViewState::default().view(&rows); // default = Ip ascending
let order: Vec<&str> = idx.iter().map(|&i| rows[i].ip.as_str()).collect();
assert_eq!(order, ["10.255.1.2", "10.255.1.9", "10.255.1.10", "10.255.1.112"]);
}
#[test]
fn upsert_into_new_ip_inserts_and_returns_true() {
let mut rows = bench_fleet();
let n0 = rows.len();
let fresh = MinerRow { ip: "10.9.9.9".into(), ..Default::default() };
let is_new = fresh.upsert_into(&mut rows);
assert!(is_new, "a never-seen IP is an insert");
assert_eq!(rows.len(), n0 + 1);
assert!(rows.iter().any(|r| r.ip == "10.9.9.9"));
}
#[test]
fn cell_light_three_states() {
let on = MinerRow { light_flashing: Some(true), ..Default::default() };
let off = MinerRow { light_flashing: Some(false), ..Default::default() };
let unknown = MinerRow { light_flashing: None, ..Default::default() };
assert_eq!(Column::Light.cell(&on), "on");
assert_eq!(Column::Light.cell(&off), "off");
assert_eq!(Column::Light.cell(&unknown), "");
}
#[test]
fn cell_pool_slots_including_out_of_range() {
let r = MinerRow {
pools: vec![
("stratum+tcp://a:1".into(), "wA".into()),
("stratum+tcp://b:2".into(), "wB".into()),
],
..Default::default()
};
assert_eq!(Column::Pool1Url.cell(&r), "stratum+tcp://a:1");
assert_eq!(Column::Pool1Worker.cell(&r), "wA");
assert_eq!(Column::Pool2Url.cell(&r), "stratum+tcp://b:2");
assert_eq!(Column::Pool2Worker.cell(&r), "wB");
// Third pool is unconfigured -> blank, not a panic.
assert_eq!(Column::Pool3Url.cell(&r), "");
assert_eq!(Column::Pool3Worker.cell(&r), "");
}
#[test]
fn passes_filters_ands_across_columns() {
let rows = vec![
MinerRow { ip: "10.0.0.1".into(), is_mining: true, model: "A".into(), ..Default::default() },
MinerRow { ip: "10.0.0.2".into(), is_mining: true, model: "B".into(), ..Default::default() },
MinerRow { ip: "10.0.0.3".into(), is_mining: false, model: "A".into(), ..Default::default() },
];
let mut view = ViewState::default();
view.filters.insert(Column::Status, HashSet::from(["hashing".to_string()]));
view.filters.insert(Column::Model, HashSet::from(["A".to_string()]));
let idx = view.view(&rows);
assert_eq!(idx.len(), 1, "only the hashing AND model-A row passes");
assert_eq!(rows[idx[0]].ip, "10.0.0.1");
}
#[test]
fn passes_filters_ors_within_one_column() {
let rows = bench_fleet();
let mut view = ViewState::default();
view.filters.insert(
Column::Status,
HashSet::from(["slow".to_string(), "not hashing".to_string()]),
);
let idx = view.view(&rows);
// fixtures: 1 slow + 2 not-hashing.
assert_eq!(idx.len(), 3);
}
#[test]
fn apply_visible_reorder_rejects_non_permutation_same_length() {
let mut view = ViewState::default();
let before = view.order.clone();
let hidden = *view
.order
.iter()
.find(|c| **c != Column::Ip && !view.visible.contains(c))
.expect("a hidden column exists by default");
let mut disp = view.display_columns(); // Ip first, correct length
disp[1] = hidden; // same length + Ip first, but no longer a permutation
view.apply_visible_reorder(&disp);
assert_eq!(view.order, before, "a same-length non-permutation must be ignored");
}
/// Microbenchmark: the DEFAULT view (Ip ascending) at 5000 rows. The existing
/// bench_view_pipeline overrides sort to Hashrate, so it never exercised the
/// default path (previously a lexical string sort).
#[test]
#[ignore]
fn bench_view_pipeline_default_sort() {
use std::time::Instant;
let rows = synthetic_fleet(5000);
let view = ViewState::default();
let iters = 200u32;
let t = Instant::now();
let mut sink = 0usize;
for _ in 0..iters {
sink += view.view(&rows).len();
}
let per = t.elapsed() / iters;
println!("bench_view_pipeline_default_sort: {:?}/op (sink={sink})", per);
assert!(per.as_millis() < 60, "default (Ip) sort regressed: {per:?}/op");
}
/// Microbenchmark: sort by every column once, at 5000 rows. Guards the
/// decorate-sort-undecorate path (string columns must not re-allocate keys
/// per comparison).
#[test]
#[ignore]
fn bench_sort_by_each_column() {
use std::time::Instant;
let rows = synthetic_fleet(5000);
let iters = 10u32;
let mut worst = std::time::Duration::ZERO;
for &col in ALL_COLUMNS.iter() {
let mut view = ViewState::default();
view.sort = Some((col, false));
let t = Instant::now();
let mut sink = 0usize;
for _ in 0..iters {
sink += view.view(&rows).len();
}
let per = t.elapsed() / iters;
if per > worst {
worst = per;
}
assert!(per.as_millis() < 120, "{col:?} sort regressed: {per:?}/op (sink={sink})");
}
println!("bench_sort_by_each_column: worst column = {:?}/op", worst);
}
/// Microbenchmark: filtered view (one selective predicate) at 5000 rows.
#[test]
#[ignore]
fn bench_view_pipeline_with_filter() {
use std::time::Instant;
let rows = synthetic_fleet(5000);
let mut view = ViewState::default();
view.filters.insert(Column::Model, HashSet::from(["Model-3".to_string()]));
view.sort = Some((Column::Hashrate, false));
let iters = 200u32;
let t = Instant::now();
let mut sink = 0usize;
for _ in 0..iters {
sink += view.view(&rows).len();
}
let per = t.elapsed() / iters;
println!("bench_view_pipeline_with_filter: {sink} avg matches, {:?}/op", per);
assert!(per.as_millis() < 60, "filtered view() regressed: {per:?}/op");
}
/// Microbenchmark: cold-start fleet population via upsert_into (the O(n) scan
/// per insert; documents the quadratic worst case).
#[test]
#[ignore]
fn bench_upsert_cold_start_population() {
use std::time::Instant;
let n = 3000u32;
let fresh = synthetic_fleet(n);
let t = Instant::now();
let mut rows: Vec<MinerRow> = Vec::new();
for r in fresh {
r.upsert_into(&mut rows);
}
let elapsed = t.elapsed();
println!("bench_upsert_cold_start_population: {n} rows cold-start = {:?}", elapsed);
assert!(elapsed.as_millis() < 2000, "cold-start upsert regressed: {elapsed:?} for {n} rows");
}
}
+235 -59
View File
@@ -8,7 +8,9 @@ use futures_util::StreamExt;
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
@@ -228,27 +230,51 @@ pub fn fake_scan_enabled() -> bool {
/// 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.
pub fn start_scan(lines: Vec<String>) -> Receiver<ScanMsg> {
///
/// 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() {
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 tx.send(ScanMsg::Row(row)).is_err() {
return;
}
let _ = tx.send(ScanMsg::Progress { done: i + 1, total, ip: String::new() });
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;
}
let _ = tx.send(ScanMsg::Done("fixtures".into()));
})
.expect("spawn fake-scan thread");
return rx;
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.
@@ -256,11 +282,11 @@ pub fn start_scan(lines: Vec<String>) -> Receiver<ScanMsg> {
Ok(t) if !t.is_empty() => t,
Ok(_) => {
let _ = tx.send(ScanMsg::Failed("no addresses in the given ranges".into()));
return rx;
return ScanHandle { rx, cancel };
}
Err(e) => {
let _ = tx.send(ScanMsg::Failed(e));
return rx;
return ScanHandle { rx, cancel };
}
};
let total = targets.len();
@@ -268,49 +294,54 @@ pub fn start_scan(lines: Vec<String>) -> Receiver<ScanMsg> {
let _ = tx.send(ScanMsg::Started { total, targets: target_set });
let cidrs = targets_to_cidrs(&targets);
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 {
done += 1;
if let Some(miner) = miner {
let row = to_row(&*miner).await;
if tx.send(ScanMsg::Row(row)).is_err() {
return; // UI gone
}
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;
}
if done % step == 0 || done == total {
let _ = tx.send(ScanMsg::Progress { done, total, ip: ip.to_string() });
};
}
// 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
}
}
let _ = tx.send(ScanMsg::Done(format!("{total} addresses")));
});
})
.expect("spawn scan thread");
rx
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 {
@@ -518,4 +549,149 @@ mod tests {
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");
}
}
+28 -14
View File
@@ -5,7 +5,6 @@ use crate::model::*;
use crate::scan::{self, ScanMsg};
use std::cell::RefCell;
use std::collections::HashSet;
use std::sync::mpsc::Receiver;
use wx_rs::{Widget, WxEvent, WxEventKind, sizer_flags as sf};
pub const ID_RANGES: i32 = 101;
@@ -90,7 +89,7 @@ pub struct App {
pub table: Option<Widget>,
table_parent: Widget,
root_sizer: Widget,
pub scan_rx: Option<Receiver<ScanMsg>>,
pub scan: Option<scan::ScanHandle>,
pub scanning: bool,
scan_total: usize,
target_ips: HashSet<String>,
@@ -204,7 +203,7 @@ pub fn build(frame: Widget) -> App {
table: None,
table_parent,
root_sizer: root,
scan_rx: Some(scan::start_scan(ranges.clone())),
scan: Some(scan::start_scan(ranges.clone())),
scanning: true,
scan_total: 0,
target_ips: HashSet::new(),
@@ -296,10 +295,10 @@ impl App {
}
pub fn drain_scan(&mut self) {
let Some(rx) = &self.scan_rx else { return };
let Some(handle) = &self.scan else { return };
let mut changed = false;
loop {
match rx.try_recv() {
match handle.rx.try_recv() {
Ok(ScanMsg::Started { total, targets }) => {
// Drop miners no longer in the target range.
let before = self.rows.len();
@@ -359,7 +358,7 @@ impl App {
self.table_parent.layout();
self.countdown = if self.playing { self.auto_secs } else { 0 };
}
self.scan_rx = None;
self.scan = None;
break;
}
}
@@ -396,11 +395,21 @@ impl App {
}
}
/// Start a fresh scan of the saved ranges.
fn start_new_scan(&mut self) {
self.scan_rx = Some(scan::start_scan(scan::load_ranges()));
/// Cancel any in-flight scan, then start a fresh one over `lines`. Signalling
/// the old scan to stop before replacing it prevents two scan threads (and
/// two tokio runtimes) probing the network at once.
fn begin_scan(&mut self, lines: Vec<String>) {
if let Some(old) = self.scan.take() {
old.stop();
}
self.scan = Some(scan::start_scan(lines));
self.scanning = true;
self.countdown = 0;
}
/// Start a fresh scan of the saved ranges.
fn start_new_scan(&mut self) {
self.begin_scan(scan::load_ranges());
wx_rs::set_status_text("scanning...");
}
@@ -483,6 +492,10 @@ impl App {
}
}
self.view.apply_visible_reorder(&new_visible);
// Rebuild so the control's column creation order matches the new
// display order again; fill_rows/header_click/update_headers all assume
// creation order == display_columns(), which the drag alone breaks.
self.rebuild_table();
}
/// Build (but do not show) the ranges editor. The caller shows it modally
@@ -543,9 +556,7 @@ impl App {
let _ = scan::save_auto_secs(secs);
}
let _ = scan::save_ranges(&lines);
self.scan_rx = Some(scan::start_scan(lines.clone()));
self.scanning = true;
self.countdown = 0;
self.begin_scan(lines);
wx_rs::set_status_text("scanning...");
self.ranges_dialog.close(1);
}
@@ -757,11 +768,14 @@ impl App {
wx_rs::set_status_text(&format!("{} miners - paused", self.rows.len()));
}
ID_STOP => {
// Halt the loop and drop any in-flight scan.
// Halt the loop and cancel any in-flight scan (dropping
// the receiver alone would leave the thread probing).
self.playing = false;
self.countdown = 0;
self.scanning = false;
self.scan_rx = None;
if let Some(old) = self.scan.take() {
old.stop();
}
self.progress.show(false);
self.table_parent.layout();
wx_rs::set_status_text(&format!("{} miners - stopped", self.rows.len()));