From 2c6535f9486f442b3a83b1ed1d7dceaa747b7224 Mon Sep 17 00:00:00 2001 From: Noah <2+noah@noreply.gitea.bluefla.re> Date: Thu, 22 Oct 2026 10:43:39 -0600 Subject: [PATCH] Wire the API and UI through one start-up path Add an app layer that binds and starts the management API and the web UI, publishes the runtime snapshot, and exposes a bound-address result so callers can discover ephemeral ports. The binary now uses the same function the tests use, so the wiring CI exercises is the wiring that runs on a board, and it gained ALKANE_WEB_LISTEN alongside ALKANE_API_LISTEN. The snapshot is built from the live runtime: active chains, stop reason and the last applied frequency rather than the boot default. --- src/app.rs | 209 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + src/main.rs | 29 +++++--- 3 files changed, 230 insertions(+), 9 deletions(-) create mode 100644 src/app.rs diff --git a/src/app.rs b/src/app.rs new file mode 100644 index 0000000..c6974e1 --- /dev/null +++ b/src/app.rs @@ -0,0 +1,209 @@ +// SPDX-License-Identifier: MIT +//! Process wiring: start the API and UI servers and publish the hardware snapshot. +//! +//! The binary and the tests use the same function, so the wiring that CI exercises is the wiring +//! that runs on a board. Servers are bound before they are spawned, which lets a caller discover +//! ephemeral ports instead of guessing them. + +use crate::management::{bind_local, serve, HardwareSnapshot, MiningStatus}; +use crate::runtime::MinerRuntime; +use crate::web; +use std::io; +use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::sync::Arc; +use std::thread::JoinHandle; +use std::time::Duration; + +/// Bound servers and their worker threads. +pub struct Servers { + pub api: Option, + pub web: Option, + handles: Vec>, +} + +impl Servers { + /// Addresses actually bound, which matters when port 0 was requested. + pub fn addresses(&self) -> (Option, Option) { + (self.api, self.web) + } + + /// Wait for the workers. Only useful in tests; the binary runs until it is killed. + pub fn join(self) { + for handle in self.handles { + let _ = handle.join(); + } + } +} + +/// Bind and start the cgminer-style API and the web UI, each when an address is given. +pub fn start( + status: Arc, + api: Option, + web_bind: Option, +) -> io::Result { + let api_listener = match api { + Some(address) => Some(bind_local(address)?), + None => None, + }; + let api_address = api_listener + .as_ref() + .map(|listener| listener.local_addr()) + .transpose()?; + let web_listener = match web_bind { + Some(address) => Some(TcpListener::bind(address)?), + None => None, + }; + let web_address = web_listener + .as_ref() + .map(|listener| listener.local_addr()) + .transpose()?; + + let mut handles = Vec::new(); + if let Some(listener) = api_listener { + let snapshot = Arc::clone(&status); + handles.push(std::thread::spawn(move || { + if let Err(error) = serve(listener, snapshot) { + eprintln!("management API stopped: {error}"); + } + })); + } + if let Some(listener) = web_listener { + let snapshot = Arc::clone(&status); + handles.push(std::thread::spawn(move || { + if let Err(error) = web::serve_listener(listener, snapshot) { + eprintln!("web UI stopped: {error}"); + } + })); + } + Ok(Servers { + api: api_address, + web: web_address, + handles, + }) +} + +/// Build the API snapshot from the live runtime. +pub fn snapshot(runtime: &MinerRuntime, target: &str) -> HardwareSnapshot { + let plan = runtime.plan(); + HardwareSnapshot { + plan: plan.clone(), + active_chains: runtime.active_chains(), + stopped: runtime.stop_reason().map(|reason| match reason { + crate::fault::StopReason::Temperature => "temperature", + crate::fault::StopReason::NoChainsLeft => "no chains left", + }), + frequency_mhz: runtime.operating_point().frequency_mhz, + target: target.to_owned(), + } +} + +/// Read one HTTP response body from a bound server, for health checks and tests. +pub fn http_get(address: SocketAddr, path: &str) -> io::Result { + use std::io::{Read, Write}; + let mut stream = TcpStream::connect_timeout(&address, Duration::from_secs(2))?; + stream.set_read_timeout(Some(Duration::from_secs(2)))?; + stream.write_all(format!("GET {path} HTTP/1.1\r\nHost: miner\r\n\r\n").as_bytes())?; + let mut reply = String::new(); + stream.read_to_string(&mut reply)?; + Ok(reply) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::detect::{ + ChainReport, ChipModel, EepromState, Envelope, FanZone, HardwarePlan, OperatingPoint, + }; + use crate::fault::FaultPolicy; + use crate::tuning::{PidConfig, TuningTarget}; + use std::io::{Read, Write}; + + fn runtime() -> MinerRuntime { + MinerRuntime::new( + HardwarePlan { + profile: "s19jpro-bm1362-pic".into(), + chip: ChipModel::Bm1362, + chains: vec![ChainReport { + index: 0, + chip: ChipModel::Bm1362, + chips_found: 126, + eeprom: EepromState::Absent, + response_per_mille: Some(950), + }], + envelope: Envelope { + v_min_mv: 1100, + v_max_mv: 1500, + f_min_mhz: 300, + f_max_mhz: 700, + }, + operating_point: OperatingPoint { + voltage_mv: 1200, + frequency_mhz: 300, + confirmed: false, + }, + psu: "APW12".into(), + fan_zones: vec![FanZone { + fan: 0, + zones: vec![0], + }], + }, + FaultPolicy::default(), + TuningTarget::PowerW(2_400.0), + PidConfig::default(), + 95_000, + ) + } + + #[test] + fn both_servers_serve_the_published_snapshot() { + let status = Arc::new(MiningStatus::new()); + status.set_hardware(snapshot(&runtime(), "power:2400")); + let servers = start( + Arc::clone(&status), + Some("127.0.0.1:0".parse().unwrap()), + Some("127.0.0.1:0".parse().unwrap()), + ) + .expect("start"); + let (api, web) = servers.addresses(); + let api = api.expect("api address"); + let web = web.expect("web address"); + + let page = http_get(web, "/api/hardware").expect("web"); + assert!(page.contains("s19jpro-bm1362-pic")); + assert!(page.contains("power:2400")); + + let mut client = + TcpStream::connect_timeout(&api, Duration::from_secs(2)).expect("api connect"); + client + .set_read_timeout(Some(Duration::from_secs(3))) + .expect("timeout"); + client.write_all(b"summary").expect("api write"); + let mut summary = String::new(); + client.read_to_string(&mut summary).expect("api read"); + assert!(summary.contains("SUMMARY")); + } + + #[test] + fn servers_are_optional() { + let status = Arc::new(MiningStatus::new()); + let servers = start(status, None, None).expect("start"); + assert_eq!(servers.addresses(), (None, None)); + } + + #[test] + fn the_snapshot_reports_runtime_state_not_boot_defaults() { + let mut runtime = runtime(); + runtime.tick(&crate::runtime::Tick { + power_w: Some(1_000.0), + hashrate_ths: None, + hottest_mc: Some(60_000), + ambient_mc: None, + dt_s: 1.0, + }); + let snapshot = snapshot(&runtime, "power:2400"); + assert_eq!(snapshot.target, "power:2400"); + assert_eq!(snapshot.active_chains, vec![0]); + assert!(snapshot.frequency_mhz > 300); + assert!(snapshot.stopped.is_none()); + } +} diff --git a/src/lib.rs b/src/lib.rs index 447a6e1..5f9f677 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,6 +3,7 @@ //! An entry in the target matrix is a development obligation, not a claim that //! the pairing already mines. Hardware backends are supplied by SDK images. +pub mod app; pub mod bm1362; pub mod bm1366; pub mod bm1370; diff --git a/src/main.rs b/src/main.rs index ec6912a..4f757b3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: MIT +use alkane_os::app; use alkane_os::hal_wire::HalClient; -use alkane_os::management::{bind_local, serve, MiningStatus}; +use alkane_os::management::MiningStatus; use alkane_os::miner::{Bm1366Miner, ChipModel}; use alkane_os::stratum_client::{PoolConnection, PoolEvent}; use alkane_os::target_matrix; @@ -26,14 +27,21 @@ fn sim_mine(mut args: impl Iterator) -> Result<(), Box let password = std::env::var("ALKANE_POOL_PASSWORD") .map_err(|_| "set ALKANE_POOL_PASSWORD in the environment")?; let status = Arc::new(MiningStatus::new()); - if let Ok(bind) = std::env::var("ALKANE_API_LISTEN") { - let listener = bind_local(bind.parse()?)?; - let snapshot = Arc::clone(&status); - std::thread::spawn(move || { - if let Err(error) = serve(listener, snapshot) { - eprintln!("management API stopped: {error}"); - } - }); + let api = std::env::var("ALKANE_API_LISTEN") + .ok() + .map(|bind| bind.parse()) + .transpose()?; + let web = std::env::var("ALKANE_WEB_LISTEN") + .ok() + .map(|bind| bind.parse()) + .transpose()?; + let servers = app::start(Arc::clone(&status), api, web)?; + 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}/"); } // Connect to the pool before enabling power. The SDK HAL server owns the @@ -101,6 +109,9 @@ fn main() { } _ => { eprintln!("usage: alkane-os --list-targets | --version | --mine-simulator HAL_SOCKET POOL_ADDRESS WORKER BM1362|BM1366 [MAX_ACCEPTS]"); + eprintln!( + "env: ALKANE_API_LISTEN=ADDR ALKANE_WEB_LISTEN=ADDR ALKANE_POOL_PASSWORD=..." + ); std::process::exit(2); } }