use std::{borrow::Cow, error::Error, fmt};
pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
pub type Result<T, E = BoxError> = std::result::Result<T, E>;
pub const DEFAULT_ERROR_CODE: &str = "unknown_error";
pub const MAX_ERROR_CODE_LENGTH: usize = 128;
pub const MAX_DIAGNOSTIC_FIELD_LENGTH: usize = 512;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
Validation,
Authentication,
Authorization,
NotFound,
Conflict,
RateLimit,
Timeout,
Dependency,
Unavailable,
Internal,
}
impl ErrorKind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Validation => "validation",
Self::Authentication => "authentication",
Self::Authorization => "authorization",
Self::NotFound => "not_found",
Self::Conflict => "conflict",
Self::RateLimit => "rate_limit",
Self::Timeout => "timeout",
Self::Dependency => "dependency",
Self::Unavailable => "unavailable",
Self::Internal => "internal",
}
}
#[must_use]
pub const fn retryable(self) -> bool {
matches!(
self,
Self::RateLimit | Self::Timeout | Self::Dependency | Self::Unavailable
)
}
#[must_use]
pub const fn client_fault(self) -> bool {
matches!(
self,
Self::Validation
| Self::Authentication
| Self::Authorization
| Self::NotFound
| Self::Conflict
| Self::RateLimit
)
}
}
impl fmt::Display for ErrorKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ErrorCode(String);
impl ErrorCode {
pub fn new(value: impl Into<String>) -> std::result::Result<Self, ErrorCodeError> {
Self::try_new(value)
}
pub fn try_new(value: impl Into<String>) -> std::result::Result<Self, ErrorCodeError> {
let value = value.into().trim().to_owned();
validate_error_code(&value)?;
Ok(Self(value))
}
pub fn from_parts(
parts: impl IntoIterator<Item = impl AsRef<str>>,
) -> std::result::Result<Self, ErrorCodeError> {
let mut code = String::new();
for part in parts {
let part = part.as_ref().trim();
if part.is_empty() {
return Err(ErrorCodeError::Empty);
}
if !code.is_empty() {
code.push('_');
}
code.push_str(part);
}
Self::try_new(code)
}
#[must_use]
pub fn from_static(value: &'static str) -> Self {
Self::try_new(value).unwrap_or_else(|_| Self::unknown())
}
#[must_use]
pub fn unknown() -> Self {
Self(DEFAULT_ERROR_CODE.to_owned())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
}
impl fmt::Display for ErrorCode {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorCodeError {
Empty,
TooLong {
#[doc = "The configured upper bound."]
max: usize,
},
InvalidCharacters,
}
impl fmt::Display for ErrorCodeError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Empty => formatter.write_str("error code must not be empty"),
Self::TooLong { max } => {
write!(
formatter,
"error code must be less than or equal to {max} bytes"
)
}
Self::InvalidCharacters => {
formatter.write_str("error code contains unsupported characters")
}
}
}
}
impl Error for ErrorCodeError {}
impl ClassifyError for ErrorCodeError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> Cow<'static, str> {
Cow::Borrowed(match self {
Self::Empty => "error_code_empty",
Self::TooLong { .. } => "error_code_too_long",
Self::InvalidCharacters => "error_code_invalid_characters",
})
}
}
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ErrorDescriptor {
kind: ErrorKind,
code: ErrorCode,
message: String,
retryable: bool,
visibility: ErrorVisibility,
}
impl fmt::Debug for ErrorDescriptor {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ErrorDescriptor")
.field("kind", &self.kind)
.field("code", &self.code)
.field("message", &"[REDACTED]")
.field("retryable", &self.retryable)
.field("visibility", &self.visibility)
.finish()
}
}
impl ErrorDescriptor {
#[must_use]
pub fn new(kind: ErrorKind, code: ErrorCode, message: impl Into<String>) -> Self {
Self {
kind,
code,
message: normalize_error_message(kind, message),
retryable: kind.retryable(),
visibility: ErrorVisibility::default_for_kind(kind),
}
}
pub fn try_new(
kind: ErrorKind,
code: impl Into<String>,
message: impl Into<String>,
) -> std::result::Result<Self, ErrorCodeError> {
Ok(Self::new(kind, ErrorCode::try_new(code)?, message))
}
#[must_use]
pub const fn kind(&self) -> ErrorKind {
self.kind
}
#[must_use]
pub fn code(&self) -> &ErrorCode {
&self.code
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
#[must_use]
pub const fn retryable(&self) -> bool {
self.retryable
}
#[must_use]
pub const fn visibility(&self) -> ErrorVisibility {
self.visibility
}
#[must_use]
pub fn public_message(&self) -> Cow<'_, str> {
if self.visibility.exposes_message() {
Cow::Borrowed(self.message())
} else {
Cow::Borrowed(generic_error_message(self.kind))
}
}
#[must_use]
pub const fn with_retryable(mut self, retryable: bool) -> Self {
self.retryable = retryable;
self
}
#[must_use]
pub const fn with_visibility(mut self, visibility: ErrorVisibility) -> Self {
self.visibility = visibility;
self
}
#[must_use]
pub const fn with_public_message(self) -> Self {
self.with_visibility(ErrorVisibility::Public)
}
#[must_use]
pub const fn with_private_message(self) -> Self {
self.with_visibility(ErrorVisibility::Private)
}
}
fn normalize_error_message(kind: ErrorKind, message: impl Into<String>) -> String {
let message = message.into().trim().to_owned();
if message.is_empty() {
generic_error_message(kind).to_owned()
} else {
message
}
}
impl fmt::Display for ErrorDescriptor {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.public_message())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorVisibility {
Public,
Private,
}
impl ErrorVisibility {
#[must_use]
pub const fn default_for_kind(kind: ErrorKind) -> Self {
if kind.client_fault() {
Self::Public
} else {
Self::Private
}
}
#[must_use]
pub const fn exposes_message(self) -> bool {
matches!(self, Self::Public)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorLogLevel {
Debug,
Info,
Warn,
Error,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ErrorBoundaryDecision {
descriptor: ErrorDescriptor,
log_level: ErrorLogLevel,
alert: bool,
}
impl ErrorBoundaryDecision {
#[must_use]
pub const fn descriptor(&self) -> &ErrorDescriptor {
&self.descriptor
}
#[must_use]
pub const fn log_level(&self) -> ErrorLogLevel {
self.log_level
}
#[must_use]
pub const fn alert(&self) -> bool {
self.alert
}
#[must_use]
pub fn public_message(&self) -> Cow<'_, str> {
self.descriptor.public_message()
}
#[must_use]
pub fn into_descriptor(self) -> ErrorDescriptor {
self.descriptor
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct ErrorBoundaryPolicy {
expose_server_error_messages: bool,
alert_internal_errors: bool,
}
impl Default for ErrorBoundaryPolicy {
fn default() -> Self {
Self {
expose_server_error_messages: false,
alert_internal_errors: true,
}
}
}
impl ErrorBoundaryPolicy {
#[must_use]
pub const fn new() -> Self {
Self {
expose_server_error_messages: false,
alert_internal_errors: true,
}
}
#[must_use]
pub const fn http_api() -> Self {
Self {
expose_server_error_messages: false,
alert_internal_errors: true,
}
}
#[must_use]
pub const fn worker() -> Self {
Self {
expose_server_error_messages: false,
alert_internal_errors: true,
}
}
#[must_use]
pub const fn cli() -> Self {
Self {
expose_server_error_messages: true,
alert_internal_errors: false,
}
}
#[must_use]
pub const fn trusted_internal() -> Self {
Self {
expose_server_error_messages: true,
alert_internal_errors: true,
}
}
#[must_use]
pub const fn exposes_server_error_messages(self) -> bool {
self.expose_server_error_messages
}
#[must_use]
pub const fn alerts_internal_errors(self) -> bool {
self.alert_internal_errors
}
#[must_use]
pub const fn with_server_error_messages(mut self, expose: bool) -> Self {
self.expose_server_error_messages = expose;
self
}
#[must_use]
pub const fn with_internal_error_alerts(mut self, alert: bool) -> Self {
self.alert_internal_errors = alert;
self
}
#[must_use]
pub fn decide<E>(&self, error: &E) -> ErrorBoundaryDecision
where
E: ClassifyError + ?Sized,
{
self.decide_descriptor(error.error_descriptor())
}
#[must_use]
pub fn decide_descriptor(&self, descriptor: ErrorDescriptor) -> ErrorBoundaryDecision {
let kind = descriptor.kind();
let descriptor = if self.expose_server_error_messages {
descriptor.with_public_message()
} else {
descriptor
};
ErrorBoundaryDecision {
descriptor,
log_level: log_level_for_kind(kind),
alert: self.alert_internal_errors && matches!(kind, ErrorKind::Internal),
}
}
}
#[must_use]
pub const fn generic_error_message(kind: ErrorKind) -> &'static str {
match kind {
ErrorKind::Validation => "request validation failed",
ErrorKind::Authentication => "authentication is required",
ErrorKind::Authorization => "permission is denied",
ErrorKind::NotFound => "resource was not found",
ErrorKind::Conflict => "resource conflict",
ErrorKind::RateLimit => "too many requests",
ErrorKind::Timeout | ErrorKind::Dependency | ErrorKind::Unavailable => {
"service is unavailable"
}
ErrorKind::Internal => "internal server error",
}
}
const fn log_level_for_kind(kind: ErrorKind) -> ErrorLogLevel {
match kind {
ErrorKind::Validation
| ErrorKind::Authentication
| ErrorKind::Authorization
| ErrorKind::NotFound
| ErrorKind::Conflict => ErrorLogLevel::Info,
ErrorKind::RateLimit => ErrorLogLevel::Debug,
ErrorKind::Timeout | ErrorKind::Dependency | ErrorKind::Unavailable => ErrorLogLevel::Warn,
ErrorKind::Internal => ErrorLogLevel::Error,
}
}
pub trait ClassifyError: fmt::Display {
fn error_kind(&self) -> ErrorKind;
fn error_code(&self) -> Cow<'static, str> {
Cow::Borrowed(DEFAULT_ERROR_CODE)
}
fn error_descriptor(&self) -> ErrorDescriptor {
let code = ErrorCode::try_new(self.error_code().into_owned()).unwrap_or_else(|_| {
ErrorCode::unknown()
});
ErrorDescriptor::new(self.error_kind(), code, self.to_string())
}
}
#[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)
}
}
impl ClassifyError for ErrorDescriptor {
fn error_kind(&self) -> ErrorKind {
self.kind
}
fn error_code(&self) -> Cow<'static, str> {
Cow::Owned(self.code.as_str().to_owned())
}
fn error_descriptor(&self) -> ErrorDescriptor {
self.clone()
}
}
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
}
fn validate_error_code(value: &str) -> std::result::Result<(), ErrorCodeError> {
if value.is_empty() {
return Err(ErrorCodeError::Empty);
}
if value.len() > MAX_ERROR_CODE_LENGTH {
return Err(ErrorCodeError::TooLong {
max: MAX_ERROR_CODE_LENGTH,
});
}
if !value
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
{
return Err(ErrorCodeError::InvalidCharacters);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::{
ClassifyError, Diagnostic, DiagnosticKind, ErrorBoundaryPolicy, ErrorCode, ErrorCodeError,
ErrorDescriptor, ErrorKind, ErrorVisibility, MAX_ERROR_CODE_LENGTH,
};
fn code(value: &'static str) -> ErrorCode {
ErrorCode::new(value).expect("static test error code should be valid")
}
#[test]
fn error_codes_are_stable_snake_case_identifiers() {
assert_eq!(
ErrorCode::new(" invalid_request ")
.expect("code should be valid")
.as_str(),
"invalid_request"
);
assert_eq!(
ErrorCode::from_parts(["mfa_factor", "not_found"])
.expect("parts should build")
.as_str(),
"mfa_factor_not_found"
);
assert!(matches!(
ErrorCode::from_parts(["mfa factor", "not_found"]),
Err(ErrorCodeError::InvalidCharacters)
));
assert!(matches!(
ErrorCode::try_new("InvalidRequest"),
Err(ErrorCodeError::InvalidCharacters)
));
assert!(matches!(
ErrorCode::try_new("a".repeat(MAX_ERROR_CODE_LENGTH + 1)),
Err(ErrorCodeError::TooLong { .. })
));
}
#[test]
fn static_error_codes_fall_back_without_panicking() {
assert_eq!(ErrorCode::from_static("bad code").as_str(), "unknown_error");
}
#[test]
fn error_code_errors_are_classified_as_validation_failures() {
let error = ErrorCode::try_new("InvalidRequest").expect_err("code should be invalid");
let descriptor = error.error_descriptor();
assert_eq!(descriptor.kind(), ErrorKind::Validation);
assert_eq!(descriptor.code().as_str(), "error_code_invalid_characters");
}
#[test]
fn descriptor_inherits_retryability_from_kind() {
let dependency =
ErrorDescriptor::new(ErrorKind::Dependency, code("database_down"), "db down");
let validation =
ErrorDescriptor::new(ErrorKind::Validation, code("invalid_input"), "bad input");
assert!(dependency.retryable());
assert!(!validation.retryable());
}
#[test]
fn descriptor_try_new_rejects_dynamic_invalid_codes() {
assert!(matches!(
ErrorDescriptor::try_new(ErrorKind::Validation, "mfa factor_not_found", "missing"),
Err(ErrorCodeError::InvalidCharacters)
));
}
#[test]
fn descriptor_hides_server_fault_messages_by_default() {
let internal = ErrorDescriptor::new(
ErrorKind::Internal,
code("internal_error"),
"database failed",
);
let validation =
ErrorDescriptor::new(ErrorKind::Validation, code("invalid_input"), "bad input");
assert_eq!(internal.visibility(), ErrorVisibility::Private);
assert_eq!(internal.public_message(), "internal server error");
assert_eq!(internal.to_string(), "internal server error");
assert!(!format!("{internal:?}").contains("database failed"));
assert_eq!(validation.visibility(), ErrorVisibility::Public);
assert_eq!(validation.public_message(), "bad input");
assert_eq!(validation.to_string(), "bad input");
}
#[test]
fn descriptor_uses_generic_message_when_message_is_empty() {
let descriptor = ErrorDescriptor::new(ErrorKind::Validation, code("invalid_input"), " ");
assert_eq!(descriptor.message(), "request validation failed");
assert_eq!(descriptor.public_message(), "request validation failed");
}
#[test]
fn boundary_policy_can_expose_server_messages_for_trusted_boundaries() {
let descriptor = ErrorDescriptor::new(
ErrorKind::Dependency,
code("storage_unavailable"),
"storage down",
);
let decision = ErrorBoundaryPolicy::trusted_internal().decide_descriptor(descriptor);
assert_eq!(decision.public_message(), "storage down");
}
#[test]
fn boundary_presets_match_their_external_contract() {
assert!(!ErrorBoundaryPolicy::http_api().exposes_server_error_messages());
assert!(ErrorBoundaryPolicy::http_api().alerts_internal_errors());
assert!(!ErrorBoundaryPolicy::worker().exposes_server_error_messages());
assert!(ErrorBoundaryPolicy::worker().alerts_internal_errors());
assert!(ErrorBoundaryPolicy::cli().exposes_server_error_messages());
assert!(!ErrorBoundaryPolicy::cli().alerts_internal_errors());
assert!(ErrorBoundaryPolicy::trusted_internal().exposes_server_error_messages());
assert!(ErrorBoundaryPolicy::trusted_internal().alerts_internal_errors());
}
#[test]
fn diagnostic_normalizes_operational_context() {
let diagnostic = Diagnostic::dependency(
"PostgreSQL",
"ensure-database",
DiagnosticKind::ResourceMissing,
"database example_resource is missing",
)
.with_resource("example_resource")
.with_remediation("enable create_on_startup or create the database")
.with_retryable(false);
assert_eq!(diagnostic.component(), "postgresql");
assert_eq!(diagnostic.operation(), "ensure_database");
assert_eq!(diagnostic.kind(), DiagnosticKind::ResourceMissing);
assert_eq!(diagnostic.resource(), Some("example_resource"));
assert!(diagnostic.remediation().is_some());
assert!(!diagnostic.retryable());
let debug = format!("{diagnostic:?}");
assert!(!debug.contains("database example_resource is missing"));
assert!(!debug.contains("enable create_on_startup"));
}
#[cfg(feature = "config")]
#[test]
fn diagnostic_can_be_created_from_config_validation_error() {
let error = crate::config::ConfigValidationError::single(
"http.timeout",
"must be greater than zero",
);
let diagnostic = Diagnostic::from(error);
assert_eq!(diagnostic.component(), "configuration");
assert_eq!(diagnostic.operation(), "validate_configuration");
assert_eq!(diagnostic.kind(), DiagnosticKind::InvalidConfiguration);
assert!(diagnostic.message().contains("http.timeout"));
}
}