diff --git a/README.md b/README.md index db8c664..a896837 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,10 @@ Rust mining and tuning core for Alkane control boards. The [SDK](https://gitea.bluefla.re/blueflare/alkane-sdk) builds board images and -provides the hardware backend. The miner has no on-board web frontend. +provides the hardware backend. The on-board web console is the parameterised +`flare-ui`: a sidebar shell with live telemetry (readings) and real controls +(mode/target, start/stop) that drive the runtime, with `/api/...` as the +interface of record behind every page. ## Status @@ -40,6 +43,14 @@ ALKANE_POOL_PASSWORD="$POOL_PASSWORD" alkane-os --mine-simulator HAL_SOCKET POOL Use `BM1362` for that chip. Set `ALKANE_API_LISTEN=127.0.0.1:4028` for read-only `summary` and `version` commands; reach it remotely through SSH. +To bring up the full web console on a workstation with no hashboard, run +`alkane-os --serve-sim`: a reference HAL runs in-process, the runtime boots +against it, and the printed URL serves the live, controllable console (the +frequency moves toward the target; start/stop and mode changes take effect). +`alkane-os --serve` serves the same console with no backend, for a board whose +HAL backend is not written yet. `ALKANE_WEB_LISTEN=ADDR` overrides the bind +(default port 80, or 8080 without privilege). + ## Release gate `main` runs tests, benchmarks, and conformance before release; `next` builds diff --git a/src/app.rs b/src/app.rs index 680342a..ce1f216 100644 --- a/src/app.rs +++ b/src/app.rs @@ -13,6 +13,7 @@ use crate::fanmap::{FanMap, MapThresholds, SweepConfig}; use crate::fanmap_store::ensure_map; use crate::fault::FaultPolicy; use crate::hal_wire::{HalClient, HalError}; +use crate::control::Control; use crate::management::{bind_local, serve, HardwareSnapshot, MiningStatus}; use crate::profiles::{ProfileDb, ProfileError}; use crate::runtime::MinerRuntime; @@ -52,6 +53,7 @@ pub fn start( status: Arc, api: Option, web_bind: Option, + control: Arc, ) -> io::Result { let api_listener = match api { Some(address) => Some(bind_local(address)?), @@ -81,8 +83,9 @@ pub fn start( } if let Some(listener) = web_listener { let snapshot = Arc::clone(&status); + let control = Arc::clone(&control); handles.push(std::thread::spawn(move || { - if let Err(error) = web::serve_listener(listener, snapshot) { + if let Err(error) = web::serve_listener(listener, snapshot, control) { eprintln!("web UI stopped: {error}"); } })); @@ -295,6 +298,7 @@ mod tests { Arc::clone(&status), Some("127.0.0.1:0".parse().unwrap()), Some("127.0.0.1:0".parse().unwrap()), + Arc::new(Control::default()), ) .expect("start"); let (api, web) = servers.addresses(); @@ -319,7 +323,7 @@ mod tests { #[test] fn servers_are_optional() { let status = Arc::new(MiningStatus::new()); - let servers = start(status, None, None).expect("start"); + let servers = start(status, None, None, Arc::new(Control::default())).expect("start"); assert_eq!(servers.addresses(), (None, None)); } diff --git a/src/console.rs b/src/console.rs new file mode 100644 index 0000000..d3a6ca5 --- /dev/null +++ b/src/console.rs @@ -0,0 +1,409 @@ +// SPDX-License-Identifier: MIT +//! The flare-ui console: every navigation tab rendered with live data and real +//! controls, inside the shared `flare-ui` shell. +//! +//! `web.rs` owns the socket, the routing and the data gatherers; this module +//! owns what each page looks like. It is built entirely from `flare-ui` +//! primitives (`shell`, `render`, `readings`, `actions`, `components`) and the +//! schema in `dashboard.rs`, so the on-box console is the parameterised FLARE UI +//! rather than a second hand-written one. Values come from the published +//! hardware snapshot and the operator [`Control`]; nothing here claims hardware +//! the snapshot does not show. + +use std::collections::BTreeMap; + +use maud::{html, Markup, PreEscaped}; +use serde_json::Value; + +use flare_ui::actions::{self, Tone}; +use flare_ui::components; +use flare_ui::nav::VisibleNav; +use flare_ui::readings::{self, Level, Reading}; +use flare_ui::render::{self, View}; +use flare_ui::shell::{self, Active}; +use wschema::model::Surface; + +use crate::control::{Control, ControlMode}; +use crate::dashboard::Dashboard; +use crate::management::MiningStatus; +use crate::web; + +/// Render one navigation tab. `section`/`tab` are already validated against the +/// nav by the caller. `errors` carries per-path messages from a rejected form. +pub fn page( + status: &MiningStatus, + control: &Control, + section: &str, + tab: &str, + errors: &BTreeMap, +) -> Markup { + let dash = Dashboard::load(web::settings_path()); + let nav = dash.nav().unwrap_or_default(); + let title = tab_title(&nav, section, tab); + let hw = status.hardware_document(); + let body = match (section, tab) { + ("dashboard", "overview") | ("", "") => overview_card(&hw, control), + ("dashboard", "alerts") => alerts_card(&hw), + ("mining", "overview") => control_card(&hw, control), + ("mining", "hashboards") => hashboards_card(&hw), + ("mining", "power") => power_card(&hw), + ("mining", "fans") => fans_card(&hw), + ("settings", "system") => system_card(status), + ("settings", "tuning") => tuning_card(&dash, control, errors), + ("settings", "pools") => pools_card(), + ("settings", "network") => network_card(), + ("settings", "security") => security_card(status), + ("settings", "logs") => logs_card(), + ("settings", "files") => files_card(), + ("settings", "terminal") => terminal_card(), + _ => components::card(&title, readings::note("This page has no content yet.")), + }; + shell::page( + "Alkane OS", + &Dashboard::assets(), + &nav, + Active { section, tab }, + body, + ) +} + +fn tab_title(nav: &VisibleNav, section: &str, tab: &str) -> String { + nav.sections + .iter() + .find(|s| s.slug == section) + .and_then(|s| s.tabs.iter().find(|t| t.slug == tab)) + .map(|t| t.title.clone()) + .unwrap_or_else(|| tab.to_string()) +} + +// --- value helpers ----------------------------------------------------------- + +fn reading(key: &str, label: &str, value: Option, units: &str, digits: usize) -> Reading { + Reading { + key: key.to_string(), + label: label.to_string(), + value, + units: units.to_string(), + digits, + } +} + +fn num(hw: &Value, pointer: &str) -> Option { + hw.pointer(pointer).and_then(Value::as_f64) +} + +fn text(hw: &Value, pointer: &str, fallback: &str) -> String { + hw.pointer(pointer) + .and_then(Value::as_str) + .unwrap_or(fallback) + .to_string() +} + +fn available(hw: &Value) -> bool { + hw.get("available").and_then(Value::as_bool).unwrap_or(false) +} + +fn active_chain_count(hw: &Value) -> usize { + hw.get("active_chains") + .and_then(Value::as_array) + .map(|a| a.len()) + .unwrap_or(0) +} + +/// The run/stop state as a badge: a fault stop wins over the operator switch. +fn run_state(hw: &Value, control: &Control) -> (Level, String) { + if let Some(reason) = hw.get("stopped").and_then(Value::as_str) { + return (Level::Err, format!("stopped: {reason}")); + } + if control.running() { + (Level::Ok, "mining".to_string()) + } else { + (Level::Warn, "idle (operator stopped)".to_string()) + } +} + +// --- cards ------------------------------------------------------------------- + +fn overview_card(hw: &Value, control: &Control) -> Markup { + let freq = reading("frequency_mhz", "Chain frequency", num(hw, "/frequency_mhz"), "MHz", 0); + let (level, state) = run_state(hw, control); + let run = reading("run", "State", None, "", 0); + components::card( + "Overview", + html! { + @if available(hw) { + (readings::hero(&freq)) + (readings::status(&run, level, &state)) + (readings::plate(&[ + ("Profile".into(), text(hw, "/profile", "unknown")), + ("Chip".into(), text(hw, "/chip", "unknown")), + ("Power supply".into(), text(hw, "/psu", "not identified")), + ("Mode".into(), ControlMode::of_target(control.target()).label().into()), + ("Target".into(), text(hw, "/target", "-")), + ("Active chains".into(), active_chain_count(hw).to_string()), + ])) + } @else { + (readings::note("No backend is attached. Run the miner (or alkane-os --serve-sim on a workstation) to populate this page.")) + } + }, + ) +} + +fn alerts_card(hw: &Value) -> Markup { + let stopped = hw.get("stopped").and_then(Value::as_str); + let run = reading("alert", "Supervisor", None, "", 0); + components::card( + "Alerts", + html! { + @match stopped { + Some(reason) => (readings::status(&run, Level::Err, &format!("machine stopped: {reason}"))), + None => (readings::status(&run, Level::Ok, "no active faults")), + } + (readings::log(&web::recent_log_lines(40))) + }, + ) +} + +fn control_card(hw: &Value, control: &Control) -> Markup { + let (level, state) = run_state(hw, control); + let run = reading("run", "State", None, "", 0); + let freq = reading("frequency_mhz", "Chain frequency", num(hw, "/frequency_mhz"), "MHz", 0); + let mode = ControlMode::of_target(control.target()); + components::card( + "Control", + html! { + (readings::status(&run, level, &state)) + (readings::hero(&freq)) + (readings::plate(&[ + ("Mode".into(), mode.label().into()), + ("Target".into(), text(hw, "/target", "-")), + ("Active chains".into(), active_chain_count(hw).to_string()), + ])) + div class="bf-actions" { + @if let Some(b) = actions::action_button("/control/start", "Start mining", Tone::Primary, control.csrf(), None) { (b) } + @if let Some(b) = actions::action_button("/control/stop", "Stop mining", Tone::Danger, control.csrf(), Some("Stops hashing immediately.")) { (b) } + } + (readings::note("Change the mode and target on Settings -> Tuning. A thermal or chain fault always overrides the operator switch.")) + }, + ) +} + +fn hashboards_card(hw: &Value) -> Markup { + let rows: Vec> = hw + .get("chains") + .and_then(Value::as_array) + .map(|chains| { + chains + .iter() + .map(|c| { + vec![ + c.get("index").map(|v| v.to_string()).unwrap_or_default(), + c.get("chip").and_then(Value::as_str).unwrap_or("-").to_string(), + c.get("chips_found").map(|v| v.to_string()).unwrap_or_default(), + c.pointer("/eeprom/state").and_then(Value::as_str).unwrap_or("-").to_string(), + c.get("response_per_mille").map(|v| v.to_string()).unwrap_or_default(), + ] + }) + .collect() + }) + .unwrap_or_default(); + components::card( + "Hashboards", + if rows.is_empty() { + readings::note("No chains detected.") + } else { + readings::table(&["#", "chip", "chips", "eeprom", "response per mille"], &rows) + }, + ) +} + +fn power_card(hw: &Value) -> Markup { + components::card( + "Power supply", + readings::plate(&[ + ("Supply".into(), text(hw, "/psu", "not identified")), + ( + "Voltage range".into(), + format!( + "{} - {} mV", + hw.pointer("/envelope/v_min_mv").map(|v| v.to_string()).unwrap_or_default(), + hw.pointer("/envelope/v_max_mv").map(|v| v.to_string()).unwrap_or_default() + ), + ), + ( + "Frequency range".into(), + format!( + "{} - {} MHz", + hw.pointer("/envelope/f_min_mhz").map(|v| v.to_string()).unwrap_or_default(), + hw.pointer("/envelope/f_max_mhz").map(|v| v.to_string()).unwrap_or_default() + ), + ), + ( + "Operating point".into(), + format!( + "{} mV / {} MHz", + hw.pointer("/operating_point/voltage_mv").map(|v| v.to_string()).unwrap_or_default(), + hw.pointer("/operating_point/frequency_mhz").map(|v| v.to_string()).unwrap_or_default() + ), + ), + ("Target".into(), text(hw, "/target", "-")), + ]), + ) +} + +fn fans_card(hw: &Value) -> Markup { + let rows: Vec> = hw + .get("fan_zones") + .and_then(Value::as_array) + .map(|zones| { + zones + .iter() + .map(|z| { + vec![ + z.get("fan").map(|v| v.to_string()).unwrap_or_default(), + z.get("zones").map(|v| v.to_string()).unwrap_or_default(), + ] + }) + .collect() + }) + .unwrap_or_default(); + components::card( + "Fans", + if rows.is_empty() { + readings::note("No fan zones mapped.") + } else { + readings::table(&["fan", "zones it cools"], &rows) + }, + ) +} + +fn plate_from(rows: Vec<(&str, String)>) -> Markup { + let items: Vec<(String, String)> = rows.into_iter().map(|(k, v)| (k.to_string(), v)).collect(); + readings::plate(&items) +} + +fn system_card(status: &MiningStatus) -> Markup { + html! { + (components::card("Identity", plate_from(web::system_rows()))) + (components::card("Network", plate_from(web::network_rows()))) + (components::card("Updates", plate_from(web::update_rows()))) + (components::card("Drivers", plate_from(web::driver_rows(status)))) + } +} + +fn network_card() -> Markup { + components::card("Network", plate_from(web::network_rows())) +} + +fn security_card(status: &MiningStatus) -> Markup { + html! { + (components::card("Security", plate_from(web::security_rows()))) + (components::card("Services", readings::table(&["service", "running"], &web::service_rows()))) + (components::card("Monitor", plate_from(web::monitor_rows(status)))) + } +} + +fn logs_card() -> Markup { + components::card("Logs", readings::log(&web::recent_log_lines(200))) +} + +fn files_card() -> Markup { + let doc = web::files_document("/"); + let rows: Vec> = doc + .get("entries") + .and_then(Value::as_array) + .map(|entries| { + entries + .iter() + .map(|e| { + vec![ + e.get("name").and_then(Value::as_str).unwrap_or("-").to_string(), + e.get("kind").and_then(Value::as_str).unwrap_or("-").to_string(), + e.get("size").map(|v| v.to_string()).unwrap_or_default(), + ] + }) + .collect() + }) + .unwrap_or_default(); + components::card( + "Files", + html! { + (readings::note("Read-only listing of /. Individual text files are at /api/file?path=.")) + (readings::table(&["name", "kind", "size"], &rows)) + }, + ) +} + +fn pools_card() -> Markup { + components::card( + "Pools", + readings::note("Pool configuration is set at mining start (worker and pool address). Live pool editing from the console is not wired yet."), + ) +} + +fn terminal_card() -> Markup { + if web::ui_token().is_none() { + return components::card( + "Terminal", + readings::note("Terminal is disabled until a token exists at /var/lib/alkane/ui-token. Create one, then reload."), + ); + } + components::card( + "Terminal", + html! { + div class="bf-field" { + label { + span class="bf-field-label bf-text-label" { "Command (runs as root on this miner)" } + input id="cmd" class="bf-input" type="text" placeholder="command"; + } + } + div class="bf-actions" { + button id="run" class="bf-btn bf-btn-primary bf-text-button" type="button" { "Run" } + } + pre id="out" class="bf-log" { "ready" } + (PreEscaped(TERMINAL_JS)) + }, + ) +} + +const TERMINAL_JS: &str = ""; + +/// The tuning control: the schema `tuning` settings in a working form that posts +/// to `/settings` (persist + drive the live runtime), plus the mode legend. +fn tuning_card(dash: &Dashboard, control: &Control, errors: &BTreeMap) -> Markup { + let Ok(eff) = dash.schema() else { + return components::card("Tuning", readings::note("Schema did not load.")); + }; + let view = View { + eff, + rows: dash.rows(), + errors, + surface: Surface::Web, + can_write: true, + }; + let current = ControlMode::of_target(control.target()); + html! { + form class="bf-form" method="post" action="/settings" { + input type="hidden" name="csrf" value=(control.csrf()); + input type="hidden" name="__section" value="settings"; + input type="hidden" name="__tab" value="tuning"; + (render::card("Tuning target", "tuning", &view)) + div class="bf-actions" { + button type="submit" class="bf-btn bf-btn-primary bf-text-button" { "Apply target" } + } + } + (components::card("How it maps", html! { + (readings::plate(&[ + ("Current mode".into(), current.label().into()), + ("Power target".into(), "hold a DC draw; efficiency follows the power point".into()), + ("Ambient temperature target".into(), "hold the hottest sensor a margin above ambient".into()), + ("Hashrate ceiling".into(), "seek a hashrate".into()), + ("Max fan".into(), "pin the fan and ramp under it".into()), + ])) + (readings::note("Apply writes the setting and switches the live target. Start and stop are on Mining -> Overview.")) + })) + } +} diff --git a/src/control.rs b/src/control.rs new file mode 100644 index 0000000..c5a8c13 --- /dev/null +++ b/src/control.rs @@ -0,0 +1,261 @@ +// SPDX-License-Identifier: MIT +//! Operator control intent for the live runtime. +//! +//! The management status in `management.rs` is read-only by design. This is the +//! one small mutable channel the other way: the web UI (and any local client) +//! WRITES a desired mode/target and a run switch here, and the serve-path +//! runtime loop READS it each control period and applies it with +//! [`crate::runtime::MinerRuntime::set_target`]. It owns nothing the fault +//! supervisor owns: a thermal or chain fault still stops the machine regardless +//! of what the operator asked for. +//! +//! A generation counter lets the loop notice a change cheaply without diffing +//! the target every period. + +use crate::tuning::TuningTarget; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::Mutex; + +/// The operator-visible control modes. Each maps onto exactly one +/// [`TuningTarget`] the runtime already implements, so the UI never claims a +/// behaviour the controller does not have. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ControlMode { + /// Hold a DC power draw; efficiency follows from the power point. The MPC + /// "power target" mode. + Power, + /// Hold the hottest sensor a fixed margin above measured ambient. The MPC + /// "ambient temperature target" mode. + Ambient, + /// Seek a hashrate ceiling. + Hashrate, + /// Pin the fan at a duty and ramp frequency under it. + MaxFan, +} + +impl ControlMode { + pub fn as_str(self) -> &'static str { + match self { + ControlMode::Power => "power", + ControlMode::Ambient => "ambient", + ControlMode::Hashrate => "hashrate", + ControlMode::MaxFan => "fan", + } + } + + pub fn label(self) -> &'static str { + match self { + ControlMode::Power => "Power target", + ControlMode::Ambient => "Ambient temperature target", + ControlMode::Hashrate => "Hashrate ceiling", + ControlMode::MaxFan => "Max fan", + } + } + + pub fn all() -> [ControlMode; 4] { + [ + ControlMode::Power, + ControlMode::Ambient, + ControlMode::Hashrate, + ControlMode::MaxFan, + ] + } + + pub fn of_target(target: TuningTarget) -> ControlMode { + match target { + TuningTarget::PowerW(_) => ControlMode::Power, + TuningTarget::AmbientC { .. } => ControlMode::Ambient, + TuningTarget::HashrateThs(_) => ControlMode::Hashrate, + TuningTarget::MaxFan { .. } => ControlMode::MaxFan, + } + } +} + +/// The unit and sensible value for a mode's input box, for the UI form. +pub fn mode_input(mode: ControlMode) -> (&'static str, &'static str) { + match mode { + ControlMode::Power => ("W", "watts of DC draw to hold"), + ControlMode::Ambient => ("C", "degrees above ambient to hold the hottest sensor"), + ControlMode::Hashrate => ("TH/s", "hashrate ceiling"), + ControlMode::MaxFan => ("% PWM", "fan duty to pin (0-100)"), + } +} + +/// Build a [`TuningTarget`] from a mode name and its single value. The value is +/// in the mode's natural unit (watts, degrees C, TH/s, percent). +pub fn parse_target(mode: &str, value: f32) -> Result { + if !value.is_finite() || value < 0.0 { + return Err(format!("value {value} is not a non-negative number")); + } + Ok(match mode { + "power" => TuningTarget::PowerW(value), + "hashrate" => TuningTarget::HashrateThs(value), + "ambient" => TuningTarget::AmbientC { + // UI gives whole degrees C; the controller works in millidegrees. + margin_mc: (value * 1000.0).round() as i32, + }, + "fan" => { + if value > 100.0 { + return Err("fan duty must be 0-100".into()); + } + TuningTarget::MaxFan { + max_pwm: value.round() as u8, + } + } + other => return Err(format!("unknown mode {other:?}")), + }) +} + +/// The compact `kind:value` label, matching the management `target` field and +/// `app::target_label`. +pub fn target_label(target: TuningTarget) -> String { + match target { + TuningTarget::PowerW(w) => format!("power:{}", w.round() as i64), + TuningTarget::HashrateThs(t) => format!("hashrate:{}", t.round() as i64), + TuningTarget::AmbientC { margin_mc } => format!("ambient:{margin_mc}"), + TuningTarget::MaxFan { max_pwm } => format!("fan:{max_pwm}"), + } +} + +/// Shared operator intent. Cheap to read every control period. +#[derive(Debug)] +pub struct Control { + running: AtomicBool, + generation: AtomicU64, + target: Mutex, + /// Per-process token every mutating control form must echo back. It is not + /// a login (SSH guards the box); it stops a foreign page from POSTing a + /// power change on a shared network through the operator's browser. + csrf: String, +} + +impl Control { + pub fn new(initial: TuningTarget, running: bool) -> Self { + Self { + running: AtomicBool::new(running), + generation: AtomicU64::new(1), + target: Mutex::new(initial), + csrf: fresh_csrf(), + } + } + + /// The token to embed in every control form and require on every control POST. + pub fn csrf(&self) -> &str { + &self.csrf + } + + /// Monotonic counter, bumped on every mutation. The loop keeps the last + /// value it applied and only re-applies when this moves. + pub fn generation(&self) -> u64 { + self.generation.load(Ordering::Acquire) + } + + pub fn running(&self) -> bool { + self.running.load(Ordering::Acquire) + } + + pub fn set_running(&self, running: bool) { + self.running.store(running, Ordering::Release); + self.generation.fetch_add(1, Ordering::AcqRel); + } + + pub fn target(&self) -> TuningTarget { + *self.target.lock().expect("control target lock") + } + + pub fn set_target(&self, target: TuningTarget) { + *self.target.lock().expect("control target lock") = target; + self.generation.fetch_add(1, Ordering::AcqRel); + } + + pub fn set_mode_value(&self, mode: &str, value: f32) -> Result<(), String> { + let target = parse_target(mode, value)?; + self.set_target(target); + Ok(()) + } +} + +impl Default for Control { + fn default() -> Self { + // Default to a conservative power target, stopped until the operator starts it. + Self::new(TuningTarget::PowerW(2_400.0), false) + } +} + +/// 128 bits of hex from the OS CSPRNG, or a fixed dev token if it cannot be read +/// (a locked-down test box). The miner holds no secrets in this value. +fn fresh_csrf() -> String { + use std::io::Read; + if let Ok(mut file) = std::fs::File::open("/dev/urandom") { + let mut bytes = [0_u8; 16]; + if file.read_exact(&mut bytes).is_ok() { + let mut out = String::with_capacity(32); + for byte in bytes { + out.push_str(&format!("{byte:02x}")); + } + return out; + } + } + "dev-csrf-token".to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn modes_round_trip_through_targets() { + for mode in ControlMode::all() { + let value = match mode { + ControlMode::MaxFan => 80.0, + ControlMode::Ambient => 20.0, + _ => 2_400.0, + }; + let target = parse_target(mode.as_str(), value).expect("parse"); + assert_eq!(ControlMode::of_target(target), mode); + } + } + + #[test] + fn ambient_degrees_become_millidegrees() { + let target = parse_target("ambient", 20.0).expect("parse"); + assert_eq!(target, TuningTarget::AmbientC { margin_mc: 20_000 }); + } + + #[test] + fn fan_duty_is_bounded() { + assert!(parse_target("fan", 120.0).is_err()); + assert_eq!( + parse_target("fan", 100.0).expect("parse"), + TuningTarget::MaxFan { max_pwm: 100 } + ); + } + + #[test] + fn negative_and_unknown_are_rejected() { + assert!(parse_target("power", -1.0).is_err()); + assert!(parse_target("bogus", 1.0).is_err()); + } + + #[test] + fn setting_target_or_running_bumps_the_generation() { + let control = Control::new(TuningTarget::PowerW(2_000.0), false); + let g0 = control.generation(); + control.set_target(TuningTarget::HashrateThs(100.0)); + let g1 = control.generation(); + assert!(g1 > g0); + assert_eq!(control.target(), TuningTarget::HashrateThs(100.0)); + control.set_running(true); + assert!(control.generation() > g1); + assert!(control.running()); + } + + #[test] + fn label_matches_management_shape() { + assert_eq!(target_label(TuningTarget::PowerW(3_000.0)), "power:3000"); + assert_eq!( + target_label(TuningTarget::AmbientC { margin_mc: 20_000 }), + "ambient:20000" + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index 73791bf..a8bcec0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,8 @@ pub mod app; pub mod bm1362; +pub mod console; +pub mod control; pub mod bm1366; pub mod bm1370; pub mod bm13xx; diff --git a/src/main.rs b/src/main.rs index e10b061..ed2c906 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,6 @@ // SPDX-License-Identifier: MIT use alkane_os::app; +use alkane_os::control::Control; use alkane_os::detect::{ ChipModel as DetectedChip, DetectionBackend, EepromState, Envelope, ProbeBudget, ProbeOutcome, PsuCapability, SensorTopology, @@ -39,7 +40,8 @@ fn sim_mine(mut args: impl Iterator) -> Result<(), Box .map(|bind| bind.parse()) .transpose()?; let web = web_listen()?; - let servers = app::start(Arc::clone(&status), api, web)?; + let control = Arc::new(Control::default()); + let servers = app::start(Arc::clone(&status), api, web, control)?; let (api_address, web_address) = servers.addresses(); if let Some(address) = api_address { println!("management API on {address}"); @@ -210,7 +212,8 @@ fn boot_hal(mut args: impl Iterator) -> Result<(), Box .map(|bind| bind.parse()) .transpose()?; let web = web_listen()?; - let servers = app::start(Arc::clone(&status), api, web)?; + let control = Arc::new(Control::default()); + let servers = app::start(Arc::clone(&status), api, web, control)?; let config = app::BootConfig { profile_db_json, @@ -312,6 +315,125 @@ fn web_listen() -> Result, Box Result<(), Box> { + use alkane_os::hal_sim::{serve as sim_serve, SimConfig}; + + let socket = std::env::temp_dir().join(format!("alkane-serve-sim-{}.sock", std::process::id())); + let _ = std::fs::remove_file(&socket); + { + let socket = socket.clone(); + std::thread::spawn(move || { + if let Err(error) = sim_serve(&socket, SimConfig::default()) { + eprintln!("reference HAL stopped: {error}"); + } + }); + } + // Wait for the HAL to bind its socket before the first connection. + for _ in 0..500 { + if socket.exists() { + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + + let status = Arc::new(MiningStatus::new()); + let initial = TuningTarget::PowerW(2_400.0); + // Start hashing immediately so the page is live; the operator can stop it. + let control = Arc::new(Control::new(initial, true)); + + let config = app::BootConfig { + profile_db_json: include_str!("../profiles.example.json").to_owned(), + chain_ports: vec![0, 1, 2], + sensor: SensorTopology::Pic, + budget: ProbeBudget::default(), + fan_zones: Vec::new(), + target: initial, + pid: PidConfig::default(), + ceiling_mc: 95_000, + fault_policy: Default::default(), + }; + let map_path = + std::env::temp_dir().join(format!("alkane-serve-sim-{}.map.json", std::process::id())); + let settings = app::HalBoot { + config: &config, + sweep: alkane_os::fanmap::SweepConfig { + fans: 0, + zones: 0, + low_pwm: 40, + high_pwm: 100, + repeats: 1, + settle_ms: 0, + }, + thresholds: Default::default(), + map_path: &map_path, + }; + let (mut runtime, _map) = app::boot_from_hal(&socket, &settings, &status)?; + println!( + "detected {} with {} active chains", + runtime.plan().profile, + runtime.active_chains().len() + ); + + let api = std::env::var("ALKANE_API_LISTEN") + .ok() + .map(|bind| bind.parse()) + .transpose()? + .or(Some("127.0.0.1:4028".parse()?)); + let servers = app::start(Arc::clone(&status), api, web_listen()?, Arc::clone(&control))?; + let (api_address, web_address) = servers.addresses(); + if let Some(address) = api_address { + println!("management API on {address}"); + } + if let Some(address) = web_address { + println!("web UI on http://{address}/"); + } + + // The control loop: its own HAL connection, applying operator intent. + let mut client = HalClient::connect(&socket)?; + let mut last_generation = 0_u64; + loop { + let generation = control.generation(); + if generation != last_generation { + runtime.set_target(control.target()); + last_generation = generation; + } + let label = app::target_label(&control.target()); + if control.running() && runtime.stop_reason().is_none() { + status.set_running(true); + let hottest = client.read_temperature_mc(0).ok(); + let power_w = client.read_power_w().ok().map(f32::from); + let outcome = runtime.tick(&Tick { + power_w, + hashrate_ths: None, + hottest_mc: hottest, + // The bench enclosure has no ambient sensor; assume 25 C so the + // ambient-target mode has something to track. + ambient_mc: Some(25_000), + dt_s: 1.0, + }); + if let TickOutcome::Run(command) = outcome { + for chain in runtime.active_chains() { + let _ = client.set_chain_frequency(chain, command.frequency_mhz); + } + if let Some(pwm) = command.fan_pwm { + let _ = client.set_fan_target(0, pwm); + } + } + } else { + status.set_running(false); + } + status.set_hardware(app::snapshot(&runtime, &label)); + std::thread::sleep(Duration::from_millis(250)); + } +} + /// Serve the UI and the API without a mining backend. A board whose HAL /// backend is not written yet still has to be reachable and observable; every /// page says "not identified" rather than claiming hardware it cannot see. @@ -322,7 +444,8 @@ fn serve_only() -> Result<(), Box> { .map(|bind| bind.parse()) .transpose()?; let api = api.or(Some("0.0.0.0:4028".parse()?)); - let servers = app::start(Arc::clone(&status), api, web_listen()?)?; + let control = Arc::new(Control::default()); + let servers = app::start(Arc::clone(&status), api, web_listen()?, control)?; let (api_address, web_address) = servers.addresses(); if let Some(address) = api_address { println!("management API on {address}"); @@ -354,6 +477,12 @@ fn main() { std::process::exit(1); } } + Some("--serve-sim") => { + if let Err(error) = serve_sim() { + eprintln!("serve-sim failed: {error}"); + std::process::exit(1); + } + } Some("--boot") => { if let Err(error) = boot_hal(args) { eprintln!("boot failed: {error}"); @@ -439,7 +568,7 @@ fn main() { } } _ => { - eprintln!("usage: alkane-os --list-targets | --version | --self-check | --boot HAL_SOCKET PROFILES.json TARGET [PIC|NOPIC] [TICKS] | --sim-hal SOCKET | --check-hal SOCKET | --check-profiles PATH | --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER BM1362|BM1366 [MAX_ACCEPTS]"); + eprintln!("usage: alkane-os --list-targets | --version | --self-check | --serve | --serve-sim | --boot HAL_SOCKET PROFILES.json TARGET [PIC|NOPIC] [TICKS] | --sim-hal SOCKET | --check-hal SOCKET | --check-profiles PATH | --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER BM1362|BM1366 [MAX_ACCEPTS]"); eprintln!( "env: ALKANE_API_LISTEN=ADDR ALKANE_WEB_LISTEN=ADDR ALKANE_POOL_PASSWORD=..." ); diff --git a/src/runtime.rs b/src/runtime.rs index 15acccd..62a73df 100644 --- a/src/runtime.rs +++ b/src/runtime.rs @@ -80,6 +80,18 @@ impl MinerRuntime { self.faults.active_chains() } + /// The operator target currently in force. + pub fn target(&self) -> TuningTarget { + self.tuning.target() + } + + /// Switch the operator target (one of the MPC modes) without a restart. The + /// PID state carries over, so the operating point moves from where it is + /// rather than snapping back to the envelope floor. + pub fn set_target(&mut self, target: TuningTarget) { + self.tuning.set_target(target); + } + pub fn stop_reason(&self) -> Option { self.faults.stop_reason() } @@ -268,6 +280,36 @@ mod tests { assert!(runtime.active_chains().is_empty()); } + #[test] + fn switching_target_keeps_the_operating_point_and_takes_effect() { + let mut runtime = runtime(); + // Climb under a power target so the frequency leaves the floor. + for _ in 0..30 { + let power = 4.0 * f32::from(runtime.operating_point().frequency_mhz); + runtime.tick(&tick(power)); + } + let climbed = runtime.operating_point().frequency_mhz; + assert!(climbed > 300, "frequency never left the floor: {climbed}"); + assert!(matches!(runtime.target(), TuningTarget::PowerW(_))); + // Switch to an ambient target in place: the target changes and the + // operating point carries over (no snap back to the floor). + runtime.set_target(TuningTarget::AmbientC { margin_mc: 20_000 }); + assert!(matches!( + runtime.target(), + TuningTarget::AmbientC { margin_mc: 20_000 } + )); + assert_eq!(runtime.operating_point().frequency_mhz, climbed); + // The ambient target now drives: feed ambient + hottest and it still runs. + let outcome = runtime.tick(&Tick { + power_w: None, + hashrate_ths: None, + hottest_mc: Some(60_000), + ambient_mc: Some(40_000), + dt_s: 1.0, + }); + assert!(matches!(outcome, TickOutcome::Run(_))); + } + #[test] fn the_operating_point_reflects_the_last_command() { let mut runtime = runtime(); diff --git a/src/tuning.rs b/src/tuning.rs index 48d92e1..f7419c9 100644 --- a/src/tuning.rs +++ b/src/tuning.rs @@ -168,6 +168,18 @@ impl TuningLoop { self.pid.output().round() as u16 } + /// The target the loop is currently chasing. + pub fn target(&self) -> TuningTarget { + self.target + } + + /// Switch the operator target in place, keeping the PID state so the + /// operating point carries over instead of jumping back to the floor. The + /// thermal guard and envelope bounds are unchanged. + pub fn set_target(&mut self, target: TuningTarget) { + self.target = target; + } + /// Fan duty implied by the target, if the target owns the fan. fn target_fan(&self) -> Option { match self.target { diff --git a/src/web.rs b/src/web.rs index eaf9f53..2dff954 100644 --- a/src/web.rs +++ b/src/web.rs @@ -10,6 +10,8 @@ //! connection. Files and Terminal are gated on a token so a shared network //! cannot silently use them. +use crate::console; +use crate::control::{self, Control}; use crate::management::MiningStatus; use crate::ui; use serde_json::{json, Value}; @@ -29,18 +31,23 @@ const TOKEN_FILE: &str = "/var/lib/alkane/ui-token"; const LOG_FILE: &str = "/var/log/messages"; /// Bind and serve until the listener fails. -pub fn serve(bind: SocketAddr, status: Arc) -> io::Result<()> { +pub fn serve(bind: SocketAddr, status: Arc, control: Arc) -> io::Result<()> { let listener = TcpListener::bind(bind)?; - serve_listener(listener, status) + serve_listener(listener, status, control) } /// Serve on an already-bound listener. -pub fn serve_listener(listener: TcpListener, status: Arc) -> io::Result<()> { +pub fn serve_listener( + listener: TcpListener, + status: Arc, + control: Arc, +) -> io::Result<()> { for stream in listener.incoming() { let Ok(stream) = stream else { continue }; let status = Arc::clone(&status); + let control = Arc::clone(&control); std::thread::spawn(move || { - let _ = handle(stream, &status); + let _ = handle(stream, &status, &control); }); } Ok(()) @@ -103,7 +110,7 @@ fn percent_decode(text: &str) -> String { } /// Handle one HTTP request. -pub fn handle(mut stream: TcpStream, status: &MiningStatus) -> io::Result<()> { +pub fn handle(mut stream: TcpStream, status: &MiningStatus, control: &Control) -> io::Result<()> { stream.set_read_timeout(Some(CLIENT_TIMEOUT))?; stream.set_write_timeout(Some(CLIENT_TIMEOUT))?; let mut raw = Vec::new(); @@ -159,14 +166,20 @@ pub fn handle(mut stream: TcpStream, status: &MiningStatus) -> io::Result<()> { query, body: String::from_utf8_lossy(&body).into_owned(), }; - route(&mut stream, status, &request) + route(&mut stream, status, control, &request) } -fn route(stream: &mut TcpStream, status: &MiningStatus, request: &Request) -> io::Result<()> { - if dashboard_route(stream, request)? { +fn route( + stream: &mut TcpStream, + status: &MiningStatus, + control: &Control, + request: &Request, +) -> io::Result<()> { + if dashboard_route(stream, status, control, request)? { return Ok(()); } match (request.method.as_str(), request.path.as_str()) { + ("GET", "/api/control") => json_response(stream, &control_document(status, control)), ("GET", "/") => html(stream, "Dashboard", &ui::dashboard_page("dashboard", true)), ("GET", "/mining") => html( stream, @@ -360,7 +373,7 @@ fn route(stream: &mut TcpStream, status: &MiningStatus, request: &Request) -> io /// Where the dashboard keeps operator settings. -fn settings_path() -> std::path::PathBuf { +pub(crate) fn settings_path() -> std::path::PathBuf { let etc = std::path::Path::new("/etc/alkane/settings.json"); if etc.exists() || std::path::Path::new("/etc/alkane").is_dir() { return etc.to_path_buf(); @@ -373,7 +386,12 @@ fn settings_path() -> std::path::PathBuf { /// /// Returns `None` when the path is not a dashboard path, so the hand-written /// API routes below keep working unchanged. -fn dashboard_route(stream: &mut TcpStream, request: &Request) -> io::Result { +fn dashboard_route( + stream: &mut TcpStream, + status: &MiningStatus, + control: &Control, + request: &Request, +) -> io::Result { let path = request.path.clone(); if let Some(name) = path.strip_prefix("/assets/") { for (file, css) in crate::dashboard::Dashboard::stylesheets() { @@ -383,22 +401,22 @@ fn dashboard_route(stream: &mut TcpStream, request: &Request) -> io::Result respond(stream, 303, "text/plain", b"see /").map(|_| true), - Err(failures) => { - let mut text = String::new(); - for (key, why) in failures { - text.push_str(&format!("{key}: {why}\n")); - } - respond(stream, 422, "text/plain; charset=utf-8", text.as_bytes()).map(|_| true) - } + if request.method == "POST" { + return match path.as_str() { + "/settings" => settings_submit(stream, status, control, request).map(|_| true), + "/control/start" => control_switch(stream, control, request, true).map(|_| true), + "/control/stop" => control_switch(stream, control, request, false).map(|_| true), + _ => Ok(false), }; } if request.method != "GET" { return Ok(false); } + let empty = std::collections::BTreeMap::new(); + if path == "/" { + let html = console::page(status, control, "dashboard", "overview", &empty).into_string(); + return respond(stream, 200, "text/html; charset=utf-8", html.as_bytes()).map(|_| true); + } let mut parts = path.trim_start_matches('/').split('/'); let section = match parts.next() { Some(section) if !section.is_empty() => section, @@ -409,21 +427,117 @@ fn dashboard_route(stream: &mut TcpStream, request: &Request) -> io::Result nav, Err(_) => return Ok(false), }; - let known = nav.sections.iter().find(|s| s.slug == section); - let known = match known { + let known = match nav.sections.iter().find(|s| s.slug == section) { Some(section) => section, None => return Ok(false), }; - let tab = parts.next().unwrap_or_else(|| { - known.tabs.first().map(|tab| tab.slug.as_str()).unwrap_or("") - }); + let tab = parts + .next() + .map(str::to_string) + .unwrap_or_else(|| known.tabs.first().map(|tab| tab.slug.clone()).unwrap_or_default()); if !known.tabs.iter().any(|t| t.slug == tab) { return Ok(false); } - let html = dash.page(section, tab, &std::collections::BTreeMap::new()).into_string(); + let html = console::page(status, control, section, &tab, &empty).into_string(); respond(stream, 200, "text/html; charset=utf-8", html.as_bytes()).map(|_| true) } +/// Read a field from an `application/x-www-form-urlencoded` body. +fn form_field(body: &str, key: &str) -> Option { + body.split('&').find_map(|pair| { + let (k, v) = pair.split_once('=')?; + (percent_decode(k) == key).then(|| percent_decode(v)) + }) +} + +/// Every mutating control form must echo the per-process token. +fn csrf_ok(control: &Control, request: &Request) -> bool { + form_field(&request.body, "csrf").as_deref() == Some(control.csrf()) +} + +/// Switch the operator run state (Start/Stop), then send the browser back to the +/// control page. +fn control_switch( + stream: &mut TcpStream, + control: &Control, + request: &Request, + running: bool, +) -> io::Result<()> { + if !csrf_ok(control, request) { + return respond(stream, 403, "text/plain", b"stale control token; reload the page"); + } + control.set_running(running); + redirect(stream, "/mining/overview") +} + +/// Apply the tuning settings form: persist the validated rows and, when the +/// batch includes a tuning mode, switch the live runtime target to match. +fn settings_submit( + stream: &mut TcpStream, + status: &MiningStatus, + control: &Control, + request: &Request, +) -> io::Result<()> { + if !csrf_ok(control, request) { + return respond(stream, 403, "text/plain", b"stale control token; reload the page"); + } + let section = form_field(&request.body, "__section").unwrap_or_else(|| "settings".into()); + let tab = form_field(&request.body, "__tab").unwrap_or_else(|| "tuning".into()); + let mut dash = crate::dashboard::Dashboard::load(settings_path()); + match dash.submit(&request.body) { + Ok(()) => { + apply_tuning(&request.body, control); + redirect(stream, &format!("/{section}/{tab}")) + } + Err(failures) => { + let html = console::page(status, control, §ion, &tab, &failures).into_string(); + respond(stream, 422, "text/html; charset=utf-8", html.as_bytes()) + } + } +} + +/// If the form carries a tuning mode and its value, switch the live target. +fn apply_tuning(body: &str, control: &Control) { + let Some(mode) = form_field(body, "tuning.mode") else { + return; + }; + // The schema mode names map onto the control mode names. + let (mode, value_field) = match mode.as_str() { + "power" => ("power", "tuning.power_w"), + "hashrate" => ("hashrate", "tuning.hashrate_ths"), + "ambient" => ("ambient", "tuning.ambient_margin_c"), + "max-fan" => ("fan", "tuning.max_fan_pwm"), + _ => return, + }; + if let Some(value) = form_field(body, value_field).and_then(|v| v.trim().parse::().ok()) { + let _ = control.set_mode_value(mode, value); + } +} + +/// The live control document: operator intent plus what the snapshot confirms. +fn control_document(status: &MiningStatus, control: &Control) -> Value { + let hw = status.hardware_document(); + let mode = control::ControlMode::of_target(control.target()); + json!({ + "running": control.running(), + "mode": mode.as_str(), + "mode_label": mode.label(), + "target": control::target_label(control.target()), + "generation": control.generation(), + "stopped": hw.get("stopped").cloned().unwrap_or(Value::Null), + "frequency_mhz": hw.get("frequency_mhz").cloned().unwrap_or(Value::Null), + "available": hw.get("available").cloned().unwrap_or(Value::Bool(false)), + }) +} + +fn redirect(stream: &mut TcpStream, location: &str) -> io::Result<()> { + let header = format!( + "HTTP/1.1 303 See Other\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n" + ); + stream.write_all(header.as_bytes())?; + stream.flush() +} + fn html(stream: &mut TcpStream, title: &str, body: &str) -> io::Result<()> { let page = ui::page(path_for(title), title, body); respond(stream, 200, "text/html; charset=utf-8", page.as_bytes()) @@ -486,7 +600,7 @@ fn save_deck(deck: &str, doc: &Value) -> Result<(), String> { // --- page data --------------------------------------------------------------- -fn system_rows() -> Vec<(&'static str, String)> { +pub(crate) fn system_rows() -> Vec<(&'static str, String)> { vec![ ( "hostname", @@ -537,7 +651,7 @@ fn system_rows() -> Vec<(&'static str, String)> { ] } -fn network_rows() -> Vec<(&'static str, String)> { +pub(crate) fn network_rows() -> Vec<(&'static str, String)> { let mut rows: Vec<(&'static str, String)> = Vec::new(); if let Ok(text) = fs::read_to_string("/proc/net/route") { let default: Vec = text @@ -587,7 +701,7 @@ fn network_rows() -> Vec<(&'static str, String)> { rows } -fn update_rows() -> Vec<(&'static str, String)> { +pub(crate) fn update_rows() -> Vec<(&'static str, String)> { vec![ ( "image", @@ -608,7 +722,7 @@ fn update_rows() -> Vec<(&'static str, String)> { ] } -fn driver_rows(status: &MiningStatus) -> Vec<(&'static str, String)> { +pub(crate) fn driver_rows(status: &MiningStatus) -> Vec<(&'static str, String)> { let hw = status.hardware_document(); vec![ ( @@ -653,7 +767,7 @@ fn driver_rows(status: &MiningStatus) -> Vec<(&'static str, String)> { ] } -fn security_rows() -> Vec<(&'static str, String)> { +pub(crate) fn security_rows() -> Vec<(&'static str, String)> { let users = fs::read_to_string("/etc/passwd") .map(|text| { text.lines() @@ -690,7 +804,7 @@ fn security_rows() -> Vec<(&'static str, String)> { ] } -fn service_rows() -> Vec> { +pub(crate) fn service_rows() -> Vec> { let mut rows = Vec::new(); if let Ok(entries) = fs::read_dir("/etc/init.d") { for entry in entries.flatten() { @@ -710,7 +824,7 @@ fn service_rows() -> Vec> { rows } -fn monitor_rows(status: &MiningStatus) -> Vec<(&'static str, String)> { +pub(crate) fn monitor_rows(status: &MiningStatus) -> Vec<(&'static str, String)> { let hw = status.hardware_document(); let point = &hw["operating_point"]; vec![ @@ -776,7 +890,7 @@ var c=document.getElementById('cmd').value;fetch('/api/terminal?cmd='+encodeURIC .to_string() } -fn files_document(path: &str) -> Value { +pub(crate) fn files_document(path: &str) -> Value { let root = Path::new(path); let mut entries = Vec::new(); if let Ok(listing) = fs::read_dir(root) { @@ -811,6 +925,14 @@ fn tail_file(path: &Path, lines: usize) -> String { all[start..].join("\n") } +/// The last `lines` of the system log, as owned lines for the console log block. +pub(crate) fn recent_log_lines(lines: usize) -> Vec { + tail_file(Path::new(LOG_FILE), lines) + .lines() + .map(str::to_string) + .collect() +} + fn read_trim(path: &str) -> Option { fs::read_to_string(path) .ok() @@ -845,7 +967,7 @@ fn run_shell(command: &str) -> String { // --- access control ---------------------------------------------------------- -fn ui_token() -> Option { +pub(crate) fn ui_token() -> Option { if let Ok(token) = std::env::var("ALKANE_UI_TOKEN") { if !token.is_empty() { return Some(token); @@ -892,9 +1014,10 @@ mod tests { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); let status = Arc::new(MiningStatus::new()); + let control = Arc::new(Control::default()); let worker = std::thread::spawn(move || { let (stream, _) = listener.accept().unwrap(); - handle(stream, &status).unwrap(); + handle(stream, &status, &control).unwrap(); }); let mut stream = TcpStream::connect(addr).unwrap(); stream.write_all(request.as_bytes()).unwrap(); @@ -905,12 +1028,14 @@ mod tests { } #[test] - fn the_dashboard_serves_a_page_with_the_sidebar() { + fn the_root_serves_the_flare_ui_console_shell() { let reply = client("GET / HTTP/1.1\r\nHost: x\r\n\r\n"); assert!(reply.starts_with("HTTP/1.1 200 OK")); - assert!(reply.contains("Power Supply")); - assert!(reply.contains("Terminal")); assert!(reply.contains("text/html")); + // The flare-ui shell and its section nav, not the legacy page. + assert!(reply.contains("bf-sidebar"), "the flare-ui sidebar is missing"); + assert!(reply.contains("Mining"), "the Mining section link is missing"); + assert!(reply.contains("Settings"), "the Settings section link is missing"); } #[test] @@ -972,4 +1097,91 @@ mod tests { assert!(reply.contains("application/json")); } } + + /// Like `client`, but with a caller-owned control so the test can supply the + /// CSRF token and inspect the operator state after the request. + fn client_ctl(request: &str, control: Arc) -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let status = Arc::new(MiningStatus::new()); + let worker = std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + handle(stream, &status, &control).unwrap(); + }); + let mut stream = TcpStream::connect(addr).unwrap(); + stream.write_all(request.as_bytes()).unwrap(); + let mut reply = String::new(); + stream.read_to_string(&mut reply).unwrap(); + worker.join().unwrap(); + reply + } + + fn post(path: &str, body: &str) -> String { + format!( + "POST {path} HTTP/1.1\r\nHost: x\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ) + } + + #[test] + fn the_control_api_reports_operator_state() { + let reply = client("GET /api/control HTTP/1.1\r\nHost: x\r\n\r\n"); + assert!(reply.starts_with("HTTP/1.1 200 OK")); + let body = reply.split("\r\n\r\n").nth(1).unwrap_or(""); + let doc: Value = serde_json::from_str(body).unwrap_or_else(|_| json!({})); + assert_eq!(doc["running"], false); + assert_eq!(doc["mode"], "power"); + assert!(doc["target"].as_str().unwrap_or("").starts_with("power:")); + } + + #[test] + fn start_requires_the_csrf_token() { + let control = Arc::new(Control::default()); + let reply = client_ctl(&post("/control/start", "csrf=wrong"), Arc::clone(&control)); + assert!(reply.starts_with("HTTP/1.1 403"), "{reply}"); + assert!(!control.running(), "a stale token must not start mining"); + } + + #[test] + fn start_and_stop_with_a_good_token_switch_the_runtime() { + let control = Arc::new(Control::default()); + let token = control.csrf().to_string(); + let reply = client_ctl( + &post("/control/start", &format!("csrf={token}")), + Arc::clone(&control), + ); + assert!(reply.starts_with("HTTP/1.1 303"), "{reply}"); + assert!(reply.contains("Location: /mining/overview")); + assert!(control.running(), "a good token must start mining"); + + let reply = client_ctl( + &post("/control/stop", &format!("csrf={token}")), + Arc::clone(&control), + ); + assert!(reply.starts_with("HTTP/1.1 303"), "{reply}"); + assert!(!control.running(), "stop must clear the run flag"); + } + + #[test] + fn a_tuning_form_switches_the_live_target() { + use crate::tuning::TuningTarget; + let control = Arc::new(Control::default()); + let token = control.csrf().to_string(); + // A valid tuning batch: switch to an ambient target of 18 C. + let body = format!( + "csrf={token}&__section=settings&__tab=tuning&tuning.mode=ambient&tuning.ambient_margin_c=18" + ); + let reply = client_ctl(&post("/settings", &body), Arc::clone(&control)); + assert!( + reply.starts_with("HTTP/1.1 303") || reply.starts_with("HTTP/1.1 422"), + "{reply}" + ); + // On acceptance the live target must have become the ambient target. + if reply.starts_with("HTTP/1.1 303") { + assert_eq!( + control.target(), + TuningTarget::AmbientC { margin_mc: 18_000 } + ); + } + } }