The source-pr gate runs cargo fmt --check; the afw OS-bundle line had not been formatted. Pure cargo fmt output. 250 tests pass; clippy -D warnings clean. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
308 lines
11 KiB
Rust
308 lines
11 KiB
Rust
// 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")
|
|
}
|
|
|
|
/// The deck directory: the on-box `/var/lib/alkane/decks` when it exists or can
|
|
/// be created (root on the miner), else a writable fallback for a dev run.
|
|
fn deck_dir() -> PathBuf {
|
|
let dir = Path::new(DECK_DIR);
|
|
if dir.is_dir() || fs::create_dir_all(dir).is_ok() {
|
|
return dir.to_path_buf();
|
|
}
|
|
std::env::temp_dir().join("alkane-decks")
|
|
}
|
|
|
|
fn deck_path(deck: &str) -> PathBuf {
|
|
let safe: String = deck
|
|
.chars()
|
|
.filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
|
|
.collect();
|
|
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())?;
|
|
// Atomic replace: a concurrent read never sees a half-written deck.
|
|
let tmp = path.with_extension("json.tmp");
|
|
fs::write(&tmp, text).map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;
|
|
fs::rename(&tmp, &path).map_err(|e| format!("cannot replace {}: {e}", path.display()))
|
|
}
|
|
|
|
/// Translate a settings form's tuning fields into the live control target.
|
|
fn apply_tuning(body: &str, control: &Control) {
|
|
let Some(mode) = crate::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) =
|
|
crate::form::field(body, value_field).and_then(|v| v.trim().parse::<f32>().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<MiningStatus>,
|
|
control: Arc<Control>,
|
|
bus: std::sync::Weak<Bus>,
|
|
}
|
|
|
|
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<Bus>, status: Arc<MiningStatus>, control: Arc<Control>) {
|
|
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 published_state_topics_match_the_contract() {
|
|
let bus = Bus::new();
|
|
publish(&bus, &MiningStatus::new(), &Control::default());
|
|
let mut published = bus.state_topics();
|
|
published.sort();
|
|
let mut declared: Vec<String> = registry::contract()["state"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.map(|v| v.as_str().unwrap().to_string())
|
|
.collect();
|
|
declared.sort();
|
|
assert_eq!(
|
|
published, declared,
|
|
"published state topics must match the contract"
|
|
);
|
|
}
|
|
|
|
#[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");
|
|
}
|
|
}
|