use std::{borrow::Cow, collections::BTreeMap, fmt, future::Future, sync::Arc, time::Duration};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::result::{BoxError, ClassifyError, ErrorKind};
pub const MAX_RESOURCE_ID_LENGTH: usize = 128;
pub const MAX_RESOURCE_NAME_LENGTH: usize = 128;
pub const MAX_RESOURCE_LABEL_KEY_LENGTH: usize = 64;
pub const MAX_RESOURCE_LABEL_VALUE_LENGTH: usize = 256;
pub const MAX_RESOURCE_MESSAGE_LENGTH: usize = 1024;
pub const DEFAULT_RESOURCE_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
pub enum ResourceKind {
Configuration,
Database,
Filesystem,
Cryptography,
Http,
Ldap,
Messaging,
Worker,
External,
Other,
}
impl ResourceKind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Configuration => "configuration",
Self::Database => "database",
Self::Filesystem => "filesystem",
Self::Cryptography => "cryptography",
Self::Http => "http",
Self::Ldap => "ldap",
Self::Messaging => "messaging",
Self::Worker => "worker",
Self::External => "external",
Self::Other => "other",
}
}
}
impl fmt::Display for ResourceKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
pub enum ResourceCriticality {
Required,
Optional,
}
impl ResourceCriticality {
#[must_use]
pub const fn required(self) -> bool {
matches!(self, Self::Required)
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Required => "required",
Self::Optional => "optional",
}
}
}
impl fmt::Display for ResourceCriticality {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
pub enum ResourceStatus {
Healthy,
Degraded,
Unhealthy,
Unknown,
}
impl ResourceStatus {
#[must_use]
pub const fn healthy(self) -> bool {
matches!(self, Self::Healthy)
}
#[must_use]
pub const fn unhealthy(self) -> bool {
matches!(self, Self::Unhealthy)
}
#[must_use]
pub const fn degraded(self) -> bool {
matches!(self, Self::Degraded)
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Healthy => "healthy",
Self::Degraded => "degraded",
Self::Unhealthy => "unhealthy",
Self::Unknown => "unknown",
}
}
}
impl fmt::Display for ResourceStatus {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "ResourceDescriptorWire")]
#[non_exhaustive]
pub struct ResourceDescriptor {
pub id: String,
pub name: String,
pub kind: ResourceKind,
pub criticality: ResourceCriticality,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub labels: BTreeMap<String, String>,
}
impl fmt::Debug for ResourceDescriptor {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ResourceDescriptor")
.field("id", &self.id)
.field("name", &self.name)
.field("kind", &self.kind)
.field("criticality", &self.criticality)
.field("label_count", &self.labels.len())
.finish()
}
}
impl ResourceDescriptor {
pub fn required(
id: impl Into<String>,
name: impl Into<String>,
kind: ResourceKind,
) -> Result<Self, ResourceDescriptorError> {
Self::new(id, name, kind, ResourceCriticality::Required)
}
pub fn optional(
id: impl Into<String>,
name: impl Into<String>,
kind: ResourceKind,
) -> Result<Self, ResourceDescriptorError> {
Self::new(id, name, kind, ResourceCriticality::Optional)
}
pub fn new(
id: impl Into<String>,
name: impl Into<String>,
kind: ResourceKind,
criticality: ResourceCriticality,
) -> Result<Self, ResourceDescriptorError> {
Ok(Self {
id: normalize_resource_id(id)?,
name: normalize_resource_name(name)?,
kind,
criticality,
labels: BTreeMap::new(),
})
}
pub fn with_label(
mut self,
key: impl Into<String>,
value: impl Into<String>,
) -> Result<Self, ResourceDescriptorError> {
let key = normalize_resource_label_key(key)?;
let value = normalize_resource_label_value(&key, value)?;
self.labels.insert(key, value);
Ok(self)
}
fn validate(&self) -> Result<(), ResourceDescriptorError> {
normalize_resource_id(&self.id)?;
normalize_resource_name(&self.name)?;
for (key, value) in &self.labels {
normalize_resource_label_key(key)?;
normalize_resource_label_value(key, value)?;
}
Ok(())
}
}
#[derive(Deserialize)]
struct ResourceDescriptorWire {
id: String,
name: String,
kind: ResourceKind,
criticality: ResourceCriticality,
#[serde(default)]
labels: BTreeMap<String, String>,
}
impl TryFrom<ResourceDescriptorWire> for ResourceDescriptor {
type Error = ResourceDescriptorError;
fn try_from(value: ResourceDescriptorWire) -> Result<Self, Self::Error> {
let mut descriptor = Self::new(value.id, value.name, value.kind, value.criticality)?;
for (key, value) in value.labels {
descriptor = descriptor.with_label(key, value)?;
}
Ok(descriptor)
}
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "ResourceDiagnosticWire")]
#[non_exhaustive]
pub struct ResourceDiagnostic {
pub resource: ResourceDescriptor,
pub status: ResourceStatus,
pub summary: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub remediations: Vec<String>,
}
impl fmt::Debug for ResourceDiagnostic {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ResourceDiagnostic")
.field("resource", &self.resource)
.field("status", &self.status)
.field("summary", &"[REDACTED]")
.field("detail_count", &self.details.len())
.field("remediation_count", &self.remediations.len())
.finish()
}
}
impl ResourceDiagnostic {
#[must_use]
pub fn healthy(resource: ResourceDescriptor, summary: impl Into<String>) -> Self {
Self::new(resource, ResourceStatus::Healthy, summary)
}
#[must_use]
pub fn degraded(resource: ResourceDescriptor, summary: impl Into<String>) -> Self {
Self::new(resource, ResourceStatus::Degraded, summary)
}
#[must_use]
pub fn unhealthy(resource: ResourceDescriptor, summary: impl Into<String>) -> Self {
Self::new(resource, ResourceStatus::Unhealthy, summary)
}
#[must_use]
pub fn unknown(resource: ResourceDescriptor, summary: impl Into<String>) -> Self {
Self::new(resource, ResourceStatus::Unknown, summary)
}
#[must_use]
pub fn new(
resource: ResourceDescriptor,
status: ResourceStatus,
summary: impl Into<String>,
) -> Self {
Self {
resource,
status,
summary: normalize_message(summary, "resource diagnostic completed"),
details: Vec::new(),
remediations: Vec::new(),
}
}
#[must_use]
pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
if let Some(detail) = normalize_optional_message(detail) {
self.details.push(detail);
}
self
}
#[must_use]
pub fn with_remediation(mut self, remediation: impl Into<String>) -> Self {
if let Some(remediation) = normalize_optional_message(remediation) {
self.remediations.push(remediation);
}
self
}
#[must_use]
pub const fn readiness_blocking(&self) -> bool {
self.resource.criticality.required()
&& matches!(
self.status,
ResourceStatus::Unhealthy | ResourceStatus::Unknown
)
}
}
#[derive(Deserialize)]
struct ResourceDiagnosticWire {
resource: ResourceDescriptor,
status: ResourceStatus,
summary: String,
#[serde(default)]
details: Vec<String>,
#[serde(default)]
remediations: Vec<String>,
}
impl TryFrom<ResourceDiagnosticWire> for ResourceDiagnostic {
type Error = ResourceDescriptorError;
fn try_from(value: ResourceDiagnosticWire) -> Result<Self, Self::Error> {
value.resource.validate()?;
let mut diagnostic = ResourceDiagnostic::new(value.resource, value.status, value.summary);
for detail in value.details {
diagnostic = diagnostic.with_detail(detail);
}
for remediation in value.remediations {
diagnostic = diagnostic.with_remediation(remediation);
}
Ok(diagnostic)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "ResourceDiagnosticsReportWire")]
#[non_exhaustive]
pub struct ResourceDiagnosticsReport {
pub service_name: String,
pub status: ResourceStatus,
pub summary: ResourceDiagnosticsSummary,
pub resources: Vec<ResourceDiagnostic>,
}
impl ResourceDiagnosticsReport {
pub fn new(
service_name: impl Into<String>,
resources: Vec<ResourceDiagnostic>,
) -> Result<Self, ResourceRegistryError> {
let service_name = normalize_diagnostics_service_name(service_name)
.map_err(|_| ResourceRegistryError::InvalidServiceName)?;
for (index, diagnostic) in resources.iter().enumerate() {
diagnostic
.resource
.validate()
.map_err(|source| ResourceRegistryError::InvalidDescriptor { index, source })?;
}
let status = aggregate_status(&resources);
let summary = ResourceDiagnosticsSummary::from_diagnostics(&resources);
Ok(Self {
service_name,
status,
summary,
resources,
})
}
#[must_use]
pub fn ready(&self) -> bool {
self.resources
.iter()
.all(|diagnostic| !diagnostic.readiness_blocking())
}
#[must_use]
pub fn readiness_blockers(&self) -> Vec<&ResourceDiagnostic> {
self.resources
.iter()
.filter(|diagnostic| diagnostic.readiness_blocking())
.collect()
}
}
#[derive(Deserialize)]
struct ResourceDiagnosticsReportWire {
service_name: String,
#[serde(default, rename = "status")]
_status: Option<ResourceStatus>,
#[serde(default, rename = "summary")]
_summary: Option<ResourceDiagnosticsSummary>,
#[serde(default)]
resources: Vec<ResourceDiagnostic>,
}
impl TryFrom<ResourceDiagnosticsReportWire> for ResourceDiagnosticsReport {
type Error = ResourceRegistryError;
fn try_from(value: ResourceDiagnosticsReportWire) -> Result<Self, Self::Error> {
Self::new(value.service_name, value.resources)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ResourceDiagnosticsSummary {
pub total: usize,
pub healthy: usize,
pub degraded: usize,
pub unhealthy: usize,
pub unknown: usize,
pub readiness_blocking: usize,
}
impl ResourceDiagnosticsSummary {
#[must_use]
fn from_diagnostics(resources: &[ResourceDiagnostic]) -> Self {
let mut summary = Self {
total: resources.len(),
..Self::default()
};
for diagnostic in resources {
match diagnostic.status {
ResourceStatus::Healthy => summary.healthy += 1,
ResourceStatus::Degraded => summary.degraded += 1,
ResourceStatus::Unhealthy => summary.unhealthy += 1,
ResourceStatus::Unknown => summary.unknown += 1,
}
if diagnostic.readiness_blocking() {
summary.readiness_blocking += 1;
}
}
summary
}
}
#[async_trait]
pub trait ResourceProbe: Send + Sync + 'static {
fn descriptor(&self) -> ResourceDescriptor;
async fn probe(&self) -> Result<ResourceDiagnostic, BoxError>;
}
#[must_use]
pub fn static_resource_probe(
descriptor: ResourceDescriptor,
diagnostic: fn(ResourceDescriptor, String) -> ResourceDiagnostic,
summary: impl Into<String>,
) -> Arc<dyn ResourceProbe> {
let summary = summary.into();
resource_probe(descriptor, move |descriptor| {
let summary = summary.clone();
async move { Ok(diagnostic(descriptor, summary)) }
})
}
#[must_use]
pub fn resource_probe<F, Fut>(descriptor: ResourceDescriptor, probe: F) -> Arc<dyn ResourceProbe>
where
F: Fn(ResourceDescriptor) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<ResourceDiagnostic, BoxError>> + Send + 'static,
{
Arc::new(FnResourceProbe { descriptor, probe })
}
#[derive(Clone)]
pub struct ResourceRegistry {
service_name: String,
probes: Vec<Arc<dyn ResourceProbe>>,
probe_timeout: Duration,
}
impl ResourceRegistry {
pub fn new(service_name: impl Into<String>) -> Result<Self, ResourceRegistryError> {
Ok(Self {
service_name: normalize_diagnostics_service_name(service_name)
.map_err(|_| ResourceRegistryError::InvalidServiceName)?,
probes: Vec::new(),
probe_timeout: DEFAULT_RESOURCE_PROBE_TIMEOUT,
})
}
#[must_use]
pub const fn with_probe_timeout(mut self, probe_timeout: Duration) -> Self {
self.probe_timeout = probe_timeout;
self
}
#[must_use]
pub fn with_probe(mut self, probe: Arc<dyn ResourceProbe>) -> Self {
self.probes.push(probe);
self
}
pub fn push_probe(&mut self, probe: Arc<dyn ResourceProbe>) {
self.probes.push(probe);
}
#[must_use]
pub fn probes(&self) -> &[Arc<dyn ResourceProbe>] {
&self.probes
}
#[must_use]
pub const fn probe_timeout(&self) -> Duration {
self.probe_timeout
}
pub fn validate(&self) -> Result<(), ResourceRegistryError> {
normalize_diagnostics_service_name(&self.service_name)
.map_err(|_| ResourceRegistryError::InvalidServiceName)?;
if self.probe_timeout.is_zero() {
return Err(ResourceRegistryError::InvalidProbeTimeout);
}
let mut seen = BTreeMap::<String, usize>::new();
for (index, probe) in self.probes.iter().enumerate() {
let descriptor = probe.descriptor();
descriptor
.validate()
.map_err(|source| ResourceRegistryError::InvalidDescriptor { index, source })?;
if let Some(first_index) = seen.insert(descriptor.id.clone(), index) {
return Err(ResourceRegistryError::DuplicateResourceId {
id: descriptor.id,
first_index,
second_index: index,
});
}
}
Ok(())
}
pub async fn run(&self) -> Result<ResourceDiagnosticsReport, BoxError> {
self.validate()?;
let mut diagnostics = Vec::with_capacity(self.probes.len());
for probe in &self.probes {
let descriptor = probe.descriptor();
match tokio::time::timeout(self.probe_timeout, probe.probe()).await {
Ok(Ok(mut diagnostic)) => {
diagnostic.resource = descriptor;
diagnostics.push(diagnostic);
}
Ok(Err(_)) => diagnostics.push(ResourceDiagnostic::unhealthy(
descriptor,
"resource probe failed",
)),
Err(_) => diagnostics.push(ResourceDiagnostic::unhealthy(
descriptor,
"resource probe timed out",
)),
}
}
Ok(ResourceDiagnosticsReport::new(
self.service_name.clone(),
diagnostics,
)?)
}
}
impl fmt::Debug for ResourceRegistry {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ResourceRegistry")
.field("service_name", &self.service_name)
.field("probes", &self.probes.len())
.field("probe_timeout", &self.probe_timeout)
.finish()
}
}
impl Default for ResourceRegistry {
fn default() -> Self {
Self {
service_name: String::new(),
probes: Vec::new(),
probe_timeout: DEFAULT_RESOURCE_PROBE_TIMEOUT,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum ResourceRegistryError {
#[error(
"resource diagnostic service name must be non-empty and contain only ASCII letters, digits, '-', '_', '.', or ':'"
)]
InvalidServiceName,
#[error("resource diagnostic probe timeout must be greater than zero")]
InvalidProbeTimeout,
#[error("resource diagnostic probe at index {index} has invalid descriptor")]
InvalidDescriptor {
index: usize,
#[source]
source: ResourceDescriptorError,
},
#[error("duplicate resource diagnostic id {id} at indexes {first_index} and {second_index}")]
DuplicateResourceId {
id: String,
first_index: usize,
second_index: usize,
},
}
impl ClassifyError for ResourceRegistryError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> Cow<'static, str> {
Cow::Borrowed(match self {
Self::InvalidServiceName => "resource_diagnostics_invalid_service_name",
Self::InvalidProbeTimeout => "resource_diagnostics_invalid_probe_timeout",
Self::InvalidDescriptor { .. } => "resource_diagnostics_invalid_descriptor",
Self::DuplicateResourceId { .. } => "resource_diagnostics_duplicate_resource_id",
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum ResourceDescriptorError {
#[error("resource diagnostic id must not be empty")]
EmptyId,
#[error("resource diagnostic id must be less than or equal to {max} bytes")]
IdTooLong {
#[doc = "The configured upper bound."]
max: usize,
},
#[error(
"resource diagnostic id must contain only ASCII letters, digits, '-', '_', '.', or ':'"
)]
InvalidId,
#[error("resource diagnostic name must not be empty")]
EmptyName,
#[error("resource diagnostic name must be less than or equal to {max} bytes")]
NameTooLong {
#[doc = "The configured upper bound."]
max: usize,
},
#[error("resource diagnostic name must not contain control characters")]
InvalidName,
#[error("resource diagnostic label key must not be empty")]
EmptyLabelKey,
#[error("resource diagnostic label key must be less than or equal to {max} bytes")]
LabelKeyTooLong {
#[doc = "The configured upper bound."]
max: usize,
},
#[error(
"resource diagnostic label key must contain only ASCII letters, digits, '-', '_', '.', or ':'"
)]
InvalidLabelKey,
#[error("resource diagnostic label {key} value must not be empty")]
EmptyLabelValue {
#[doc = "The associated key."]
key: String,
},
#[error("resource diagnostic label {key} value must be less than or equal to {max} bytes")]
LabelValueTooLong {
#[doc = "The associated key."]
key: String,
#[doc = "The configured upper bound."]
max: usize,
},
#[error("resource diagnostic label {key} value must not contain control characters")]
InvalidLabelValue {
#[doc = "The associated key."]
key: String,
},
}
impl ClassifyError for ResourceDescriptorError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> Cow<'static, str> {
Cow::Borrowed(match self {
Self::EmptyId => "resource_descriptor_empty_id",
Self::IdTooLong { .. } => "resource_descriptor_id_too_long",
Self::InvalidId => "resource_descriptor_invalid_id",
Self::EmptyName => "resource_descriptor_empty_name",
Self::NameTooLong { .. } => "resource_descriptor_name_too_long",
Self::InvalidName => "resource_descriptor_invalid_name",
Self::EmptyLabelKey => "resource_descriptor_empty_label_key",
Self::LabelKeyTooLong { .. } => "resource_descriptor_label_key_too_long",
Self::InvalidLabelKey => "resource_descriptor_invalid_label_key",
Self::EmptyLabelValue { .. } => "resource_descriptor_empty_label_value",
Self::LabelValueTooLong { .. } => "resource_descriptor_label_value_too_long",
Self::InvalidLabelValue { .. } => "resource_descriptor_invalid_label_value",
})
}
}
struct FnResourceProbe<F> {
descriptor: ResourceDescriptor,
probe: F,
}
#[async_trait]
impl<F, Fut> ResourceProbe for FnResourceProbe<F>
where
F: Fn(ResourceDescriptor) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<ResourceDiagnostic, BoxError>> + Send + 'static,
{
fn descriptor(&self) -> ResourceDescriptor {
self.descriptor.clone()
}
async fn probe(&self) -> Result<ResourceDiagnostic, BoxError> {
(self.probe)(self.descriptor.clone()).await
}
}
fn aggregate_status(resources: &[ResourceDiagnostic]) -> ResourceStatus {
if resources.iter().any(|diagnostic| {
diagnostic.resource.criticality.required() && diagnostic.status == ResourceStatus::Unhealthy
}) {
return ResourceStatus::Unhealthy;
}
if resources
.iter()
.any(|diagnostic| diagnostic.status == ResourceStatus::Unknown)
{
return ResourceStatus::Unknown;
}
if resources
.iter()
.any(|diagnostic| diagnostic.status == ResourceStatus::Unhealthy)
{
return ResourceStatus::Degraded;
}
if resources
.iter()
.any(|diagnostic| diagnostic.status == ResourceStatus::Degraded)
{
return ResourceStatus::Degraded;
}
ResourceStatus::Healthy
}
fn normalize_diagnostics_service_name(
value: impl Into<String>,
) -> Result<String, ResourceRegistryError> {
let value = value.into().trim().to_owned();
if valid_identifier(&value) {
Ok(value)
} else {
Err(ResourceRegistryError::InvalidServiceName)
}
}
fn normalize_resource_id(value: impl Into<String>) -> Result<String, ResourceDescriptorError> {
let value = value.into().trim().to_owned();
if value.is_empty() {
return Err(ResourceDescriptorError::EmptyId);
}
if value.len() > MAX_RESOURCE_ID_LENGTH {
return Err(ResourceDescriptorError::IdTooLong {
max: MAX_RESOURCE_ID_LENGTH,
});
}
if !valid_identifier(&value) {
return Err(ResourceDescriptorError::InvalidId);
}
Ok(value)
}
fn normalize_resource_name(value: impl Into<String>) -> Result<String, ResourceDescriptorError> {
let value = value.into().trim().to_owned();
if value.is_empty() {
return Err(ResourceDescriptorError::EmptyName);
}
if value.len() > MAX_RESOURCE_NAME_LENGTH {
return Err(ResourceDescriptorError::NameTooLong {
max: MAX_RESOURCE_NAME_LENGTH,
});
}
if value.chars().any(char::is_control) {
return Err(ResourceDescriptorError::InvalidName);
}
Ok(value)
}
fn normalize_resource_label_key(
value: impl Into<String>,
) -> Result<String, ResourceDescriptorError> {
let value = value.into().trim().to_owned();
if value.is_empty() {
return Err(ResourceDescriptorError::EmptyLabelKey);
}
if value.len() > MAX_RESOURCE_LABEL_KEY_LENGTH {
return Err(ResourceDescriptorError::LabelKeyTooLong {
max: MAX_RESOURCE_LABEL_KEY_LENGTH,
});
}
if !valid_identifier(&value) {
return Err(ResourceDescriptorError::InvalidLabelKey);
}
Ok(value)
}
fn normalize_resource_label_value(
key: &str,
value: impl Into<String>,
) -> Result<String, ResourceDescriptorError> {
let value = value.into().trim().to_owned();
if value.is_empty() {
return Err(ResourceDescriptorError::EmptyLabelValue {
key: key.to_owned(),
});
}
if value.len() > MAX_RESOURCE_LABEL_VALUE_LENGTH {
return Err(ResourceDescriptorError::LabelValueTooLong {
key: key.to_owned(),
max: MAX_RESOURCE_LABEL_VALUE_LENGTH,
});
}
if value.chars().any(char::is_control) {
return Err(ResourceDescriptorError::InvalidLabelValue {
key: key.to_owned(),
});
}
Ok(value)
}
fn valid_identifier(value: &str) -> bool {
!value.is_empty()
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
}
fn normalize_message(value: impl Into<String>, fallback: &str) -> String {
let mut value = value
.into()
.trim()
.chars()
.filter(|character| !character.is_control())
.collect::<String>();
if value.is_empty() {
fallback.to_owned()
} else {
truncate_resource_message(&mut value);
value
}
}
fn normalize_optional_message(value: impl Into<String>) -> Option<String> {
let mut value = value
.into()
.trim()
.chars()
.filter(|character| !character.is_control())
.collect::<String>();
if value.is_empty() {
return None;
}
truncate_resource_message(&mut value);
Some(value)
}
fn truncate_resource_message(value: &mut String) {
if value.len() <= MAX_RESOURCE_MESSAGE_LENGTH {
return;
}
value.truncate(MAX_RESOURCE_MESSAGE_LENGTH);
while !value.is_char_boundary(value.len()) {
value.pop();
}
}
#[cfg(test)]
mod tests {
use super::*;
fn registry() -> ResourceRegistry {
ResourceRegistry::new("example_service").expect("static service name is valid")
}
fn required(id: &str, name: &str, kind: ResourceKind) -> ResourceDescriptor {
ResourceDescriptor::required(id, name, kind).expect("static descriptor is valid")
}
fn optional(id: &str, name: &str, kind: ResourceKind) -> ResourceDescriptor {
ResourceDescriptor::optional(id, name, kind).expect("static descriptor is valid")
}
#[tokio::test]
async fn registry_runs_static_probes_and_rolls_up_status() {
let registry = registry()
.with_probe(static_resource_probe(
required("contracts", "HTTP Contracts", ResourceKind::Configuration),
ResourceDiagnostic::healthy,
"contracts are valid",
))
.with_probe(static_resource_probe(
optional("smtp", "SMTP", ResourceKind::Messaging),
ResourceDiagnostic::degraded,
"SMTP is not configured",
));
let report = registry.run().await.expect("diagnostics should run");
assert!(report.ready());
assert_eq!(report.status, ResourceStatus::Degraded);
assert_eq!(report.summary.total, 2);
assert_eq!(report.summary.healthy, 1);
assert_eq!(report.summary.degraded, 1);
}
#[tokio::test]
async fn registry_runs_closure_probes_with_captured_state() {
let expected_schema_version = 1;
let registry = registry().with_probe(resource_probe(
required("contracts", "HTTP Contracts", ResourceKind::Http),
move |resource| async move {
Ok(ResourceDiagnostic::healthy(resource, "contracts are valid")
.with_detail(format!("schema_version={expected_schema_version}")))
},
));
let report = registry.run().await.expect("diagnostics should run");
assert!(report.ready());
assert_eq!(report.status, ResourceStatus::Healthy);
assert_eq!(report.resources[0].details, ["schema_version=1".to_owned()]);
}
#[tokio::test]
async fn required_unhealthy_resource_blocks_readiness() {
let registry = registry().with_probe(static_resource_probe(
required("oidc-key", "OIDC Key", ResourceKind::Cryptography),
ResourceDiagnostic::unhealthy,
"signing key is missing",
));
let report = registry.run().await.expect("diagnostics should run");
assert!(!report.ready());
assert_eq!(report.status, ResourceStatus::Unhealthy);
assert_eq!(report.summary.readiness_blocking, 1);
assert_eq!(report.readiness_blockers()[0].resource.id, "oidc-key");
}
#[tokio::test]
async fn required_unknown_resource_blocks_readiness() {
let registry = registry().with_probe(static_resource_probe(
required("database", "Database", ResourceKind::Database),
ResourceDiagnostic::unknown,
"database health was not checked",
));
let report = registry.run().await.expect("diagnostics should run");
assert!(!report.ready());
assert_eq!(report.status, ResourceStatus::Unknown);
assert_eq!(report.summary.readiness_blocking, 1);
}
#[tokio::test]
async fn registry_rejects_duplicate_resource_ids() {
let descriptor = required("config", "Configuration", ResourceKind::Configuration);
let registry = registry()
.with_probe(static_resource_probe(
descriptor.clone(),
ResourceDiagnostic::healthy,
"ok",
))
.with_probe(static_resource_probe(
descriptor,
ResourceDiagnostic::healthy,
"ok",
));
assert!(matches!(
registry.run().await,
Err(error) if error.to_string().contains("duplicate resource diagnostic id")
));
}
#[tokio::test]
async fn registry_rejects_empty_service_name() {
assert!(matches!(
ResourceRegistry::new(" "),
Err(ResourceRegistryError::InvalidServiceName)
));
}
#[tokio::test]
async fn registry_anchors_probe_results_to_registered_descriptor() {
let registry = registry().with_probe(resource_probe(
required("database", "Database", ResourceKind::Database),
|_| async move {
Ok(ResourceDiagnostic::healthy(
optional("other", "Other", ResourceKind::Other),
"database is reachable",
))
},
));
let report = registry.run().await.expect("diagnostics should run");
assert_eq!(report.resources[0].resource.id, "database");
assert_eq!(report.resources[0].resource.name, "Database");
assert_eq!(
report.resources[0].resource.criticality,
ResourceCriticality::Required
);
assert_eq!(report.resources[0].summary, "database is reachable");
}
#[tokio::test]
async fn registry_bounds_each_probe_and_reports_timeout() {
let registry =
registry()
.with_probe_timeout(Duration::from_millis(1))
.with_probe(resource_probe(
required("database", "Database", ResourceKind::Database),
|_| async move {
std::future::pending::<Result<ResourceDiagnostic, BoxError>>().await
},
));
let report = registry
.run()
.await
.expect("timeout should become a diagnostic");
assert!(!report.ready());
assert_eq!(report.resources[0].summary, "resource probe timed out");
assert!(report.resources[0].details.is_empty());
}
#[tokio::test]
async fn registry_does_not_copy_probe_errors_into_serialized_reports() {
let private_detail = "private-probe-error";
let registry = registry().with_probe(resource_probe(
required("database", "Database", ResourceKind::Database),
move |_| async move {
Err::<ResourceDiagnostic, BoxError>(Box::new(std::io::Error::other(private_detail)))
},
));
let report = registry
.run()
.await
.expect("failure should become a diagnostic");
let wire = serde_json::to_string(&report).expect("report should serialize");
assert_eq!(report.resources[0].summary, "resource probe failed");
assert!(report.resources[0].details.is_empty());
assert!(!wire.contains(private_detail));
}
#[tokio::test]
async fn registry_rejects_zero_probe_timeout() {
let error = registry()
.with_probe_timeout(Duration::ZERO)
.run()
.await
.expect_err("zero timeout should fail validation");
assert_eq!(
error.to_string(),
"resource diagnostic probe timeout must be greater than zero"
);
}
#[test]
fn descriptor_construction_and_deserialization_share_validation() {
assert!(matches!(
ResourceDescriptor::required("", "Database", ResourceKind::Database),
Err(ResourceDescriptorError::EmptyId)
));
assert!(matches!(
ResourceDescriptor::required("bad id", "Database", ResourceKind::Database),
Err(ResourceDescriptorError::InvalidId)
));
assert!(matches!(
required("database", "Database", ResourceKind::Database).with_label("", "true"),
Err(ResourceDescriptorError::EmptyLabelKey)
));
assert!(
serde_json::from_value::<ResourceDescriptor>(serde_json::json!({
"id": "",
"name": "Database",
"kind": "database",
"criticality": "required"
}))
.is_err()
);
}
#[test]
fn diagnostic_debug_redacts_labels_and_operator_messages_without_changing_wire_data() {
let label = "private-resource-label";
let summary = "private-resource-summary";
let detail = "private-resource-detail";
let remediation = "private-resource-remediation";
let descriptor = required("database", "Database", ResourceKind::Database)
.with_label("endpoint", label)
.expect("resource label should validate");
let diagnostic = ResourceDiagnostic::unhealthy(descriptor, summary)
.with_detail(detail)
.with_remediation(remediation);
let output = format!("{diagnostic:?}");
assert!(output.contains("label_count"));
for sensitive in [label, summary, detail, remediation] {
assert!(!output.contains(sensitive));
}
let wire = serde_json::to_value(&diagnostic).expect("diagnostic should serialize");
assert_eq!(wire["resource"]["labels"]["endpoint"], label);
assert_eq!(wire["summary"], summary);
assert_eq!(wire["details"][0], detail);
assert_eq!(wire["remediations"][0], remediation);
}
#[test]
fn report_deserialization_recomputes_status_and_summary() {
let value = serde_json::json!({
"service_name": "example_service",
"status": "healthy",
"summary": {
"total": 0,
"healthy": 0,
"degraded": 0,
"unhealthy": 0,
"unknown": 0,
"readiness_blocking": 0
},
"resources": [{
"resource": {
"id": "database",
"name": "Database",
"kind": "database",
"criticality": "required"
},
"status": "unhealthy",
"summary": "database is unavailable"
}]
});
let report: ResourceDiagnosticsReport =
serde_json::from_value(value).expect("report JSON should deserialize");
assert_eq!(report.status, ResourceStatus::Unhealthy);
assert_eq!(report.summary.total, 1);
assert_eq!(report.summary.readiness_blocking, 1);
}
}