diff --git a/src/app.rs b/src/app.rs index c6974e1..03be9b6 100644 --- a/src/app.rs +++ b/src/app.rs @@ -5,9 +5,17 @@ //! 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::detect::{ + run_detection, DetectionBackend, DetectionFailure, DetectionRequest, FanZone, ProbeBudget, + SensorTopology, +}; +use crate::fault::FaultPolicy; use crate::management::{bind_local, serve, HardwareSnapshot, MiningStatus}; +use crate::profiles::{ProfileDb, ProfileError}; use crate::runtime::MinerRuntime; +use crate::tuning::{PidConfig, TuningTarget}; use crate::web; +use std::fmt; use std::io; use std::net::{SocketAddr, TcpListener, TcpStream}; use std::sync::Arc; @@ -97,6 +105,73 @@ pub fn snapshot(runtime: &MinerRuntime, target: &str) -> HardwareSnapshot { } } +/// Everything a boot needs besides the backend. +#[derive(Clone, Debug, PartialEq)] +pub struct BootConfig { + pub profile_db_json: String, + pub chain_ports: Vec, + pub sensor: SensorTopology, + pub budget: ProbeBudget, + pub fan_zones: Vec, + pub target: TuningTarget, + pub pid: PidConfig, + pub ceiling_mc: i32, + pub fault_policy: FaultPolicy, +} + +/// Why boot did not reach a running runtime. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum BootError { + Profile(ProfileError), + Detection(DetectionFailure), +} + +impl fmt::Display for BootError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Profile(error) => write!(f, "profile database rejected: {error:?}"), + Self::Detection(error) => write!(f, "hardware detection refused: {error:?}"), + } + } +} + +impl std::error::Error for BootError {} + +/// Operator target in the form the API and UI report. +pub fn target_label(target: &TuningTarget) -> String { + match *target { + TuningTarget::PowerW(watts) => format!("power:{watts:.0}"), + TuningTarget::HashrateThs(rate) => format!("hashrate:{rate:.0}"), + TuningTarget::AmbientC { margin_mc } => format!("ambient:{margin_mc}"), + TuningTarget::MaxFan { max_pwm } => format!("fan:{max_pwm}"), + } +} + +/// Detect, decide, and publish: the sequence a family image runs at start-up. +pub fn boot( + backend: &mut B, + config: &BootConfig, + status: &MiningStatus, +) -> Result> { + let db = ProfileDb::from_json(&config.profile_db_json).map_err(BootError::Profile)?; + let request = DetectionRequest { + chain_ports: &config.chain_ports, + budget: config.budget, + sensor: config.sensor, + fan_zones: config.fan_zones.clone(), + }; + let plan = run_detection(backend, &db, &request).map_err(BootError::Detection)?; + let runtime = MinerRuntime::new( + plan, + config.fault_policy, + config.target, + config.pid, + config.ceiling_mc, + ); + status.set_hardware(snapshot(&runtime, &target_label(&config.target))); + Ok(runtime) +} + /// 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}; @@ -114,6 +189,7 @@ mod tests { use crate::detect::{ ChainReport, ChipModel, EepromState, Envelope, FanZone, HardwarePlan, OperatingPoint, }; + use crate::detect::{ProbeOutcome, PsuCapability}; use crate::fault::FaultPolicy; use crate::tuning::{PidConfig, TuningTarget}; use std::io::{Read, Write}; @@ -206,4 +282,137 @@ mod tests { assert!(snapshot.frequency_mhz > 300); assert!(snapshot.stopped.is_none()); } + + struct BootBackend { + outcome: ProbeOutcome, + psu: Option, + } + + impl DetectionBackend for BootBackend { + type Error = (); + + fn probe(&mut self, _chain: u8, _attempt: u8) -> Result { + Ok(self.outcome) + } + + fn eeprom(&mut self, _chain: u8) -> Result { + Ok(EepromState::Absent) + } + + fn identify_psu(&mut self) -> Result, ()> { + Ok(self.psu.clone()) + } + } + + const DB: &str = r#"{"schema":1,"profiles":[{"name":"s19jpro-bm1362-pic", + "chip":"bm1362","sensor":"pic","chains":3, + "envelope":{"v_min_mv":1100,"v_max_mv":1500,"f_min_mhz":300,"f_max_mhz":700}}]}"#; + + fn boot_config() -> BootConfig { + BootConfig { + profile_db_json: DB.into(), + chain_ports: vec![0, 1, 2], + sensor: SensorTopology::Pic, + budget: ProbeBudget::default(), + fan_zones: Vec::new(), + target: TuningTarget::PowerW(2_400.0), + pid: PidConfig::default(), + ceiling_mc: 95_000, + fault_policy: FaultPolicy::default(), + } + } + + fn psu() -> PsuCapability { + PsuCapability { + name: "APW12".into(), + envelope: Envelope { + v_min_mv: 1200, + v_max_mv: 1600, + f_min_mhz: 0, + f_max_mhz: 1_000, + }, + max_dc_watts: 3_600, + } + } + + #[test] + fn boot_detects_and_publishes() { + let mut backend = BootBackend { + outcome: ProbeOutcome::Identified { + chip: ChipModel::Bm1362, + chips: 126, + }, + psu: Some(psu()), + }; + let status = MiningStatus::new(); + let runtime = boot(&mut backend, &boot_config(), &status).expect("boot"); + assert_eq!(runtime.active_chains(), vec![0, 1, 2]); + let document = status.hardware_document(); + assert_eq!(document["available"], true); + assert_eq!(document["target"], "power:2400"); + assert_eq!(document["psu"], "APW12"); + } + + #[test] + fn boot_refuses_an_unknown_chip() { + let mut backend = BootBackend { + outcome: ProbeOutcome::Silent, + psu: Some(psu()), + }; + let status = MiningStatus::new(); + assert!(matches!( + boot(&mut backend, &boot_config(), &status), + Err(BootError::Detection(DetectionFailure::Refused(_))) + )); + assert_eq!(status.hardware_document()["available"], false); + } + + #[test] + fn boot_refuses_a_bad_profile_database() { + let mut backend = BootBackend { + outcome: ProbeOutcome::Identified { + chip: ChipModel::Bm1362, + chips: 126, + }, + psu: Some(psu()), + }; + let mut config = boot_config(); + config.profile_db_json = "{\"schema\": 9}".into(); + assert!(matches!( + boot(&mut backend, &config, &MiningStatus::new()), + Err(BootError::Profile(_)) + )); + } + + #[test] + fn boot_refuses_a_missing_psu() { + let mut backend = BootBackend { + outcome: ProbeOutcome::Identified { + chip: ChipModel::Bm1362, + chips: 126, + }, + psu: None, + }; + assert!(matches!( + boot(&mut backend, &boot_config(), &MiningStatus::new()), + Err(BootError::Detection(DetectionFailure::Refused(_))) + )); + } + + #[test] + fn target_labels_are_stable() { + assert_eq!(target_label(&TuningTarget::PowerW(3_000.0)), "power:3000"); + assert_eq!( + target_label(&TuningTarget::HashrateThs(200.0)), + "hashrate:200" + ); + assert_eq!( + target_label(&TuningTarget::AmbientC { margin_mc: 20_000 }), + "ambient:20000" + ); + assert_eq!( + target_label(&TuningTarget::MaxFan { max_pwm: 100 }), + "fan:100" + ); + } }