flare_core/server/handle/default.rs
1//! ServerHandle trait 及其默认实现
2//!
3//! 提供消息发送和连接管理的轻量级接口
4
5use crate::common::error::Result;
6use crate::common::protocol::Frame;
7use crate::server::connection::ConnectionManagerTrait;
8use async_trait::async_trait;
9use std::sync::Arc;
10
11/// 服务器操作处理器
12///
13/// 提供消息发送和连接管理的轻量级接口
14/// 可以在任何需要发送消息或管理连接的地方注入此 trait,而不需要注入整个 Server
15///
16/// # 示例
17///
18/// ```rust
19/// use flare_core::server::ServerHandle;
20/// use flare_core::common::error::Result;
21/// use flare_core::common::protocol::Frame;
22/// use std::sync::Arc;
23///
24/// struct MyHandler {
25/// server_handle: Arc<dyn ServerHandle>,
26/// }
27///
28/// impl MyHandler {
29/// async fn send_message(&self, connection_id: &str, frame: &Frame) -> Result<()> {
30/// self.server_handle.send_to(connection_id, frame).await
31/// }
32/// }
33/// ```
34#[async_trait]
35pub trait ServerHandle: Send + Sync {
36 /// 向指定连接发送消息
37 ///
38 /// # 参数
39 /// - `connection_id`: 目标连接 ID
40 /// - `frame`: 要发送的 Frame
41 ///
42 /// # 返回
43 /// 发送成功返回 `Ok(())`,失败返回错误
44 async fn send_to(&self, connection_id: &str, frame: &Frame) -> Result<()>;
45
46 /// 同一 Frame 发送到多个连接(群扇出主路径)。
47 /// 默认逐连接;带连接管理器的实现按(序列化格式, 压缩)分组、
48 /// 每组序列化一次共享给组内无加密连接。返回(成功数, 失败数)。
49 async fn send_to_connections(&self, connection_ids: &[String], frame: &Frame) -> (i32, i32) {
50 let mut success = 0i32;
51 let mut failure = 0i32;
52 for connection_id in connection_ids {
53 match self.send_to(connection_id, frame).await {
54 Ok(()) => success += 1,
55 Err(_) => failure += 1,
56 }
57 }
58 (success, failure)
59 }
60
61 /// 向指定用户的所有连接发送消息
62 ///
63 /// # 参数
64 /// - `user_id`: 目标用户 ID
65 /// - `frame`: 要发送的 Frame
66 ///
67 /// # 返回
68 /// 发送成功返回 `Ok(())`,失败返回错误
69 async fn send_to_user(&self, user_id: &str, frame: &Frame) -> Result<()>;
70
71 /// 广播消息到所有连接
72 ///
73 /// # 参数
74 /// - `frame`: 要广播的 Frame
75 ///
76 /// # 返回
77 /// 广播成功返回 `Ok(())`,失败返回错误
78 async fn broadcast(&self, frame: &Frame) -> Result<()>;
79
80 /// 广播消息到所有连接,排除指定的连接
81 ///
82 /// # 参数
83 /// - `frame`: 要广播的 Frame
84 /// - `exclude_connection_id`: 要排除的连接 ID
85 ///
86 /// # 返回
87 /// 广播成功返回 `Ok(())`,失败返回错误
88 async fn broadcast_except(&self, frame: &Frame, exclude_connection_id: &str) -> Result<()>;
89
90 /// 断开指定连接
91 ///
92 /// # 参数
93 /// - `connection_id`: 要断开的连接 ID
94 ///
95 /// # 返回
96 /// 断开成功返回 `Ok(())`,失败返回错误
97 async fn disconnect(&self, connection_id: &str) -> Result<()>;
98
99 /// 获取连接数量
100 ///
101 /// # 返回
102 /// 当前连接数量
103 fn connection_count(&self) -> usize;
104
105 /// 获取用户数量
106 ///
107 /// # 返回
108 /// 当前用户数量
109 fn user_count(&self) -> usize;
110}
111
112/// ServerHandle 的默认实现
113///
114/// 基于连接管理器和消息解析器实现,轻量级且易于使用
115///
116/// # 示例
117///
118/// ```rust
119/// use flare_core::server::DefaultServerHandle;
120/// use flare_core::server::connection::ConnectionManager;
121/// use flare_core::server::ConnectionManagerTrait;
122/// use std::sync::Arc;
123///
124/// let connection_manager = Arc::new(ConnectionManager::new());
125/// let handle = Arc::new(DefaultServerHandle::new(
126/// connection_manager as Arc<dyn ConnectionManagerTrait>,
127/// ));
128/// ```
129pub struct DefaultServerHandle {
130 /// 连接管理器
131 connection_manager: Arc<dyn ConnectionManagerTrait>,
132}
133
134impl DefaultServerHandle {
135 /// 创建新的 ServerHandle 实例
136 ///
137 /// # 参数
138 /// - `connection_manager`: 连接管理器 trait 对象
139 ///
140 /// # 返回
141 /// 返回新的 `DefaultServerHandle` 实例
142 pub fn new(connection_manager: Arc<dyn ConnectionManagerTrait>) -> Self {
143 Self { connection_manager }
144 }
145}
146
147#[async_trait]
148impl ServerHandle for DefaultServerHandle {
149 async fn send_to(&self, connection_id: &str, frame: &Frame) -> Result<()> {
150 // 传入 None,让 ConnectionManager 根据连接的协商信息创建 parser
151 self.connection_manager
152 .send_frame_to(connection_id, frame, None)
153 .await
154 }
155
156 async fn send_to_connections(&self, connection_ids: &[String], frame: &Frame) -> (i32, i32) {
157 self.connection_manager
158 .send_frame_to_connections(connection_ids, frame)
159 .await
160 }
161
162 async fn send_to_user(&self, user_id: &str, frame: &Frame) -> Result<()> {
163 // 传入 None,让 ConnectionManager 为每个连接使用其协商的格式
164 self.connection_manager
165 .send_frame_to_user(user_id, frame, None)
166 .await
167 }
168
169 async fn broadcast(&self, frame: &Frame) -> Result<()> {
170 // 传入 None,让 ConnectionManager 为每个连接使用其协商的格式
171 self.connection_manager.broadcast_frame(frame, None).await
172 }
173
174 async fn broadcast_except(&self, frame: &Frame, exclude_connection_id: &str) -> Result<()> {
175 // 传入 None,让 ConnectionManager 为每个连接使用其协商的格式
176 self.connection_manager
177 .broadcast_frame_except(frame, exclude_connection_id, None)
178 .await
179 }
180
181 async fn disconnect(&self, connection_id: &str) -> Result<()> {
182 self.connection_manager
183 .remove_connection(connection_id)
184 .await
185 }
186
187 fn connection_count(&self) -> usize {
188 // 同步快照:廉价原子读,禁止阻塞/网络(见 ConnectionManagerTrait::connection_count_snapshot)。
189 self.connection_manager.connection_count_snapshot()
190 }
191
192 fn user_count(&self) -> usize {
193 self.connection_manager.user_count_snapshot()
194 }
195}