loveyu-kit 0.2.0

面向 Axum 项目的可组合 API 工具库
Documentation
//! 消息发送的通用错误。

use thiserror::Error;

/// 消息提供方调用错误。
///
/// 错误中不应包含 Webhook Key、Token 或其他认证凭据。
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum MessagingError {
    /// 客户端配置不合法。
    #[error("{provider} 配置无效:{message}")]
    InvalidConfig {
        /// 提供方稳定标识。
        provider: &'static str,
        /// 已脱敏的错误说明。
        message: String,
    },
    /// 待发送消息不合法。
    #[error("{provider} 消息无效:{message}")]
    InvalidMessage {
        /// 提供方稳定标识。
        provider: &'static str,
        /// 已脱敏的错误说明。
        message: String,
    },
    /// 消息序列化失败。
    #[error("{provider} 消息序列化失败:{source}")]
    Serialize {
        /// 提供方稳定标识。
        provider: &'static str,
        /// JSON 序列化错误。
        #[source]
        source: serde_json::Error,
    },
    /// HTTP 请求未成功完成。
    #[error("请求 {provider} 失败:{source}")]
    Request {
        /// 提供方稳定标识。
        provider: &'static str,
        /// 已移除请求 URL 的 HTTP 错误。
        #[source]
        source: reqwest::Error,
    },
    /// 读取待上传文件失败。
    #[error("{provider} {operation}失败:{source}")]
    Io {
        /// 提供方稳定标识。
        provider: &'static str,
        /// 不包含本地路径的操作说明。
        operation: &'static str,
        /// 底层 IO 错误。
        #[source]
        source: std::io::Error,
    },
    /// HTTP 响应状态不是成功状态。
    #[error("{provider} 返回 HTTP {status}:{response}")]
    HttpStatus {
        /// 提供方稳定标识。
        provider: &'static str,
        /// HTTP 状态码。
        status: u16,
        /// 已限长和脱敏的响应摘要。
        response: String,
    },
    /// HTTP 响应体超过客户端限制。
    #[error("{provider} 响应体超过 {max_bytes} 字节限制")]
    ResponseTooLarge {
        /// 提供方稳定标识。
        provider: &'static str,
        /// 允许读取的最大字节数。
        max_bytes: usize,
    },
    /// 待发送请求体超过客户端限制。
    #[error("{provider} 请求体超过 {max_bytes} 字节限制")]
    RequestTooLarge {
        /// 提供方稳定标识。
        provider: &'static str,
        /// 允许发送的最大字节数。
        max_bytes: usize,
    },
    /// 等待客户端并发请求名额超时。
    #[error("{provider} 请求在 {timeout:?} 内未获得并发名额")]
    RequestQueueTimeout {
        /// 提供方稳定标识。
        provider: &'static str,
        /// 等待并发名额的最长时间。
        timeout: std::time::Duration,
    },
    /// 提供方响应不符合预期协议。
    #[error("{provider} 返回无效响应:{response}")]
    InvalidResponse {
        /// 提供方稳定标识。
        provider: &'static str,
        /// 已限长和脱敏的响应摘要。
        response: String,
        /// JSON 解析错误。
        #[source]
        source: serde_json::Error,
    },
    /// 响应 JSON 可解析,但字段间不符合协议约束。
    #[error("{provider} 返回不一致的协议数据:{message};响应:{response}")]
    Protocol {
        /// 提供方稳定标识。
        provider: &'static str,
        /// 协议不一致说明。
        message: String,
        /// 已限长和脱敏的响应摘要。
        response: String,
    },
    /// 提供方通过业务码拒绝发送。
    #[error("{provider} 拒绝发送({code}):{message}")]
    ProviderRejected {
        /// 提供方稳定标识。
        provider: &'static str,
        /// 提供方业务码。
        code: i64,
        /// 提供方返回的错误说明。
        message: String,
    },
}

impl MessagingError {
    /// 返回稳定的消息提供方标识。
    #[must_use]
    pub const fn provider(&self) -> &'static str {
        match self {
            Self::InvalidConfig { provider, .. }
            | Self::InvalidMessage { provider, .. }
            | Self::Serialize { provider, .. }
            | Self::Request { provider, .. }
            | Self::Io { provider, .. }
            | Self::HttpStatus { provider, .. }
            | Self::ResponseTooLarge { provider, .. }
            | Self::RequestTooLarge { provider, .. }
            | Self::RequestQueueTimeout { provider, .. }
            | Self::InvalidResponse { provider, .. }
            | Self::Protocol { provider, .. }
            | Self::ProviderRejected { provider, .. } => provider,
        }
    }

    /// 返回 HTTP 状态码(如果本次失败已收到 HTTP 响应)。
    #[must_use]
    pub const fn http_status(&self) -> Option<u16> {
        match self {
            Self::HttpStatus { status, .. } => Some(*status),
            _ => None,
        }
    }

    /// 返回提供方业务码。
    #[must_use]
    pub const fn provider_code(&self) -> Option<i64> {
        match self {
            Self::ProviderRejected { code, .. } => Some(*code),
            _ => None,
        }
    }

    /// 判断本次失败是否具有重试可能。
    ///
    /// 这只是给 Outbox Worker 的分类提示,客户端本身不会自动重试,
    /// 避免在请求实际已送达时重复发送。
    #[must_use]
    pub fn is_retryable(&self) -> bool {
        match self {
            Self::Request { source, .. } => source.is_timeout() || source.is_connect(),
            Self::RequestQueueTimeout { .. } => true,
            Self::HttpStatus { status, .. } => *status == 408 || *status == 429 || *status >= 500,
            // 企业微信使用 -1 表示系统繁忙,调用方可以在保证幂等后重试。
            Self::ProviderRejected { code, .. } => *code == -1,
            _ => false,
        }
    }

    /// 转换为可写入当前请求聚合日志的外部服务诊断。
    ///
    /// 只包含已脱敏错误和稳定分类字段,不会写入 Webhook Key。
    #[cfg(feature = "logging")]
    pub fn to_diagnostic(&self, operation: impl Into<String>) -> crate::observability::Diagnostic {
        let mut diagnostic = crate::observability::Diagnostic::new(
            crate::observability::DiagnosticKind::ExternalService,
            operation,
            self,
        )
        .with_detail("provider", self.provider())
        .with_detail("retryable", self.is_retryable());
        if let Some(status) = self.http_status() {
            diagnostic = diagnostic.with_detail("http_status", status);
        }
        if let Some(code) = self.provider_code() {
            diagnostic = diagnostic.with_detail("provider_code", code);
        }
        diagnostic
    }
}