flare_core/server/builder/
flare.rs1use 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
42pub 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 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 pub fn with_connection_manager(mut self, manager: Arc<ConnectionManager>) -> Self {
118 self.connection_manager = Some(manager);
119 self
120 }
121
122 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 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 pub fn enable_auth(mut self) -> Self {
142 self.base = self.base.enable_auth();
143 self
144 }
145
146 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 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 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 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 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 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 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 pub fn with_max_connections(mut self, max: usize) -> Self {
213 self.base = self.base.with_max_connections(max);
214 self
215 }
216
217 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 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 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 pub fn with_fanout_concurrency(mut self, max: usize) -> Self {
237 self.base = self.base.with_fanout_concurrency(max);
238 self
239 }
240
241 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 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 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 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 pub fn with_middleware(mut self, middleware: ArcMessageMiddleware) -> Self {
289 self.middlewares.push(middleware);
290 self
291 }
292
293 pub fn with_processor(mut self, processor: ArcMessageProcessor) -> Self {
301 self.processors.push(processor);
302 self
303 }
304
305 pub fn build(self) -> Result<FlareServer> {
320 crate::server::builder::common::validate_auth_config(
322 &self.base.config,
323 &self.base.authenticator,
324 )?;
325
326 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
369pub struct FlareServer {
371 wrapper: ServerWrapper,
372 #[allow(dead_code)] event_handler: Arc<dyn ServerEventHandler>,
374}
375
376impl FlareServer {
377 pub async fn start(&self) -> Result<()> {
379 self.wrapper.start().await
380 }
381
382 pub async fn stop(&self) -> Result<()> {
384 self.wrapper.stop().await
385 }
386
387 pub fn is_running(&self) -> bool {
389 self.wrapper.is_running()
390 }
391
392 pub fn connection_count(&self) -> usize {
394 self.wrapper.connection_count()
395 }
396
397 pub fn user_count(&self) -> usize {
399 self.wrapper.user_count()
400 }
401
402 pub async fn send_to(&self, connection_id: &str, frame: &Frame) -> Result<()> {
404 self.wrapper.send_to(connection_id, frame).await
405 }
406
407 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 pub async fn broadcast(&self, frame: &Frame) -> Result<()> {
414 self.wrapper.broadcast(frame).await
415 }
416
417 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 pub async fn disconnect(&self, connection_id: &str) -> Result<()> {
426 self.wrapper.disconnect(connection_id).await
427 }
428
429 pub fn protocols(&self) -> Vec<crate::common::config_types::TransportProtocol> {
431 self.wrapper.protocols()
432 }
433
434 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 pub fn get_server_handle(&self) -> Option<Arc<dyn ServerHandle>> {
446 self.wrapper.get_server_handle()
447 }
448}