footing 0.1.13

Feature-gated foundations for Rust backend services
Documentation
use std::fmt;

/// Maximum supported diagnostic field length.
pub const MAX_DIAGNOSTIC_FIELD_LENGTH: usize = 512;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// Classification of diagnostic.
pub enum DiagnosticKind {
    /// The configuration is invalid.
    InvalidConfiguration,
    /// Indicates authentication failed.
    AuthenticationFailed,
    /// Indicates permission denied.
    PermissionDenied,
    /// Indicates resource missing.
    ResourceMissing,
    /// Indicates resource conflict.
    ResourceConflict,
    /// Indicates unavailable.
    Unavailable,
    /// Indicates capacity exhausted.
    CapacityExhausted,
    /// Indicates state mismatch.
    StateMismatch,
    /// Indicates execution failed.
    ExecutionFailed,
    /// The value is unknown.
    Unknown,
}

impl DiagnosticKind {
    #[must_use]
    /// Returns this value as str.
    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]
/// Represents remediation.
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]
    /// Creates a new instance.
    pub fn new(summary: impl Into<String>) -> Self {
        Self {
            summary: bounded_text(summary),
        }
    }

    #[must_use]
    /// Returns the summary.
    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]
/// Represents diagnostic.
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]
    /// Creates a new instance.
    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]
    /// Creates dependency.
    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]
    /// Creates configuration.
    pub fn configuration(component: impl Into<String>, message: impl Into<String>) -> Self {
        Self::new(
            component,
            "validate_configuration",
            DiagnosticKind::InvalidConfiguration,
            message,
        )
    }

    #[must_use]
    /// Configures resource and returns the updated value.
    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]
    /// Configures remediation and returns the updated value.
    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]
    /// Configures retryable and returns the updated value.
    pub const fn with_retryable(mut self, retryable: bool) -> Self {
        self.retryable = retryable;
        self
    }

    #[must_use]
    /// Returns the component.
    pub fn component(&self) -> &str {
        &self.component
    }

    #[must_use]
    /// Returns the operation.
    pub fn operation(&self) -> &str {
        &self.operation
    }

    #[must_use]
    /// Returns the resource.
    pub fn resource(&self) -> Option<&str> {
        self.resource.as_deref()
    }

    #[must_use]
    /// Returns the kind.
    pub const fn kind(&self) -> DiagnosticKind {
        self.kind
    }

    #[must_use]
    /// Returns the message.
    pub fn message(&self) -> &str {
        &self.message
    }

    #[must_use]
    /// Returns the remediation.
    pub fn remediation(&self) -> Option<&Remediation> {
        self.remediation.as_ref()
    }

    #[must_use]
    /// Returns the retryable.
    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(())
    }
}

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(value.floor_char_boundary(MAX_DIAGNOSTIC_FIELD_LENGTH));
    value
}