Skip to main content

ydp_core/
transport.rs

1use bytes::Bytes;
2use std::{fmt, future::Future, sync::Arc};
3/// 传输错误;默认格式不展开可能包含凭据的底层原因。
4#[derive(Clone)]
5pub struct TransportError(Arc<dyn std::error::Error + Send + Sync>);
6impl TransportError {
7    /// 保存拥有型、可跨任务传递的原因,不发生 IO。
8    /// ```
9    /// let error = ydp_core::TransportError::new(std::io::Error::other("连接关闭"));
10    /// assert!(std::error::Error::source(&error).is_some());
11    /// ```
12    pub fn new(source: impl std::error::Error + Send + Sync + 'static) -> Self {
13        Self(Arc::new(source))
14    }
15}
16impl fmt::Debug for TransportError {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        f.write_str("TransportError { source: 隐藏 }")
19    }
20}
21impl fmt::Display for TransportError {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        f.write_str("传输失败")
24    }
25}
26impl std::error::Error for TransportError {
27    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
28        Some(self.0.as_ref())
29    }
30}
31/// 已建立的完整文本消息传输;两个方向必须可以在同一任务独立推进。
32pub trait Transport: Send + 'static {
33    /// 拥有型读半部。
34    type Reader: MessageReader;
35    /// 拥有型写半部。
36    type Writer: MessageWriter;
37    /// 消耗传输并转交两半;不建立新连接。
38    /// ```no_run
39    /// fn halves<T: ydp_core::Transport>(transport: T) { let (_reader, _writer) = transport.split(); }
40    /// ```
41    fn split(self) -> (Self::Reader, Self::Writer);
42}
43/// 完整消息读取边界;只有连接终结时运行时才丢弃进行中的操作。
44pub trait MessageReader: Send + 'static {
45    /// 异步取得完整 UTF-8 JSON 字节;EOF 返回 None;Pending 不得阻塞线程。
46    /// ```no_run
47    /// async fn read<R: ydp_core::MessageReader>(reader: &mut R) { let _ = reader.recv().await; }
48    /// ```
49    fn recv(
50        &mut self,
51    ) -> impl Future<Output = std::result::Result<Option<Bytes>, TransportError>> + Send;
52}
53/// 唯一 Writer owner 操作的写边界;不得在等待时阻挡 Reader。
54pub trait MessageWriter: Send + 'static {
55    /// 接受完整文本消息;成功不证明远端接收,资源可保持到 flush。
56    /// ```no_run
57    /// async fn write<W: ydp_core::MessageWriter>(writer: &mut W) { let _ = writer.send(bytes::Bytes::from_static(b"{}")).await; }
58    /// ```
59    fn send(
60        &mut self,
61        bytes: Bytes,
62    ) -> impl Future<Output = std::result::Result<(), TransportError>> + Send;
63    /// 推进已接受数据;成功不证明远端执行。
64    /// ```no_run
65    /// async fn flush<W: ydp_core::MessageWriter>(writer: &mut W) { let _ = writer.flush().await; }
66    /// ```
67    fn flush(&mut self) -> impl Future<Output = std::result::Result<(), TransportError>> + Send;
68    /// 开始传输关闭;核心同时推进 Reader,终结时允许销毁两半。
69    /// ```no_run
70    /// async fn close<W: ydp_core::MessageWriter>(writer: &mut W) { let _ = writer.close().await; }
71    /// ```
72    fn close(&mut self) -> impl Future<Output = std::result::Result<(), TransportError>> + Send;
73}