footing 0.5.5

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;

/// Maximum supported health resource or service name length.
pub const MAX_HEALTH_NAME_LENGTH: usize = 128;
/// Maximum supported sanitized health-check message length.
pub const MAX_HEALTH_MESSAGE_LENGTH: usize = 1024;

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
/// State of health.
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub enum HealthState {
    /// Indicates serving.
    #[default]
    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.
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct HealthCheck {
    name: String,
    state: HealthState,
    #[cfg_attr(feature = "openapi", schema(required = true))]
    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)
    }

    /// 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 {
        self.message = normalize_health_message(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.
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
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]
    /// 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: 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.len() > MAX_HEALTH_NAME_LENGTH
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
    {
        return Err(ObservabilityError::InvalidHealthName);
    }
    Ok(value)
}

fn normalize_health_message(value: impl Into<String>) -> Option<String> {
    crate::text::normalize_message(value, MAX_HEALTH_MESSAGE_LENGTH)
}

#[cfg(feature = "diagnostics")]
impl From<&crate::diagnostics::ResourceDiagnosticsReport> for HealthReport {
    fn from(report: &crate::diagnostics::ResourceDiagnosticsReport) -> Self {
        let checks = report
            .resources()
            .iter()
            .map(|diagnostic| {
                let state = match diagnostic.status() {
                    crate::diagnostics::ResourceStatus::Healthy => HealthState::Serving,
                    crate::diagnostics::ResourceStatus::Degraded => HealthState::Degraded,
                    crate::diagnostics::ResourceStatus::Unhealthy
                    | crate::diagnostics::ResourceStatus::Unknown
                        if diagnostic.resource().criticality().required() =>
                    {
                        HealthState::Unavailable
                    }
                    crate::diagnostics::ResourceStatus::Unhealthy
                    | crate::diagnostics::ResourceStatus::Unknown => HealthState::Degraded,
                };
                HealthCheck {
                    name: diagnostic.resource().id().to_owned(),
                    state,
                    message: normalize_health_message(diagnostic.summary()),
                }
            })
            .collect::<Vec<_>>();
        let state = aggregate_health(&checks);
        Self {
            service: report.service_name().to_owned(),
            state,
            checks,
        }
    }
}

#[cfg(feature = "diagnostics")]
impl From<crate::diagnostics::ResourceDiagnosticsReport> for HealthReport {
    fn from(report: crate::diagnostics::ResourceDiagnosticsReport) -> Self {
        Self::from(&report)
    }
}