robotrt-obs-core 0.1.0-beta.2

RobotRT modular robotics runtime and middleware components.
Documentation
use core_types::Timestamp;

use crate::{
    alert::{Alert, AlertSeverity},
    aggregator::MetricsAggregator,
    bus::AlertBus,
};

/// Bridges a [`crate::aggregator::MetricsAggregator`] health report to the alert bus.
///
/// On each call to [`HealthWatcher::poll`] the watcher queries the aggregator's
/// health report and fires an alert for any component that is `Degraded` or
/// `Unhealthy`.
pub struct HealthWatcher {
    pub name: String,
}

impl HealthWatcher {
    pub fn new(name: impl Into<String>) -> Self {
        Self { name: name.into() }
    }

    /// Poll the aggregator and fire alerts for degraded / unhealthy components.
    /// Returns the number of alerts fired.
    pub fn poll(&self, agg: &MetricsAggregator, bus: &mut AlertBus, now: Timestamp) -> usize {
        use core_types::HealthStatus;

        let report = agg.health_report();
        let mut n = 0;
        for comp in &report.components {
            let (severity, reason) = match &comp.status {
                HealthStatus::Healthy => continue,
                HealthStatus::Degraded { reason } => (AlertSeverity::Warn, reason.clone()),
                HealthStatus::Unhealthy { reason } => (AlertSeverity::Error, reason.clone()),
            };
            bus.fire(Alert::new(
                comp.name.clone(),
                format!("{}_HEALTH", comp.name.to_uppercase()),
                reason,
                severity,
                now,
            ));
            n += 1;
        }
        n
    }
}