Skip to main content

flare_core/client/builder/
simple.rs

1//! 简单模式客户端构建器
2//!
3//! 提供最小实现,使用闭包定义消息处理逻辑,适合快速原型开发和学习。
4//!
5//! ## 特点
6//! - ✅ **使用闭包处理消息和事件**:无需实现 trait,直接使用闭包
7//! - ✅ **最小依赖**:只提供基本的消息处理功能
8//! - ✅ **零配置**:使用默认配置即可运行
9//! - ✅ **轻量级**:不包含中间件、管道等高级功能
10//! - ✅ **快速上手**:几行代码即可启动客户端
11//!
12//! ## 适用场景
13//! - 快速原型开发
14//! - 学习和测试
15//! - 小型应用
16//! - 需要完全控制消息处理流程的场景
17//!
18//! ## 架构说明
19//!
20//! 简单模式基于 `HybridClient`,共享所有核心能力(多协议支持、序列化协商、心跳检测等),
21//! 但消息处理逻辑通过闭包定义,不依赖高级抽象。
22
23#[cfg(not(target_arch = "wasm32"))]
24use crate::client::HybridClient;
25#[cfg(target_arch = "wasm32")]
26use crate::client::WebSocketClient;
27use crate::client::builder::{BaseClientBuilderConfig, ClientWrapper};
28use crate::common::error::Result;
29use crate::common::protocol::Frame;
30use crate::transport::events::{ConnectionEvent, ConnectionObserver};
31use std::sync::Arc;
32
33/// 客户端消息处理函数类型
34pub type ClientMessageHandler = Box<dyn Fn(&Frame) -> Result<()> + Send + Sync>;
35
36/// 客户端事件处理函数类型
37pub type ClientEventHandler = Box<dyn Fn(&ConnectionEvent) + Send + Sync>;
38
39/// 简化的客户端观察者
40struct SimpleClientObserver {
41    message_handler: Option<ClientMessageHandler>,
42    event_handler: Option<ClientEventHandler>,
43}
44
45impl ConnectionObserver for SimpleClientObserver {
46    fn on_event(&self, event: &ConnectionEvent) {
47        if let Some(ref handler) = self.event_handler {
48            handler(event);
49        }
50
51        if let ConnectionEvent::Message(data) = event
52            && let Some(ref handler) = self.message_handler
53            && let Ok(frame) = crate::common::MessageParser::new(
54                crate::common::protocol::SerializationFormat::Protobuf,
55                crate::common::compression::CompressionAlgorithm::None,
56                crate::common::encryption::EncryptionAlgorithm::None,
57            )
58            .parse(data)
59            && let Err(e) = handler(&frame)
60        {
61            tracing::error!("消息处理错误: {:?}", e);
62        }
63    }
64}
65
66/// 简化的客户端实例
67pub struct SimpleClient {
68    wrapper: ClientWrapper,
69    observer: Arc<SimpleClientObserver>,
70}
71
72impl SimpleClient {
73    /// 连接到服务器
74    pub async fn connect(&mut self) -> Result<()> {
75        self.wrapper
76            .add_observer(self.observer.clone() as Arc<dyn ConnectionObserver>)
77            .await;
78        self.wrapper.connect().await
79    }
80
81    /// 断开连接
82    pub async fn disconnect(&mut self) -> Result<()> {
83        self.wrapper.disconnect().await
84    }
85
86    /// 发送消息
87    pub async fn send_frame(&mut self, frame: &Frame) -> Result<()> {
88        self.wrapper.send_frame(frame).await
89    }
90
91    /// 发送并等待响应(按 message_id 匹配)
92    pub async fn send_frame_and_wait(
93        &mut self,
94        frame: &Frame,
95        timeout: std::time::Duration,
96    ) -> Result<Frame> {
97        self.wrapper.send_frame_and_wait(frame, timeout).await
98    }
99
100    /// 检查连接状态
101    pub async fn is_connected(&self) -> bool {
102        self.wrapper.is_connected_async().await
103    }
104
105    /// 获取连接 ID
106    pub async fn connection_id(&self) -> Option<String> {
107        self.wrapper.connection_id_async().await
108    }
109
110    /// 获取活动协议
111    pub fn active_protocol(&self) -> crate::common::config_types::TransportProtocol {
112        self.wrapper.active_protocol()
113    }
114
115    /// 获取当前消息解析器快照(协商完成后与 `flare_chat_server` 等 Flare 服务端一致)
116    pub async fn parser_snapshot(&self) -> crate::common::MessageParser {
117        self.wrapper.parser_snapshot().await
118    }
119
120    /// 等待 CONNECT_ACK 协商完成
121    pub async fn wait_for_negotiation(&self, timeout: std::time::Duration) -> Result<()> {
122        self.wrapper.wait_for_negotiation(timeout).await
123    }
124}
125
126/// 简单模式客户端构建器
127///
128/// 提供最小实现,使用闭包定义消息处理逻辑,适合快速原型开发和学习。
129///
130/// ## 设计原则
131///
132/// - **公共逻辑统一处理**:基于 `HybridClient`,共享所有核心能力(多协议、序列化协商、心跳等)
133/// - **最小抽象**:消息处理通过闭包定义,不依赖 trait 实现
134/// - **零配置**:使用默认配置即可运行
135///
136/// ## 使用方式
137///
138/// 使用闭包定义消息和事件处理逻辑,无需实现 trait。
139pub struct ClientBuilder {
140    base: BaseClientBuilderConfig,
141    message_handler: Option<ClientMessageHandler>,
142    event_handler: Option<ClientEventHandler>,
143}
144
145impl ClientBuilder {
146    /// 创建新的客户端构建器
147    ///
148    /// # 参数
149    /// - `server_url`: 服务器地址,例如 "ws://127.0.0.1:8080" 或 "quic://127.0.0.1:8080"
150    pub fn new(server_url: impl Into<String>) -> Self {
151        Self {
152            base: BaseClientBuilderConfig::new(server_url),
153            message_handler: None,
154            event_handler: None,
155        }
156    }
157
158    /// 设置消息处理函数
159    ///
160    /// # 参数
161    /// - `handler`: 消息处理函数,接收 Frame
162    pub fn on_message<F>(mut self, handler: F) -> Self
163    where
164        F: Fn(&Frame) -> Result<()> + Send + Sync + 'static,
165    {
166        self.message_handler = Some(Box::new(handler));
167        self
168    }
169
170    /// 设置事件处理函数
171    ///
172    /// # 参数
173    /// - `handler`: 事件处理函数,接收 ConnectionEvent
174    pub fn on_event<F>(mut self, handler: F) -> Self
175    where
176        F: Fn(&ConnectionEvent) + Send + Sync + 'static,
177    {
178        self.event_handler = Some(Box::new(handler));
179        self
180    }
181
182    /// 设置传输协议
183    pub fn with_protocol(
184        mut self,
185        protocol: crate::common::config_types::TransportProtocol,
186    ) -> Self {
187        self.base = self.base.with_protocol(protocol);
188        self
189    }
190
191    /// 启用多协议竞速
192    ///
193    /// 协议列表的顺序就是优先级顺序,前面的协议优先级更高
194    pub fn with_protocol_race(
195        mut self,
196        protocols: Vec<crate::common::config_types::TransportProtocol>,
197    ) -> Self {
198        self.base = self.base.with_protocol_race(protocols);
199        self
200    }
201
202    /// 为特定协议设置服务器地址
203    pub fn with_protocol_url(
204        mut self,
205        protocol: crate::common::config_types::TransportProtocol,
206        url: String,
207    ) -> Self {
208        self.base = self.base.with_protocol_url(protocol, url);
209        self
210    }
211
212    /// 设置用户 ID
213    pub fn with_user_id(mut self, user_id: String) -> Self {
214        self.base = self.base.with_user_id(user_id);
215        self
216    }
217
218    /// 设置设备信息(CONNECT 协商与设备管理)
219    pub fn with_device_info(mut self, device_info: crate::common::device::DeviceInfo) -> Self {
220        self.base = self.base.with_device_info(device_info);
221        self
222    }
223
224    /// 设置 Token(用于认证,如果服务端启用认证,必须提供)
225    pub fn with_token(mut self, token: String) -> Self {
226        self.base = self.base.with_token(token);
227        self
228    }
229
230    /// 设置序列化格式
231    pub fn with_format(mut self, format: crate::common::protocol::SerializationFormat) -> Self {
232        self.base = self.base.with_format(format);
233        self
234    }
235
236    /// 设置压缩算法
237    pub fn with_compression(
238        mut self,
239        compression: crate::common::compression::CompressionAlgorithm,
240    ) -> Self {
241        self.base = self.base.with_compression(compression);
242        self
243    }
244
245    /// 设置心跳配置
246    pub fn with_heartbeat(
247        mut self,
248        heartbeat: crate::common::config_types::HeartbeatConfig,
249    ) -> Self {
250        self.base = self.base.with_heartbeat(heartbeat);
251        self
252    }
253
254    /// 设置 TLS 配置
255    pub fn with_tls(mut self, tls: crate::common::config_types::TlsConfig) -> Self {
256        self.base = self.base.with_tls(tls);
257        self
258    }
259
260    /// 设置连接超时
261    pub fn with_connect_timeout(mut self, timeout: std::time::Duration) -> Self {
262        self.base = self.base.with_connect_timeout(timeout);
263        self
264    }
265
266    /// 设置重连间隔
267    pub fn with_reconnect_interval(mut self, interval: std::time::Duration) -> Self {
268        self.base = self.base.with_reconnect_interval(interval);
269        self
270    }
271
272    /// 设置最大重连次数
273    pub fn with_max_reconnect_attempts(mut self, max: Option<u32>) -> Self {
274        self.base = self.base.with_max_reconnect_attempts(max);
275        self
276    }
277
278    /// 启用消息路由
279    ///
280    /// 启用后,可以通过 ClientCore 的 router 方法注册消息处理器
281    pub fn enable_router(mut self) -> Self {
282        self.base = self.base.enable_router();
283        self
284    }
285
286    /// 构建客户端
287    ///
288    /// # 返回
289    /// 返回配置好的 SimpleClient 实例
290    pub fn build(self) -> Result<SimpleClient> {
291        let observer = Arc::new(SimpleClientObserver {
292            message_handler: self.message_handler,
293            event_handler: self.event_handler,
294        });
295
296        let client = {
297            #[cfg(not(target_arch = "wasm32"))]
298            {
299                HybridClient::new(self.base.config)?
300            }
301            #[cfg(target_arch = "wasm32")]
302            {
303                WebSocketClient::new(self.base.config)
304            }
305        };
306        let wrapper = ClientWrapper::new(client);
307
308        Ok(SimpleClient { wrapper, observer })
309    }
310}