use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use super::error::{Error, ErrorCode, Result};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HealthStatus {
pub healthy: bool,
pub status: String,
#[serde(default)]
pub details: BTreeMap<String, String>,
}
impl HealthStatus {
pub fn healthy(status: impl Into<String>) -> Self {
HealthStatus {
healthy: true,
status: status.into(),
details: BTreeMap::new(),
}
}
pub fn unhealthy(status: impl Into<String>) -> Self {
HealthStatus {
healthy: false,
status: status.into(),
details: BTreeMap::new(),
}
}
pub fn with_detail(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.details.insert(key.into(), value.into());
self
}
pub fn from_error(err: Error) -> Result<HealthStatus> {
match err.code() {
ErrorCode::Cancelled | ErrorCode::Config => Err(err),
_ => Ok(match err.http_status() {
None => HealthStatus::unhealthy("unreachable").with_detail("error", err.message()),
Some(status) => HealthStatus::unhealthy("unhealthy")
.with_detail("httpStatus", status.to_string()),
}),
}
}
}