1use crate::common::Frame;
2use crate::server::{ConnectionHandler, ConnectionManagerTrait, ServerEventHandler};
3use async_trait::async_trait;
4use std::sync::Arc;
5use tracing::info;
6
7pub struct ServerMessageWrapper {
12 pub(crate) event_handler: Arc<dyn ServerEventHandler>,
14 connection_manager: Option<Arc<crate::server::connection::ConnectionManager>>,
16 device_manager: Option<Arc<crate::server::device::DeviceManager>>,
18 parser: crate::common::MessageParser,
20}
21
22impl ServerMessageWrapper {
24 pub fn new(
32 event_handler: Arc<dyn ServerEventHandler>,
33 connection_manager: Option<Arc<crate::server::connection::ConnectionManager>>,
34 device_manager: Option<Arc<crate::server::device::DeviceManager>>,
35 parser: crate::common::MessageParser,
36 ) -> Self {
37 Self {
38 event_handler,
39 connection_manager,
40 device_manager,
41 parser,
42 }
43 }
44
45 async fn handle_and_send_response<F>(
49 &self,
50 handler_future: F,
51 message_id: String,
52 connection_id: &str,
53 log_context: &str,
54 ) -> crate::common::error::Result<()>
55 where
56 F: std::future::Future<Output = crate::common::error::Result<Option<Frame>>>,
57 {
58 let response_frame = match handler_future.await {
59 Ok(Some(response)) => {
60 tracing::trace!(
61 "[ServerMessageWrapper] {}: 自定义响应: connection_id={}, message_id={}",
62 log_context,
63 connection_id,
64 message_id
65 );
66 response
67 }
68 Ok(None) => {
69 tracing::trace!(
70 "[ServerMessageWrapper] {}: 自动 ACK: connection_id={}, message_id={}",
71 log_context,
72 connection_id,
73 message_id
74 );
75 use crate::common::protocol::Reliability;
76 use crate::common::protocol::builder::{ack_message, frame_with_payload_command};
77 frame_with_payload_command(ack_message(message_id, None), Reliability::AtLeastOnce)
78 }
79 Err(e) => {
80 tracing::error!(
82 "[ServerMessageWrapper] {}: 处理失败,发送错误 ACK, connection_id={}, message_id={}, error={}",
83 log_context,
84 connection_id,
85 message_id,
86 e
87 );
88 use crate::common::protocol::Reliability;
89 use crate::common::protocol::builder::{ack_message, frame_with_payload_command};
90 use std::collections::HashMap;
91
92 let mut metadata = HashMap::new();
94 metadata.insert("error".to_string(), b"true".to_vec());
95 metadata.insert("error_message".to_string(), e.to_string().into_bytes());
96
97 frame_with_payload_command(
98 ack_message(message_id, Some(metadata)),
99 Reliability::AtLeastOnce,
100 )
101 }
102 };
103
104 if let Some(manager) = &self.connection_manager {
106 self.send_response_frame_async(response_frame, connection_id, log_context, manager)
107 .await;
108 }
109
110 Ok(())
111 }
112
113 async fn send_response_frame_async(
115 &self,
116 frame_to_send: Frame,
117 connection_id: &str,
118 log_context: &str,
119 manager: &Arc<crate::server::connection::ConnectionManager>,
120 ) {
121 let manager_trait = Arc::clone(manager) as Arc<dyn ConnectionManagerTrait>;
122 let conn_id: Arc<str> = Arc::from(connection_id);
124 let message_id = frame_to_send.message_id.clone();
126 let log_ctx: Arc<str> = Arc::from(log_context);
128
129 tokio::spawn(async move {
130 if let Some((conn, conn_info)) = manager_trait.get_connection(&conn_id).await {
131 let format = conn_info.serialization_format;
133 let compression = conn_info.compression.clone();
134 let encryption = conn_info.encryption.clone();
135 let negotiation_completed = conn_info.negotiation_completed;
136
137 let parser = if negotiation_completed {
139 conn_info.cached_parser.clone().unwrap_or_else(|| {
141 tracing::warn!(
143 "[ServerMessageWrapper] 协商已完成但缓存 parser 不存在,回退到动态创建: connection_id={}",
144 conn_id
145 );
146 std::sync::Arc::new(crate::common::MessageParser::new(
147 format,
148 compression.clone(),
149 encryption.clone(),
150 ))
151 })
152 } else {
153 std::sync::Arc::new(crate::common::MessageParser::new(
157 crate::common::protocol::SerializationFormat::Json,
158 crate::common::compression::CompressionAlgorithm::None,
159 crate::common::encryption::EncryptionAlgorithm::None,
160 ))
161 };
162
163 tracing::trace!(
164 "[ServerMessageWrapper] {}: 发送消息: connection_id={}, message_id={}, format={:?}",
165 log_ctx,
166 conn_id,
167 message_id,
168 format
169 );
170
171 if let Ok(data) = parser.serialize(&frame_to_send) {
172 let mut c = conn.lock().await;
173 match c.send(&data).await {
174 Ok(_) => tracing::debug!(
175 "[ServerMessageWrapper] {}: 已发送, connection_id={}, message_id={}, data_len={}",
176 log_ctx,
177 conn_id,
178 message_id,
179 data.len()
180 ),
181 Err(e) => tracing::error!(
182 "[ServerMessageWrapper] {}: 发送失败, connection_id={}, message_id={}, error={}",
183 log_ctx,
184 conn_id,
185 message_id,
186 e
187 ),
188 }
189 } else {
190 tracing::error!(
191 "[ServerMessageWrapper] {}: 序列化失败, connection_id={}, message_id={}",
192 log_ctx,
193 conn_id,
194 message_id
195 );
196 }
197 } else {
198 tracing::warn!(
199 "[ServerMessageWrapper] {}: 连接不存在,无法发送消息: connection_id={}, message_id={}",
200 log_ctx,
201 conn_id,
202 message_id
203 );
204 }
205 });
206 }
207
208 fn update_connection_active_async(&self, connection_id: &str) {
210 if let Some(manager) = &self.connection_manager {
211 let manager_trait = Arc::clone(manager) as Arc<dyn ConnectionManagerTrait>;
212 let conn_id: Arc<str> = Arc::from(connection_id);
214 tokio::spawn(async move {
215 let _ = manager_trait.update_connection_active(&conn_id).await;
216 });
217 }
218 }
219
220 async fn handle_system_command(
222 &self,
223 frame: &Frame,
224 sys_type: i32,
225 connection_id: &str,
226 ) -> crate::common::error::Result<()> {
227 use crate::common::protocol::flare::core::commands::system_command::Type as SysType;
228
229 match SysType::try_from(sys_type) {
230 Ok(SysType::Ping) => {
231 self.update_connection_active_async(connection_id);
233
234 match self.event_handler.handle_ping(frame, connection_id).await {
236 Ok(Some(custom_response)) => {
237 if let Some(manager) = &self.connection_manager {
238 self.send_response_frame_async(
239 custom_response,
240 connection_id,
241 "handle_ping",
242 manager,
243 )
244 .await;
245 }
246 }
247 _ => {
248 use crate::common::protocol::{
250 Reliability, frame_with_system_command, pong,
251 };
252 let pong_frame =
253 frame_with_system_command(pong(), Reliability::AtLeastOnce);
254 if let Some(manager) = &self.connection_manager {
255 self.send_response_frame_async(
256 pong_frame,
257 connection_id,
258 "handle_ping",
259 manager,
260 )
261 .await;
262 }
263 }
264 }
265 }
266 Ok(SysType::Pong) => {
267 let _ = self.event_handler.handle_pong(frame, connection_id).await;
269 self.update_connection_active_async(connection_id);
270 }
271 Ok(SysType::Event) => {
272 self.update_connection_active_async(connection_id);
274
275 let frame_clone = frame.clone();
277 let frame_message_id = frame.message_id.clone();
279 let conn_id: Arc<str> = Arc::from(connection_id);
281 let wrapper = self.clone_for_async();
282
283 tokio::spawn(async move {
284 if let Err(e) = wrapper
285 .handle_and_send_response(
286 wrapper
287 .event_handler
288 .handle_system_event(&frame_clone, &conn_id),
289 frame_message_id,
290 &conn_id,
291 "handle_system_event",
292 )
293 .await
294 {
295 tracing::error!(
296 "[ServerMessageWrapper] handle_system_event: 处理失败, connection_id={}, error={}",
297 conn_id,
298 e
299 );
300 }
301 });
302 }
303 Ok(SysType::NegotiationReady) => {
304 self.update_connection_active_async(connection_id);
306
307 if let Some(manager) = &self.connection_manager {
308 let manager_clone = Arc::clone(manager);
309 let conn_id: Arc<str> = Arc::from(connection_id);
310
311 tokio::spawn(async move {
312 if let Err(e) = (*manager_clone).mark_negotiation_confirmed(&conn_id) {
313 tracing::error!(
314 "[ServerMessageWrapper] 标记协商确认失败: connection_id={}, error={}",
315 conn_id,
316 e
317 );
318 } else {
319 tracing::debug!(
320 "[ServerMessageWrapper] ✅ 协商已确认: connection_id={}",
321 conn_id
322 );
323 }
324 });
325 }
326 }
327 _ => {
328 tracing::debug!("[ServerMessageWrapper] 未处理的系统命令类型: {}", sys_type);
329 }
330 }
331
332 Ok(())
333 }
334
335 async fn handle_message_command(
337 &self,
338 _frame: &Frame,
339 command: &crate::common::protocol::PayloadCommand,
340 connection_id: &str,
341 ) -> crate::common::error::Result<()> {
342 let message_id = command.message_id.clone();
343
344 use crate::common::protocol::flare::core::commands::payload_command::Type as PayloadType;
345
346 if let Ok(payload_type) = PayloadType::try_from(command.r#type) {
347 let handler_future = match payload_type {
348 PayloadType::Message => self.event_handler.handle_message(command, connection_id),
349 PayloadType::Event => self.event_handler.handle_event(command, connection_id),
350 PayloadType::Ack => self.event_handler.handle_ack(command, connection_id),
351 PayloadType::Data => self.event_handler.handle_data(command, connection_id),
352 PayloadType::Unspecified => {
353 tracing::warn!(
354 "[ServerMessageWrapper] handle_message_command: Unspecified payload type, connection_id={}",
355 connection_id
356 );
357 return Ok(());
358 }
359 };
360
361 self.handle_and_send_response(
363 handler_future,
364 message_id,
365 connection_id,
366 "handle_message_command",
367 )
368 .await?;
369
370 return Ok(());
371 }
372
373 tracing::error!(
374 "[ServerMessageWrapper] handle_message_command: 无法识别载荷类型, connection_id={}, message_id={}",
375 connection_id,
376 message_id
377 );
378 Err(crate::common::error::FlareError::general_error(
379 "Unknown message type",
380 ))
381 }
382
383 async fn handle_notification_command(
385 &self,
386 frame: &Frame,
387 command: &crate::common::protocol::NotificationCommand,
388 connection_id: &str,
389 ) -> crate::common::error::Result<()> {
390 self.handle_and_send_response(
392 self.event_handler
393 .handle_notification_command(command, connection_id),
394 frame.message_id.clone(),
395 connection_id,
396 "handle_notification_command",
397 )
398 .await
399 }
400
401 async fn handle_custom_command(
403 &self,
404 frame: &Frame,
405 command: &crate::common::protocol::flare::core::commands::CustomCommand,
406 connection_id: &str,
407 ) -> crate::common::error::Result<()> {
408 self.update_connection_active_async(connection_id);
409
410 let cmd_name = command.name.clone();
411 let log_ctx = format!("handle_custom_command[{}]", cmd_name);
412
413 self.handle_and_send_response(
415 self.event_handler
416 .handle_custom_command(command, connection_id),
417 frame.message_id.clone(),
418 connection_id,
419 &log_ctx,
420 )
421 .await
422 }
423
424 fn clone_for_async(&self) -> Self {
426 Self {
427 event_handler: self.event_handler.clone(),
428 connection_manager: self.connection_manager.clone(),
429 device_manager: self.device_manager.clone(),
430 parser: self.parser.clone(),
431 }
432 }
433}
434
435impl Clone for ServerMessageWrapper {
436 fn clone(&self) -> Self {
437 self.clone_for_async()
438 }
439}
440
441#[async_trait]
443impl ConnectionHandler for ServerMessageWrapper {
444 async fn handle_frame(
446 &self,
447 frame: &Frame,
448 connection_id: &str,
449 ) -> crate::common::error::Result<Option<Frame>> {
450 if let Some(cmd) = &frame.command {
452 match &cmd.r#type {
453 Some(crate::common::protocol::flare::core::commands::command::Type::System(
454 sys_cmd,
455 )) => {
456 let sys_type = sys_cmd.r#type;
458 use crate::common::protocol::flare::core::commands::system_command::Type as SysType;
460 if sys_type != SysType::Connect as i32 {
461 let wrapper = self.clone_for_async();
462 let frame_clone = frame.clone();
463 let conn_id: Arc<str> = Arc::from(connection_id);
465 tokio::spawn(async move {
466 if let Err(e) = wrapper
467 .handle_system_command(&frame_clone, sys_type, &conn_id)
468 .await
469 {
470 tracing::error!("[ServerMessageWrapper] 处理系统命令失败: {}", e);
471 }
472 });
473 }
474 }
475 Some(crate::common::protocol::flare::core::commands::command::Type::Payload(
476 msg_cmd,
477 )) => {
478 let wrapper = self.clone_for_async();
480 let msg_cmd_clone = msg_cmd.clone();
481 let frame_clone = frame.clone();
482 let conn_id: Arc<str> = Arc::from(connection_id);
484 tokio::spawn(async move {
485 if let Err(e) = wrapper
486 .handle_message_command(&frame_clone, &msg_cmd_clone, &conn_id)
487 .await
488 {
489 tracing::error!("[ServerMessageWrapper] 处理消息命令失败: {}", e);
490 }
491 });
492 }
493 Some(
494 crate::common::protocol::flare::core::commands::command::Type::Notification(
495 notif_cmd,
496 ),
497 ) => {
498 let wrapper = self.clone_for_async();
500 let notif_cmd_clone = notif_cmd.clone();
501 let frame_clone = frame.clone();
502 let conn_id: Arc<str> = Arc::from(connection_id);
504 tokio::spawn(async move {
505 if let Err(e) = wrapper
506 .handle_notification_command(&frame_clone, ¬if_cmd_clone, &conn_id)
507 .await
508 {
509 tracing::error!("[ServerMessageWrapper] 处理通知命令失败: {}", e);
510 }
511 });
512 }
513 Some(crate::common::protocol::flare::core::commands::command::Type::Custom(
514 custom_cmd,
515 )) => {
516 let wrapper = self.clone_for_async();
518 let custom_cmd_clone = custom_cmd.clone();
519 let frame_clone = frame.clone();
520 let conn_id: Arc<str> = Arc::from(connection_id);
522 tokio::spawn(async move {
523 if let Err(e) = wrapper
524 .handle_custom_command(&frame_clone, &custom_cmd_clone, &conn_id)
525 .await
526 {
527 tracing::error!("[ServerMessageWrapper] 处理自定义命令失败: {}", e);
528 }
529 });
530 }
531 None => {
532 tracing::debug!("[ServerMessageWrapper] 未处理的命令类型");
533 }
534 }
535 }
536
537 Ok(None)
539 }
540
541 async fn on_connect(&self, connection_id: &str) -> crate::common::error::Result<()> {
542 info!("[ServerMessageWrapper] ✅ 新连接: {}", connection_id);
543 self.event_handler.on_connect(connection_id).await
544 }
545
546 async fn on_disconnect(&self, connection_id: &str) -> crate::common::error::Result<()> {
547 info!("[ServerMessageWrapper] ❌ 连接断开: {}", connection_id);
548
549 let _ = self.event_handler.on_disconnect(connection_id, None).await;
551
552 if let (Some(device_mgr), Some(manager)) = (&self.device_manager, &self.connection_manager)
554 {
555 let manager_trait = Arc::clone(manager) as Arc<dyn ConnectionManagerTrait>;
556 let device_mgr_clone = device_mgr.clone();
557 let conn_id: Arc<str> = Arc::from(connection_id);
559
560 tokio::spawn(async move {
561 if let Some((_, conn_info)) = manager_trait.get_connection(&conn_id).await
563 && let Some(user_id) = conn_info.user_id
564 {
565 if let Err(e) = device_mgr_clone.remove_device(&user_id, &conn_id).await {
566 tracing::debug!(
567 "[ServerMessageWrapper] Failed to remove device from DeviceManager: {}",
568 e
569 );
570 } else {
571 tracing::info!(
572 "[ServerMessageWrapper] Successfully removed device from DeviceManager: user_id={}, connection_id={}",
573 user_id,
574 conn_id
575 );
576 }
577 }
578 });
579 }
580
581 Ok(())
582 }
583}
584
585impl ServerMessageWrapper {
587 pub(crate) async fn on_error(
593 &self,
594 connection_id: &str,
595 error: &str,
596 ) -> crate::common::error::Result<()> {
597 tracing::error!(
598 "[ServerMessageWrapper] ❌ 连接错误: connection_id={}, error={}",
599 connection_id,
600 error
601 );
602
603 if let Err(e) = self.event_handler.on_error(connection_id, error).await {
605 tracing::error!(
606 "[ServerMessageWrapper] 事件处理器处理错误失败: connection_id={}, error={}",
607 connection_id,
608 e
609 );
610 }
611
612 Ok(())
613 }
614}