Skip to main content

spacedb_console/
dashboard.rs

1//! The dashboard — the four boards assembled from one snapshot of observations.
2//!
3//! A Dioxus/WASM shell binds [`Dashboard`] fields to components; [`render_text`]
4//! produces the same view as an operator snapshot, so the model is demonstrable
5//! (and tested) with no browser.
6
7use std::fmt::Write as _;
8
9use serde::{Deserialize, Serialize};
10
11use crate::access::{rollup_access, AccessOverview};
12use crate::alerts::{derive_alerts, Alert, AlertThresholds, Severity};
13use crate::economics::{rollup_economics, Economics};
14use crate::fleet::{assess_fleet, FleetHealth, HealthStatus};
15use crate::observe::{
16    AgentBudgetObs, AuditObs, CapabilityObs, HomeObs, LagObs, SettledObs, ShardObs, StrongObs,
17};
18
19/// One snapshot of everything the console observes.
20#[derive(Clone, Debug, Default, Serialize, Deserialize)]
21pub struct Observations {
22    pub homes: Vec<HomeObs>,
23    pub shards: Vec<ShardObs>,
24    pub strong: Vec<StrongObs>,
25    pub lags: Vec<LagObs>,
26    pub capabilities: Vec<CapabilityObs>,
27    pub audit: Vec<AuditObs>,
28    pub settled: Vec<SettledObs>,
29    pub budgets: Vec<AgentBudgetObs>,
30    pub unsettled_claims: usize,
31}
32
33/// Operator-tunable thresholds for the whole dashboard.
34#[derive(Clone, Copy, Debug)]
35pub struct Config {
36    pub now: u64,
37    pub alerts: AlertThresholds,
38    pub expiry_window: u64,
39}
40
41impl Config {
42    pub fn at(now: u64) -> Self {
43        Self {
44            now,
45            alerts: AlertThresholds::default(),
46            expiry_window: 7 * 86_400, // a week
47        }
48    }
49}
50
51/// The four boards.
52#[derive(Clone, Debug, Serialize, Deserialize)]
53pub struct Dashboard {
54    pub health: FleetHealth,
55    pub alerts: Vec<Alert>,
56    pub economics: Economics,
57    pub access: AccessOverview,
58}
59
60impl Dashboard {
61    /// Compute the whole dashboard from a snapshot.
62    pub fn assemble(obs: &Observations, config: &Config) -> Dashboard {
63        let health = assess_fleet(
64            &obs.homes,
65            &obs.shards,
66            &obs.strong,
67            &obs.lags,
68            config.alerts.lag_ops_warn,
69        );
70        let alerts = derive_alerts(
71            &obs.homes,
72            &obs.shards,
73            &obs.strong,
74            &obs.lags,
75            &obs.budgets,
76            &config.alerts,
77        );
78        let economics = rollup_economics(
79            &obs.settled,
80            &obs.budgets,
81            obs.unsettled_claims,
82            config.alerts.budget_low_pct,
83        );
84        let access = rollup_access(&obs.capabilities, &obs.audit, config.now, config.expiry_window);
85        Dashboard {
86            health,
87            alerts,
88            economics,
89            access,
90        }
91    }
92
93    /// The number of alerts at or above `Critical` — i.e. the page-me count.
94    pub fn critical_count(&self) -> usize {
95        self.alerts
96            .iter()
97            .filter(|a| a.severity == Severity::Critical)
98            .count()
99    }
100
101    /// A plain-text operator snapshot (what the Dioxus shell renders graphically).
102    pub fn render_text(&self) -> String {
103        let h = &self.health;
104        let badge = match h.status {
105            HealthStatus::Green => "GREEN",
106            HealthStatus::Amber => "AMBER",
107            HealthStatus::Red => "RED",
108        };
109        // Written straight into `out`: `push_str(&format!(..))` built and
110        // dropped a String per line. Writing to a String cannot fail.
111        let mut out = String::new();
112        let _ = writeln!(out, "SpaceDB Operator Console — fleet {badge}");
113        let _ = writeln!(
114            out,
115            "Fleet:    {}/{} homes online · {} shards ({} under-replicated, {} at-risk, {} lost, {} over-replicated) · {} GiB",
116            h.homes_online,
117            h.homes_total,
118            h.shards_total,
119            h.shards_under_replicated,
120            h.shards_at_risk,
121            h.shards_lost,
122            h.shards_over_replicated,
123            h.bytes_stored / (1 << 30),
124        );
125        let _ = writeln!(
126            out,
127            "Strong:   {}/{} collections with quorum · worst lag {} ops",
128            h.strong_collections - h.strong_without_quorum,
129            h.strong_collections,
130            h.worst_lag_ops,
131        );
132        let _ = writeln!(
133            out,
134            "Access:   {} human + {} agent caps · {} expiring soon · {} revoked · {} recent denials",
135            self.access.active_human,
136            self.access.active_agent,
137            self.access.expiring_soon,
138            self.access.revoked,
139            self.access.denied_recent,
140        );
141        let _ = writeln!(
142            out,
143            "Economics: {} micro-$MATA revenue (S {} / C {} / T {}) · {} unsettled claims",
144            self.economics.revenue_micro_mata,
145            self.economics.per_rail.storage,
146            self.economics.per_rail.compute,
147            self.economics.per_rail.transit,
148            self.economics.unsettled_claims,
149        );
150        let _ = writeln!(out, "Alerts:   {} ({} critical)", self.alerts.len(), self.critical_count());
151        for a in &self.alerts {
152            let _ = writeln!(out, "  [{:?}] {:?} {} — {}", a.severity, a.kind, a.subject, a.detail);
153        }
154        out
155    }
156}