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, 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 {
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)
}
#[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 {
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 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.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> {
let value = value.into();
let mut normalized = String::with_capacity(value.len().min(MAX_HEALTH_MESSAGE_LENGTH));
let mut pending_space = false;
for character in value.chars() {
if character.is_control() || character.is_whitespace() {
pending_space = !normalized.is_empty();
continue;
}
let separator_length = usize::from(pending_space);
if normalized.len() + separator_length + character.len_utf8() > MAX_HEALTH_MESSAGE_LENGTH {
break;
}
if pending_space {
normalized.push(' ');
}
normalized.push(character);
pending_space = false;
}
(!normalized.is_empty()).then_some(normalized)
}
#[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)
}
}