pi_result 0.2.0

Thin, typed, and observable Result aliases and error interoperability utilities
Documentation
//! 边界转换辅助 trait。
//!
//! 本模块在 `error-stack::ResultExt` 之上提供薄语义别名,用于表达:
//!
//! - 把任意 `Result<T, E>` 收敛到统一公共错误 `Result<T>`
//! - 把任意 `Result<T, E>` 切换到新的 typed context `Result<T, C>`
//! - 让依赖库已经返回的 `pi_result::Result<T>` 继续并入上层库自己的错误链
//!
//! 这些辅助 trait 不替代 `error-stack`,只是让代码在语义上更贴近
//! “跨边界切换解释视角”的意图。
//!
//! # 跨库并入说明
//!
//! 若依赖库 B 已经公开返回 `pi_result::Result<T>`:
//!
//! - 上层库 A 若不需要改公共语义,可先 `attach(...)` 再直接 `?`
//! - 上层库 A 若需要补自己的 typed context,可先 `.into_typed(...)` 再 `?`
//! - 上层库 A 若需要重新解释为新的公共 `ErrorKind`,可先 `.into_error(...)` 再 `?`
//!
//! 换句话说,库 B 的公共 `Result<T>` 不是错误链的终点,它仍然可以作为
//! 库 A / App 继续构建、补充和重新解释错误链的输入。

use std::error::Error as StdError;

use error_stack::{IntoReport, ResultExt};

use crate::{Result, kind::ErrorKind, result::TypedResult};

/// 把任意可 `IntoReport` 的错误结果收敛为统一公共错误的扩展 trait。
///
/// # 设计意图
///
/// 该 trait 本质上是 `ResultExt::change_context(ErrorKind)` 的薄语义别名。
/// 其目标是让调用点更明确地表达:“这里进入了公共稳定错误边界”。
///
/// 它不仅适用于 `RawResult<T, E>`,也适用于依赖库已经返回的
/// `pi_result::Result<T>` 或 `pi_result::TypedResult<T, C>`。
pub trait IntoErrorExt<T, E>: Sized {
    /// 切换到统一公共错误语义。
    ///
    /// # 示例
    ///
    /// ```rust
    /// use pi_result::prelude::*;
    ///
    /// #[derive(Debug, pi_result::thiserror::Error)]
    /// #[error("parse failed")]
    /// struct ParseError;
    ///
    /// let report = Err::<(), ParseError>(ParseError)
    ///     .attach(Operation("parse_config"))
    ///     .into_error(ErrorKind::InvalidInput)
    ///     .expect_err("expected public report");
    ///
    /// assert_eq!(report.current_kind(), &ErrorKind::InvalidInput);
    /// assert!(report.contains::<ParseError>());
    /// ```
    fn into_error(self, kind: ErrorKind) -> Result<T>
    where
        E: IntoReport;

    /// 懒加载地切换到统一公共错误语义。
    ///
    /// 只有在 `Err` 路径上才会执行闭包。
    fn into_error_lazy<F>(self, f: F) -> Result<T>
    where
        E: IntoReport,
        F: FnOnce() -> ErrorKind;
}

impl<T, E> IntoErrorExt<T, E> for core::result::Result<T, E> {
    fn into_error(self, kind: ErrorKind) -> Result<T>
    where
        E: IntoReport,
    {
        self.change_context(kind)
    }

    fn into_error_lazy<F>(self, f: F) -> Result<T>
    where
        E: IntoReport,
        F: FnOnce() -> ErrorKind,
    {
        self.change_context_lazy(f)
    }
}

/// 把任意可 `IntoReport` 的错误结果切换到新的 typed context 的扩展 trait。
///
/// # 设计意图
///
/// 该 trait 本质上是 `ResultExt::change_context(context)` 的薄语义别名。
/// 其目标是让调用点更明确地表达:“这里切换到了新的内部解释视角”。
///
/// 这意味着上层库完全可以把依赖库已经返回的 `pi_result::Result<T>`
/// 继续并入自己的 typed context 传播链,而不需要丢弃下层已经构建好的
/// `Report` 信息。
pub trait IntoTypedContextExt<T, E>: Sized {
    /// 切换到新的 typed context。
    fn into_typed<C>(self, context: C) -> TypedResult<T, C>
    where
        C: StdError + Send + Sync + 'static,
        E: IntoReport;

    /// 懒加载地切换到新的 typed context。
    ///
    /// 只有在 `Err` 路径上才会执行闭包。
    fn into_typed_lazy<C, F>(self, f: F) -> TypedResult<T, C>
    where
        C: StdError + Send + Sync + 'static,
        E: IntoReport,
        F: FnOnce() -> C;
}

impl<T, E> IntoTypedContextExt<T, E> for core::result::Result<T, E> {
    fn into_typed<C>(self, context: C) -> TypedResult<T, C>
    where
        C: StdError + Send + Sync + 'static,
        E: IntoReport,
    {
        self.change_context(context)
    }

    fn into_typed_lazy<C, F>(self, f: F) -> TypedResult<T, C>
    where
        C: StdError + Send + Sync + 'static,
        E: IntoReport,
        F: FnOnce() -> C,
    {
        self.change_context_lazy(f)
    }
}

#[cfg(test)]
mod tests {
    use super::{IntoErrorExt, IntoTypedContextExt};
    use crate::{ErrorKind, RawResult, TypedResult};
    use error_stack::Report;
    use std::sync::atomic::{AtomicBool, Ordering};
    use thiserror::Error;

    #[derive(Debug, Error)]
    #[error("raw leaf error")]
    struct RawLeafError;

    #[derive(Debug, Error, PartialEq, Eq)]
    enum LocalContext {
        #[error("decode failed")]
        Decode,

        #[error("load failed")]
        Load,
    }

    #[test]
    fn test_into_error_converts_raw_result_to_public_error() {
        let result: RawResult<(), RawLeafError> = Err(RawLeafError);
        let error = result
            .into_error(ErrorKind::InvalidInput)
            .expect_err("expected public report");

        assert_eq!(error.current_context(), &ErrorKind::InvalidInput);
        assert!(error.contains::<RawLeafError>());
    }

    #[test]
    fn test_into_typed_converts_raw_result_to_typed_report() {
        let result: RawResult<(), RawLeafError> = Err(RawLeafError);
        let error = result
            .into_typed(LocalContext::Decode)
            .expect_err("expected typed report");

        assert_eq!(error.current_context(), &LocalContext::Decode);
        assert!(error.contains::<RawLeafError>());
    }

    #[test]
    fn test_into_error_preserves_existing_typed_context() {
        let result: TypedResult<(), LocalContext> =
            Err(Report::new(LocalContext::Load).attach("load_config"));

        let error = result
            .into_error(ErrorKind::Dependency)
            .expect_err("expected public report");

        assert_eq!(error.current_context(), &ErrorKind::Dependency);
        assert!(error.contains::<LocalContext>());
        assert!(error.contains::<ErrorKind>());
        assert!(error.contains::<&'static str>());
    }

    #[test]
    fn test_into_error_lazy_is_not_evaluated_on_ok_path() {
        static CALLED: AtomicBool = AtomicBool::new(false);

        let result: RawResult<u32, RawLeafError> = Ok(7);
        let value = result
            .into_error_lazy(|| {
                CALLED.store(true, Ordering::SeqCst);
                ErrorKind::Internal
            })
            .expect("ok path should pass through");

        assert_eq!(value, 7);
        assert!(!CALLED.load(Ordering::SeqCst));
    }

    #[test]
    fn test_into_typed_lazy_is_not_evaluated_on_ok_path() {
        static CALLED: AtomicBool = AtomicBool::new(false);

        let result: RawResult<&'static str, RawLeafError> = Ok("ok");
        let value = result
            .into_typed_lazy(|| {
                CALLED.store(true, Ordering::SeqCst);
                LocalContext::Decode
            })
            .expect("ok path should pass through");

        assert_eq!(value, "ok");
        assert!(!CALLED.load(Ordering::SeqCst));
    }

    #[test]
    fn test_into_error_lazy_is_evaluated_on_err_path() {
        static CALLED: AtomicBool = AtomicBool::new(false);

        let result: RawResult<(), RawLeafError> = Err(RawLeafError);
        let error = result
            .into_error_lazy(|| {
                CALLED.store(true, Ordering::SeqCst);
                ErrorKind::Internal
            })
            .expect_err("err path should convert");

        assert_eq!(error.current_context(), &ErrorKind::Internal);
        assert!(CALLED.load(Ordering::SeqCst));
    }
}