diff --git a/src/app.rs b/src/app.rs index ce1f216..d6a748c 100644 --- a/src/app.rs +++ b/src/app.rs @@ -13,7 +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::bus::Bus; use crate::management::{bind_local, serve, HardwareSnapshot, MiningStatus}; use crate::profiles::{ProfileDb, ProfileError}; use crate::runtime::MinerRuntime; @@ -53,7 +53,7 @@ pub fn start( status: Arc, api: Option, web_bind: Option, - control: Arc, + bus: Arc, ) -> io::Result { let api_listener = match api { Some(address) => Some(bind_local(address)?), @@ -82,10 +82,9 @@ pub fn start( })); } if let Some(listener) = web_listener { - let snapshot = Arc::clone(&status); - let control = Arc::clone(&control); + let ctx = web::WebContext::new(Arc::clone(&bus)); handles.push(std::thread::spawn(move || { - if let Err(error) = web::serve_listener(listener, snapshot, control) { + if let Err(error) = web::serve_listener(listener, ctx) { eprintln!("web UI stopped: {error}"); } })); @@ -294,11 +293,15 @@ mod tests { fn both_servers_serve_the_published_snapshot() { let status = Arc::new(MiningStatus::new()); status.set_hardware(snapshot(&runtime(), "power:2400")); + let bus = crate::bus::Bus::new(); + let control = Arc::new(crate::control::Control::default()); + crate::service::register(&bus, Arc::clone(&status), Arc::clone(&control)); + crate::service::publish(&bus, &status, &control); let servers = start( Arc::clone(&status), Some("127.0.0.1:0".parse().unwrap()), Some("127.0.0.1:0".parse().unwrap()), - Arc::new(Control::default()), + bus, ) .expect("start"); let (api, web) = servers.addresses(); @@ -323,7 +326,7 @@ mod tests { #[test] fn servers_are_optional() { let status = Arc::new(MiningStatus::new()); - let servers = start(status, None, None, Arc::new(Control::default())).expect("start"); + let servers = start(status, None, None, crate::bus::Bus::new()).expect("start"); assert_eq!(servers.addresses(), (None, None)); } diff --git a/src/bus.rs b/src/bus.rs new file mode 100644 index 0000000..5f11f07 --- /dev/null +++ b/src/bus.rs @@ -0,0 +1,275 @@ +// SPDX-License-Identifier: MIT +//! The command/state bus: the single point of command for the miner. +//! +//! Modeled on wardenOS's bus (flare-edge `sprint`): one hub that the HTTP API, +//! the web UI, and any future remote/flare client all go through, so there is no +//! second way to change the machine. State is *retained* - a reader subscribes +//! to / reads a topic and gets the last published document - and commands are +//! *request/reply* to the service that owns the verb. +//! +//! wardenOS runs this as an MQTT-5 broker over a Unix socket with per-user ACLs. +//! Here the wire is in-process (std threads, no broker, no async): the facade +//! below - `publish_state` / `read_state` / `request` / `emit` - matches the +//! warden `Bus` surface, so callers never learn the transport and the broker can +//! be swapped in later without touching them. The registry in `registry.rs` is +//! the contract (topics and verbs), exactly as warden's `topics.json` is. +//! +//! Topic kinds, mirroring warden: +//! - `state` (retained): telemetry and status. Read = `read_state`. +//! - `evt` (not retained): events (log lines, faults). `emit` keeps a bounded +//! ring the UI and API can tail. +//! - `req`/`reply`: a command to an owning service. `register` + `request`. + +use serde_json::{json, Value}; +use std::collections::{BTreeMap, VecDeque}; +use std::sync::{Arc, Mutex, RwLock}; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// How many recent events the bus keeps for tailing. +const EVENT_RING: usize = 256; + +/// Why a request could not be served. Serializes to the warden-style +/// `{ "error": CODE, "message": ... }` envelope. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum BusError { + /// No service owns this verb. + NoHandler(String), + /// The request body was malformed for this verb. + BadRequest(String), + /// The owning service refused the request (out of range, wrong state). + Rejected(String), +} + +impl BusError { + pub fn code(&self) -> &'static str { + match self { + BusError::NoHandler(_) => "E_NO_HANDLER", + BusError::BadRequest(_) => "E_BAD_REQUEST", + BusError::Rejected(_) => "E_REJECTED", + } + } + + pub fn message(&self) -> &str { + match self { + BusError::NoHandler(m) | BusError::BadRequest(m) | BusError::Rejected(m) => m, + } + } + + /// The JSON error envelope a surface returns to its client. + pub fn envelope(&self) -> Value { + json!({ "error": self.code(), "message": self.message() }) + } +} + +impl std::fmt::Display for BusError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}: {}", self.code(), self.message()) + } +} + +impl std::error::Error for BusError {} + +/// A command handler: owns one verb, validates and applies the request, and +/// returns the result document (or a [`BusError`]). +pub type Handler = Box Result + Send + Sync>; + +/// One emitted event, kept in the ring for tailing. +#[derive(Clone, Debug)] +pub struct Event { + pub topic: String, + pub body: Value, + pub at_unix: u64, +} + +/// The in-process bus. +pub struct Bus { + state: RwLock>, + handlers: RwLock>, + events: Mutex>, +} + +impl Default for Bus { + fn default() -> Self { + Self::new_inner() + } +} + +impl Bus { + fn new_inner() -> Self { + Self { + state: RwLock::new(BTreeMap::new()), + handlers: RwLock::new(BTreeMap::new()), + events: Mutex::new(VecDeque::with_capacity(EVENT_RING)), + } + } + + /// A shared bus handle. The hub is cheap to clone (`Arc`). + pub fn new() -> Arc { + Arc::new(Self::new_inner()) + } + + // --- state (retained) ---------------------------------------------------- + + /// Publish a retained state document. A later reader gets this verbatim. + pub fn publish_state(&self, topic: &str, doc: Value) { + if let Ok(mut map) = self.state.write() { + map.insert(topic.to_string(), doc); + } + } + + /// Read the last retained document for a topic, if any. + pub fn read_state(&self, topic: &str) -> Option { + self.state.read().ok().and_then(|map| map.get(topic).cloned()) + } + + /// Read a retained document, or a fallback when nothing is published yet. + pub fn read_state_or(&self, topic: &str, fallback: Value) -> Value { + self.read_state(topic).unwrap_or(fallback) + } + + /// Drop a retained document (the warden "clear via empty will" semantics). + pub fn clear_state(&self, topic: &str) { + if let Ok(mut map) = self.state.write() { + map.remove(topic); + } + } + + /// Every state topic currently published, for introspection and parity tests. + pub fn state_topics(&self) -> Vec { + self.state + .read() + .map(|map| map.keys().cloned().collect()) + .unwrap_or_default() + } + + // --- commands (request/reply) -------------------------------------------- + + /// Register the service that owns `verb`. Re-registering replaces it. + pub fn register(&self, verb: &str, handler: F) + where + F: Fn(&Value) -> Result + Send + Sync + 'static, + { + if let Ok(mut map) = self.handlers.write() { + map.insert(verb.to_string(), Box::new(handler)); + } + } + + /// Dispatch a command to its owning service. This is the single write path: + /// the API and the UI both call this, so a verb cannot be driven two ways. + pub fn request(&self, verb: &str, body: &Value) -> Result { + let map = self + .handlers + .read() + .map_err(|_| BusError::Rejected("bus handler lock poisoned".into()))?; + let handler = map + .get(verb) + .ok_or_else(|| BusError::NoHandler(format!("no service owns {verb}")))?; + handler(body) + } + + /// True when a service owns the verb. + pub fn has_verb(&self, verb: &str) -> bool { + self.handlers.read().map(|m| m.contains_key(verb)).unwrap_or(false) + } + + /// Every registered verb, sorted, for introspection and parity tests. + pub fn verbs(&self) -> Vec { + self.handlers + .read() + .map(|map| map.keys().cloned().collect()) + .unwrap_or_default() + } + + // --- events (non-retained) ----------------------------------------------- + + /// Emit an event onto the ring (faults, log lines, notices). + pub fn emit(&self, topic: &str, body: Value) { + let at_unix = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + if let Ok(mut ring) = self.events.lock() { + if ring.len() == EVENT_RING { + ring.pop_front(); + } + ring.push_back(Event { + topic: topic.to_string(), + body, + at_unix, + }); + } + } + + /// The most recent `n` events, oldest first. + pub fn recent_events(&self, n: usize) -> Vec { + self.events + .lock() + .map(|ring| ring.iter().rev().take(n).rev().cloned().collect()) + .unwrap_or_default() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn retained_state_round_trips() { + let bus = Bus::new(); + assert_eq!(bus.read_state("miner/state/x"), None); + bus.publish_state("miner/state/x", json!({"v": 1})); + assert_eq!(bus.read_state("miner/state/x"), Some(json!({"v": 1}))); + bus.publish_state("miner/state/x", json!({"v": 2})); + assert_eq!(bus.read_state("miner/state/x").unwrap()["v"], 2); + bus.clear_state("miner/state/x"); + assert_eq!(bus.read_state("miner/state/x"), None); + } + + #[test] + fn a_request_reaches_its_owning_handler() { + let bus = Bus::new(); + bus.register("control/echo", |body| Ok(body.clone())); + let out = bus.request("control/echo", &json!({"hi": true})).unwrap(); + assert_eq!(out["hi"], true); + } + + #[test] + fn an_unowned_verb_is_a_no_handler_error() { + let bus = Bus::new(); + let err = bus.request("nope", &json!({})).unwrap_err(); + assert_eq!(err.code(), "E_NO_HANDLER"); + assert_eq!(err.envelope()["error"], "E_NO_HANDLER"); + } + + #[test] + fn a_handler_can_reject_and_the_code_is_preserved() { + let bus = Bus::new(); + bus.register("control/set", |_| Err(BusError::Rejected("out of range".into()))); + let err = bus.request("control/set", &json!({})).unwrap_err(); + assert_eq!(err.code(), "E_REJECTED"); + assert_eq!(err.message(), "out of range"); + } + + #[test] + fn registering_a_verb_replaces_the_prior_owner() { + let bus = Bus::new(); + bus.register("v", |_| Ok(json!(1))); + bus.register("v", |_| Ok(json!(2))); + assert_eq!(bus.request("v", &json!({})).unwrap(), json!(2)); + assert!(bus.has_verb("v")); + assert_eq!(bus.verbs(), vec!["v".to_string()]); + } + + #[test] + fn the_event_ring_is_bounded_and_ordered() { + let bus = Bus::new(); + for i in 0..(EVENT_RING + 10) { + bus.emit("evt/log", json!({ "i": i })); + } + let recent = bus.recent_events(5); + assert_eq!(recent.len(), 5); + // oldest-first, and the very last is the newest emitted. + assert_eq!(recent.last().unwrap().body["i"], (EVENT_RING + 10 - 1) as i64); + assert!(recent[0].body["i"].as_i64().unwrap() < recent[1].body["i"].as_i64().unwrap()); + } +} diff --git a/src/console.rs b/src/console.rs index d3a6ca5..d11717b 100644 --- a/src/console.rs +++ b/src/console.rs @@ -2,13 +2,11 @@ //! 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. +//! Content comes from the bus: telemetry is read from `state` topics and every +//! control is a form that POSTs to a bus verb through `web.rs`. Host facts (the +//! system/security/logs/files/terminal pages) are read directly. The module is +//! built entirely from `flare-ui` primitives so the on-box console is the +//! parameterised FLARE UI rather than a second hand-written one. use std::collections::BTreeMap; @@ -23,48 +21,44 @@ use flare_ui::render::{self, View}; use flare_ui::shell::{self, Active}; use wschema::model::Surface; -use crate::control::{Control, ControlMode}; +use crate::bus::Bus; use crate::dashboard::Dashboard; -use crate::management::MiningStatus; -use crate::web; +use crate::registry::topics; +use crate::{service, 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. +/// Render one navigation tab. `section`/`tab` are already validated by the +/// caller. `errors` carries messages from a rejected form (`""` = a general +/// banner, a path key = a field error). pub fn page( - status: &MiningStatus, - control: &Control, + bus: &Bus, + csrf: &str, section: &str, tab: &str, errors: &BTreeMap, ) -> Markup { - let dash = Dashboard::load(web::settings_path()); + let dash = Dashboard::load(service::settings_path()); let nav = dash.nav().unwrap_or_default(); let title = tab_title(&nav, section, tab); - let hw = status.hardware_document(); + let hw = bus.read_state_or(topics::HARDWARE, serde_json::json!({"available": false})); + let ctl = bus.read_state_or(topics::CONTROL, serde_json::json!({"running": false})); let body = match (section, tab) { - ("dashboard", "overview") | ("", "") => overview_card(&hw, control), + ("dashboard", "overview") | ("", "") => overview_card(&hw, &ctl), ("dashboard", "alerts") => alerts_card(&hw), - ("mining", "overview") => control_card(&hw, control), + ("mining", "overview") => control_card(&hw, &ctl, csrf), ("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", "system") => system_card(&hw), + ("settings", "tuning") => tuning_card(&dash, &ctl, csrf, errors), ("settings", "pools") => pools_card(), ("settings", "network") => network_card(), - ("settings", "security") => security_card(status), + ("settings", "security") => security_card(&hw), ("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, - ) + shell::page("Alkane OS", &Dashboard::assets(), &nav, Active { section, tab }, body) } fn tab_title(nav: &VisibleNav, section: &str, tab: &str) -> String { @@ -88,15 +82,12 @@ fn reading(key: &str, label: &str, value: Option, units: &str, digits: usiz } } -fn num(hw: &Value, pointer: &str) -> Option { - hw.pointer(pointer).and_then(Value::as_f64) +fn num(doc: &Value, pointer: &str) -> Option { + doc.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 text(doc: &Value, pointer: &str, fallback: &str) -> String { + doc.pointer(pointer).and_then(Value::as_str).unwrap_or(fallback).to_string() } fn available(hw: &Value) -> bool { @@ -104,18 +95,15 @@ fn available(hw: &Value) -> bool { } fn active_chain_count(hw: &Value) -> usize { - hw.get("active_chains") - .and_then(Value::as_array) - .map(|a| a.len()) - .unwrap_or(0) + 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) { +/// Run/stop badge: a fault stop wins over the operator switch. +fn run_state(hw: &Value, ctl: &Value) -> (Level, String) { if let Some(reason) = hw.get("stopped").and_then(Value::as_str) { return (Level::Err, format!("stopped: {reason}")); } - if control.running() { + if ctl.get("running").and_then(Value::as_bool).unwrap_or(false) { (Level::Ok, "mining".to_string()) } else { (Level::Warn, "idle (operator stopped)".to_string()) @@ -124,9 +112,9 @@ fn run_state(hw: &Value, control: &Control) -> (Level, String) { // --- cards ------------------------------------------------------------------- -fn overview_card(hw: &Value, control: &Control) -> Markup { +fn overview_card(hw: &Value, ctl: &Value) -> Markup { let freq = reading("frequency_mhz", "Chain frequency", num(hw, "/frequency_mhz"), "MHz", 0); - let (level, state) = run_state(hw, control); + let (level, state) = run_state(hw, ctl); let run = reading("run", "State", None, "", 0); components::card( "Overview", @@ -138,7 +126,7 @@ fn overview_card(hw: &Value, control: &Control) -> Markup { ("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()), + ("Mode".into(), text(ctl, "/mode_label", "-")), ("Target".into(), text(hw, "/target", "-")), ("Active chains".into(), active_chain_count(hw).to_string()), ])) @@ -164,24 +152,23 @@ fn alerts_card(hw: &Value) -> Markup { ) } -fn control_card(hw: &Value, control: &Control) -> Markup { - let (level, state) = run_state(hw, control); +fn control_card(hw: &Value, ctl: &Value, csrf: &str) -> Markup { + let (level, state) = run_state(hw, ctl); 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()), + ("Mode".into(), text(ctl, "/mode_label", "-")), ("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) } + @if let Some(b) = actions::action_button("/control/start", "Start mining", Tone::Primary, csrf, None) { (b) } + @if let Some(b) = actions::action_button("/control/stop", "Stop mining", Tone::Danger, 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.")) }, @@ -282,12 +269,12 @@ fn plate_from(rows: Vec<(&str, String)>) -> Markup { readings::plate(&items) } -fn system_card(status: &MiningStatus) -> Markup { +fn system_card(hw: &Value) -> 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)))) + (components::card("Drivers", plate_from(web::driver_rows(hw)))) } } @@ -295,11 +282,11 @@ fn network_card() -> Markup { components::card("Network", plate_from(web::network_rows())) } -fn security_card(status: &MiningStatus) -> Markup { +fn security_card(hw: &Value) -> 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)))) + (components::card("Monitor", plate_from(web::monitor_rows(hw)))) } } @@ -373,7 +360,12 @@ fetch('/api/terminal?cmd='+encodeURIComponent(c),{method:'POST'})\ /// 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 { +fn tuning_card( + dash: &Dashboard, + ctl: &Value, + csrf: &str, + errors: &BTreeMap, +) -> Markup { let Ok(eff) = dash.schema() else { return components::card("Tuning", readings::note("Schema did not load.")); }; @@ -384,10 +376,15 @@ fn tuning_card(dash: &Dashboard, control: &Control, errors: &BTreeMap, - /// 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 { @@ -135,15 +131,9 @@ impl Control { 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 { @@ -182,23 +172,6 @@ impl Default for Control { } } -/// 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::*; diff --git a/src/lib.rs b/src/lib.rs index a8bcec0..81a85cf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,8 +5,11 @@ pub mod app; pub mod bm1362; +pub mod bus; pub mod console; pub mod control; +pub mod registry; +pub mod service; pub mod bm1366; pub mod bm1370; pub mod bm13xx; diff --git a/src/main.rs b/src/main.rs index ed2c906..6c02768 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: MIT use alkane_os::app; +use alkane_os::bus::Bus; use alkane_os::control::Control; +use alkane_os::service; use alkane_os::detect::{ ChipModel as DetectedChip, DetectionBackend, EepromState, Envelope, ProbeBudget, ProbeOutcome, PsuCapability, SensorTopology, @@ -41,7 +43,10 @@ fn sim_mine(mut args: impl Iterator) -> Result<(), Box .transpose()?; let web = web_listen()?; let control = Arc::new(Control::default()); - let servers = app::start(Arc::clone(&status), api, web, control)?; + let bus = Bus::new(); + service::register(&bus, Arc::clone(&status), Arc::clone(&control)); + service::publish(&bus, &status, &control); + let servers = app::start(Arc::clone(&status), api, web, Arc::clone(&bus))?; let (api_address, web_address) = servers.addresses(); if let Some(address) = api_address { println!("management API on {address}"); @@ -213,7 +218,10 @@ fn boot_hal(mut args: impl Iterator) -> Result<(), Box .transpose()?; let web = web_listen()?; let control = Arc::new(Control::default()); - let servers = app::start(Arc::clone(&status), api, web, control)?; + let bus = Bus::new(); + service::register(&bus, Arc::clone(&status), Arc::clone(&control)); + service::publish(&bus, &status, &control); + let servers = app::start(Arc::clone(&status), api, web, Arc::clone(&bus))?; let config = app::BootConfig { profile_db_json, @@ -285,6 +293,7 @@ fn boot_hal(mut args: impl Iterator) -> Result<(), Box // Publish every period: a client watching the API must see the live operating point, // not the boot-time snapshot. status.set_hardware(app::snapshot(&runtime, &label)); + service::publish(&bus, &status, &control); if let Some(reason) = runtime.stop_reason() { println!("stopped: {reason:?}"); break; @@ -347,6 +356,8 @@ fn serve_sim() -> Result<(), Box> { 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 bus = Bus::new(); + service::register(&bus, Arc::clone(&status), Arc::clone(&control)); let config = app::BootConfig { profile_db_json: include_str!("../profiles.example.json").to_owned(), @@ -386,7 +397,7 @@ fn serve_sim() -> Result<(), Box> { .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 servers = app::start(Arc::clone(&status), api, web_listen()?, Arc::clone(&bus))?; let (api_address, web_address) = servers.addresses(); if let Some(address) = api_address { println!("management API on {address}"); @@ -430,6 +441,7 @@ fn serve_sim() -> Result<(), Box> { status.set_running(false); } status.set_hardware(app::snapshot(&runtime, &label)); + service::publish(&bus, &status, &control); std::thread::sleep(Duration::from_millis(250)); } } @@ -445,7 +457,10 @@ fn serve_only() -> Result<(), Box> { .transpose()?; let api = api.or(Some("0.0.0.0:4028".parse()?)); let control = Arc::new(Control::default()); - let servers = app::start(Arc::clone(&status), api, web_listen()?, control)?; + let bus = Bus::new(); + service::register(&bus, Arc::clone(&status), Arc::clone(&control)); + service::publish(&bus, &status, &control); + let servers = app::start(Arc::clone(&status), api, web_listen()?, Arc::clone(&bus))?; let (api_address, web_address) = servers.addresses(); if let Some(address) = api_address { println!("management API on {address}"); diff --git a/src/registry.rs b/src/registry.rs new file mode 100644 index 0000000..a20f7b5 --- /dev/null +++ b/src/registry.rs @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: MIT +//! The bus registry: the single source of truth for every topic and verb. +//! +//! wardenOS keeps this as `bus/registry/topics.json` and generates the broker +//! ACL, the constants and the retain rules from it with `busgen`. alkane-os is +//! std-only and in-process, so the registry lives here as typed constants plus a +//! machine-readable description ([`contract`]). A test asserts that every verb a +//! service registers and every state topic it publishes appears here, so the +//! contract cannot drift from the code - the property `busgen` gives warden. + +use serde_json::{json, Value}; + +/// Retained state topics (read with `Bus::read_state`). +pub mod topics { + /// Full hardware/runtime snapshot (profile, chip, PSU, chains, operating point). + pub const HARDWARE: &str = "miner/state/hardware"; + /// cgminer-style summary (elapsed, accepted, rejected, mining/stopped). + pub const SUMMARY: &str = "miner/state/summary"; + /// Operator control state (running, mode, target, generation). + pub const CONTROL: &str = "miner/state/control"; +} + +/// Event topics (emitted with `Bus::emit`, tailed from the ring). +pub mod events { + /// A human-facing notice (fault, state change) for the alerts view. + pub const NOTICE: &str = "miner/evt/notice"; +} + +/// Command verbs (dispatched with `Bus::request`). Each is owned by one service. +pub mod verbs { + /// Start hashing (operator). Body: `{}`. + pub const CONTROL_START: &str = "control/start"; + /// Stop hashing (operator). Body: `{}`. + pub const CONTROL_STOP: &str = "control/stop"; + /// Switch the live MPC target. Body: `{ "mode": "power|ambient|hashrate|fan", "value": }`. + pub const CONTROL_SET_TARGET: &str = "control/set_target"; + /// Apply a settings form (persist + drive the runtime). Body: `{ "form": "" }`. + pub const SETTINGS_APPLY: &str = "settings/apply"; + /// Load a dashboard deck. Body: `{ "deck": "" }` -> the deck document. + pub const DASHBOARD_LOAD: &str = "dashboard/load"; + /// Save a dashboard deck. Body: `{ "deck": "", "doc": }`. + pub const DASHBOARD_SAVE: &str = "dashboard/save"; + /// Reset a dashboard deck to the compiled default. Body: `{ "deck": "" }`. + pub const DASHBOARD_RESET: &str = "dashboard/reset"; +} + +/// The declared contract: every verb and state topic the miner service owns. +/// The parity test checks the live bus against this, so a new verb that is not +/// listed here, or a listed verb no service registers, fails CI. +pub fn contract() -> Value { + json!({ + "state": [topics::HARDWARE, topics::SUMMARY, topics::CONTROL], + "events": [events::NOTICE], + "verbs": [ + verbs::CONTROL_START, + verbs::CONTROL_STOP, + verbs::CONTROL_SET_TARGET, + verbs::SETTINGS_APPLY, + verbs::DASHBOARD_LOAD, + verbs::DASHBOARD_SAVE, + verbs::DASHBOARD_RESET, + ], + }) +} + +/// The verbs in the contract, as a sorted list. +pub fn contract_verbs() -> Vec { + let mut v: Vec = contract()["verbs"] + .as_array() + .map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()) + .unwrap_or_default(); + v.sort(); + v +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_contract_lists_distinct_verbs_and_topics() { + let verbs = contract_verbs(); + let mut unique = verbs.clone(); + unique.dedup(); + assert_eq!(verbs, unique, "duplicate verb in the contract"); + assert!(verbs.contains(&verbs::CONTROL_SET_TARGET.to_string())); + assert_eq!(contract()["state"].as_array().unwrap().len(), 3); + } +} diff --git a/src/service.rs b/src/service.rs new file mode 100644 index 0000000..8124508 --- /dev/null +++ b/src/service.rs @@ -0,0 +1,285 @@ +// SPDX-License-Identifier: MIT +//! The miner service: the one owner of the control verbs, the settings/dashboard +//! verbs, and the published state topics. +//! +//! Every surface - the HTTP API, the web console, a future remote/flare client - +//! reaches the machine only by a `Bus::request` to a verb registered here, or by +//! reading a state topic published here. There is no second write path, which is +//! the wardenOS property: one dispatch shared by all surfaces. + +use serde_json::{json, Value}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use crate::bus::{Bus, BusError}; +use crate::control::{self, Control, ControlMode}; +use crate::management::MiningStatus; +use crate::registry::{topics, verbs}; +use crate::ui; + +const DECK_DIR: &str = "/var/lib/alkane/decks"; + +/// Where the dashboard keeps operator settings (the schema rows). +pub(crate) fn settings_path() -> PathBuf { + let etc = Path::new("/etc/alkane/settings.json"); + if etc.exists() || Path::new("/etc/alkane").is_dir() { + return etc.to_path_buf(); + } + // A read-only root or a test run: keep the file beside the binary. + std::env::temp_dir().join("alkane-settings.json") +} + +fn deck_path(deck: &str) -> PathBuf { + let safe: String = deck + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_') + .collect(); + Path::new(DECK_DIR).join(format!("{safe}.json")) +} + +pub(crate) fn load_deck(deck: &str) -> Value { + fs::read_to_string(deck_path(deck)) + .ok() + .and_then(|text| ui::validate_deck(&text).ok()) + .unwrap_or_else(|| ui::default_deck(deck)) +} + +fn save_deck(deck: &str, doc: &Value) -> Result<(), String> { + let path = deck_path(deck); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|e| format!("cannot create {}: {e}", parent.display()))?; + } + let text = serde_json::to_string_pretty(doc).map_err(|e| e.to_string())?; + fs::write(&path, text).map_err(|e| format!("cannot write {}: {e}", path.display())) +} + +/// Read one 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)) + }) +} + +fn percent_decode(text: &str) -> String { + let bytes = text.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'+' => { + out.push(b' '); + i += 1; + } + b'%' if i + 2 < bytes.len() => { + let hi = (bytes[i + 1] as char).to_digit(16); + let lo = (bytes[i + 2] as char).to_digit(16); + match (hi, lo) { + (Some(hi), Some(lo)) => { + out.push((hi * 16 + lo) as u8); + i += 3; + } + _ => { + out.push(bytes[i]); + i += 1; + } + } + } + b => { + out.push(b); + i += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + +/// Translate a settings form's tuning fields into the live control target. +fn apply_tuning(body: &str, control: &Control) { + let Some(mode) = form_field(body, "tuning.mode") else { + return; + }; + 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 owner of the control state: it mutates [`Control`] and, like a wardenOS +/// service, republishes the affected state the instant a command applies, so a +/// reader never sees a command lag behind the periodic telemetry publish. The +/// bus is held `Weak` to avoid an `Arc` cycle (the bus owns the handlers). +struct MinerService { + status: Arc, + control: Arc, + bus: std::sync::Weak, +} + +impl MinerService { + fn republish_control(&self) { + if let Some(bus) = self.bus.upgrade() { + bus.publish_state(topics::CONTROL, control_document(&self.status, &self.control)); + } + } +} + +/// Register every miner verb on the bus. Called once at start-up. +pub fn register(bus: &Arc, status: Arc, control: Arc) { + let svc = Arc::new(MinerService { + status, + control, + bus: Arc::downgrade(bus), + }); + { + let s = Arc::clone(&svc); + bus.register(verbs::CONTROL_START, move |_| { + s.control.set_running(true); + s.republish_control(); + Ok(json!({ "running": true })) + }); + } + { + let s = Arc::clone(&svc); + bus.register(verbs::CONTROL_STOP, move |_| { + s.control.set_running(false); + s.republish_control(); + Ok(json!({ "running": false })) + }); + } + { + let s = Arc::clone(&svc); + bus.register(verbs::CONTROL_SET_TARGET, move |body| { + let mode = body + .get("mode") + .and_then(Value::as_str) + .ok_or_else(|| BusError::BadRequest("mode is required".into()))?; + let value = body + .get("value") + .and_then(Value::as_f64) + .ok_or_else(|| BusError::BadRequest("value is required".into()))? + as f32; + s.control.set_mode_value(mode, value).map_err(BusError::Rejected)?; + s.republish_control(); + Ok(json!({ + "target": control::target_label(s.control.target()), + "mode": ControlMode::of_target(s.control.target()).as_str(), + })) + }); + } + { + // A settings form: persist the validated rows, then drive the runtime + // from the tuning fields. Body carries the raw urlencoded form. + let s = Arc::clone(&svc); + bus.register(verbs::SETTINGS_APPLY, move |body| { + let form = body + .get("form") + .and_then(Value::as_str) + .ok_or_else(|| BusError::BadRequest("form is required".into()))?; + let mut dash = crate::dashboard::Dashboard::load(settings_path()); + dash.submit(form).map_err(|failures| { + let mut msg = String::new(); + for (k, why) in failures { + msg.push_str(&format!("{k}: {why}; ")); + } + BusError::Rejected(msg.trim_end().to_string()) + })?; + apply_tuning(form, &s.control); + s.republish_control(); + Ok(json!({ "applied": true })) + }); + } + bus.register(verbs::DASHBOARD_LOAD, |body| { + let deck = body.get("deck").and_then(Value::as_str).unwrap_or("dashboard"); + Ok(load_deck(deck)) + }); + bus.register(verbs::DASHBOARD_SAVE, |body| { + let deck = body.get("deck").and_then(Value::as_str).unwrap_or("dashboard"); + let doc = body + .get("doc") + .ok_or_else(|| BusError::BadRequest("doc is required".into()))?; + let validated = ui::validate_deck(&doc.to_string()).map_err(BusError::Rejected)?; + save_deck(deck, &validated).map_err(BusError::Rejected)?; + Ok(validated) + }); + bus.register(verbs::DASHBOARD_RESET, |body| { + let deck = body.get("deck").and_then(Value::as_str).unwrap_or("dashboard"); + let doc = ui::default_deck(deck); + save_deck(deck, &doc).map_err(BusError::Rejected)?; + Ok(doc) + }); +} + +/// Publish the current miner state onto the bus. Called each control period and +/// once at start-up. These documents are exactly what the API and UI read back. +pub fn publish(bus: &Bus, status: &MiningStatus, control: &Control) { + bus.publish_state(topics::HARDWARE, status.hardware_document()); + bus.publish_state(topics::SUMMARY, status.summary_document()); + bus.publish_state(topics::CONTROL, control_document(status, control)); +} + +/// The operator control document (also the `/api/control` body). +pub fn control_document(status: &MiningStatus, control: &Control) -> Value { + let hw = status.hardware_document(); + let mode = 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)), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::registry; + + #[test] + fn registered_verbs_match_the_contract() { + let bus = Bus::new(); + register(&bus, Arc::new(MiningStatus::new()), Arc::new(Control::default())); + let mut registered = bus.verbs(); + registered.sort(); + // Every registered verb is declared in the contract (nothing undocumented), + // and every contract verb is actually registered (nothing missing). + assert_eq!(registered, registry::contract_verbs()); + } + + #[test] + fn control_verbs_drive_the_shared_control() { + let bus = Bus::new(); + let control = Arc::new(Control::default()); + register(&bus, Arc::new(MiningStatus::new()), Arc::clone(&control)); + bus.request(verbs::CONTROL_START, &json!({})).unwrap(); + assert!(control.running()); + bus.request(verbs::CONTROL_STOP, &json!({})).unwrap(); + assert!(!control.running()); + bus.request(verbs::CONTROL_SET_TARGET, &json!({"mode": "ambient", "value": 18.0})) + .unwrap(); + assert_eq!( + control.target(), + crate::tuning::TuningTarget::AmbientC { margin_mc: 18_000 } + ); + } + + #[test] + fn set_target_rejects_a_bad_mode() { + let bus = Bus::new(); + register(&bus, Arc::new(MiningStatus::new()), Arc::new(Control::default())); + let err = bus + .request(verbs::CONTROL_SET_TARGET, &json!({"mode": "bogus", "value": 1.0})) + .unwrap_err(); + assert_eq!(err.code(), "E_REJECTED"); + } +} diff --git a/src/web.rs b/src/web.rs index 2dff954..90064cc 100644 --- a/src/web.rs +++ b/src/web.rs @@ -1,24 +1,28 @@ // SPDX-License-Identifier: MIT -//! On-box web UI and its API. +//! On-box web console and HTTP API: a thin HTTP translator over the bus. //! -//! The page is a convenience; `/api/...` stays the interface of record, so every -//! value the UI shows is also available as JSON and nothing is reachable only -//! through the browser. +//! Every value the console shows is a bus `state` topic read, and every change +//! it makes is a bus `request` to a verb the miner service owns. There is no +//! second command path: `/api/...` and the browser forms funnel through the same +//! bus the way wardenOS's web console and machine API share one dispatch. The +//! JSON API stays the interface of record - nothing is reachable only through +//! the browser. //! -//! No framework and no dependency: the request parser is bounded, only the -//! methods each route needs are accepted, and every response closes the -//! connection. Files and Terminal are gated on a token so a shared network -//! cannot silently use them. +//! No framework and no async: the request parser is bounded, only the methods +//! each route needs are accepted, every response closes the connection, and the +//! Files and Terminal endpoints are gated on a token so a shared network cannot +//! silently use them. Browser forms that change the machine carry a per-process +//! CSRF token checked here, at the HTTP edge. +use crate::bus::Bus; use crate::console; -use crate::control::{self, Control}; -use crate::management::MiningStatus; -use crate::ui; +use crate::registry::{topics, verbs}; use serde_json::{json, Value}; +use std::collections::BTreeMap; use std::fs; use std::io::{self, Read, Write}; use std::net::{SocketAddr, TcpListener, TcpStream}; -use std::path::{Path, PathBuf}; +use std::path::Path; use std::process::Command; use std::sync::Arc; use std::time::Duration; @@ -26,28 +30,55 @@ use std::time::Duration; const MAX_HEAD: usize = 8192; const MAX_BODY: usize = 64 * 1024; const CLIENT_TIMEOUT: Duration = Duration::from_millis(2000); -const DECK_DIR: &str = "/var/lib/alkane/decks"; const TOKEN_FILE: &str = "/var/lib/alkane/ui-token"; const LOG_FILE: &str = "/var/log/messages"; +/// What the HTTP edge needs: the bus (its only way to touch the machine) and the +/// per-process CSRF token for browser forms. +pub struct WebContext { + pub bus: Arc, + pub csrf: String, +} + +impl WebContext { + pub fn new(bus: Arc) -> Arc { + Arc::new(Self { + bus, + csrf: fresh_csrf(), + }) + } +} + +/// 128 bits of hex from the OS CSPRNG, or a fixed dev token if it cannot be read. +/// Not a password (SSH guards the box); it stops a foreign page from POSTing a +/// change through the operator's browser on a shared network. +pub fn fresh_csrf() -> String { + if let Ok(mut file) = 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() +} + /// Bind and serve until the listener fails. -pub fn serve(bind: SocketAddr, status: Arc, control: Arc) -> io::Result<()> { +pub fn serve(bind: SocketAddr, ctx: Arc) -> io::Result<()> { let listener = TcpListener::bind(bind)?; - serve_listener(listener, status, control) + serve_listener(listener, ctx) } /// Serve on an already-bound listener. -pub fn serve_listener( - listener: TcpListener, - status: Arc, - control: Arc, -) -> io::Result<()> { +pub fn serve_listener(listener: TcpListener, ctx: Arc) -> io::Result<()> { for stream in listener.incoming() { let Ok(stream) = stream else { continue }; - let status = Arc::clone(&status); - let control = Arc::clone(&control); + let ctx = Arc::clone(&ctx); std::thread::spawn(move || { - let _ = handle(stream, &status, &control); + let _ = handle(stream, &ctx); }); } Ok(()) @@ -110,7 +141,7 @@ fn percent_decode(text: &str) -> String { } /// Handle one HTTP request. -pub fn handle(mut stream: TcpStream, status: &MiningStatus, control: &Control) -> io::Result<()> { +pub fn handle(mut stream: TcpStream, ctx: &WebContext) -> io::Result<()> { stream.set_read_timeout(Some(CLIENT_TIMEOUT))?; stream.set_write_timeout(Some(CLIENT_TIMEOUT))?; let mut raw = Vec::new(); @@ -166,155 +197,52 @@ pub fn handle(mut stream: TcpStream, status: &MiningStatus, control: &Control) - query, body: String::from_utf8_lossy(&body).into_owned(), }; - route(&mut stream, status, control, &request) + route(&mut stream, ctx, &request) } -fn route( - stream: &mut TcpStream, - status: &MiningStatus, - control: &Control, - request: &Request, -) -> io::Result<()> { - if dashboard_route(stream, status, control, request)? { +fn route(stream: &mut TcpStream, ctx: &WebContext, request: &Request) -> io::Result<()> { + if dashboard_route(stream, ctx, request)? { return Ok(()); } + let bus = &ctx.bus; 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( + ("GET", "/api/hardware") => { + json_response(stream, &bus.read_state_or(topics::HARDWARE, json!({"available": false}))) + } + ("GET", "/api/summary") => { + json_response(stream, &bus.read_state_or(topics::SUMMARY, json!({}))) + } + ("GET", "/api/control") => json_response( stream, - "Mining overview", - &ui::dashboard_page("overview", true), + &bus.read_state_or(topics::CONTROL, json!({"running": false, "available": false})), ), - ("GET", "/mining/hashboards") => { - let hw = status.hardware_document(); - let rows: Vec> = hw["chains"] - .as_array() - .map(|chains| { - chains - .iter() - .map(|chain| { - vec![ - chain["index"].to_string(), - chain["chip"].as_str().unwrap_or("-").to_string(), - chain["chips_found"].to_string(), - chain["eeprom"].to_string(), - chain["response_per_mille"].to_string(), - ] - }) - .collect() - }) - .unwrap_or_default(); - html( - stream, - "Hashboards", - &ui::table_page( - &["#", "chip", "chips", "eeprom", "response per mille"], - &rows, - ), - ) + ("GET", "/api/dashboard") => { + let deck = request.param_or("deck", "dashboard"); + match bus.request(verbs::DASHBOARD_LOAD, &json!({"deck": deck})) { + Ok(doc) => json_response(stream, &doc), + Err(error) => json_response(stream, &error.envelope()), + } } - ("GET", "/mining/power") => { - let hw = status.hardware_document(); - let point = &hw["operating_point"]; - html( - stream, - "Power supply", - &ui::kv_page(&[ - ( - "supply", - hw["psu"].as_str().unwrap_or("not identified").to_string(), - ), - ( - "voltage range (mV)", - format!( - "{} - {}", - hw["envelope"]["v_min_mv"], hw["envelope"]["v_max_mv"] - ), - ), - ( - "frequency range (MHz)", - format!( - "{} - {}", - hw["envelope"]["f_min_mhz"], hw["envelope"]["f_max_mhz"] - ), - ), - ( - "running at", - format!( - "{} mV / {} MHz", - point["voltage_mv"], point["frequency_mhz"] - ), - ), - ("target", hw["target"].as_str().unwrap_or("-").to_string()), - ]), - ) + ("PUT", "/api/dashboard") => { + let deck = request.param_or("deck", "dashboard"); + let result = if request.param("reset").is_some() { + bus.request(verbs::DASHBOARD_RESET, &json!({"deck": deck})) + } else { + match serde_json::from_str::(&request.body) { + Ok(doc) => bus.request(verbs::DASHBOARD_SAVE, &json!({"deck": deck, "doc": doc})), + Err(error) => { + return respond(stream, 400, "text/plain", error.to_string().as_bytes()) + } + } + }; + match result { + Ok(doc) => json_response(stream, &doc), + Err(error) => { + let code = if error.code() == "E_REJECTED" { 400 } else { 500 }; + respond(stream, code, "application/json", error.envelope().to_string().as_bytes()) + } + } } - ("GET", "/mining/fans") => { - let hw = status.hardware_document(); - let rows: Vec> = hw["fan_zones"] - .as_array() - .map(|zones| { - zones - .iter() - .map(|zone| vec![zone["fan"].to_string(), zone["zones"].to_string()]) - .collect() - }) - .unwrap_or_default(); - html( - stream, - "Fans", - &ui::table_page(&["fan", "zones it cools"], &rows), - ) - } - ("GET", "/settings/system") => html( - stream, - "System", - &ui::sections_page(&[ - ("Identity", ui::kv_page(&system_rows())), - ("Network", ui::kv_page(&network_rows())), - ("Updates", ui::kv_page(&update_rows())), - ]), - ), - ("GET", "/settings/drivers") => html( - stream, - "Drivers", - &ui::sections_page(&[ - ("Chains", ui::kv_page(&driver_rows(status))), - ("Firmware", ui::kv_page(&update_rows())), - ]), - ), - ("GET", "/settings/security") => html(stream, "Security", &ui::kv_page(&security_rows())), - ("GET", "/settings/services") => html( - stream, - "Services", - &ui::table_page(&["service", "running"], &service_rows()), - ), - ("GET", "/settings/monitor") => { - html(stream, "Monitor", &ui::kv_page(&monitor_rows(status))) - } - ("GET", "/settings/logs") => { - let lines = request - .param_or("lines", "200") - .parse::() - .unwrap_or(200) - .min(2000); - let tail = tail_file(Path::new(LOG_FILE), lines); - html( - stream, - "Logs", - &format!( - "

{}

{}
", - ui::escape(LOG_FILE), - ui::escape(&tail) - ), - ) - } - ("GET", "/settings/files") => { - let path = request.param_or("path", "/"); - html(stream, "Files", &files_page(&path)) - } - ("GET", "/settings/terminal") => html(stream, "Terminal", &terminal_page()), ("POST", "/api/terminal") => { if !authorised(request) { return respond(stream, 403, "text/plain", b"terminal requires a token"); @@ -323,27 +251,6 @@ fn route( let output = run_shell(&command); respond(stream, 200, "text/plain; charset=utf-8", output.as_bytes()) } - ("GET", "/api/hardware") => json_response(stream, &status.hardware_document()), - ("GET", "/api/summary") => json_response(stream, &status.summary_document()), - ("GET", "/api/dashboard") => { - let deck = request.param_or("deck", "dashboard"); - json_response(stream, &load_deck(&deck)) - } - ("PUT", "/api/dashboard") => { - let deck = request.param_or("deck", "dashboard"); - if request.param("reset").is_some() { - let doc = ui::default_deck(&deck); - let _ = save_deck(&deck, &doc); - return json_response(stream, &doc); - } - match ui::validate_deck(&request.body) { - Ok(doc) => match save_deck(&deck, &doc) { - Ok(()) => json_response(stream, &doc), - Err(error) => respond(stream, 500, "text/plain", error.as_bytes()), - }, - Err(reason) => respond(stream, 400, "text/plain", reason.as_bytes()), - } - } ("GET", "/api/logs") => { let lines = request .param_or("lines", "200") @@ -371,27 +278,10 @@ fn route( } } - -/// Where the dashboard keeps operator settings. -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(); - } - // A read-only root or a test run: keep the file beside the binary. - std::env::temp_dir().join("alkane-settings.json") -} - -/// Serve the schema-driven UI: assets, pages and the settings form. -/// -/// 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, - status: &MiningStatus, - control: &Control, - request: &Request, -) -> io::Result { +/// Serve the schema-driven console (nav GET) and the browser command forms +/// (`/settings`, `/control/*`). Returns `false` for anything else so the API +/// routes keep working. +fn dashboard_route(stream: &mut TcpStream, ctx: &WebContext, 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() { @@ -403,26 +293,25 @@ fn dashboard_route( } 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), + "/settings" => settings_submit(stream, ctx, request).map(|_| true), + "/control/start" => control_switch(stream, ctx, request, true).map(|_| true), + "/control/stop" => control_switch(stream, ctx, request, false).map(|_| true), _ => Ok(false), }; } if request.method != "GET" { return Ok(false); } - let empty = std::collections::BTreeMap::new(); + let empty = 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); + return render_page(stream, ctx, "dashboard", "overview", &empty); } let mut parts = path.trim_start_matches('/').split('/'); let section = match parts.next() { Some(section) if !section.is_empty() => section, _ => return Ok(false), }; - let dash = crate::dashboard::Dashboard::load(settings_path()); + let dash = crate::dashboard::Dashboard::load(crate::service::settings_path()); let nav = match dash.nav() { Ok(nav) => nav, Err(_) => return Ok(false), @@ -438,7 +327,17 @@ fn dashboard_route( if !known.tabs.iter().any(|t| t.slug == tab) { return Ok(false); } - let html = console::page(status, control, section, &tab, &empty).into_string(); + render_page(stream, ctx, section, &tab, &empty) +} + +fn render_page( + stream: &mut TcpStream, + ctx: &WebContext, + section: &str, + tab: &str, + errors: &BTreeMap, +) -> io::Result { + let html = console::page(&ctx.bus, &ctx.csrf, section, tab, errors).into_string(); respond(stream, 200, "text/html; charset=utf-8", html.as_bytes()).map(|_| true) } @@ -450,86 +349,46 @@ fn form_field(body: &str, key: &str) -> Option { }) } -/// 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()) +/// Every mutating browser form must echo the per-process token. +fn csrf_ok(ctx: &WebContext, request: &Request) -> bool { + form_field(&request.body, "csrf").as_deref() == Some(ctx.csrf.as_str()) } -/// Switch the operator run state (Start/Stop), then send the browser back to the -/// control page. +/// Start/Stop: a bus command, then back to the control page. fn control_switch( stream: &mut TcpStream, - control: &Control, + ctx: &WebContext, request: &Request, running: bool, ) -> io::Result<()> { - if !csrf_ok(control, request) { + if !csrf_ok(ctx, request) { return respond(stream, 403, "text/plain", b"stale control token; reload the page"); } - control.set_running(running); - redirect(stream, "/mining/overview") + let verb = if running { verbs::CONTROL_START } else { verbs::CONTROL_STOP }; + match ctx.bus.request(verb, &json!({})) { + Ok(_) => redirect(stream, "/mining/overview"), + Err(error) => respond(stream, 500, "text/plain", error.to_string().as_bytes()), + } } -/// 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) { +/// Apply a settings form through the bus: persist the rows and drive the runtime. +fn settings_submit(stream: &mut TcpStream, ctx: &WebContext, request: &Request) -> io::Result<()> { + if !csrf_ok(ctx, 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(); + match ctx.bus.request(verbs::SETTINGS_APPLY, &json!({"form": request.body})) { + Ok(_) => redirect(stream, &format!("/{section}/{tab}")), + Err(error) => { + let mut errors = BTreeMap::new(); + errors.insert(String::new(), error.message().to_string()); + let html = console::page(&ctx.bus, &ctx.csrf, §ion, &tab, &errors).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" @@ -538,67 +397,11 @@ fn redirect(stream: &mut TcpStream, location: &str) -> io::Result<()> { 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()) -} - -fn path_for(title: &str) -> &'static str { - match title { - "Dashboard" => "/", - "Mining overview" => "/mining", - "Hashboards" => "/mining/hashboards", - "Power supply" => "/mining/power", - "Fans" => "/mining/fans", - "System" => "/settings/system", - "Drivers" => "/settings/drivers", - "Security" => "/settings/security", - "Services" => "/settings/services", - "Monitor" => "/settings/monitor", - "Logs" => "/settings/logs", - "Files" => "/settings/files", - "Terminal" => "/settings/terminal", - _ => "/", - } -} - fn json_response(stream: &mut TcpStream, value: &Value) -> io::Result<()> { - respond( - stream, - 200, - "application/json", - value.to_string().as_bytes(), - ) + respond(stream, 200, "application/json", value.to_string().as_bytes()) } -// --- dashboard storage ------------------------------------------------------- - -fn deck_path(deck: &str) -> PathBuf { - let safe: String = deck - .chars() - .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_') - .collect(); - Path::new(DECK_DIR).join(format!("{safe}.json")) -} - -fn load_deck(deck: &str) -> Value { - fs::read_to_string(deck_path(deck)) - .ok() - .and_then(|text| ui::validate_deck(&text).ok()) - .unwrap_or_else(|| ui::default_deck(deck)) -} - -fn save_deck(deck: &str, doc: &Value) -> Result<(), String> { - let path = deck_path(deck); - if let Some(parent) = path.parent() { - fs::create_dir_all(parent) - .map_err(|e| format!("cannot create {}: {e}", parent.display()))?; - } - let text = serde_json::to_string_pretty(doc).map_err(|e| e.to_string())?; - fs::write(&path, text).map_err(|e| format!("cannot write {}: {e}", path.display())) -} - -// --- page data --------------------------------------------------------------- +// --- page data (host facts the console renders) ------------------------------ pub(crate) fn system_rows() -> Vec<(&'static str, String)> { vec![ @@ -722,8 +525,8 @@ pub(crate) fn update_rows() -> Vec<(&'static str, String)> { ] } -pub(crate) fn driver_rows(status: &MiningStatus) -> Vec<(&'static str, String)> { - let hw = status.hardware_document(); +/// Driver rows from the published hardware document. +pub(crate) fn driver_rows(hw: &Value) -> Vec<(&'static str, String)> { vec![ ( "chain driver", @@ -731,10 +534,7 @@ pub(crate) fn driver_rows(status: &MiningStatus) -> Vec<(&'static str, String)> ), ( "board profile", - hw["profile"] - .as_str() - .unwrap_or("not identified") - .to_string(), + hw["profile"].as_str().unwrap_or("not identified").to_string(), ), ( "power supply", @@ -742,19 +542,11 @@ pub(crate) fn driver_rows(status: &MiningStatus) -> Vec<(&'static str, String)> ), ( "chains detected", - hw["chains"] - .as_array() - .map(|c| c.len()) - .unwrap_or(0) - .to_string(), + hw["chains"].as_array().map(|c| c.len()).unwrap_or(0).to_string(), ), ( "chains active", - hw["active_chains"] - .as_array() - .map(|c| c.len()) - .unwrap_or(0) - .to_string(), + hw["active_chains"].as_array().map(|c| c.len()).unwrap_or(0).to_string(), ), ( "stopped", @@ -777,12 +569,7 @@ pub(crate) fn security_rows() -> Vec<(&'static str, String)> { }) .unwrap_or_else(|_| "unreadable".into()); let keys = fs::read_to_string("/root/.ssh/authorized_keys") - .map(|text| { - text.lines() - .filter(|l| !l.trim().is_empty()) - .count() - .to_string() - }) + .map(|text| text.lines().filter(|l| !l.trim().is_empty()).count().to_string()) .unwrap_or_else(|_| "0".into()); let dropbear = if running("dropbear") { "running" @@ -824,8 +611,8 @@ pub(crate) fn service_rows() -> Vec> { rows } -pub(crate) fn monitor_rows(status: &MiningStatus) -> Vec<(&'static str, String)> { - let hw = status.hardware_document(); +/// Monitor rows from the published hardware document plus host load/memory. +pub(crate) fn monitor_rows(hw: &Value) -> Vec<(&'static str, String)> { let point = &hw["operating_point"]; vec![ ( @@ -855,41 +642,6 @@ pub(crate) fn monitor_rows(status: &MiningStatus) -> Vec<(&'static str, String)> ] } -fn files_page(path: &str) -> String { - let doc = files_document(path); - let mut rows = Vec::new(); - if let Some(entries) = doc["entries"].as_array() { - for entry in entries { - rows.push(vec![ - entry["name"].as_str().unwrap_or("-").to_string(), - entry["kind"].as_str().unwrap_or("-").to_string(), - entry["size"].to_string(), - ]); - } - } - format!( - "
read-only listing; individual text files are at /api/file?path=
{}", - ui::escape(path), - ui::table_page(&["name", "kind", "size"], &rows) - ) -} - -fn terminal_page() -> String { - if ui_token().is_none() { - return format!( - "

Terminal is disabled until a token exists at {}. Create one with \ - head -c 16 /dev/urandom | od -An -tx1 | tr -d ' \\n' > {}; chmod 600 {}.

", - TOKEN_FILE, TOKEN_FILE, TOKEN_FILE - ); - } - "
\ -commands run as root on this miner
ready
\ -" - .to_string() -} - pub(crate) fn files_document(path: &str) -> Value { let root = Path::new(path); let mut entries = Vec::new(); @@ -989,10 +741,12 @@ fn authorised(request: &Request) -> bool { fn respond(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) -> io::Result<()> { let reason = match code { 200 => "OK", + 303 => "See Other", 400 => "Bad Request", 403 => "Forbidden", 404 => "Not Found", 413 => "Payload Too Large", + 422 => "Unprocessable Entity", 431 => "Request Header Fields Too Large", 500 => "Internal Server Error", _ => "Error", @@ -1009,104 +763,37 @@ fn respond(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) - #[cfg(test)] mod tests { use super::*; + use crate::control::Control; + use crate::management::MiningStatus; + use crate::service; + + /// A context whose bus has the miner service registered and state published + /// once, with the test holding the `Control` so it can assert operator state. + fn context() -> (Arc, Arc) { + let bus = Bus::new(); + let control = Arc::new(Control::default()); + let status = Arc::new(MiningStatus::new()); + service::register(&bus, Arc::clone(&status), Arc::clone(&control)); + service::publish(&bus, &status, &control); + ( + Arc::new(WebContext { + bus, + csrf: "test-csrf".to_string(), + }), + control, + ) + } fn client(request: &str) -> String { + client_ctx(request, context().0) + } + + fn client_ctx(request: &str, ctx: 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 control = Arc::new(Control::default()); 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 - } - - #[test] - 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("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] - fn every_page_answers() { - for path in [ - "/mining", - "/mining/hashboards", - "/mining/power", - "/mining/fans", - "/settings/system", - "/settings/drivers", - "/settings/security", - "/settings/services", - "/settings/monitor", - "/settings/logs", - "/settings/files", - "/settings/terminal", - ] { - let reply = client(&format!("GET {path} HTTP/1.1\r\nHost: x\r\n\r\n")); - assert!(reply.starts_with("HTTP/1.1 200 OK"), "{path}: {reply}"); - } - } - - #[test] - fn the_dashboard_api_serves_the_default_template() { - let reply = client("GET /api/dashboard?deck=bogus HTTP/1.1\r\nHost: x\r\n\r\n"); - 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["version"], 1); - assert!(doc["blocks"] - .as_array() - .map(|b| !b.is_empty()) - .unwrap_or(false)); - } - - #[test] - fn the_dashboard_api_rejects_a_bad_document() { - let body = "not json"; - let reply = client(&format!( - "PUT /api/dashboard?deck=test HTTP/1.1\r\nHost: x\r\nContent-Length: {}\r\n\r\n{body}", - body.len() - )); - assert!(reply.starts_with("HTTP/1.1 400"), "{reply}"); - } - - #[test] - fn the_terminal_is_forbidden_without_a_token() { - std::env::remove_var("ALKANE_UI_TOKEN"); - let reply = - client("POST /api/terminal?cmd=id HTTP/1.1\r\nHost: x\r\nContent-Length: 0\r\n\r\n"); - assert!(reply.starts_with("HTTP/1.1 403"), "{reply}"); - } - - #[test] - fn the_api_still_serves_hardware_and_summary() { - for path in ["/api/hardware", "/api/summary"] { - let reply = client(&format!("GET {path} HTTP/1.1\r\nHost: x\r\n\r\n")); - assert!(reply.starts_with("HTTP/1.1 200 OK"), "{path}"); - 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(); + handle(stream, &ctx).unwrap(); }); let mut stream = TcpStream::connect(addr).unwrap(); stream.write_all(request.as_bytes()).unwrap(); @@ -1123,10 +810,47 @@ mod tests { ) } + #[test] + 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("text/html")); + 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] + fn every_nav_page_answers() { + for path in [ + "/mining", + "/mining/hashboards", + "/mining/power", + "/mining/fans", + "/settings/system", + "/settings/tuning", + "/settings/security", + "/settings/logs", + "/settings/files", + "/settings/terminal", + ] { + let reply = client(&format!("GET {path} HTTP/1.1\r\nHost: x\r\n\r\n")); + assert!(reply.starts_with("HTTP/1.1 200 OK"), "{path}: {reply}"); + } + } + + #[test] + fn the_api_serves_state_from_the_bus() { + for path in ["/api/hardware", "/api/summary", "/api/control"] { + let reply = client(&format!("GET {path} HTTP/1.1\r\nHost: x\r\n\r\n")); + assert!(reply.starts_with("HTTP/1.1 200 OK"), "{path}"); + assert!(reply.contains("application/json")); + } + } + #[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); @@ -1134,30 +858,48 @@ mod tests { assert!(doc["target"].as_str().unwrap_or("").starts_with("power:")); } + #[test] + fn the_dashboard_api_serves_the_default_template() { + let reply = client("GET /api/dashboard?deck=bogus HTTP/1.1\r\nHost: x\r\n\r\n"); + 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["version"], 1); + assert!(doc["blocks"].as_array().map(|b| !b.is_empty()).unwrap_or(false)); + } + + #[test] + fn the_dashboard_api_rejects_a_bad_document() { + let body = "not json"; + let reply = client(&format!( + "PUT /api/dashboard?deck=test HTTP/1.1\r\nHost: x\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + )); + assert!(reply.starts_with("HTTP/1.1 400"), "{reply}"); + } + + #[test] + fn the_terminal_is_forbidden_without_a_token() { + std::env::remove_var("ALKANE_UI_TOKEN"); + let reply = client("POST /api/terminal?cmd=id HTTP/1.1\r\nHost: x\r\nContent-Length: 0\r\n\r\n"); + assert!(reply.starts_with("HTTP/1.1 403"), "{reply}"); + } + #[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)); + let (ctx, control) = context(); + let reply = client_ctx(&post("/control/start", "csrf=wrong"), ctx); 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), - ); + let (ctx, control) = context(); + let reply = client_ctx(&post("/control/start", "csrf=test-csrf"), Arc::clone(&ctx)); 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), - ); + let reply = client_ctx(&post("/control/stop", "csrf=test-csrf"), ctx); assert!(reply.starts_with("HTTP/1.1 303"), "{reply}"); assert!(!control.running(), "stop must clear the run flag"); } @@ -1165,23 +907,15 @@ mod tests { #[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)); + let (ctx, control) = context(); + let body = "csrf=test-csrf&__section=settings&__tab=tuning&tuning.mode=ambient&tuning.ambient_margin_c=18"; + let reply = client_ctx(&post("/settings", body), ctx); 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 } - ); + assert_eq!(control.target(), TuningTarget::AmbientC { margin_mc: 18_000 }); } } }