pi_result 0.2.0

Thin, typed, and observable Result aliases and error interoperability utilities
Documentation
//! 稳定版错误检查辅助。
//!
//! 本模块基于 `error-stack 0.6` 的稳定 API 提供观测辅助,优先围绕:
//!
//! - `current_context()`
//! - `contains::<T>()`
//! - `downcast_ref::<T>()`
//!
//! 来构建,不把 nightly-only 的 `request_ref()` / `request_value()` 作为主路径。

use crate::{Error, ErrorKind, ErrorReport};

#[cfg(nightly)]
pub use error_stack::iter::{RequestRef, RequestValue};

/// 针对统一公共错误对象 `pi_result::Error` 的稳定检查扩展。
pub trait ErrorInspectExt {
    /// 获取当前公共解释语义。
    fn current_kind(&self) -> &ErrorKind;

    /// 检查错误栈中是否包含指定公共语义。
    fn has_kind(&self, kind: ErrorKind) -> bool;

    /// 检查错误栈中是否包含某个 typed context。
    fn contains_context<C>(&self) -> bool
    where
        C: Send + Sync + 'static;

    /// 读取最近一个匹配的 attachment 或 context。
    fn attachment_ref<A>(&self) -> Option<&A>
    where
        A: Send + Sync + 'static;
}

impl ErrorInspectExt for Error {
    fn current_kind(&self) -> &ErrorKind {
        self.current_context()
    }

    fn has_kind(&self, kind: ErrorKind) -> bool {
        self.frames()
            .filter_map(|frame| frame.downcast_ref::<ErrorKind>())
            .copied()
            .any(|current| current == kind)
    }

    fn contains_context<C>(&self) -> bool
    where
        C: Send + Sync + 'static,
    {
        self.contains::<C>()
    }

    fn attachment_ref<A>(&self) -> Option<&A>
    where
        A: Send + Sync + 'static,
    {
        self.downcast_ref::<A>()
    }
}

/// 通用 report 检查辅助函数。
///
/// 该函数适用于任意 `Report<C>`,用于检测某个 context 或 attachment 是否出现在错误栈中。
pub fn contains_type<C, T>(report: &ErrorReport<C>) -> bool
where
    C: Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    report.contains::<T>()
}

/// 通用 report 提取辅助函数。
///
/// 该函数返回错误栈中最近一个匹配的 context 或 attachment。
pub fn downcast_ref<C, T>(report: &ErrorReport<C>) -> Option<&T>
where
    C: Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    report.downcast_ref::<T>()
}

/// nightly 增强版错误检查扩展。
///
/// 该 trait 仅在同时满足以下条件时可用:
///
/// - 使用 nightly Rust 工具链编译
///
/// 它封装 `error-stack` 的 `request_ref()` / `request_value()`,
/// 用于枚举整条错误链上全部匹配的 attachment 或 provider 数据。
#[cfg(nightly)]
pub trait NightlyErrorInspectExt {
    /// 枚举整条错误链上所有匹配的引用型数据,最近的 frame 先返回。
    fn request_refs<T>(&self) -> RequestRef<'_, T>
    where
        T: ?Sized + Send + Sync + 'static;

    /// 枚举整条错误链上所有匹配的值型数据,最近的 frame 先返回。
    fn request_values<T>(&self) -> RequestValue<'_, T>
    where
        T: Send + Sync + 'static;
}

#[cfg(nightly)]
impl<C> NightlyErrorInspectExt for ErrorReport<C> {
    fn request_refs<T>(&self) -> RequestRef<'_, T>
    where
        T: ?Sized + Send + Sync + 'static,
    {
        self.request_ref::<T>()
    }

    fn request_values<T>(&self) -> RequestValue<'_, T>
    where
        T: Send + Sync + 'static,
    {
        self.request_value::<T>()
    }
}

/// nightly 增强版通用枚举辅助函数。
#[cfg(nightly)]
pub fn request_refs<C, T>(report: &ErrorReport<C>) -> RequestRef<'_, T>
where
    T: ?Sized + Send + Sync + 'static,
{
    report.request_ref::<T>()
}

/// nightly 增强版通用值枚举辅助函数。
#[cfg(nightly)]
pub fn request_values<C, T>(report: &ErrorReport<C>) -> RequestValue<'_, T>
where
    T: Send + Sync + 'static,
{
    report.request_value::<T>()
}

#[cfg(test)]
mod tests {
    use super::{ErrorInspectExt, contains_type, downcast_ref};
    use crate::{Error, ErrorKind, attachment::Operation};
    use error_stack::Report;
    use thiserror::Error;

    #[derive(Debug, Error, PartialEq, Eq)]
    #[error("decode failed")]
    struct DecodeContext;

    #[test]
    fn test_current_kind_returns_public_context() {
        let report: Error = Report::new(ErrorKind::InvalidState);
        assert_eq!(report.current_kind(), &ErrorKind::InvalidState);
    }

    #[test]
    fn test_has_kind_checks_public_kind_in_stack() {
        let report: Error = Report::new(DecodeContext)
            .attach(Operation("decode_frame"))
            .change_context(ErrorKind::Dependency);

        assert!(report.has_kind(ErrorKind::Dependency));
        assert!(!report.has_kind(ErrorKind::Timeout));
    }

    #[test]
    fn test_contains_context_detects_inner_typed_context() {
        let report: Error = Report::new(DecodeContext).change_context(ErrorKind::Internal);
        assert!(report.contains_context::<DecodeContext>());
        assert!(!report.contains_context::<Operation>());
    }

    #[test]
    fn test_attachment_ref_returns_latest_matching_attachment() {
        let report: Error = Report::new(ErrorKind::Internal)
            .attach(Operation("first"))
            .attach(Operation("second"));

        assert_eq!(
            report.attachment_ref::<Operation>(),
            Some(&Operation("second"))
        );
    }

    #[test]
    fn test_generic_helpers_work_for_any_report_type() {
        let report = Report::new(DecodeContext).attach(Operation("decode"));

        assert!(contains_type::<DecodeContext, DecodeContext>(&report));
        assert!(contains_type::<DecodeContext, Operation>(&report));
        assert_eq!(
            downcast_ref::<DecodeContext, Operation>(&report),
            Some(&Operation("decode"))
        );
    }
}

#[cfg(all(test, nightly))]
mod nightly_tests {
    use super::{NightlyErrorInspectExt, request_refs, request_values};
    use crate::{Error, ErrorKind, attachment::Operation};
    use error_stack::Report;
    use std::fmt;

    #[derive(Debug, PartialEq, Eq)]
    struct Suggestion(&'static str);

    impl fmt::Display for Suggestion {
        fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
            fmt.write_str(self.0)
        }
    }

    #[derive(Debug, PartialEq, Eq)]
    struct ProvidedContext {
        retry: u32,
        code: u16,
    }

    impl fmt::Display for ProvidedContext {
        fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(
                fmt,
                "provided context retry={} code={}",
                self.retry, self.code
            )
        }
    }

    impl std::error::Error for ProvidedContext {
        fn provide<'a>(&'a self, request: &mut core::error::Request<'a>) {
            request.provide_ref(&self.retry);
            request.provide_value(u64::from(self.code));
        }
    }

    #[test]
    fn test_request_refs_enumerates_all_matching_attachments() {
        let report: Error = Report::new(ErrorKind::Internal)
            .attach(Suggestion("first"))
            .attach(Suggestion("second"))
            .attach(Operation("decode"));

        let suggestions = report
            .request_refs::<Suggestion>()
            .map(|suggestion| suggestion.0)
            .collect::<Vec<_>>();

        assert_eq!(suggestions, vec!["second", "first"]);
    }

    #[test]
    fn test_request_values_enumerates_all_provided_values_in_recent_first_order() {
        let report = Report::new(ProvidedContext { retry: 1, code: 10 })
            .change_context(ProvidedContext { retry: 2, code: 20 });

        let retries = report.request_refs::<u32>().copied().collect::<Vec<_>>();
        let codes = report.request_values::<u64>().collect::<Vec<_>>();

        assert_eq!(retries, vec![2, 1]);
        assert_eq!(codes, vec![20, 10]);
    }

    #[test]
    fn test_generic_request_helpers_work_for_any_report_type() {
        let report = Report::new(ProvidedContext { retry: 7, code: 70 })
            .attach(Suggestion("check input"))
            .change_context(ProvidedContext { retry: 8, code: 80 });

        let suggestions = request_refs::<ProvidedContext, Suggestion>(&report)
            .map(|suggestion| suggestion.0)
            .collect::<Vec<_>>();
        let codes = request_values::<ProvidedContext, u64>(&report).collect::<Vec<_>>();

        assert_eq!(suggestions, vec!["check input"]);
        assert_eq!(codes, vec![80, 70]);
    }
}