use std::{collections::BTreeMap, fmt, time::Duration};
use serde::{Deserialize, Serialize};
use super::error::{ResourceDescriptorError, ResourceRegistryError};
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)
}
pub(super) 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
}
}
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
}
pub(super) 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();
}
}