use std::fmt;
pub const MAX_DIAGNOSTIC_FIELD_LENGTH: usize = 512;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DiagnosticKind {
InvalidConfiguration,
AuthenticationFailed,
PermissionDenied,
ResourceMissing,
ResourceConflict,
Unavailable,
CapacityExhausted,
StateMismatch,
ExecutionFailed,
Unknown,
}
impl DiagnosticKind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::InvalidConfiguration => "invalid_configuration",
Self::AuthenticationFailed => "authentication_failed",
Self::PermissionDenied => "permission_denied",
Self::ResourceMissing => "resource_missing",
Self::ResourceConflict => "resource_conflict",
Self::Unavailable => "unavailable",
Self::CapacityExhausted => "capacity_exhausted",
Self::StateMismatch => "state_mismatch",
Self::ExecutionFailed => "execution_failed",
Self::Unknown => "unknown",
}
}
}
impl fmt::Display for DiagnosticKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Remediation {
summary: String,
}
impl fmt::Debug for Remediation {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("Remediation([REDACTED])")
}
}
impl Remediation {
#[must_use]
pub fn new(summary: impl Into<String>) -> Self {
Self {
summary: bounded_text(summary),
}
}
#[must_use]
pub fn summary(&self) -> &str {
&self.summary
}
}
impl fmt::Display for Remediation {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.summary())
}
}
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Diagnostic {
component: String,
operation: String,
resource: Option<String>,
kind: DiagnosticKind,
message: String,
remediation: Option<Remediation>,
retryable: bool,
}
impl fmt::Debug for Diagnostic {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Diagnostic")
.field("component", &self.component)
.field("operation", &self.operation)
.field("kind", &self.kind)
.field("resource", &self.resource.as_ref().map(|_| "[REDACTED]"))
.field("message", &"[REDACTED]")
.field(
"remediation",
&self.remediation.as_ref().map(|_| "[REDACTED]"),
)
.field("retryable", &self.retryable)
.finish()
}
}
impl Diagnostic {
#[must_use]
pub fn new(
component: impl Into<String>,
operation: impl Into<String>,
kind: DiagnosticKind,
message: impl Into<String>,
) -> Self {
Self {
component: bounded_identifier(component, "component"),
operation: bounded_identifier(operation, "operation"),
resource: None,
kind,
message: bounded_text(message),
remediation: None,
retryable: false,
}
}
#[must_use]
pub fn dependency(
component: impl Into<String>,
operation: impl Into<String>,
kind: DiagnosticKind,
message: impl Into<String>,
) -> Self {
Self::new(component, operation, kind, message)
}
#[must_use]
pub fn configuration(component: impl Into<String>, message: impl Into<String>) -> Self {
Self::new(
component,
"validate_configuration",
DiagnosticKind::InvalidConfiguration,
message,
)
}
#[must_use]
pub fn with_resource(mut self, resource: impl Into<String>) -> Self {
let resource = bounded_text(resource);
if !resource.is_empty() {
self.resource = Some(resource);
}
self
}
#[must_use]
pub fn with_remediation(mut self, remediation: impl Into<String>) -> Self {
let remediation = Remediation::new(remediation);
if !remediation.summary().is_empty() {
self.remediation = Some(remediation);
}
self
}
#[must_use]
pub const fn with_retryable(mut self, retryable: bool) -> Self {
self.retryable = retryable;
self
}
#[must_use]
pub fn component(&self) -> &str {
&self.component
}
#[must_use]
pub fn operation(&self) -> &str {
&self.operation
}
#[must_use]
pub fn resource(&self) -> Option<&str> {
self.resource.as_deref()
}
#[must_use]
pub const fn kind(&self) -> DiagnosticKind {
self.kind
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
#[must_use]
pub fn remediation(&self) -> Option<&Remediation> {
self.remediation.as_ref()
}
#[must_use]
pub const fn retryable(&self) -> bool {
self.retryable
}
}
impl fmt::Display for Diagnostic {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"{} {} {}: {}",
self.component, self.operation, self.kind, self.message
)?;
if let Some(resource) = &self.resource {
write!(formatter, " resource={resource}")?;
}
if let Some(remediation) = &self.remediation {
write!(formatter, "; remediation: {remediation}")?;
}
Ok(())
}
}
#[cfg(feature = "config")]
impl From<&crate::config::ConfigValidationError> for Diagnostic {
fn from(value: &crate::config::ConfigValidationError) -> Self {
let message = value
.issues()
.first()
.map(|issue| format!("{}: {}", issue.path(), issue.message()))
.unwrap_or_else(|| "configuration validation failed".to_owned());
Diagnostic::configuration("configuration", message)
}
}
#[cfg(feature = "config")]
impl From<crate::config::ConfigValidationError> for Diagnostic {
fn from(value: crate::config::ConfigValidationError) -> Self {
Diagnostic::from(&value)
}
}
fn bounded_identifier(value: impl Into<String>, fallback: &str) -> String {
let value = value.into().trim().to_ascii_lowercase().replace('-', "_");
let value = value
.chars()
.filter(|character| {
character.is_ascii_lowercase() || *character == '_' || character.is_ascii_digit()
})
.collect::<String>();
let value = if value.is_empty() {
fallback.to_owned()
} else {
value
};
truncate_text(value)
}
fn bounded_text(value: impl Into<String>) -> String {
truncate_text(value.into().trim().to_owned())
}
fn truncate_text(mut value: String) -> String {
if value.len() <= MAX_DIAGNOSTIC_FIELD_LENGTH {
return value;
}
value.truncate(MAX_DIAGNOSTIC_FIELD_LENGTH);
while !value.is_char_boundary(value.len()) {
value.pop();
}
value
}