pi_result 0.2.0

Thin, typed, and observable Result aliases and error interoperability utilities
Documentation
//! 公共稳定错误语义定义。
//!
//! 本模块定义 `pi_result` 对外默认暴露的公共错误分类 `ErrorKind`。
//! 这些分类应保持粗粒度、稳定、可长期维护,不直接绑定下层依赖库的
//! 叶子错误细节。更具体的定位信息应继续通过:
//!
//! - 内部 `LocalError`
//! - `error_stack::Report` 的 typed context
//! - 结构化 attachment
//! - 逐层附加的业务上下文
//!
//! 来表达。

use thiserror::Error;

/// `pi_result` 对外默认暴露的稳定公共错误语义。
///
/// # 设计目标
///
/// - 用于公共 API 的粗粒度分类
/// - 便于最终错误处理者进行稳定匹配
/// - 尽量避免随底层依赖错误类型调整而频繁变化
///
/// # 注意事项
///
/// - `ErrorKind` 表示“当前公开解释视角”,不是根因全集。
/// - 更细的诊断信息应继续放在 typed context 和 attachment 中。
/// - 本枚举使用 `#[non_exhaustive]`,调用方在匹配时应保留兜底分支。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
#[non_exhaustive]
pub enum ErrorKind {
    /// 输入数据不合法、格式错误或不满足接口约束。
    #[error("invalid input")]
    InvalidInput,

    /// 当前对象或系统状态不满足操作前置条件。
    #[error("invalid state")]
    InvalidState,

    /// 请求的对象或资源不存在。
    #[error("not found")]
    NotFound,

    /// 请求创建的对象已经存在。
    #[error("already exists")]
    AlreadyExists,

    /// 当前操作与已有状态或并发操作冲突。
    #[error("conflict")]
    Conflict,

    /// 当前主体没有执行该操作所需的权限。
    #[error("permission denied")]
    PermissionDenied,

    /// 通用 IO 失败,且当前层未进一步细分为更具体公共语义。
    #[error("io error")]
    Io,

    /// 操作超时。
    #[error("timeout")]
    Timeout,

    /// 操作被显式取消。
    #[error("cancelled")]
    Cancelled,

    /// 资源当前繁忙,暂时无法处理请求。
    #[error("busy")]
    Busy,

    /// 当前服务、组件或依赖暂时不可用。
    #[error("unavailable")]
    Unavailable,

    /// 当前能力、协议、平台或输入组合不被支持。
    #[error("unsupported")]
    Unsupported,

    /// 系统资源耗尽,例如配额、空间、句柄、连接数等不足。
    #[error("resource exhausted")]
    ResourceExhausted,

    /// 数据已损坏、内容不一致或无法信任。
    #[error("corrupted data")]
    Corrupted,

    /// 失败来自外部依赖、子系统或第三方组件。
    #[error("dependency failure")]
    Dependency,

    /// 未细分到更具体公共语义的内部错误。
    #[error("internal error")]
    Internal,

    /// 暂时无法稳定归类到更具体公共语义的兜底类型。
    #[error("other error")]
    Other,
}

#[cfg(test)]
mod tests {
    use super::ErrorKind;

    #[test]
    fn test_error_kind_display_messages_are_stable() {
        assert_eq!(ErrorKind::InvalidInput.to_string(), "invalid input");
        assert_eq!(ErrorKind::Io.to_string(), "io error");
        assert_eq!(ErrorKind::Timeout.to_string(), "timeout");
        assert_eq!(ErrorKind::Dependency.to_string(), "dependency failure");
        assert_eq!(ErrorKind::Internal.to_string(), "internal error");
        assert_eq!(ErrorKind::Other.to_string(), "other error");
    }

    #[test]
    fn test_error_kind_is_copy_and_hashable() {
        use std::collections::HashSet;

        let mut set = HashSet::new();
        set.insert(ErrorKind::Busy);
        set.insert(ErrorKind::Busy);
        set.insert(ErrorKind::Unavailable);

        assert!(set.contains(&ErrorKind::Busy));
        assert!(set.contains(&ErrorKind::Unavailable));
        assert_eq!(set.len(), 2);
    }
}