Wire the API and UI through one start-up path
source-pr / source (pull_request) Successful in 12s

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.
This commit is contained in:
2026-10-22 10:43:39 -06:00
parent e3e0dab0ec
commit 2c6535f948
3 changed files with 230 additions and 9 deletions
+209
View File
@@ -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<SocketAddr>,
pub web: Option<SocketAddr>,
handles: Vec<JoinHandle<()>>,
}
impl Servers {
/// Addresses actually bound, which matters when port 0 was requested.
pub fn addresses(&self) -> (Option<SocketAddr>, Option<SocketAddr>) {
(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<MiningStatus>,
api: Option<SocketAddr>,
web_bind: Option<SocketAddr>,
) -> io::Result<Servers> {
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<String> {
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());
}
}
+1
View File
@@ -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;
+20 -9
View File
@@ -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<Item = String>) -> Result<(), Box<dyn Error>
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);
}
}