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,68 @@
|
||||
#!/bin/sh
|
||||
# Build an .afw firmware package for one control board and architecture.
|
||||
#
|
||||
# Modelled on the Warden `.wfw` bundle (scada/flare-edge/docs/firmware-format.md):
|
||||
# one file, a strict POSIX ustar tar, a JSON manifest first, then the payload,
|
||||
# with the payload's size and sha256 in the manifest so the device can verify
|
||||
# before it touches flash.
|
||||
#
|
||||
# Differences from .wfw, both deliberate:
|
||||
#
|
||||
# * the payload is COMPRESSED (`payload.tar.gz`) because these images ship to
|
||||
# boards over metered links, and a firmware bundle is mostly redundant;
|
||||
# * the manifest carries `board` and `arch`, and both go in the file name, so a
|
||||
# bundle can never be mistaken for another board family. Flashing the wrong
|
||||
# family is how boards are lost.
|
||||
#
|
||||
# Signature: `.wfw` carries an Ed25519 detached signature. We have no release
|
||||
# key yet, so `.afw` currently ships `members=2` and says so in the manifest
|
||||
# (`signature: "unsigned"`). Do not claim integrity beyond the sha256 until a
|
||||
# key exists.
|
||||
#
|
||||
# usage: make-afw.sh BOARD ARCH VERSION INPUT_DIR [OUTPUT_DIR]
|
||||
# e.g. make-afw.sh am335x-bb armv7 0.1.0 /tmp/release
|
||||
set -eu
|
||||
|
||||
BOARD=${1:?board family, e.g. am335x-bb}
|
||||
ARCH=${2:?architecture, e.g. armv7 or aarch64}
|
||||
VERSION=${3:?version, e.g. 0.1.0}
|
||||
INPUT=${4:?directory holding the release files}
|
||||
OUTPUT=${5:-dist}
|
||||
|
||||
mkdir -p "$OUTPUT"
|
||||
WORK=$(mktemp -d)
|
||||
trap 'rm -rf "$WORK"' EXIT
|
||||
|
||||
# The payload is a tar of the release tree, gzipped at maximum.
|
||||
tar --format=ustar --owner=0 --group=0 --numeric-owner \
|
||||
--create --file "$WORK/payload.tar" -C "$INPUT" .
|
||||
gzip -9 -n -c "$WORK/payload.tar" > "$WORK/payload.tar.gz"
|
||||
|
||||
PAYLOAD_SIZE=$(wc -c < "$WORK/payload.tar.gz")
|
||||
PAYLOAD_SHA=$(sha256sum "$WORK/payload.tar.gz" | cut -d' ' -f1)
|
||||
BUILD_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
cat > "$WORK/manifest.json" <<MANIFEST
|
||||
{
|
||||
"schema": 1,
|
||||
"format": "afw",
|
||||
"board": "$BOARD",
|
||||
"arch": "$ARCH",
|
||||
"version": "$VERSION",
|
||||
"build_date": "$BUILD_DATE",
|
||||
"compression": "gzip",
|
||||
"signature": "unsigned",
|
||||
"payload": {
|
||||
"file": "payload.tar.gz",
|
||||
"size": $PAYLOAD_SIZE,
|
||||
"sha256": "$PAYLOAD_SHA"
|
||||
}
|
||||
}
|
||||
MANIFEST
|
||||
|
||||
NAME="alkane-os-$VERSION-$BOARD-$ARCH.afw"
|
||||
(cd "$WORK" && tar --format=ustar --owner=0 --group=0 --numeric-owner \
|
||||
--create --file "$OUTPUT/$NAME" manifest.json payload.tar.gz)
|
||||
printf '%s\n' "$OUTPUT/$NAME"
|
||||
printf 'board %s\narch %s\npayload %s bytes\nsha256 %s\n' \
|
||||
"$BOARD" "$ARCH" "$PAYLOAD_SIZE" "$PAYLOAD_SHA"
|
||||
+478
-1
@@ -127,7 +127,484 @@
|
||||
}
|
||||
],
|
||||
"pages": [],
|
||||
"settings": [],
|
||||
"settings": [
|
||||
{
|
||||
"path": "tuning.mode",
|
||||
"label": "Tuning target",
|
||||
"help": "What the controller holds: a power draw, a hashrate, an ambient margin, or a fan ceiling.",
|
||||
"kind": {
|
||||
"t": "enum",
|
||||
"values": [
|
||||
{
|
||||
"v": "power",
|
||||
"label": "Power"
|
||||
},
|
||||
{
|
||||
"v": "hashrate",
|
||||
"label": "Hashrate"
|
||||
},
|
||||
{
|
||||
"v": "ambient",
|
||||
"label": "Ambient"
|
||||
},
|
||||
{
|
||||
"v": "max-fan",
|
||||
"label": "Max Fan"
|
||||
}
|
||||
]
|
||||
},
|
||||
"default": {
|
||||
"value": "power"
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 10,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "dropdown"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.power_w",
|
||||
"label": "Power target",
|
||||
"help": "DC power to hold when the target is power.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 200,
|
||||
"hi": 4000,
|
||||
"units": "W"
|
||||
},
|
||||
"default": {
|
||||
"value": 1200
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 20,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.hashrate_ths",
|
||||
"label": "Hashrate target",
|
||||
"help": "Hashrate to maximise up to, when the target is hashrate.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 1,
|
||||
"hi": 200,
|
||||
"units": "TH/s"
|
||||
},
|
||||
"default": {
|
||||
"value": 60
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 30,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.ambient_margin_c",
|
||||
"label": "Ambient margin",
|
||||
"help": "Hold the hottest sensor this far above measured ambient.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 40,
|
||||
"units": "C"
|
||||
},
|
||||
"default": {
|
||||
"value": 20
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 40,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.max_fan_pwm",
|
||||
"label": "Fan ceiling",
|
||||
"help": "Fan duty cap, percent, when the target is max-fan.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 100,
|
||||
"units": "%"
|
||||
},
|
||||
"default": {
|
||||
"value": 80
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 50,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.ceiling_mc",
|
||||
"label": "Frequency ceiling",
|
||||
"help": "Upper bound on the operating frequency, MHz.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 100,
|
||||
"hi": 1000,
|
||||
"units": "MHz"
|
||||
},
|
||||
"default": {
|
||||
"value": 700
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 60,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.kp_milli",
|
||||
"label": "Proportional gain",
|
||||
"help": "PID proportional term, thousandths of a unit.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 10000
|
||||
},
|
||||
"default": {
|
||||
"value": 500
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 100,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.ki_milli",
|
||||
"label": "Integral gain",
|
||||
"help": "PID integral term, milli-units.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 10000
|
||||
},
|
||||
"default": {
|
||||
"value": 100
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 110,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.kd_milli",
|
||||
"label": "Derivative gain",
|
||||
"help": "PID derivative term, milli-units.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 10000
|
||||
},
|
||||
"default": {
|
||||
"value": 0
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 120,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.out_min_milli",
|
||||
"label": "Output floor",
|
||||
"help": "Lowest control output the loop may emit, milli-units.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 1000000
|
||||
},
|
||||
"default": {
|
||||
"value": 0
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 130,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.out_max_milli",
|
||||
"label": "Output ceiling",
|
||||
"help": "Highest control output the loop may emit, milli-units.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 5000000
|
||||
},
|
||||
"default": {
|
||||
"value": 1000000
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 140,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.max_step_milli",
|
||||
"label": "Maximum step",
|
||||
"help": "Largest output change per second, milli-units.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 500000
|
||||
},
|
||||
"default": {
|
||||
"value": 50000
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 150,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "tuning.pid.deadband_milli",
|
||||
"label": "Deadband",
|
||||
"help": "Errors inside this band are ignored, milli-units.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 50000
|
||||
},
|
||||
"default": {
|
||||
"value": 1000
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "tuning",
|
||||
"order": 160,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "fans.zone_count",
|
||||
"label": "Fan zones",
|
||||
"help": "Number of independently driven fan zones.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 1,
|
||||
"hi": 8
|
||||
},
|
||||
"default": {
|
||||
"value": 4
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "fans",
|
||||
"order": 10,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "fans.pwm_min",
|
||||
"label": "Minimum duty",
|
||||
"help": "Duty floor applied to every zone, percent.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 0,
|
||||
"hi": 100,
|
||||
"units": "%"
|
||||
},
|
||||
"default": {
|
||||
"value": 20
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "fans",
|
||||
"order": 20,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "fans.sweep_steps",
|
||||
"label": "Sweep steps",
|
||||
"help": "Steps per zone when mapping fans to sensors.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 1,
|
||||
"hi": 32
|
||||
},
|
||||
"default": {
|
||||
"value": 8
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "fans",
|
||||
"order": 30,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "detect.chain_ports",
|
||||
"label": "Chain ports",
|
||||
"help": "Chain UART ports to probe, comma separated.",
|
||||
"kind": {
|
||||
"t": "str"
|
||||
},
|
||||
"default": {
|
||||
"value": "1,2,3"
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "detect",
|
||||
"order": 10,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "list"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "detect.probe_budget",
|
||||
"label": "Probe budget",
|
||||
"help": "Attempts per chain before detection gives up.",
|
||||
"kind": {
|
||||
"t": "int",
|
||||
"lo": 1,
|
||||
"hi": 20
|
||||
},
|
||||
"default": {
|
||||
"value": 3
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "detect",
|
||||
"order": 20,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "stepper"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "profiles.db",
|
||||
"label": "Profile database",
|
||||
"help": "Path to the board's tuning profile database.",
|
||||
"kind": {
|
||||
"t": "str"
|
||||
},
|
||||
"default": {
|
||||
"value": "/etc/alkane/profiles.json"
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "system",
|
||||
"order": 10,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "text"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "system.name",
|
||||
"label": "Board name",
|
||||
"help": "Name shown in the dashboard header.",
|
||||
"kind": {
|
||||
"t": "str"
|
||||
},
|
||||
"default": {
|
||||
"value": "alkane"
|
||||
},
|
||||
"owner": "synced",
|
||||
"guarded": false,
|
||||
"section": "system",
|
||||
"order": 20,
|
||||
"apply": {
|
||||
"class": "none"
|
||||
},
|
||||
"display": {
|
||||
"t": "text"
|
||||
}
|
||||
}
|
||||
],
|
||||
"groups": [],
|
||||
"actions": [],
|
||||
"rules": [],
|
||||
|
||||
@@ -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