mofa_kernel/agent/secretary/connection.rs
1//! 用户连接抽象
2//!
3//! 定义秘书与用户之间的通信接口,具体实现位于 mofa-foundation。
4
5use async_trait::async_trait;
6
7// =============================================================================
8// 用户连接 Trait
9// =============================================================================
10
11/// 用户连接Trait
12///
13/// 定义秘书与用户之间的通信接口。
14/// 不同的连接方式(WebSocket、TCP、Channel等)都可以实现这个trait。
15///
16/// # 类型参数
17///
18/// - `Input`: 用户发送的输入类型
19/// - `Output`: 秘书发送的输出类型
20///
21/// # 示例
22///
23/// ```rust,ignore
24/// struct WebSocketConnection {
25/// ws: WebSocket,
26/// }
27///
28/// #[async_trait]
29/// impl UserConnection for WebSocketConnection {
30/// type Input = UserMessage;
31/// type Output = SecretaryResponse;
32///
33/// async fn receive(&self) -> anyhow::Result<Self::Input> {
34/// let msg = self.ws.recv().await?;
35/// Ok(serde_json::from_str(&msg)?)
36/// }
37///
38/// async fn send(&self, output: Self::Output) -> anyhow::Result<()> {
39/// self.ws.send(serde_json::to_string(&output)?).await?;
40/// Ok(())
41/// }
42///
43/// fn is_connected(&self) -> bool {
44/// self.ws.is_open()
45/// }
46/// }
47/// ```
48#[async_trait]
49pub trait UserConnection: Send + Sync {
50 /// 用户输入类型
51 type Input: Send + 'static;
52
53 /// 秘书输出类型
54 type Output: Send + 'static;
55
56 /// 接收用户输入(阻塞)
57 async fn receive(&self) -> anyhow::Result<Self::Input>;
58
59 /// 尝试接收用户输入(非阻塞)
60 ///
61 /// 返回 `Ok(Some(input))` 表示收到输入
62 /// 返回 `Ok(None)` 表示没有可用输入
63 /// 返回 `Err(e)` 表示发生错误
64 async fn try_receive(&self) -> anyhow::Result<Option<Self::Input>>;
65
66 /// 发送输出给用户
67 async fn send(&self, output: Self::Output) -> anyhow::Result<()>;
68
69 /// 检查连接是否有效
70 fn is_connected(&self) -> bool;
71
72 /// 关闭连接
73 async fn close(&self) -> anyhow::Result<()> {
74 Ok(())
75 }
76}
77
78// =============================================================================
79// 连接工厂
80// =============================================================================
81
82/// 连接工厂Trait
83///
84/// 用于创建连接实例
85#[async_trait]
86pub trait ConnectionFactory: Send + Sync {
87 /// 连接类型
88 type Connection: UserConnection;
89
90 /// 创建连接
91 async fn create(&self) -> anyhow::Result<Self::Connection>;
92}