footing 0.1.1

Feature-gated foundations for Rust backend services
Documentation
//! Health-check values and aggregate reports.

use std::fmt;

use serde::{Deserialize, Deserializer, Serialize};

use super::error::ObservabilityError;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
/// State of health.
pub enum HealthState {
    /// Indicates serving.
    Serving,
    /// The component is degraded.
    Degraded,
    /// Indicates unavailable.
    Unavailable,
}

impl HealthState {
    #[must_use]
    /// Returns the healthy.
    pub const fn healthy(self) -> bool {
        matches!(self, Self::Serving)
    }
}

#[derive(Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
/// Represents health check.
pub struct HealthCheck {
    name: String,
    state: HealthState,
    message: Option<String>,
}

impl fmt::Debug for HealthCheck {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("HealthCheck")
            .field("name", &self.name)
            .field("state", &self.state)
            .field("message", &self.message.as_ref().map(|_| "[REDACTED]"))
            .finish()
    }
}

impl HealthCheck {
    /// Creates a new instance.
    pub fn new(name: impl Into<String>, state: HealthState) -> Result<Self, ObservabilityError> {
        let name = normalize_health_name(name)?;
        Ok(Self {
            name,
            state,
            message: None,
        })
    }

    /// Creates serving.
    pub fn serving(name: impl Into<String>) -> Result<Self, ObservabilityError> {
        Self::new(name, HealthState::Serving)
    }

    #[must_use]
    /// Creates new lossy.
    pub fn new_lossy(name: impl Into<String>, state: HealthState) -> Self {
        Self {
            name: normalize_health_name(name).unwrap_or_else(|_| "component".to_owned()),
            state,
            message: None,
        }
    }

    #[must_use]
    /// Creates serving lossy.
    pub fn serving_lossy(name: impl Into<String>) -> Self {
        Self::new_lossy(name, HealthState::Serving)
    }

    /// Creates unavailable.
    pub fn unavailable(
        name: impl Into<String>,
        message: impl Into<String>,
    ) -> Result<Self, ObservabilityError> {
        Ok(Self::new(name, HealthState::Unavailable)?.with_message(message))
    }

    #[must_use]
    /// Configures message and returns the updated value.
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        let message = message.into();
        if !message.trim().is_empty() {
            self.message = Some(message);
        }
        self
    }

    #[must_use]
    /// Returns the name.
    pub fn name(&self) -> &str {
        &self.name
    }

    #[must_use]
    /// Returns the state.
    pub const fn state(&self) -> HealthState {
        self.state
    }

    #[must_use]
    /// Returns the message.
    pub fn message(&self) -> Option<&str> {
        self.message.as_deref()
    }
}

impl<'de> Deserialize<'de> for HealthCheck {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct HealthCheckWire {
            name: String,
            state: HealthState,
            message: Option<String>,
        }

        let wire = HealthCheckWire::deserialize(deserializer)?;
        let mut check = Self::new(wire.name, wire.state).map_err(serde::de::Error::custom)?;
        if let Some(message) = wire.message {
            check = check.with_message(message);
        }
        Ok(check)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
/// Report describing health.
pub struct HealthReport {
    service: String,
    state: HealthState,
    checks: Vec<HealthCheck>,
}

impl HealthReport {
    /// Creates a new instance.
    pub fn new(
        service: impl Into<String>,
        checks: Vec<HealthCheck>,
    ) -> Result<Self, ObservabilityError> {
        let service = normalize_health_name(service)?;
        let state = aggregate_health(&checks);
        Ok(Self {
            service,
            state,
            checks,
        })
    }

    /// Creates serving.
    pub fn serving(service: impl Into<String>) -> Result<Self, ObservabilityError> {
        Self::new(service, Vec::new())
    }

    #[must_use]
    /// Creates new lossy.
    pub fn new_lossy(service: impl Into<String>, checks: Vec<HealthCheck>) -> Self {
        let state = aggregate_health(&checks);
        Self {
            service: normalize_health_name(service).unwrap_or_else(|_| "service".to_owned()),
            state,
            checks,
        }
    }

    #[must_use]
    /// Creates serving lossy.
    pub fn serving_lossy(service: impl Into<String>) -> Self {
        Self::new_lossy(service, Vec::new())
    }

    #[must_use]
    /// Returns the service.
    pub fn service(&self) -> &str {
        &self.service
    }

    #[must_use]
    /// Returns the state.
    pub const fn state(&self) -> HealthState {
        self.state
    }

    #[must_use]
    /// Returns the checks.
    pub fn checks(&self) -> &[HealthCheck] {
        &self.checks
    }
}

impl<'de> Deserialize<'de> for HealthReport {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct HealthReportWire {
            service: String,
            #[serde(rename = "state")]
            #[serde(default)]
            _state: Option<HealthState>,
            #[serde(default)]
            checks: Vec<HealthCheck>,
        }

        let wire = HealthReportWire::deserialize(deserializer)?;
        Self::new(wire.service, wire.checks).map_err(serde::de::Error::custom)
    }
}

fn aggregate_health(checks: &[HealthCheck]) -> HealthState {
    checks
        .iter()
        .map(HealthCheck::state)
        .max()
        .unwrap_or(HealthState::Serving)
}

fn normalize_health_name(value: impl Into<String>) -> Result<String, ObservabilityError> {
    let value = value.into().trim().to_owned();
    if value.is_empty()
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
    {
        return Err(ObservabilityError::InvalidHealthName);
    }
    Ok(value)
}