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]
pub enum HealthState {
Serving,
Degraded,
Unavailable,
}
impl HealthState {
#[must_use]
pub const fn healthy(self) -> bool {
matches!(self, Self::Serving)
}
}
#[derive(Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
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 {
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)
}
#[must_use]
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]
pub fn serving_lossy(name: impl Into<String>) -> Self {
Self::new_lossy(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 {
let message = message.into();
if !message.trim().is_empty() {
self.message = Some(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]
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 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]
pub fn serving_lossy(service: impl Into<String>) -> Self {
Self::new_lossy(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,
#[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)
}