Skip to main content

flare_core/server/events/
event_wrapper.rs

1use crate::common::Frame;
2use crate::server::{ConnectionHandler, ConnectionManagerTrait, ServerEventHandler};
3use async_trait::async_trait;
4use std::sync::Arc;
5use tracing::info;
6
7/// 服务端事件包装器
8///
9/// 将 `DefaultServerMessageObserver` 的功能直接集成到 `ConnectionHandler` 中,
10/// 提供统一的消息和连接事件处理
11pub struct ServerMessageWrapper {
12    /// 事件处理器,用于处理所有事件和消息
13    pub(crate) event_handler: Arc<dyn ServerEventHandler>,
14    /// 连接管理器(用于发送响应和更新连接状态)
15    connection_manager: Option<Arc<crate::server::connection::ConnectionManager>>,
16    /// 设备管理器(用于连接断开时清理设备)
17    device_manager: Option<Arc<crate::server::device::DeviceManager>>,
18    /// 消息解析器(用于序列化响应)
19    parser: crate::common::MessageParser,
20}
21
22// 内部处理实现
23impl ServerMessageWrapper {
24    /// 创建新的服务端消息包装器
25    ///
26    /// # 参数
27    /// - `event_handler`: 事件处理器,用于处理所有事件和消息
28    /// - `connection_manager`: 连接管理器(可选,用于发送响应)
29    /// - `device_manager`: 设备管理器(可选,用于设备管理)
30    /// - `parser`: 消息解析器(用于序列化响应)
31    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    /// 统一处理 handler 调用、响应处理和发送
46    ///
47    /// 封装完整流程:调用 handler → 自动 ACK(如果返回 None)→ 发送响应
48    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                // Handler 处理失败,发送包含错误信息的 ACK
81                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                // 在 metadata 中放入错误信息
93                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        // 发送响应(如果有连接管理器)
105        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    /// 异步发送响应 Frame 到客户端
114    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        // 使用 Arc<str> 避免 String clone,减少内存分配
123        let conn_id: Arc<str> = Arc::from(connection_id);
124        // message_id 是 String,需要 clone(因为需要移动到异步任务中)
125        let message_id = frame_to_send.message_id.clone();
126        // 使用 Arc<str> 避免 String clone,减少内存分配
127        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                // 先克隆值用于日志(避免在创建 parser 时移动)
132                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                // 使用缓存的 parser(避免每次消息发送都创建新的 parser)
138                let parser = if negotiation_completed {
139                    // 协商已完成,使用缓存的 parser
140                    conn_info.cached_parser.clone().unwrap_or_else(|| {
141                        // 如果缓存不存在(不应该发生),回退到动态创建
142                        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                    // 协商未完成,使用默认的 JSON、不压缩、不加密 parser
154                    // 注意:这里可以创建一个全局共享的 parser,但为了简单起见,暂时每次创建
155                    // 因为协商未完成的消息很少
156                    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    /// 异步更新连接活跃时间
209    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            // 使用 Arc<str> 避免 String clone,减少内存分配
213            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    /// 处理系统命令
221    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                // 处理 PING:回复 PONG 并更新连接活跃时间
232                self.update_connection_active_async(connection_id);
233
234                // 调用事件处理器,如果返回 None 则使用默认 PONG
235                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                        // 默认处理:回复 PONG
249                        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                // 处理 PONG:更新连接活跃时间
268                let _ = self.event_handler.handle_pong(frame, connection_id).await;
269                self.update_connection_active_async(connection_id);
270            }
271            Ok(SysType::Event) => {
272                // 处理 System::Event
273                self.update_connection_active_async(connection_id);
274
275                // Frame 需要 clone,因为需要移动到异步任务中
276                let frame_clone = frame.clone();
277                // message_id 是 String,需要 clone(因为需要移动到异步任务中)
278                let frame_message_id = frame.message_id.clone();
279                // 使用 Arc<str> 避免 String clone,减少内存分配
280                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                // 处理 NEGOTIATION_READY:标记协商已确认
305                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    /// 处理载荷命令
336    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            // 统一处理并发送响应
362            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    /// 处理通知命令
384    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        // 统一处理并发送响应
391        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    /// 处理自定义命令
402    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        // 统一处理并发送响应
414        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    /// 克隆用于异步任务(只克隆必要的字段)
425    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/// 实现连接处理的接口
442#[async_trait]
443impl ConnectionHandler for ServerMessageWrapper {
444    /// 处理消息
445    async fn handle_frame(
446        &self,
447        frame: &Frame,
448        connection_id: &str,
449    ) -> crate::common::error::Result<Option<Frame>> {
450        // 根据命令类型路由到相应的处理方法
451        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                    // 处理系统命令(CONNECT 由 ServerCore 处理,这里只处理 PING/PONG/Event/NEGOTIATION_READY)
457                    let sys_type = sys_cmd.r#type;
458                    // CONNECT 命令由 ServerCore 统一处理,这里跳过
459                    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                        // 使用 Arc<str> 避免 String clone,减少内存分配
464                        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                    // 处理载荷命令
479                    let wrapper = self.clone_for_async();
480                    let msg_cmd_clone = msg_cmd.clone();
481                    let frame_clone = frame.clone();
482                    // 使用 Arc<str> 避免 String clone,减少内存分配
483                    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                    // 处理通知命令
499                    let wrapper = self.clone_for_async();
500                    let notif_cmd_clone = notif_cmd.clone();
501                    let frame_clone = frame.clone();
502                    // 使用 Arc<str> 避免 String clone,减少内存分配
503                    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, &notif_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                    // 处理自定义命令
517                    let wrapper = self.clone_for_async();
518                    let custom_cmd_clone = custom_cmd.clone();
519                    let frame_clone = frame.clone();
520                    // 使用 Arc<str> 避免 String clone,减少内存分配
521                    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        // 消息处理是异步的,这里不返回响应
538        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        // 通知事件处理器
550        let _ = self.event_handler.on_disconnect(connection_id, None).await;
551
552        // 清理设备(如果有设备管理器)
553        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            // 使用 Arc<str> 避免 String clone,减少内存分配
558            let conn_id: Arc<str> = Arc::from(connection_id);
559
560            tokio::spawn(async move {
561                // 获取连接信息(包括 user_id)
562                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
585// 扩展方法(不在 trait 中)
586impl ServerMessageWrapper {
587    /// 处理错误事件
588    ///
589    /// # 参数
590    /// - `connection_id`: 连接 ID
591    /// - `error`: 错误信息
592    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        // 通知事件处理器
604        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}