use std::fmt;
use serde::{Deserialize, Deserializer, Serialize};
use super::error::ObservabilityError;
pub const MAX_HEALTH_NAME_LENGTH: usize = 128;
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]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub enum HealthState {
#[default]
Serving,
Degraded,
Unavailable,
}
impl HealthState {
#[must_use]
pub const fn healthy(self) -> bool {
matches!(self, Self::Serving)
}
}
#[derive(Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
#[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 {
pub fn new(name: impl Into<String>, state: HealthState) -> Result<Self, ObservabilityError> {
let name = normalize_health_name(name)?;
Ok(Self {
name,
state,
message: None,
})
}
pub fn serving(name: impl Into<String>) -> Result<Self, ObservabilityError> {
Self::new(name, HealthState::Serving)
}
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]
pub fn with_message(mut self, message: impl Into<String>) -> Self {
self.message = normalize_health_message(message);
self
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub const fn state(&self) -> HealthState {
self.state
}
#[must_use]
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]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct HealthReport {
service: String,
state: HealthState,
checks: Vec<HealthCheck>,
}
impl HealthReport {
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,
})
}
pub fn serving(service: impl Into<String>) -> Result<Self, ObservabilityError> {
Self::new(service, Vec::new())
}
#[must_use]
pub fn service(&self) -> &str {
&self.service
}
#[must_use]
pub const fn state(&self) -> HealthState {
self.state
}
#[must_use]
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,
state: HealthState,
checks: Vec<HealthCheck>,
}
let wire = HealthReportWire::deserialize(deserializer)?;
let report = Self::new(wire.service, wire.checks).map_err(serde::de::Error::custom)?;
if wire.state != report.state {
return Err(serde::de::Error::custom(
"health report state must match its checks",
));
}
Ok(report)
}
}
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)
}
}