use std::sync::{Arc, RwLock};
use std::thread;
use std::time::{Duration, Instant};
use serde::Serialize;
use serde_json::Value;
use crate::heartbeat::HeartbeatEngine;
use crate::shutdown::ShutdownHandler;
#[derive(Debug, Clone, Serialize)]
pub struct StatusValue {
value: Value,
#[serde(rename = "type")]
kind: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
unit: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
label: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
hint: Option<String>,
}
impl StatusValue {
fn new(value: Value, kind: &'static str) -> Self {
Self { value, kind, unit: None, label: None, hint: None }
}
pub fn boolean(v: bool) -> Self {
Self::new(Value::Bool(v), "bool").hint("lamp")
}
pub fn integer(v: impl Into<Value>) -> Self {
Self::new(v.into(), "int")
}
pub fn number(v: impl Into<Value>) -> Self {
Self::new(v.into(), "float")
}
pub fn text(v: impl Into<String>) -> Self {
Self::new(Value::String(v.into()), "string")
}
pub fn enumeration(v: impl Into<String>) -> Self {
Self::new(Value::String(v.into()), "enum")
}
pub fn timestamp(v: impl Into<String>) -> Self {
Self::new(Value::String(v.into()), "timestamp").hint("time")
}
pub fn duration(v: impl Into<Value>, unit: &str) -> Self {
Self::new(v.into(), "duration").unit(unit).hint("duration")
}
pub fn bytes(v: impl Into<Value>) -> Self {
Self::new(v.into(), "bytes").unit("B").hint("bytes")
}
pub fn percent(v: impl Into<Value>) -> Self {
Self::new(v.into(), "percent").unit("%").hint("percent")
}
pub fn unit(mut self, u: impl Into<String>) -> Self {
self.unit = Some(u.into());
self
}
pub fn label(mut self, l: impl Into<String>) -> Self {
self.label = Some(l.into());
self
}
pub fn hint(mut self, h: impl Into<String>) -> Self {
self.hint = Some(h.into());
self
}
pub fn into_value(self) -> Value {
serde_json::to_value(self).unwrap_or(Value::Null)
}
}
impl From<StatusValue> for Value {
fn from(sv: StatusValue) -> Self {
sv.into_value()
}
}
pub trait StatusSource: Send + Sync {
fn get_status(&self) -> Value;
fn get_name(&self) -> &str;
fn refresh_interval(&self) -> Duration;
}
struct RegisteredSource {
source: Arc<dyn StatusSource>,
last_refresh: Instant,
}
pub struct StatusEngine {
sources: RwLock<Vec<RegisteredSource>>,
last_status: RwLock<Value>,
stop_flag: RwLock<Option<ShutdownHandler>>,
}
impl StatusEngine {
pub fn new() -> Self {
Self {
sources: RwLock::new(Vec::new()),
last_status: RwLock::new(Value::Object(serde_json::Map::new())),
stop_flag: RwLock::new(None),
}
}
pub fn register_source(&self, source: Arc<dyn StatusSource>) {
let mut sources = self.sources.write().unwrap();
sources.push(RegisteredSource {
source,
last_refresh: Instant::now() - Duration::from_secs(3600), });
}
pub fn unregister_source(&self, name: &str) -> bool {
let mut sources = self.sources.write().unwrap();
let before = sources.len();
sources.retain(|reg| reg.source.get_name() != name);
sources.len() < before
}
pub fn collect(&self) -> Value {
let mut sources = self.sources.write().unwrap();
let now = Instant::now();
let mut result = serde_json::Map::new();
for reg in sources.iter_mut() {
let elapsed = now.duration_since(reg.last_refresh);
if elapsed >= reg.source.refresh_interval() {
reg.last_refresh = now;
}
let status = reg.source.get_status();
result.insert(reg.source.get_name().to_string(), status);
}
let val = Value::Object(result);
*self.last_status.write().unwrap() = val.clone();
val
}
pub fn get_last_status(&self) -> Value {
self.last_status.read().unwrap().clone()
}
#[deprecated(note = "was a no-op; use start_background() or run_status_loop()")]
pub fn start(&self, shutdown: &ShutdownHandler) {
*self.stop_flag.write().unwrap() = Some(shutdown.clone());
}
pub fn start_background(self: Arc<Self>, shutdown: &ShutdownHandler) {
self.start_background_supervised(shutdown, None);
}
pub fn start_background_supervised(
self: Arc<Self>,
shutdown: &ShutdownHandler,
heartbeat: Option<(Arc<HeartbeatEngine>, String)>,
) {
let interval = {
let sources = self.sources.read().unwrap();
sources
.iter()
.map(|s| s.source.refresh_interval())
.min()
.unwrap_or(Duration::from_secs(60))
.max(Duration::from_secs(5))
};
if let Some((engine, id)) = &heartbeat {
engine.register(id, Some(interval * 4));
}
let stop = shutdown.clone();
*self.stop_flag.write().unwrap() = Some(shutdown.clone());
thread::spawn(move || {
loop {
if self.stop_flag.read().unwrap().is_none() {
if let Some((engine, id)) = &heartbeat {
engine.cancel(id);
}
return;
}
self.collect();
if let Some((engine, id)) = &heartbeat {
engine.refresh(id);
}
log::debug!("StatusEngine collected: {}", self.get_last_status());
if stop.sleep(interval) {
if let Some((engine, id)) = &heartbeat {
engine.cancel(id);
}
return;
}
}
});
}
pub fn stop(&self) {
*self.stop_flag.write().unwrap() = None;
}
}
impl Default for StatusEngine {
fn default() -> Self {
Self::new()
}
}
pub fn run_status_loop(engine: Arc<StatusEngine>, shutdown: ShutdownHandler) {
let interval = Duration::from_secs(10);
thread::spawn(move || {
if shutdown.sleep(Duration::from_secs(10)) {
return;
}
loop {
engine.collect();
log::debug!("StatusEngine collected: {}", engine.get_last_status());
if shutdown.sleep(interval) {
return;
}
}
});
}
#[cfg(test)]
mod tests {
use super::*;
struct DummySource {
name: String,
value: Value,
interval: Duration,
}
impl StatusSource for DummySource {
fn get_status(&self) -> Value {
self.value.clone()
}
fn get_name(&self) -> &str {
&self.name
}
fn refresh_interval(&self) -> Duration {
self.interval
}
}
#[test]
fn test_register_and_collect() {
let engine = StatusEngine::new();
let source = Arc::new(DummySource {
name: "test".to_string(),
value: serde_json::json!({"ok": true}),
interval: Duration::from_secs(60),
});
engine.register_source(source);
let status = engine.collect();
assert_eq!(status["test"]["ok"], true);
}
#[test]
fn test_refresh_interval_respected() {
let engine = StatusEngine::new();
let source = Arc::new(DummySource {
name: "slow".to_string(),
value: serde_json::json!({"data": 1}),
interval: Duration::from_secs(3600),
});
engine.register_source(source);
let status = engine.collect();
assert_eq!(status["slow"]["data"], 1);
}
#[test]
fn test_multiple_sources() {
let engine = StatusEngine::new();
for i in 0..3 {
engine.register_source(Arc::new(DummySource {
name: format!("source_{}", i),
value: serde_json::json!({"id": i}),
interval: Duration::from_secs(60),
}));
}
let status = engine.collect();
for i in 0..3 {
assert_eq!(status[format!("source_{}", i)]["id"], i);
}
}
#[test]
fn test_unregister_source_removes_node_from_collect() {
let engine = StatusEngine::new();
for name in ["keep", "drop"] {
engine.register_source(Arc::new(DummySource {
name: name.to_string(),
value: serde_json::json!({"ok": true}),
interval: Duration::from_secs(60),
}));
}
assert!(engine.unregister_source("drop"));
assert!(!engine.unregister_source("drop"), "second removal must report false");
let status = engine.collect();
assert_eq!(status["keep"]["ok"], true);
assert!(status.get("drop").is_none(), "unregistered source must not be polled");
}
#[test]
fn test_unregister_source_removes_all_same_named() {
let engine = StatusEngine::new();
for _ in 0..2 {
engine.register_source(Arc::new(DummySource {
name: "dup".to_string(),
value: serde_json::json!({"ok": true}),
interval: Duration::from_secs(60),
}));
}
assert!(engine.unregister_source("dup"));
assert!(engine.collect().get("dup").is_none());
}
#[test]
fn test_get_last_status() {
let engine = StatusEngine::new();
let source = Arc::new(DummySource {
name: "test".to_string(),
value: serde_json::json!({"v": 42}),
interval: Duration::from_secs(60),
});
engine.register_source(source);
engine.collect();
let last = engine.get_last_status();
assert_eq!(last["test"]["v"], 42);
}
#[test]
fn test_start_background_collects_and_stop_ends_loop() {
use crate::shutdown::ShutdownHandler;
let engine = Arc::new(StatusEngine::new());
engine.register_source(Arc::new(DummySource {
name: "t".to_string(),
value: serde_json::json!({"v": 1}),
interval: Duration::from_secs(60),
}));
let shutdown = ShutdownHandler::new();
Arc::clone(&engine).start_background(&shutdown);
let deadline = std::time::Instant::now() + Duration::from_secs(2);
while engine.get_last_status()["t"]["v"] != 1 && std::time::Instant::now() < deadline {
thread::sleep(Duration::from_millis(10));
}
assert_eq!(engine.get_last_status()["t"]["v"], 1);
engine.stop();
shutdown.trigger(); }
#[test]
fn test_status_source_trait_for_diagnosis() {
use crate::diagnosis::{SelfDiagnosisEngine, Severity};
let engine = SelfDiagnosisEngine::new();
engine.notify(100, "test", Severity::Info);
let status = engine.get_status();
assert_eq!(status["Source name"], "RunTimeTests");
assert!(status["messages"].is_array());
}
#[test]
fn test_status_source_trait_for_heartbeat() {
use crate::heartbeat::HeartbeatEngine;
let engine = HeartbeatEngine::new(Duration::from_secs(300));
assert_eq!(engine.get_name(), "Heartbeat manager");
let status = engine.get_status();
assert!(status.is_object());
}
#[test]
fn test_status_source_trait_for_version() {
use crate::version::VersionInformation;
let v = VersionInformation::load("nonexistent.json");
assert_eq!(v.get_name(), "Version information");
let status = v.get_status();
assert_eq!(status["Version"]["value"], "dev");
assert_eq!(status["Version"]["type"], "string");
}
#[test]
fn test_status_value_wire_shapes() {
let b = serde_json::to_value(StatusValue::boolean(true)).unwrap();
assert_eq!(b, serde_json::json!({"value": true, "type": "bool", "hint": "lamp"}));
let d = serde_json::to_value(StatusValue::duration(90u64, "days")).unwrap();
assert_eq!(
d,
serde_json::json!({"value": 90, "type": "duration", "unit": "days", "hint": "duration"})
);
assert_eq!(StatusValue::bytes(1024u64).into_value()["unit"], "B");
assert_eq!(StatusValue::percent(80.0).into_value()["type"], "percent");
let t = StatusValue::text("hi").label("status.x.msg").into_value();
assert_eq!(t, serde_json::json!({"value": "hi", "type": "string", "label": "status.x.msg"}));
}
#[test]
fn test_status_value_embeds_in_json_and_source() {
let node = serde_json::json!({
"connected": StatusValue::boolean(true),
"rowsWritten": StatusValue::integer(42u64),
"plain": "unchanged",
});
assert_eq!(node["connected"]["type"], "bool");
assert_eq!(node["rowsWritten"]["value"], 42);
assert_eq!(node["plain"], "unchanged"); }
#[test]
fn test_supervised_background_registers_beats_and_deregisters() {
let engine = Arc::new(StatusEngine::new());
engine.register_source(Arc::new(Dummy));
let heartbeat = Arc::new(HeartbeatEngine::new(Duration::from_secs(60)));
let shutdown = ShutdownHandler::new();
Arc::clone(&engine).start_background_supervised(
&shutdown,
Some((Arc::clone(&heartbeat), "status-collector".to_string())),
);
let remaining = |hb: &HeartbeatEngine| -> Option<f64> {
hb.get_status()["status-collector"]["remaining_sec"].as_f64()
};
let first = remaining(&heartbeat).expect("collector must register itself");
assert!(
(first - 20.0).abs() < 1.0,
"expected a 20 s timeout (4 x 5 s), got {first}"
);
thread::sleep(Duration::from_millis(300));
let after_wait = remaining(&heartbeat).expect("still registered");
assert!(
after_wait < first,
"the deadline must approach while nothing beats"
);
assert!(
after_wait > first - 5.0,
"the collector must have beaten at least once at startup"
);
shutdown.trigger();
thread::sleep(Duration::from_millis(300));
assert!(
remaining(&heartbeat).is_none(),
"a collector that stopped on shutdown must deregister"
);
}
struct Dummy;
impl StatusSource for Dummy {
fn get_status(&self) -> Value {
serde_json::json!({"ok": true})
}
fn get_name(&self) -> &str {
"dummy"
}
fn refresh_interval(&self) -> Duration {
Duration::from_secs(5)
}
}
}