Skip to main content

flare_core/server/builder/
common.rs

1//! 服务端构建器通用组件
2//!
3//! 提供所有构建器共享的辅助类型和函数,体现"公共逻辑统一处理"的设计原则。
4//!
5//! ## 设计原则
6//!
7//! - **统一包装接口**:`ServerWrapper` 为所有构建模式提供统一的 `ServerHandle` 访问接口
8//! - **共享底层实现**:所有模式都基于 `HybridServer`,共享核心能力
9//! - **零成本抽象**:包装层不带来运行时开销
10
11use crate::common::error::Result;
12use crate::common::protocol::Frame;
13use crate::server::connection::ConnectionManagerTrait;
14use crate::server::handle::{DefaultServerHandle, ServerHandle};
15use crate::server::{HybridServer, Server};
16use std::sync::Arc;
17use tokio::sync::Mutex;
18
19/// 服务端包装器
20///
21/// 提供统一的 `ServerHandle` 访问接口,所有构建模式都使用此包装器。
22///
23/// ## 设计原则
24///
25/// - **统一接口**:所有模式(简单、观察者、Flare)都通过 `ServerWrapper` 访问服务端功能
26/// - **共享底层**:基于 `HybridServer`,共享所有核心能力
27/// - **类型安全**:通过 Rust 类型系统保证接口的正确性
28pub struct ServerWrapper {
29    server: Arc<Mutex<HybridServer>>,
30}
31
32impl ServerWrapper {
33    /// 创建新的服务端包装器
34    pub fn new(server: HybridServer) -> Self {
35        Self {
36            server: Arc::new(Mutex::new(server)),
37        }
38    }
39
40    /// 获取内部的 HybridServer(用于实现 Server trait)
41    pub fn server(&self) -> &Arc<Mutex<HybridServer>> {
42        &self.server
43    }
44
45    /// 获取 ServerHandle 组件(用于创建 DefaultServerHandle)
46    ///
47    /// # 返回
48    /// 返回 ConnectionManagerTrait,如果 ServerCore 未初始化则返回 None
49    pub fn get_server_handle_components(&self) -> Option<Arc<dyn ConnectionManagerTrait>> {
50        tokio::task::block_in_place(|| {
51            let s = self.server.blocking_lock();
52            s.core().map(|core| core.connection_manager_trait())
53        })
54    }
55
56    /// 获取 ServerHandle(直接使用 HybridServer 作为 ServerHandle)
57    ///
58    /// # 返回
59    /// 返回 ServerHandle trait object,如果 ServerCore 未初始化则返回 None
60    pub fn get_server_handle(&self) -> Option<Arc<dyn ServerHandle>> {
61        // HybridServer 实现了 ServerHandle,所以我们可以直接返回它
62        // 但需要包装为 Arc,由于 HybridServer 在 Mutex 中,我们需要一个包装器
63        self.get_server_handle_components().map(|manager_trait| {
64            Arc::new(DefaultServerHandle::new(manager_trait)) as Arc<dyn ServerHandle>
65        })
66    }
67
68    /// 启动服务器
69    pub async fn start(&self) -> Result<()> {
70        let mut s = self.server.lock().await;
71        s.start().await
72    }
73
74    /// 停止服务器
75    pub async fn stop(&self) -> Result<()> {
76        let mut s = self.server.lock().await;
77        s.stop().await
78    }
79
80    /// 检查服务器是否运行
81    pub fn is_running(&self) -> bool {
82        tokio::task::block_in_place(|| {
83            let s = self.server.blocking_lock();
84            s.is_running()
85        })
86    }
87
88    /// 获取连接数量
89    pub fn connection_count(&self) -> usize {
90        tokio::task::block_in_place(|| {
91            let s = self.server.blocking_lock();
92            ServerHandle::connection_count(&*s)
93        })
94    }
95
96    /// 获取用户数量
97    pub fn user_count(&self) -> usize {
98        tokio::task::block_in_place(|| {
99            let s = self.server.blocking_lock();
100            ServerHandle::user_count(&*s)
101        })
102    }
103
104    /// 向指定连接发送消息
105    pub async fn send_to(&self, connection_id: &str, frame: &Frame) -> Result<()> {
106        let s = self.server.lock().await;
107        ServerHandle::send_to(&*s, connection_id, frame).await
108    }
109
110    /// 向指定用户的所有连接发送消息
111    pub async fn send_to_user(&self, user_id: &str, frame: &Frame) -> Result<()> {
112        let s = self.server.lock().await;
113        ServerHandle::send_to_user(&*s, user_id, frame).await
114    }
115
116    /// 广播消息到所有连接
117    pub async fn broadcast(&self, frame: &Frame) -> Result<()> {
118        let s = self.server.lock().await;
119        ServerHandle::broadcast(&*s, frame).await
120    }
121
122    /// 广播消息到所有连接,排除指定连接
123    pub async fn broadcast_except(&self, frame: &Frame, exclude_connection_id: &str) -> Result<()> {
124        let s = self.server.lock().await;
125        ServerHandle::broadcast_except(&*s, frame, exclude_connection_id).await
126    }
127
128    /// 断开指定连接
129    pub async fn disconnect(&self, connection_id: &str) -> Result<()> {
130        let s = self.server.lock().await;
131        ServerHandle::disconnect(&*s, connection_id).await
132    }
133
134    /// 获取协议列表
135    pub fn protocols(&self) -> Vec<crate::common::config_types::TransportProtocol> {
136        tokio::task::block_in_place(|| {
137            let s = self.server.blocking_lock();
138            s.protocols().to_vec()
139        })
140    }
141}
142
143/// 验证认证配置
144///
145/// 如果启用了认证但未提供认证器,返回配置错误
146/// 这体现了"公共逻辑统一处理"的原则:所有需要认证的模式共享相同的验证逻辑
147pub fn validate_auth_config(
148    config: &crate::server::config::ServerConfig,
149    authenticator: &Option<Arc<dyn crate::server::auth::Authenticator>>,
150) -> Result<()> {
151    if config.auth_enabled && authenticator.is_none() {
152        return Err(crate::common::error::FlareError::localized(
153            crate::common::error::ErrorCode::ConfigurationError,
154            "认证已启用但未提供认证器,请使用 with_authenticator() 设置认证器",
155        ));
156    }
157    Ok(())
158}
159
160/// 创建消息解析器
161///
162/// 根据配置中的默认序列化格式和压缩算法创建解析器
163/// 这体现了"公共逻辑统一处理"的原则:所有需要解析器的模式共享相同的创建逻辑
164pub fn create_message_parser(
165    config: &crate::server::config::ServerConfig,
166) -> crate::common::MessageParser {
167    crate::common::MessageParser::new(
168        config.default_serialization_format,
169        config.default_compression.clone(),
170        config.default_encryption.clone(),
171    )
172}