pi_result 0.2.0

Thin, typed, and observable Result aliases and error interoperability utilities
Documentation
//! 标准结构化 attachment 定义。
//!
//! 本模块提供一组可复用的结构化上下文类型,用于在错误传播过程中
//! 通过 `error_stack::Report::attach` 或 `ResultExt::attach` 附加运行时信息。
//!
//! 这些 attachment 的设计目标是:
//!
//! - 语义单一
//! - 可结构化匹配
//! - 可直接打印
//! - 可跨线程传递
//! - 不把临时字符串散落在业务代码中

use std::{
    any::type_name,
    fmt,
    path::{Path, PathBuf},
};

/// 当前错误所属的逻辑模块名。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Module(pub &'static str);

impl fmt::Display for Module {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "module={}", self.0)
    }
}

/// 当前执行的操作名。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Operation(pub &'static str);

impl fmt::Display for Operation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "operation={}", self.0)
    }
}

/// 当前错误发生的阶段名。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Stage(pub &'static str);

impl fmt::Display for Stage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "stage={}", self.0)
    }
}

/// 资源名称。
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ResourceName(pub String);

impl fmt::Display for ResourceName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "resource_name={}", self.0)
    }
}

impl From<String> for ResourceName {
    fn from(value: String) -> Self {
        Self(value)
    }
}

impl From<&str> for ResourceName {
    fn from(value: &str) -> Self {
        Self(value.to_owned())
    }
}

/// 资源标识。
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ResourceId(pub String);

impl fmt::Display for ResourceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "resource_id={}", self.0)
    }
}

impl From<String> for ResourceId {
    fn from(value: String) -> Self {
        Self(value)
    }
}

impl From<&str> for ResourceId {
    fn from(value: &str) -> Self {
        Self(value.to_owned())
    }
}

/// 外部依赖名。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DependencyName(pub &'static str);

impl fmt::Display for DependencyName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "dependency={}", self.0)
    }
}

/// 当前重试次数。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RetryCount(pub usize);

impl fmt::Display for RetryCount {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "retry_count={}", self.0)
    }
}

/// 原始错误类型名。
///
/// 常用于把标准库或第三方错误并入 `pi_result` 错误链时,补充来源类型信息。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SourceTypeName(pub &'static str);

impl SourceTypeName {
    /// 通过类型参数构造来源类型名 attachment。
    pub fn of<T>() -> Self {
        Self(type_name::<T>())
    }
}

impl fmt::Display for SourceTypeName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "source_type={}", self.0)
    }
}

/// 文件系统路径 attachment。
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PathAttachment(pub PathBuf);

impl fmt::Display for PathAttachment {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "path={}", self.0.display())
    }
}

impl From<PathBuf> for PathAttachment {
    fn from(value: PathBuf) -> Self {
        Self(value)
    }
}

impl From<&Path> for PathAttachment {
    fn from(value: &Path) -> Self {
        Self(value.to_path_buf())
    }
}

#[cfg(test)]
mod tests {
    use super::{
        DependencyName, Module, Operation, PathAttachment, ResourceId, ResourceName, RetryCount,
        SourceTypeName, Stage,
    };
    use crate::ErrorKind;
    use error_stack::Report;
    use std::{collections::HashSet, path::PathBuf};

    fn assert_send_sync<T: Send + Sync>() {}

    #[test]
    fn test_attachment_display_messages_are_structured() {
        assert_eq!(Module("storage").to_string(), "module=storage");
        assert_eq!(
            Operation("load_config").to_string(),
            "operation=load_config"
        );
        assert_eq!(Stage("startup").to_string(), "stage=startup");
        assert_eq!(
            ResourceName::from("node-42").to_string(),
            "resource_name=node-42"
        );
        assert_eq!(ResourceId::from("42").to_string(), "resource_id=42");
        assert_eq!(DependencyName("redis").to_string(), "dependency=redis");
        assert_eq!(RetryCount(3).to_string(), "retry_count=3");
        assert!(
            SourceTypeName::of::<std::io::Error>()
                .to_string()
                .starts_with("source_type=")
        );

        let rendered = PathAttachment::from(PathBuf::from("config.toml")).to_string();
        assert!(rendered.starts_with("path="));
        assert!(rendered.ends_with("config.toml"));
    }

    #[test]
    fn test_attachment_types_are_cloneable_hashable_and_send_sync() {
        let mut set = HashSet::new();
        set.insert(Module("network"));
        set.insert(Module("network"));
        set.insert(Module("storage"));

        assert_eq!(set.len(), 2);
        assert_send_sync::<Module>();
        assert_send_sync::<Operation>();
        assert_send_sync::<PathAttachment>();
        assert_send_sync::<SourceTypeName>();
    }

    #[test]
    fn test_printable_attachments_can_be_attached_and_retrieved() {
        let report = Report::new(ErrorKind::Internal)
            .attach(Module("runtime"))
            .attach(Operation("spawn_worker"))
            .attach(SourceTypeName::of::<std::io::Error>())
            .attach(PathAttachment::from(PathBuf::from("worker.js")));

        assert!(report.contains::<Module>());
        assert!(report.contains::<Operation>());
        assert!(report.contains::<SourceTypeName>());
        assert!(report.contains::<PathAttachment>());

        assert_eq!(report.downcast_ref::<Module>(), Some(&Module("runtime")));
        assert_eq!(
            report.downcast_ref::<Operation>(),
            Some(&Operation("spawn_worker"))
        );

        let path = report
            .downcast_ref::<PathAttachment>()
            .expect("path attachment should exist");
        assert_eq!(path.0, PathBuf::from("worker.js"));
    }
}