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
287 lines
9.6 KiB
Rust
287 lines
9.6 KiB
Rust
// SPDX-License-Identifier: MIT
|
|
//! The command/state bus: the single point of command for the miner.
|
|
//!
|
|
//! Modeled on wardenOS's bus (flare-edge `sprint`): one hub that the HTTP API,
|
|
//! the web UI, and any future remote/flare client all go through, so there is no
|
|
//! second way to change the machine. State is *retained* - a reader subscribes
|
|
//! to / reads a topic and gets the last published document - and commands are
|
|
//! *request/reply* to the service that owns the verb.
|
|
//!
|
|
//! wardenOS runs this as an MQTT-5 broker over a Unix socket with per-user ACLs.
|
|
//! Here the wire is in-process (std threads, no broker, no async): the facade
|
|
//! below - `publish_state` / `read_state` / `request` / `emit` - matches the
|
|
//! warden `Bus` surface, so callers never learn the transport and the broker can
|
|
//! be swapped in later without touching them. The registry in `registry.rs` is
|
|
//! the contract (topics and verbs), exactly as warden's `topics.json` is.
|
|
//!
|
|
//! Topic kinds, mirroring warden:
|
|
//! - `state` (retained): telemetry and status. Read = `read_state`.
|
|
//! - `evt` (not retained): events (log lines, faults). `emit` keeps a bounded
|
|
//! ring the UI and API can tail.
|
|
//! - `req`/`reply`: a command to an owning service. `register` + `request`.
|
|
|
|
use serde_json::{json, Value};
|
|
use std::collections::{BTreeMap, VecDeque};
|
|
use std::sync::{Arc, Mutex, RwLock};
|
|
use std::time::{SystemTime, UNIX_EPOCH};
|
|
|
|
/// How many recent events the bus keeps for tailing.
|
|
const EVENT_RING: usize = 256;
|
|
|
|
/// Why a request could not be served. Serializes to the warden-style
|
|
/// `{ "error": CODE, "message": ... }` envelope.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub enum BusError {
|
|
/// No service owns this verb.
|
|
NoHandler(String),
|
|
/// The request body was malformed for this verb.
|
|
BadRequest(String),
|
|
/// The owning service refused the request (out of range, wrong state).
|
|
Rejected(String),
|
|
}
|
|
|
|
impl BusError {
|
|
pub fn code(&self) -> &'static str {
|
|
match self {
|
|
BusError::NoHandler(_) => "E_NO_HANDLER",
|
|
BusError::BadRequest(_) => "E_BAD_REQUEST",
|
|
BusError::Rejected(_) => "E_REJECTED",
|
|
}
|
|
}
|
|
|
|
pub fn message(&self) -> &str {
|
|
match self {
|
|
BusError::NoHandler(m) | BusError::BadRequest(m) | BusError::Rejected(m) => m,
|
|
}
|
|
}
|
|
|
|
/// The JSON error envelope a surface returns to its client.
|
|
pub fn envelope(&self) -> Value {
|
|
json!({ "error": self.code(), "message": self.message() })
|
|
}
|
|
}
|
|
|
|
impl std::fmt::Display for BusError {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
write!(f, "{}: {}", self.code(), self.message())
|
|
}
|
|
}
|
|
|
|
impl std::error::Error for BusError {}
|
|
|
|
/// A command handler: owns one verb, validates and applies the request, and
|
|
/// returns the result document (or a [`BusError`]).
|
|
pub type Handler = Box<dyn Fn(&Value) -> Result<Value, BusError> + Send + Sync>;
|
|
|
|
/// One emitted event, kept in the ring for tailing.
|
|
#[derive(Clone, Debug)]
|
|
pub struct Event {
|
|
pub topic: String,
|
|
pub body: Value,
|
|
pub at_unix: u64,
|
|
}
|
|
|
|
/// The in-process bus.
|
|
pub struct Bus {
|
|
state: RwLock<BTreeMap<String, Value>>,
|
|
handlers: RwLock<BTreeMap<String, Handler>>,
|
|
events: Mutex<VecDeque<Event>>,
|
|
}
|
|
|
|
impl Default for Bus {
|
|
fn default() -> Self {
|
|
Self::new_inner()
|
|
}
|
|
}
|
|
|
|
impl Bus {
|
|
fn new_inner() -> Self {
|
|
Self {
|
|
state: RwLock::new(BTreeMap::new()),
|
|
handlers: RwLock::new(BTreeMap::new()),
|
|
events: Mutex::new(VecDeque::with_capacity(EVENT_RING)),
|
|
}
|
|
}
|
|
|
|
/// A shared bus handle. The hub is cheap to clone (`Arc`).
|
|
pub fn new() -> Arc<Self> {
|
|
Arc::new(Self::new_inner())
|
|
}
|
|
|
|
// --- state (retained) ----------------------------------------------------
|
|
|
|
/// Publish a retained state document. A later reader gets this verbatim.
|
|
pub fn publish_state(&self, topic: &str, doc: Value) {
|
|
if let Ok(mut map) = self.state.write() {
|
|
map.insert(topic.to_string(), doc);
|
|
}
|
|
}
|
|
|
|
/// Read the last retained document for a topic, if any.
|
|
pub fn read_state(&self, topic: &str) -> Option<Value> {
|
|
self.state
|
|
.read()
|
|
.ok()
|
|
.and_then(|map| map.get(topic).cloned())
|
|
}
|
|
|
|
/// Read a retained document, or a fallback when nothing is published yet.
|
|
pub fn read_state_or(&self, topic: &str, fallback: Value) -> Value {
|
|
self.read_state(topic).unwrap_or(fallback)
|
|
}
|
|
|
|
/// Drop a retained document (the warden "clear via empty will" semantics).
|
|
pub fn clear_state(&self, topic: &str) {
|
|
if let Ok(mut map) = self.state.write() {
|
|
map.remove(topic);
|
|
}
|
|
}
|
|
|
|
/// Every state topic currently published, for introspection and parity tests.
|
|
pub fn state_topics(&self) -> Vec<String> {
|
|
self.state
|
|
.read()
|
|
.map(|map| map.keys().cloned().collect())
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
// --- commands (request/reply) --------------------------------------------
|
|
|
|
/// Register the service that owns `verb`. Re-registering replaces it.
|
|
pub fn register<F>(&self, verb: &str, handler: F)
|
|
where
|
|
F: Fn(&Value) -> Result<Value, BusError> + Send + Sync + 'static,
|
|
{
|
|
if let Ok(mut map) = self.handlers.write() {
|
|
map.insert(verb.to_string(), Box::new(handler));
|
|
}
|
|
}
|
|
|
|
/// Dispatch a command to its owning service. This is the single write path:
|
|
/// the API and the UI both call this, so a verb cannot be driven two ways.
|
|
pub fn request(&self, verb: &str, body: &Value) -> Result<Value, BusError> {
|
|
let map = self
|
|
.handlers
|
|
.read()
|
|
.map_err(|_| BusError::Rejected("bus handler lock poisoned".into()))?;
|
|
let handler = map
|
|
.get(verb)
|
|
.ok_or_else(|| BusError::NoHandler(format!("no service owns {verb}")))?;
|
|
handler(body)
|
|
}
|
|
|
|
/// True when a service owns the verb.
|
|
pub fn has_verb(&self, verb: &str) -> bool {
|
|
self.handlers
|
|
.read()
|
|
.map(|m| m.contains_key(verb))
|
|
.unwrap_or(false)
|
|
}
|
|
|
|
/// Every registered verb, sorted, for introspection and parity tests.
|
|
pub fn verbs(&self) -> Vec<String> {
|
|
self.handlers
|
|
.read()
|
|
.map(|map| map.keys().cloned().collect())
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
// --- events (non-retained) -----------------------------------------------
|
|
|
|
/// Emit an event onto the ring (faults, log lines, notices).
|
|
pub fn emit(&self, topic: &str, body: Value) {
|
|
let at_unix = SystemTime::now()
|
|
.duration_since(UNIX_EPOCH)
|
|
.map(|d| d.as_secs())
|
|
.unwrap_or(0);
|
|
if let Ok(mut ring) = self.events.lock() {
|
|
if ring.len() == EVENT_RING {
|
|
ring.pop_front();
|
|
}
|
|
ring.push_back(Event {
|
|
topic: topic.to_string(),
|
|
body,
|
|
at_unix,
|
|
});
|
|
}
|
|
}
|
|
|
|
/// The most recent `n` events, oldest first.
|
|
pub fn recent_events(&self, n: usize) -> Vec<Event> {
|
|
self.events
|
|
.lock()
|
|
.map(|ring| ring.iter().rev().take(n).rev().cloned().collect())
|
|
.unwrap_or_default()
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn retained_state_round_trips() {
|
|
let bus = Bus::new();
|
|
assert_eq!(bus.read_state("miner/state/x"), None);
|
|
bus.publish_state("miner/state/x", json!({"v": 1}));
|
|
assert_eq!(bus.read_state("miner/state/x"), Some(json!({"v": 1})));
|
|
bus.publish_state("miner/state/x", json!({"v": 2}));
|
|
assert_eq!(bus.read_state("miner/state/x").unwrap()["v"], 2);
|
|
bus.clear_state("miner/state/x");
|
|
assert_eq!(bus.read_state("miner/state/x"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn a_request_reaches_its_owning_handler() {
|
|
let bus = Bus::new();
|
|
bus.register("control/echo", |body| Ok(body.clone()));
|
|
let out = bus.request("control/echo", &json!({"hi": true})).unwrap();
|
|
assert_eq!(out["hi"], true);
|
|
}
|
|
|
|
#[test]
|
|
fn an_unowned_verb_is_a_no_handler_error() {
|
|
let bus = Bus::new();
|
|
let err = bus.request("nope", &json!({})).unwrap_err();
|
|
assert_eq!(err.code(), "E_NO_HANDLER");
|
|
assert_eq!(err.envelope()["error"], "E_NO_HANDLER");
|
|
}
|
|
|
|
#[test]
|
|
fn a_handler_can_reject_and_the_code_is_preserved() {
|
|
let bus = Bus::new();
|
|
bus.register("control/set", |_| {
|
|
Err(BusError::Rejected("out of range".into()))
|
|
});
|
|
let err = bus.request("control/set", &json!({})).unwrap_err();
|
|
assert_eq!(err.code(), "E_REJECTED");
|
|
assert_eq!(err.message(), "out of range");
|
|
}
|
|
|
|
#[test]
|
|
fn registering_a_verb_replaces_the_prior_owner() {
|
|
let bus = Bus::new();
|
|
bus.register("v", |_| Ok(json!(1)));
|
|
bus.register("v", |_| Ok(json!(2)));
|
|
assert_eq!(bus.request("v", &json!({})).unwrap(), json!(2));
|
|
assert!(bus.has_verb("v"));
|
|
assert_eq!(bus.verbs(), vec!["v".to_string()]);
|
|
}
|
|
|
|
#[test]
|
|
fn the_event_ring_is_bounded_and_ordered() {
|
|
let bus = Bus::new();
|
|
for i in 0..(EVENT_RING + 10) {
|
|
bus.emit("evt/log", json!({ "i": i }));
|
|
}
|
|
let recent = bus.recent_events(5);
|
|
assert_eq!(recent.len(), 5);
|
|
// oldest-first, and the very last is the newest emitted.
|
|
assert_eq!(
|
|
recent.last().unwrap().body["i"],
|
|
(EVENT_RING + 10 - 1) as i64
|
|
);
|
|
assert!(recent[0].body["i"].as_i64().unwrap() < recent[1].body["i"].as_i64().unwrap());
|
|
}
|
|
}
|