flare_core/server/builder/
simple.rs1use crate::common::error::Result;
24use crate::common::protocol::{Frame, PayloadCommand};
25use crate::server::HybridServer;
26use crate::server::builder::{BaseServerBuilderConfig, ServerWrapper};
27use crate::server::events::handler::ServerEventHandler;
28use crate::server::handle::ServerHandle;
29use async_trait::async_trait;
30use std::sync::Arc;
31use tokio::sync::Mutex;
32
33pub struct MessageContext {
37 pub connection_id: String,
39 handle: Arc<dyn ServerHandle>,
41}
42
43impl MessageContext {
44 fn new(connection_id: String, handle: Arc<dyn ServerHandle>) -> Self {
46 Self {
47 connection_id,
48 handle,
49 }
50 }
51
52 pub async fn send_to(&self, connection_id: &str, frame: &Frame) -> Result<()> {
54 self.handle.send_to(connection_id, frame).await
55 }
56
57 pub async fn send_to_user(&self, user_id: &str, frame: &Frame) -> Result<()> {
59 self.handle.send_to_user(user_id, frame).await
60 }
61
62 pub async fn broadcast(&self, frame: &Frame) -> Result<()> {
64 self.handle.broadcast(frame).await
65 }
66
67 pub async fn broadcast_except(&self, frame: &Frame, exclude_connection_id: &str) -> Result<()> {
69 self.handle
70 .broadcast_except(frame, exclude_connection_id)
71 .await
72 }
73
74 pub async fn disconnect(&self, connection_id: &str) -> Result<()> {
76 self.handle.disconnect(connection_id).await
77 }
78
79 pub fn connection_count(&self) -> usize {
81 self.handle.connection_count()
82 }
83
84 pub fn user_count(&self) -> usize {
86 self.handle.user_count()
87 }
88}
89
90pub type MessageHandlerFn = Box<
92 dyn for<'a> Fn(
93 &'a Frame,
94 &'a MessageContext,
95 ) -> std::pin::Pin<
96 Box<dyn std::future::Future<Output = Result<Option<Frame>>> + Send + 'a>,
97 > + Send
98 + Sync,
99>;
100
101pub type OnConnectFn = Box<
103 dyn for<'a> Fn(
104 &'a str,
105 &'a MessageContext,
106 )
107 -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>>
108 + Send
109 + Sync,
110>;
111
112pub type OnDisconnectFn = Box<
114 dyn for<'a> Fn(
115 &'a str,
116 &'a MessageContext,
117 )
118 -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>>
119 + Send
120 + Sync,
121>;
122
123struct SimpleConnectionHandler {
125 message_handler: Option<MessageHandlerFn>,
126 on_connect: Option<OnConnectFn>,
127 on_disconnect: Option<OnDisconnectFn>,
128 handle: Arc<Mutex<Option<Arc<dyn ServerHandle>>>>,
129}
130
131impl SimpleConnectionHandler {
132 async fn set_handle(&self, handle: Arc<dyn ServerHandle>) {
133 *self.handle.lock().await = Some(handle);
134 }
135}
136
137struct SimpleEventHandlerAdapter {
139 handler: Arc<SimpleConnectionHandler>,
140}
141
142#[async_trait]
143impl ServerEventHandler for SimpleEventHandlerAdapter {
144 async fn handle_message(
145 &self,
146 command: &PayloadCommand,
147 connection_id: &str,
148 ) -> Result<Option<Frame>> {
149 let handle = {
150 let handle_guard = self.handler.handle.lock().await;
151 handle_guard.clone()
152 };
153
154 let context = if let Some(ref handle) = handle {
155 MessageContext::new(connection_id.to_string(), Arc::clone(handle))
156 } else {
157 return Err(crate::common::error::FlareError::general_error(
158 "Server handle is not available",
159 ));
160 };
161
162 let frame = Frame {
163 message_id: command.message_id.clone(),
164 command: Some(crate::common::protocol::flare::core::commands::Command {
165 r#type: Some(
166 crate::common::protocol::flare::core::commands::command::Type::Payload(
167 command.clone(),
168 ),
169 ),
170 }),
171 metadata: std::collections::HashMap::new(),
172 reliability: crate::common::protocol::Reliability::AtLeastOnce as i32,
173 timestamp: 0,
174 };
175
176 if let Some(ref message_handler) = self.handler.message_handler {
177 message_handler(&frame, &context).await
178 } else {
179 Ok(None)
180 }
181 }
182
183 async fn on_connect(&self, connection_id: &str) -> Result<()> {
184 let handle = {
185 let handle_guard = self.handler.handle.lock().await;
186 handle_guard.clone()
187 };
188
189 let context = if let Some(ref handle) = handle {
190 MessageContext::new(connection_id.to_string(), Arc::clone(handle))
191 } else {
192 return Err(crate::common::error::FlareError::general_error(
193 "Server handle is not available",
194 ));
195 };
196
197 if let Some(ref on_connect) = self.handler.on_connect {
198 on_connect(connection_id, &context).await
199 } else {
200 Ok(())
201 }
202 }
203
204 async fn on_disconnect(&self, connection_id: &str, _reason: Option<&str>) -> Result<()> {
205 let handle = {
206 let handle_guard = self.handler.handle.lock().await;
207 handle_guard.clone()
208 };
209
210 let context = if let Some(ref handle) = handle {
211 MessageContext::new(connection_id.to_string(), Arc::clone(handle))
212 } else {
213 return Err(crate::common::error::FlareError::general_error(
214 "Server handle is not available",
215 ));
216 };
217
218 if let Some(ref on_disconnect) = self.handler.on_disconnect {
219 on_disconnect(connection_id, &context).await
220 } else {
221 Ok(())
222 }
223 }
224}
225
226pub struct SimpleServer {
230 wrapper: ServerWrapper,
231 handler: Arc<SimpleConnectionHandler>,
232 handle: Arc<dyn ServerHandle>,
233}
234
235impl SimpleServer {
236 pub async fn start(&mut self) -> Result<()> {
238 self.handler.set_handle(Arc::clone(&self.handle)).await;
240 self.wrapper.start().await
241 }
242
243 pub async fn stop(&mut self) -> Result<()> {
245 self.wrapper.stop().await
246 }
247
248 pub fn is_running(&self) -> bool {
250 self.wrapper.is_running()
251 }
252
253 pub fn connection_count(&self) -> usize {
255 self.wrapper.connection_count()
256 }
257
258 pub fn user_count(&self) -> usize {
260 self.wrapper.user_count()
261 }
262
263 pub fn handle(&self) -> Arc<dyn ServerHandle> {
265 Arc::clone(&self.handle)
266 }
267
268 pub async fn send_to(&self, connection_id: &str, frame: &Frame) -> Result<()> {
270 self.wrapper.send_to(connection_id, frame).await
271 }
272
273 pub async fn send_to_user(&self, user_id: &str, frame: &Frame) -> Result<()> {
275 self.wrapper.send_to_user(user_id, frame).await
276 }
277
278 pub async fn broadcast(&self, frame: &Frame) -> Result<()> {
280 self.wrapper.broadcast(frame).await
281 }
282
283 pub async fn broadcast_except(&self, frame: &Frame, exclude_connection_id: &str) -> Result<()> {
285 self.wrapper
286 .broadcast_except(frame, exclude_connection_id)
287 .await
288 }
289
290 pub async fn disconnect(&self, connection_id: &str) -> Result<()> {
292 self.wrapper.disconnect(connection_id).await
293 }
294
295 pub fn protocols(&self) -> Vec<crate::common::config_types::TransportProtocol> {
297 self.wrapper.protocols()
298 }
299}
300
301pub struct ServerBuilder {
315 base: BaseServerBuilderConfig,
316 message_handler: Option<MessageHandlerFn>,
317 on_connect: Option<OnConnectFn>,
318 on_disconnect: Option<OnDisconnectFn>,
319}
320
321impl ServerBuilder {
322 pub fn new(bind_address: impl Into<String>) -> Self {
327 Self {
328 base: BaseServerBuilderConfig::new(bind_address),
329 message_handler: None,
330 on_connect: None,
331 on_disconnect: None,
332 }
333 }
334
335 pub fn with_authenticator(
343 mut self,
344 authenticator: Arc<dyn crate::server::auth::Authenticator>,
345 ) -> Self {
346 self.base = self.base.with_authenticator(authenticator);
347 self
348 }
349
350 pub fn enable_auth(mut self) -> Self {
352 self.base = self.base.enable_auth();
353 self
354 }
355
356 pub fn with_auth_timeout(mut self, timeout: std::time::Duration) -> Self {
358 self.base = self.base.with_auth_timeout(timeout);
359 self
360 }
361
362 pub fn on_message<F>(mut self, handler: F) -> Self
367 where
368 F: for<'a> Fn(
369 &'a Frame,
370 &'a MessageContext,
371 ) -> std::pin::Pin<
372 Box<dyn std::future::Future<Output = Result<Option<Frame>>> + Send + 'a>,
373 > + Send
374 + Sync
375 + 'static,
376 {
377 self.message_handler = Some(Box::new(move |frame, ctx| handler(frame, ctx)));
378 self
379 }
380
381 pub fn on_connect<F>(mut self, handler: F) -> Self
386 where
387 F: for<'a> Fn(
388 &'a str,
389 &'a MessageContext,
390 ) -> std::pin::Pin<
391 Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>,
392 > + Send
393 + Sync
394 + 'static,
395 {
396 self.on_connect = Some(Box::new(move |conn_id, ctx| handler(conn_id, ctx)));
397 self
398 }
399
400 pub fn on_disconnect<F>(mut self, handler: F) -> Self
405 where
406 F: for<'a> Fn(
407 &'a str,
408 &'a MessageContext,
409 ) -> std::pin::Pin<
410 Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>,
411 > + Send
412 + Sync
413 + 'static,
414 {
415 self.on_disconnect = Some(Box::new(move |conn_id, ctx| handler(conn_id, ctx)));
416 self
417 }
418
419 pub fn with_protocol(
421 mut self,
422 protocol: crate::common::config_types::TransportProtocol,
423 ) -> Self {
424 self.base = self.base.with_protocol(protocol);
425 self
426 }
427
428 pub fn with_protocols(
430 mut self,
431 protocols: Vec<crate::common::config_types::TransportProtocol>,
432 ) -> Self {
433 self.base = self.base.with_protocols(protocols);
434 self
435 }
436
437 pub fn with_max_connections(mut self, max: usize) -> Self {
439 self.base = self.base.with_max_connections(max);
440 self
441 }
442
443 pub fn with_handshake_timeout(mut self, timeout: std::time::Duration) -> Self {
445 self.base = self.base.with_handshake_timeout(timeout);
446 self
447 }
448
449 pub fn with_max_handshake_concurrency(mut self, max: usize) -> Self {
451 self.base = self.base.with_max_handshake_concurrency(max);
452 self
453 }
454
455 pub fn with_write_timeout(mut self, timeout: std::time::Duration) -> Self {
457 self.base = self.base.with_write_timeout(timeout);
458 self
459 }
460
461 pub fn with_fanout_concurrency(mut self, max: usize) -> Self {
463 self.base = self.base.with_fanout_concurrency(max);
464 self
465 }
466
467 pub fn with_heartbeat(
469 mut self,
470 heartbeat: crate::common::config_types::HeartbeatConfig,
471 ) -> Self {
472 self.base = self.base.with_heartbeat(heartbeat);
473 self
474 }
475
476 pub fn with_tls(mut self, tls: crate::common::config_types::TlsConfig) -> Self {
478 self.base = self.base.with_tls(tls);
479 self
480 }
481
482 pub fn with_default_format(
484 mut self,
485 format: crate::common::protocol::SerializationFormat,
486 ) -> Self {
487 self.base = self.base.with_default_format(format);
488 self
489 }
490
491 pub fn with_default_compression(
493 mut self,
494 compression: crate::common::compression::CompressionAlgorithm,
495 ) -> Self {
496 self.base = self.base.with_default_compression(compression);
497 self
498 }
499
500 pub fn build(self) -> Result<SimpleServer> {
505 let handler = Arc::new(SimpleConnectionHandler {
506 message_handler: self.message_handler,
507 on_connect: self.on_connect,
508 on_disconnect: self.on_disconnect,
509 handle: Arc::new(Mutex::new(None)),
510 });
511
512 let event_handler: Arc<dyn crate::server::events::handler::ServerEventHandler> =
513 Arc::new(SimpleEventHandlerAdapter {
514 handler: handler.clone(),
515 });
516
517 let server = HybridServer::with_connection_manager(
518 self.base.config,
519 None,
520 None,
521 Some(event_handler),
522 self.base.authenticator,
523 )?;
524
525 let wrapper = ServerWrapper::new(server);
527
528 let handle = wrapper.get_server_handle().ok_or_else(|| {
530 crate::common::error::FlareError::general_error("Failed to create ServerHandle")
531 })?;
532
533 Ok(SimpleServer {
534 wrapper,
535 handler,
536 handle,
537 })
538 }
539}