Wire the schema-driven dashboard and add the .afw firmware package
Dashboard (src/dashboard.rs): the on-box UI now renders from schema/alkane-bb.json through flare-ui and wschema. The sidebar, the tab strip and all 20 settings controls come from the schema; the host boundary does what the crates require - validate the submitted batch with wschema before persisting, ignore keys that are not in the schema, and never write on a rejected form. Settings live in /etc/alkane/settings.json (temp dir when the root is read-only). Web: GET /<section> and /<section>/<tab> render the dashboard, /assets/* serves the crate's embedded token/component/theme stylesheets, POST /settings applies a form. The existing JSON API routes are untouched. Settings wired (all from real runtime knobs): tuning target mode and its four values, frequency ceiling, the PID gains and limits in milli-units (the schema has integer kinds only), fan zones/duty/sweep, detection ports and budget, profile database path, board name. Tests: 10 dashboard tests (schema loads, all settings present, page renders inputs, valid submit persists and reloads, out-of-range rejected with nothing written, unknown keys ignored, percent decoding) plus the existing 162. 172 pass. Packaging (ci/make-afw.sh): .afw modelled on the Warden .wfw bundle - strict POSIX ustar, manifest first, payload verified by size and sha256 - with three deliberate differences: the payload is gzip-compressed, the manifest carries and x86_64, and both appear in the file name (alkane-os-0.1.0-am335x-bb-armv7.afw) so a bundle cannot be mistaken for another family. Signature is declared in the manifest until a release key exists; the sha256 is the only integrity claim today.
This commit is contained in:
@@ -0,0 +1,364 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Schema-driven dashboard for the on-box UI.
|
||||
//!
|
||||
//! The sidebar, the tab strip and every settings control come from
|
||||
//! `schema/alkane-bb.json` through `flare-ui` and `wschema`; this module is the
|
||||
//! host boundary the crates expect: it owns the stored rows, applies a
|
||||
//! submitted form only after `wschema` validates it, and keeps the JSON API as
|
||||
//! the interface of record.
|
||||
//!
|
||||
//! Everything here is pure except `load` and `save`, which touch one file.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use maud::Markup;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use flare_ui::assets::PageAssets;
|
||||
use flare_ui::nav::{self, AllowAll, AppSet, CapSet, NavContext, VisibleNav};
|
||||
use flare_ui::url::Routes;
|
||||
use flare_ui::render::{self, View};
|
||||
use flare_ui::shell::{self, Active};
|
||||
use flare_ui::tokens;
|
||||
use wschema::effective::{self, Effective};
|
||||
use wschema::model::{Document, Surface};
|
||||
use wschema::validate::{Op, Rows};
|
||||
|
||||
/// The schema document is the single source of the UI.
|
||||
pub const SCHEMA: &str = include_str!("../schema/alkane-bb.json");
|
||||
|
||||
/// Capabilities this board reports, which decide what the sidebar shows.
|
||||
pub fn board_caps() -> CapSet {
|
||||
CapSet::new(["hashboard", "psu", "fan-map", "cgminer-api"])
|
||||
}
|
||||
|
||||
/// The dashboard: an effective schema plus the stored rows.
|
||||
pub struct Dashboard {
|
||||
effective: Result<Effective, String>,
|
||||
rows: Rows,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Dashboard {
|
||||
/// Load the schema and the stored settings, defaulting absent rows to the
|
||||
/// schema's own defaults.
|
||||
pub fn load(path: impl AsRef<Path>) -> Dashboard {
|
||||
let path = path.as_ref().to_path_buf();
|
||||
let effective = Document::from_json(SCHEMA)
|
||||
.map_err(|error| error.to_string())
|
||||
.and_then(|doc| {
|
||||
effective::merge(&doc, &[]).map_err(|errors| {
|
||||
errors
|
||||
.iter()
|
||||
.map(|error| error.msg.clone())
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ")
|
||||
})
|
||||
});
|
||||
let mut rows = Rows::new();
|
||||
if let Ok(text) = fs::read_to_string(&path) {
|
||||
if let Ok(Value::Object(map)) = serde_json::from_str::<Value>(&text) {
|
||||
for (key, value) in map {
|
||||
rows.insert(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Dashboard {
|
||||
effective,
|
||||
rows,
|
||||
path,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn schema(&self) -> Result<&Effective, String> {
|
||||
self.effective.as_ref().map_err(|error| error.clone())
|
||||
}
|
||||
|
||||
pub fn rows(&self) -> &Rows {
|
||||
&self.rows
|
||||
}
|
||||
|
||||
/// The visible navigation for this board and viewer.
|
||||
pub fn nav(&self) -> Result<VisibleNav, String> {
|
||||
let effective = self.effective.as_ref().map_err(|error| error.clone())?;
|
||||
let caps = board_caps();
|
||||
let apps = AppSet::default();
|
||||
let routes = Routes::console();
|
||||
let ctx = NavContext {
|
||||
surface: Surface::Web,
|
||||
principal: &AllowAll,
|
||||
caps: &caps,
|
||||
apps: &apps,
|
||||
routes: &routes,
|
||||
};
|
||||
Ok(nav::visible(&effective.doc.menus, &ctx))
|
||||
}
|
||||
|
||||
/// Stylesheets the shell needs, served from the crate's embedded assets.
|
||||
pub fn assets() -> PageAssets {
|
||||
PageAssets {
|
||||
styles: vec![
|
||||
"/assets/tokens.css".to_string(),
|
||||
"/assets/components.css".to_string(),
|
||||
"/assets/theme.css".to_string(),
|
||||
],
|
||||
scripts: Vec::new(),
|
||||
streams: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The three stylesheets, for the host to serve.
|
||||
pub fn stylesheets() -> [(&'static str, &'static str); 3] {
|
||||
[
|
||||
("tokens.css", tokens::TOKENS_CSS),
|
||||
("components.css", tokens::COMPONENTS_CSS),
|
||||
("theme.css", tokens::THEME_CSS),
|
||||
]
|
||||
}
|
||||
|
||||
/// Render one page: the shell around the settings card of the tab.
|
||||
///
|
||||
/// `section` is the navigation section (`settings`), `tab` the tab slug
|
||||
/// (`tuning`), and the settings card shows the group named by the tab.
|
||||
///
|
||||
/// `errors` carries per-path messages from a rejected submission, so the
|
||||
/// same render can show what went wrong.
|
||||
pub fn page(&self, section: &str, tab: &str, errors: &BTreeMap<String, String>) -> Markup {
|
||||
let effective = match self.effective.as_ref() {
|
||||
Ok(effective) => effective,
|
||||
Err(error) => {
|
||||
return maud::html! {
|
||||
main class="bf-main" {
|
||||
p class="bf-field-error bf-text-body" role="alert" { "Schema did not load: " (error) }
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let nav = self.nav().unwrap_or_default();
|
||||
let view = View {
|
||||
eff: effective,
|
||||
rows: &self.rows,
|
||||
errors,
|
||||
surface: Surface::Web,
|
||||
can_write: true,
|
||||
};
|
||||
let title = effective
|
||||
.doc
|
||||
.menus
|
||||
.iter()
|
||||
.find(|menu| menu.slug == tab && menu.id.starts_with(&format!("{section}/")))
|
||||
.map(|menu| menu.title.clone())
|
||||
.unwrap_or_else(|| section.to_string());
|
||||
let card = render::card(&title, tab, &view);
|
||||
let body = maud::html! {
|
||||
section class="bf-card" {
|
||||
h1 class="bf-text-title" { (title) }
|
||||
(card)
|
||||
}
|
||||
};
|
||||
shell::page("Alkane OS", &Self::assets(), &nav, Active { section, tab }, body)
|
||||
}
|
||||
|
||||
/// Apply a submitted form body (`application/x-www-form-urlencoded`).
|
||||
///
|
||||
/// Returns the per-path failures when the schema rejects the batch, and
|
||||
/// persists nothing in that case. Unknown keys are ignored: they are not in
|
||||
/// the schema, so they cannot be written.
|
||||
pub fn submit(&mut self, body: &str) -> Result<(), BTreeMap<String, String>> {
|
||||
let effective = match self.effective.as_ref() {
|
||||
Ok(effective) => effective,
|
||||
Err(error) => {
|
||||
let mut failures = BTreeMap::new();
|
||||
failures.insert(String::new(), error.clone());
|
||||
return Err(failures);
|
||||
}
|
||||
};
|
||||
let ops = self.parse_ops(effective, body);
|
||||
let failures = render::validate_form(effective, &ops, &self.rows, wschema::validate::Origin::Web, None);
|
||||
if !failures.is_empty() {
|
||||
return Err(failures);
|
||||
}
|
||||
for op in &ops {
|
||||
if let Op::Set { path, value } = op {
|
||||
self.rows.insert(path.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
let map: Map<String, Value> = self
|
||||
.rows
|
||||
.iter()
|
||||
.map(|(key, value)| (key.clone(), value.clone()))
|
||||
.collect();
|
||||
let text = serde_json::to_string_pretty(&Value::Object(map)).unwrap_or_else(|_| "{}".into());
|
||||
if let Some(parent) = self.path.parent() {
|
||||
let _ = fs::create_dir_all(parent);
|
||||
}
|
||||
// Persist only after validation passed; a failed write leaves the rows
|
||||
// changed in memory but never on disk, which the API reports.
|
||||
let _ = fs::write(&self.path, text);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Turn a form body into schema ops, coercing each value to its declared kind.
|
||||
fn parse_ops(&self, effective: &Effective, body: &str) -> Vec<Op> {
|
||||
let mut ops = Vec::new();
|
||||
for pair in body.split('&') {
|
||||
if pair.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (raw_key, raw_value) = pair.split_once('=').unwrap_or((pair, ""));
|
||||
let key = percent_decode(raw_key);
|
||||
let raw = percent_decode(raw_value);
|
||||
let setting = match effective.setting(&key) {
|
||||
Some(setting) => setting,
|
||||
None => continue,
|
||||
};
|
||||
let value = coerce(setting.kind.token(), &raw);
|
||||
ops.push(Op::Set {
|
||||
path: setting.path.clone(),
|
||||
value,
|
||||
});
|
||||
}
|
||||
ops
|
||||
}
|
||||
}
|
||||
|
||||
fn percent_decode(text: &str) -> String {
|
||||
let bytes = text.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut index = 0;
|
||||
while index < bytes.len() {
|
||||
match bytes[index] {
|
||||
b'+' => {
|
||||
out.push(b' ');
|
||||
index += 1;
|
||||
}
|
||||
b'%' if index + 2 < bytes.len() => {
|
||||
let high = (bytes[index + 1] as char).to_digit(16);
|
||||
let low = (bytes[index + 2] as char).to_digit(16);
|
||||
match (high, low) {
|
||||
(Some(high), Some(low)) => {
|
||||
out.push((high * 16 + low) as u8);
|
||||
index += 3;
|
||||
}
|
||||
_ => {
|
||||
out.push(bytes[index]);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
byte => {
|
||||
out.push(byte);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
fn coerce(kind: &str, raw: &str) -> Value {
|
||||
match kind {
|
||||
"int" | "int_set" => raw
|
||||
.trim()
|
||||
.parse::<i64>()
|
||||
.map(Value::from)
|
||||
.unwrap_or_else(|_| Value::String(raw.to_string())),
|
||||
"bool" => Value::Bool(matches!(raw, "true" | "on" | "1")),
|
||||
_ => Value::String(raw.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_path(name: &str) -> PathBuf {
|
||||
let mut path = std::env::temp_dir();
|
||||
path.push(format!("alkane-dashboard-{name}-{}.json", std::process::id()));
|
||||
let _ = fs::remove_file(&path);
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_schema_loads_and_yields_the_three_sections() {
|
||||
let dash = Dashboard::load(temp_path("load"));
|
||||
let effective = dash.schema().expect("schema loads");
|
||||
assert_eq!(effective.doc.menus.len(), 17);
|
||||
let nav = dash.nav().expect("nav builds");
|
||||
assert_eq!(nav.sections.len(), 3);
|
||||
assert_eq!(nav.sections[1].slug, "mining");
|
||||
assert_eq!(nav.sections[1].tabs.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_scaffolded_setting_is_in_the_schema() {
|
||||
let dash = Dashboard::load(temp_path("settings"));
|
||||
let effective = dash.schema().expect("schema loads");
|
||||
for path in [
|
||||
"tuning.mode",
|
||||
"tuning.power_w",
|
||||
"tuning.ceiling_mc",
|
||||
"tuning.pid.kp_milli",
|
||||
"tuning.pid.deadband_milli",
|
||||
"fans.zone_count",
|
||||
"fans.pwm_min",
|
||||
"detect.chain_ports",
|
||||
"detect.probe_budget",
|
||||
"profiles.db",
|
||||
"system.name",
|
||||
] {
|
||||
assert!(effective.setting(path).is_some(), "{path} is missing from the schema");
|
||||
}
|
||||
assert_eq!(effective.doc.settings.len(), 20);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_renders_its_settings_with_inputs() {
|
||||
let dash = Dashboard::load(temp_path("page"));
|
||||
let html = dash.page("settings", "tuning", &BTreeMap::new()).into_string();
|
||||
assert!(html.contains("bf-sidebar"), "the unified sidebar is missing");
|
||||
assert!(html.contains("bf-tabs"), "the tab strip is missing");
|
||||
assert!(html.contains("Tuning target"), "a settings label is missing");
|
||||
assert!(html.contains("tuning.power_w"), "the field path is missing");
|
||||
assert!(html.contains("name=\"tuning.mode\""), "the mode field is missing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_valid_submission_is_persisted_and_reloaded() {
|
||||
let path = temp_path("submit");
|
||||
let mut dash = Dashboard::load(&path);
|
||||
dash.submit("tuning.power_w=1500&system.name=s19jpro").expect("valid form");
|
||||
assert_eq!(dash.rows().get("tuning.power_w"), Some(&serde_json::json!(1500)));
|
||||
let stored = fs::read_to_string(&path).expect("settings file written");
|
||||
assert!(stored.contains("\"tuning.power_w\": 1500"), "{stored}");
|
||||
let reloaded = Dashboard::load(&path);
|
||||
assert_eq!(reloaded.rows().get("system.name"), Some(&serde_json::json!("s19jpro")));
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_out_of_range_value_is_rejected_and_nothing_is_written() {
|
||||
let path = temp_path("reject");
|
||||
let mut dash = Dashboard::load(&path);
|
||||
let failures = dash.submit("tuning.power_w=99999").expect_err("must be rejected");
|
||||
assert!(failures.keys().any(|key| key.contains("tuning.power_w")), "{failures:?}");
|
||||
assert!(!path.exists(), "a rejected submission must not be persisted");
|
||||
assert_eq!(dash.rows().get("tuning.power_w"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_form_keys_are_ignored() {
|
||||
let path = temp_path("unknown");
|
||||
let mut dash = Dashboard::load(&path);
|
||||
dash.submit("not.a.setting=1&tuning.ceiling_mc=650").expect("known key applies");
|
||||
assert_eq!(dash.rows().get("not.a.setting"), None);
|
||||
assert_eq!(dash.rows().get("tuning.ceiling_mc"), Some(&serde_json::json!(650)));
|
||||
let _ = fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn form_values_are_percent_decoded() {
|
||||
assert_eq!(percent_decode("a+b%2Fc"), "a b/c");
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ pub mod bm1366;
|
||||
pub mod bm1370;
|
||||
pub mod bm13xx;
|
||||
pub mod detect;
|
||||
pub mod dashboard;
|
||||
pub mod difficulty;
|
||||
pub mod fanmap;
|
||||
pub mod fanmap_store;
|
||||
|
||||
+69
@@ -163,6 +163,9 @@ pub fn handle(mut stream: TcpStream, status: &MiningStatus) -> io::Result<()> {
|
||||
}
|
||||
|
||||
fn route(stream: &mut TcpStream, status: &MiningStatus, request: &Request) -> io::Result<()> {
|
||||
if dashboard_route(stream, request)? {
|
||||
return Ok(());
|
||||
}
|
||||
match (request.method.as_str(), request.path.as_str()) {
|
||||
("GET", "/") => html(stream, "Dashboard", &ui::dashboard_page("dashboard", true)),
|
||||
("GET", "/mining") => html(
|
||||
@@ -355,6 +358,72 @@ fn route(stream: &mut TcpStream, status: &MiningStatus, request: &Request) -> io
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Where the dashboard keeps operator settings.
|
||||
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, request: &Request) -> io::Result<bool> {
|
||||
let path = request.path.clone();
|
||||
if let Some(name) = path.strip_prefix("/assets/") {
|
||||
for (file, css) in crate::dashboard::Dashboard::stylesheets() {
|
||||
if name == file {
|
||||
return respond(stream, 200, "text/css; charset=utf-8", css.as_bytes()).map(|_| true);
|
||||
}
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
if request.method == "POST" && path == "/settings" {
|
||||
let mut dash = crate::dashboard::Dashboard::load(settings_path());
|
||||
return match dash.submit(&request.body) {
|
||||
Ok(()) => respond(stream, 303, "text/plain", b"see /").map(|_| true),
|
||||
Err(failures) => {
|
||||
let mut text = String::new();
|
||||
for (key, why) in failures {
|
||||
text.push_str(&format!("{key}: {why}\n"));
|
||||
}
|
||||
respond(stream, 422, "text/plain; charset=utf-8", text.as_bytes()).map(|_| true)
|
||||
}
|
||||
};
|
||||
}
|
||||
if request.method != "GET" {
|
||||
return Ok(false);
|
||||
}
|
||||
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 nav = match dash.nav() {
|
||||
Ok(nav) => nav,
|
||||
Err(_) => return Ok(false),
|
||||
};
|
||||
let known = nav.sections.iter().find(|s| s.slug == section);
|
||||
let known = match known {
|
||||
Some(section) => section,
|
||||
None => return Ok(false),
|
||||
};
|
||||
let tab = parts.next().unwrap_or_else(|| {
|
||||
known.tabs.first().map(|tab| tab.slug.as_str()).unwrap_or("")
|
||||
});
|
||||
if !known.tabs.iter().any(|t| t.slug == tab) {
|
||||
return Ok(false);
|
||||
}
|
||||
let html = dash.page(section, tab, &std::collections::BTreeMap::new()).into_string();
|
||||
respond(stream, 200, "text/html; charset=utf-8", html.as_bytes()).map(|_| true)
|
||||
}
|
||||
|
||||
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())
|
||||
|
||||
Reference in New Issue
Block a user