Skip to main content

ydp_core/
error.rs

1use crate::{RawJson, ReceiveSeq, RequestId, SessionKey, Submission};
2use std::{fmt, sync::Arc};
3/// 通信操作的分类结果;失败不隐含自动重试。
4pub type Result<T> = std::result::Result<T, Error>;
5/// 可模式匹配的错误类别;未来版本可新增类别。
6#[derive(Clone, Debug)]
7#[non_exhaustive]
8pub enum ErrorKind {
9    /// 本地参数不符合范围或形状。
10    InvalidArgument,
11    /// 当前线程没有 Tokio runtime。
12    NoRuntime,
13    /// 参数序列化失败,尚未发布。
14    Encode,
15    /// 匹配结果或事件的领域解码失败。
16    Decode,
17    /// 端点返回的协议错误,保留原始数据的存在性。
18    Protocol {
19        /// 端点的 i32 错误代码。
20        code: i32,
21        /// 端点提供的错误说明。
22        message: String,
23        /// 可缺失、明确 null 或其他 JSON 的附加信息。
24        data: Option<RawJson>,
25    },
26    /// 本地合作式期限已到。
27    Timeout,
28    /// 明确资源预算耗尽。
29    ResourceLimit {
30        /// 固定资源名称,不包含用户参数。
31        resource: &'static str,
32    },
33    /// 对应流量类别的有界准入队列已满。
34    AdmissionFull,
35    /// 本连接的正 i32 请求 ID 已耗尽。
36    IdExhausted,
37    /// 本地 Session 已关闭。
38    SessionClosed,
39    /// Session ID 已退出,不能复用。
40    SessionIdRetired,
41    /// 当前订阅发生事件或字节溢出。
42    EventBufferFull,
43    /// 入站 envelope 无效。
44    InvalidMessage,
45    /// 响应 Session 与该 request ID 已登记的路由不一致。
46    ///
47    /// 运行时拒绝该响应 payload,只终结对应请求并保持连接及其他路由可用。Chromium 在 child
48    /// Session 退役后可能把迟到响应放到根 envelope;调用方仍须用 Session 生命周期事实判断远端
49    /// 责任,不能把本错误解释为命令未执行。
50    ResponseSessionMismatch,
51    /// 底层传输失败。
52    Transport,
53    /// 本地连接关闭。
54    ConnectionClosed,
55    /// Driver 意外退出。
56    DriverFailed,
57}
58/// 请求失败时保留的身份与提交证据;不包含参数全文。
59#[derive(Clone, Debug)]
60pub struct RequestContext {
61    /// 完整协议方法名。
62    pub method: String,
63    /// 已分配的请求 ID;编码前可为空。
64    pub request_id: Option<RequestId>,
65    /// 本地路由身份。
66    pub session_key: SessionKey,
67    /// 保守提交证据。
68    pub submission: Submission,
69    /// 已消费响应的本地接收序号。
70    pub receive_seq: Option<ReceiveSeq>,
71}
72/// 拥有型错误;Clone 共享底层原因及原始帧,协议说明和上下文中的拥有型字符串会复制。
73#[derive(Clone)]
74pub struct Error {
75    /// 可结构化匹配的类别。
76    pub kind: ErrorKind,
77    /// 请求相关错误的有界上下文。
78    pub context: Option<Box<RequestContext>>,
79    source: Option<Arc<dyn std::error::Error + Send + Sync>>,
80    frame: Option<crate::raw::Frame>,
81}
82impl Error {
83    /// 创建无底层原因的分类错误,不发生 IO。
84    /// ```
85    /// use ydp_core::{Error, ErrorKind};
86    /// let error = Error::new(ErrorKind::Timeout);
87    /// assert!(matches!(error.kind, ErrorKind::Timeout));
88    /// ```
89    pub fn new(kind: ErrorKind) -> Self {
90        Self {
91            kind,
92            context: None,
93            source: None,
94            frame: None,
95        }
96    }
97    /// 保留类型化底层原因;默认 Debug 不展开原因,避免暴露传输凭据。
98    /// ```
99    /// use ydp_core::{Error, ErrorKind};
100    /// let error = Error::with_source(ErrorKind::Transport, std::io::Error::other("失败"));
101    /// assert!(std::error::Error::source(&error).is_some());
102    /// ```
103    pub fn with_source(
104        kind: ErrorKind,
105        source: impl std::error::Error + Send + Sync + 'static,
106    ) -> Self {
107        Self {
108            kind,
109            context: None,
110            source: Some(Arc::new(source)),
111            frame: None,
112        }
113    }
114    /// 保留协议错误原始帧的独立字节许可;例如 `error.retain_frame(frame)` 后,直到错误及其克隆全部 Drop 才释放。
115    /// 不引用连接控制器;运行时回归测试覆盖没有 data 的排队错误及 receiver Drop。
116    pub(crate) fn retain_frame(&mut self, frame: crate::raw::Frame) {
117        self.frame = Some(frame);
118    }
119}
120impl fmt::Debug for Error {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        f.debug_struct("Error")
123            .field("kind", &self.kind)
124            .field("context", &self.context)
125            .finish_non_exhaustive()
126    }
127}
128impl fmt::Display for Error {
129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130        write!(f, "CDP 通信错误:{:?}", self.kind)
131    }
132}
133impl std::error::Error for Error {
134    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
135        self.source.as_ref().map(|s| s.as_ref() as _)
136    }
137}