Skip to main content

flare_core/server/builder/
flare.rs

1//! Flare 模式服务端构建器
2//!
3//! 提供完整功能实现,包含所有 `common` 和 `server` 模块的能力,推荐用于生产环境。
4//!
5//! ## 特点
6//! - ✅ **实现 `ServerEventHandler` trait(必需)**:提供细化的命令处理方法
7//! - ✅ **自动消息路由**:`ServerMessageWrapper` 自动将消息路由到对应的处理方法
8//! - ✅ **自动 ACK 处理**:如果 handler 返回 `None`,框架自动发送 ACK
9//! - ✅ **错误处理**:处理失败时自动发送错误 ACK,确保客户端能收到响应
10//! - ✅ **设备管理**:完整的设备冲突策略和多端管理
11//! - ✅ **认证机制**:JWT Token 认证
12//! - ✅ **心跳检测**:自动心跳和超时管理
13//! - ✅ **多协议支持**:WebSocket + QUIC 双协议
14//! - ✅ **序列化协商**:自动协商最佳序列化格式(JSON/Protobuf)和压缩算法(None/Gzip/Zstd)
15//!
16//! ## 适用场景
17//! - 生产环境
18//! - 需要完整功能的企业应用
19//! - 需要高性能和可扩展性的场景
20//! - 需要统一消息处理流程的场景
21//!
22//! ## 架构说明
23//!
24//! Flare 模式基于 `HybridServer`,使用 `ServerMessageWrapper` 作为消息处理器。
25//! `ServerMessageWrapper` 集成了所有核心功能:
26//! - 自动消息路由到 `ServerEventHandler` 的对应方法
27//! - 自动 ACK 处理和错误响应
28//! - 设备管理和连接生命周期管理
29//! - 所有模式共享的底层能力(多协议、序列化协商、心跳等)
30
31use crate::common::error::Result;
32use crate::common::message::{ArcMessageMiddleware, ArcMessageProcessor};
33use crate::common::protocol::Frame;
34use crate::server::HybridServer;
35use crate::server::builder::{BaseServerBuilderConfig, ServerWrapper};
36use crate::server::connection::ConnectionManager;
37use crate::server::events::handler::ServerEventHandler;
38use crate::server::handle::ServerHandle;
39use std::sync::Arc;
40use tracing::{error, info};
41
42/// Flare 模式服务端构建器
43///
44/// 提供完整功能实现,是最强大的服务端构建模式。
45///
46/// ## 设计原则
47///
48/// - **公共逻辑统一处理**:基于 `HybridServer`,共享所有核心能力
49/// - **自动消息路由**:`ServerMessageWrapper` 自动将消息路由到 `ServerEventHandler` 的对应方法
50/// - **自动 ACK 处理**:如果 handler 返回 `None`,框架自动发送 ACK
51/// - **错误处理**:处理失败时自动发送错误 ACK,确保客户端能收到响应
52///
53/// ## 使用方式
54///
55/// 用户只需要实现 `ServerEventHandler` trait,框架会自动处理:
56/// - 消息路由到对应的方法(handle_message、handle_ack、handle_notification_command 等)
57/// - ACK 和错误响应
58/// - 连接生命周期管理
59/// - 设备管理和认证
60pub struct FlareServerBuilder {
61    base: BaseServerBuilderConfig,
62    event_handler: Arc<dyn ServerEventHandler>,
63    connection_manager: Option<Arc<ConnectionManager>>,
64    device_manager: Option<Arc<crate::server::device::DeviceManager>>,
65    middlewares: Vec<ArcMessageMiddleware>,
66    processors: Vec<ArcMessageProcessor>,
67}
68
69impl FlareServerBuilder {
70    /// 创建新的 Flare 服务端构建器
71    ///
72    /// # 参数
73    /// - `bind_address`: 绑定地址
74    /// - `event_handler`: 事件处理器(必须),用户只需要实现 `ServerEventHandler` 的 `handle_message` 方法即可
75    ///
76    /// # 示例
77    /// ```rust,ignore
78    /// use flare_core::server::events::handler::ServerEventHandler;
79    /// use flare_core::common::protocol::PayloadCommand;
80    /// use flare_core::common::error::Result;
81    /// use flare_core::common::protocol::Frame;
82    /// use async_trait::async_trait;
83    /// use std::sync::Arc;
84    ///
85    /// struct MyHandler;
86    ///
87    /// #[async_trait]
88    /// impl ServerEventHandler for MyHandler {
89    ///     async fn handle_message(
90    ///         &self,
91    ///         command: &PayloadCommand,
92    ///         connection_id: &str,
93    ///     ) -> Result<Option<Frame>> {
94    ///         // 处理消息
95    ///         Ok(None)
96    ///     }
97    /// }
98    ///
99    /// let server = FlareServerBuilder::new("0.0.0.0:8080", Arc::new(MyHandler))
100    ///     .build()?;
101    /// ```
102    pub fn new(
103        bind_address: impl Into<String>,
104        event_handler: Arc<dyn ServerEventHandler>,
105    ) -> Self {
106        Self {
107            base: BaseServerBuilderConfig::new(bind_address),
108            event_handler,
109            connection_manager: None,
110            device_manager: None,
111            middlewares: Vec::new(),
112            processors: Vec::new(),
113        }
114    }
115
116    /// 设置连接管理器(可选)
117    pub fn with_connection_manager(mut self, manager: Arc<ConnectionManager>) -> Self {
118        self.connection_manager = Some(manager);
119        self
120    }
121
122    /// 设置设备管理器(可选)
123    pub fn with_device_manager(
124        mut self,
125        device_manager: Arc<crate::server::device::DeviceManager>,
126    ) -> Self {
127        self.device_manager = Some(device_manager);
128        self
129    }
130
131    /// 设置认证器(可选)
132    pub fn with_authenticator(
133        mut self,
134        authenticator: Arc<dyn crate::server::auth::Authenticator>,
135    ) -> Self {
136        self.base = self.base.with_authenticator(authenticator);
137        self
138    }
139
140    /// 启用认证
141    pub fn enable_auth(mut self) -> Self {
142        self.base = self.base.enable_auth();
143        self
144    }
145
146    /// 设置认证超时时间
147    pub fn with_auth_timeout(mut self, timeout: std::time::Duration) -> Self {
148        self.base = self.base.with_auth_timeout(timeout);
149        self
150    }
151
152    // ============================================================
153    // 配置方法(委托给 BaseServerBuilderConfig)
154    // ============================================================
155
156    /// 设置传输协议
157    pub fn with_protocol(
158        mut self,
159        protocol: crate::common::config_types::TransportProtocol,
160    ) -> Self {
161        self.base = self.base.with_protocol(protocol);
162        self
163    }
164
165    /// 启用多协议监听
166    pub fn with_protocols(
167        mut self,
168        protocols: Vec<crate::common::config_types::TransportProtocol>,
169    ) -> Self {
170        self.base = self.base.with_protocols(protocols);
171        self
172    }
173
174    /// 为特定协议设置监听地址
175    pub fn with_protocol_address(
176        mut self,
177        protocol: crate::common::config_types::TransportProtocol,
178        address: String,
179    ) -> Self {
180        self.base = self.base.with_protocol_address(protocol, address);
181        self
182    }
183
184    /// 设置默认序列化格式
185    pub fn with_default_format(
186        mut self,
187        format: crate::common::protocol::SerializationFormat,
188    ) -> Self {
189        self.base = self.base.with_default_format(format);
190        self
191    }
192
193    /// 设置默认压缩算法
194    pub fn with_default_compression(
195        mut self,
196        compression: crate::common::compression::CompressionAlgorithm,
197    ) -> Self {
198        self.base = self.base.with_default_compression(compression);
199        self
200    }
201
202    /// 设置默认加密算法
203    pub fn with_default_encryption(
204        mut self,
205        encryption: crate::common::encryption::EncryptionAlgorithm,
206    ) -> Self {
207        self.base = self.base.with_default_encryption(encryption);
208        self
209    }
210
211    /// 设置最大连接数
212    pub fn with_max_connections(mut self, max: usize) -> Self {
213        self.base = self.base.with_max_connections(max);
214        self
215    }
216
217    /// 设置握手超时时间
218    pub fn with_handshake_timeout(mut self, timeout: std::time::Duration) -> Self {
219        self.base = self.base.with_handshake_timeout(timeout);
220        self
221    }
222
223    /// 设置最大并发握手数
224    pub fn with_max_handshake_concurrency(mut self, max: usize) -> Self {
225        self.base = self.base.with_max_handshake_concurrency(max);
226        self
227    }
228
229    /// 设置单次连接写入超时时间
230    pub fn with_write_timeout(mut self, timeout: std::time::Duration) -> Self {
231        self.base = self.base.with_write_timeout(timeout);
232        self
233    }
234
235    /// 设置 fanout 发送最大并发度
236    pub fn with_fanout_concurrency(mut self, max: usize) -> Self {
237        self.base = self.base.with_fanout_concurrency(max);
238        self
239    }
240
241    /// 设置连接超时
242    pub fn with_connection_timeout(mut self, timeout: std::time::Duration) -> Self {
243        self.base = self.base.with_connection_timeout(timeout);
244        self
245    }
246
247    /// 设置心跳配置
248    pub fn with_heartbeat(
249        mut self,
250        heartbeat: crate::common::config_types::HeartbeatConfig,
251    ) -> Self {
252        self.base = self.base.with_heartbeat(heartbeat);
253        self
254    }
255
256    /// 设置 TLS 配置
257    pub fn with_tls(mut self, tls: crate::common::config_types::TlsConfig) -> Self {
258        self.base = self.base.with_tls(tls);
259        self
260    }
261
262    /// 设置设备冲突策略
263    pub fn with_device_conflict_strategy(
264        mut self,
265        strategy: crate::common::device::DeviceConflictStrategy,
266    ) -> Self {
267        self.base = self.base.with_device_conflict_strategy(strategy);
268        self
269    }
270
271    /// 添加中间件(用于消息处理管道)
272    ///
273    /// 中间件会在消息处理前后执行,可以用于日志、监控、验证等。
274    /// 中间件按添加顺序执行,优先级高的中间件会先执行。
275    ///
276    /// # 参数
277    /// - `middleware`: 中间件实例
278    ///
279    /// # 示例
280    /// ```rust,ignore
281    /// use flare_core::common::message::{LoggingMiddleware, LogLevel};
282    ///
283    /// FlareServerBuilder::new("0.0.0.0:8080", handler)
284    ///     .with_middleware(Arc::new(LoggingMiddleware::new("ServerLogging")
285    ///         .with_level(LogLevel::Info)))
286    ///     .build()?;
287    /// ```
288    pub fn with_middleware(mut self, middleware: ArcMessageMiddleware) -> Self {
289        self.middlewares.push(middleware);
290        self
291    }
292
293    /// 添加处理器(用于消息处理管道)
294    ///
295    /// 处理器用于处理具体的业务逻辑。
296    /// 如果处理器返回响应,后续处理器不会执行。
297    ///
298    /// # 参数
299    /// - `processor`: 处理器实例
300    pub fn with_processor(mut self, processor: ArcMessageProcessor) -> Self {
301        self.processors.push(processor);
302        self
303    }
304
305    /// 构建服务端
306    ///
307    /// # 错误处理
308    /// - 如果配置无效(如启用了认证但未提供认证器),返回配置错误
309    /// - 如果服务器初始化失败,返回相应的错误
310    ///
311    /// # 返回
312    /// - `Ok(FlareServer)` - 成功构建的服务端实例
313    /// - `Err(FlareError)` - 构建失败的错误信息
314    ///
315    /// Flare 模式使用 `ServerMessageWrapper` 作为消息处理器,它:
316    /// - 集成了 `ServerEventHandler` 的所有功能,自动路由消息到对应的处理方法
317    /// - 自动处理 ACK、错误响应等基础功能
318    /// - 支持设备管理、连接管理等高级特性
319    pub fn build(self) -> Result<FlareServer> {
320        // 验证配置(使用公共验证逻辑)
321        crate::server::builder::common::validate_auth_config(
322            &self.base.config,
323            &self.base.authenticator,
324        )?;
325
326        // 创建消息解析器(使用公共创建逻辑)
327        // let parser = crate::server::builder::common::create_message_parser(&self.base.config);
328
329        info!(
330            "[FlareServerBuilder] 开始构建服务端: bind_address={}, protocols={:?}, format={:?}, compression={:?}",
331            self.base.config.bind_address,
332            self.base.config.get_protocols(),
333            self.base.config.default_serialization_format,
334            self.base.config.default_compression
335        );
336
337        let middleware_count = self.middlewares.len();
338        let processor_count = self.processors.len();
339
340        let server = HybridServer::with_connection_manager_and_pipeline(
341            self.base.config,
342            self.connection_manager,
343            self.device_manager,
344            Some(self.event_handler.clone()),
345            self.base.authenticator,
346            self.middlewares,
347            self.processors,
348        )
349        .map_err(|e| {
350            error!("[FlareServerBuilder] 构建服务端失败: {}", e);
351            e
352        })?;
353
354        if middleware_count > 0 || processor_count > 0 {
355            info!(
356                "[FlareServerBuilder] 已配置 {} 个中间件和 {} 个处理器",
357                middleware_count, processor_count
358            );
359        }
360
361        info!("[FlareServerBuilder] 服务端构建成功");
362        Ok(FlareServer {
363            wrapper: ServerWrapper::new(server),
364            event_handler: self.event_handler,
365        })
366    }
367}
368
369/// Flare 服务端
370pub struct FlareServer {
371    wrapper: ServerWrapper,
372    #[allow(dead_code)] // 保留用于未来扩展(如动态更新事件处理器)
373    event_handler: Arc<dyn ServerEventHandler>,
374}
375
376impl FlareServer {
377    /// 启动服务端
378    pub async fn start(&self) -> Result<()> {
379        self.wrapper.start().await
380    }
381
382    /// 停止服务端
383    pub async fn stop(&self) -> Result<()> {
384        self.wrapper.stop().await
385    }
386
387    /// 检查服务端是否运行
388    pub fn is_running(&self) -> bool {
389        self.wrapper.is_running()
390    }
391
392    /// 获取连接数量
393    pub fn connection_count(&self) -> usize {
394        self.wrapper.connection_count()
395    }
396
397    /// 获取用户数量
398    pub fn user_count(&self) -> usize {
399        self.wrapper.user_count()
400    }
401
402    /// 向指定连接发送消息
403    pub async fn send_to(&self, connection_id: &str, frame: &Frame) -> Result<()> {
404        self.wrapper.send_to(connection_id, frame).await
405    }
406
407    /// 向指定用户的所有连接发送消息
408    pub async fn send_to_user(&self, user_id: &str, frame: &Frame) -> Result<()> {
409        self.wrapper.send_to_user(user_id, frame).await
410    }
411
412    /// 广播消息到所有连接
413    pub async fn broadcast(&self, frame: &Frame) -> Result<()> {
414        self.wrapper.broadcast(frame).await
415    }
416
417    /// 广播消息到所有连接,排除指定连接
418    pub async fn broadcast_except(&self, frame: &Frame, exclude_connection_id: &str) -> Result<()> {
419        self.wrapper
420            .broadcast_except(frame, exclude_connection_id)
421            .await
422    }
423
424    /// 断开指定连接
425    pub async fn disconnect(&self, connection_id: &str) -> Result<()> {
426        self.wrapper.disconnect(connection_id).await
427    }
428
429    /// 获取协议列表
430    pub fn protocols(&self) -> Vec<crate::common::config_types::TransportProtocol> {
431        self.wrapper.protocols()
432    }
433
434    /// 获取 ServerHandle 组件(用于创建 DefaultServerHandle)
435    ///
436    /// # 返回
437    /// 返回 ConnectionManagerTrait
438    pub fn get_server_handle_components(
439        &self,
440    ) -> Option<Arc<dyn crate::server::connection::ConnectionManagerTrait>> {
441        self.wrapper.get_server_handle_components()
442    }
443
444    /// 获取 ServerHandle(用于消息发送和连接管理)
445    pub fn get_server_handle(&self) -> Option<Arc<dyn ServerHandle>> {
446        self.wrapper.get_server_handle()
447    }
448}