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        let conn_id: Arc<str> = Arc::from(connection_id);
123        let message_id = frame_to_send.message_id.clone();
124        let log_ctx: Arc<str> = Arc::from(log_context);
125
126        tokio::spawn(async move {
127            match manager_trait
128                .send_frame_to(conn_id.as_ref(), &frame_to_send, None)
129                .await
130            {
131                Ok(()) => tracing::debug!(
132                    "[ServerMessageWrapper] {}: 已发送, connection_id={}, message_id={}",
133                    log_ctx,
134                    conn_id,
135                    message_id
136                ),
137                Err(e) => {
138                    tracing::warn!(
139                        "[ServerMessageWrapper] {}: 发送失败, connection_id={}, message_id={}, error={}",
140                        log_ctx,
141                        conn_id,
142                        message_id,
143                        e
144                    );
145                }
146            }
147        });
148    }
149
150    /// 异步更新连接活跃时间
151    fn update_connection_active_async(&self, connection_id: &str) {
152        if let Some(manager) = &self.connection_manager {
153            let manager_trait = Arc::clone(manager) as Arc<dyn ConnectionManagerTrait>;
154            // 使用 Arc<str> 避免 String clone,减少内存分配
155            let conn_id: Arc<str> = Arc::from(connection_id);
156            tokio::spawn(async move {
157                let _ = manager_trait.update_connection_active(&conn_id).await;
158            });
159        }
160    }
161
162    /// 处理系统命令
163    async fn handle_system_command(
164        &self,
165        frame: &Frame,
166        sys_type: i32,
167        connection_id: &str,
168    ) -> crate::common::error::Result<()> {
169        use crate::common::protocol::flare::core::commands::system_command::Type as SysType;
170
171        match SysType::try_from(sys_type) {
172            Ok(SysType::Ping) => {
173                // 处理 PING:回复 PONG 并更新连接活跃时间
174                self.update_connection_active_async(connection_id);
175
176                // 调用事件处理器,如果返回 None 则使用默认 PONG
177                match self.event_handler.handle_ping(frame, connection_id).await {
178                    Ok(Some(custom_response)) => {
179                        if let Some(manager) = &self.connection_manager {
180                            self.send_response_frame_async(
181                                custom_response,
182                                connection_id,
183                                "handle_ping",
184                                manager,
185                            )
186                            .await;
187                        }
188                    }
189                    _ => {
190                        // 默认处理:回复 PONG
191                        use crate::common::protocol::{
192                            Reliability, frame_with_system_command, pong,
193                        };
194                        let pong_frame =
195                            frame_with_system_command(pong(), Reliability::AtLeastOnce);
196                        if let Some(manager) = &self.connection_manager {
197                            self.send_response_frame_async(
198                                pong_frame,
199                                connection_id,
200                                "handle_ping",
201                                manager,
202                            )
203                            .await;
204                        }
205                    }
206                }
207            }
208            Ok(SysType::Pong) => {
209                // 处理 PONG:更新连接活跃时间
210                let _ = self.event_handler.handle_pong(frame, connection_id).await;
211                self.update_connection_active_async(connection_id);
212            }
213            Ok(SysType::Event) => {
214                // 处理 System::Event
215                self.update_connection_active_async(connection_id);
216
217                // Frame 需要 clone,因为需要移动到异步任务中
218                let frame_clone = frame.clone();
219                // message_id 是 String,需要 clone(因为需要移动到异步任务中)
220                let frame_message_id = frame.message_id.clone();
221                // 使用 Arc<str> 避免 String clone,减少内存分配
222                let conn_id: Arc<str> = Arc::from(connection_id);
223                let wrapper = self.clone_for_async();
224
225                tokio::spawn(async move {
226                    if let Err(e) = wrapper
227                        .handle_and_send_response(
228                            wrapper
229                                .event_handler
230                                .handle_system_event(&frame_clone, &conn_id),
231                            frame_message_id,
232                            &conn_id,
233                            "handle_system_event",
234                        )
235                        .await
236                    {
237                        tracing::error!(
238                            "[ServerMessageWrapper] handle_system_event: 处理失败, connection_id={}, error={}",
239                            conn_id,
240                            e
241                        );
242                    }
243                });
244            }
245            Ok(SysType::NegotiationReady) => {
246                // 处理 NEGOTIATION_READY:标记协商已确认
247                self.update_connection_active_async(connection_id);
248
249                if let Some(manager) = &self.connection_manager {
250                    let manager_clone = Arc::clone(manager);
251                    let conn_id: Arc<str> = Arc::from(connection_id);
252
253                    tokio::spawn(async move {
254                        if let Err(e) = (*manager_clone).mark_negotiation_confirmed(&conn_id) {
255                            tracing::error!(
256                                "[ServerMessageWrapper] 标记协商确认失败: connection_id={}, error={}",
257                                conn_id,
258                                e
259                            );
260                        } else {
261                            tracing::debug!(
262                                "[ServerMessageWrapper] ✅ 协商已确认: connection_id={}",
263                                conn_id
264                            );
265                        }
266                    });
267                }
268            }
269            _ => {
270                tracing::debug!("[ServerMessageWrapper] 未处理的系统命令类型: {}", sys_type);
271            }
272        }
273
274        Ok(())
275    }
276
277    /// 处理载荷命令
278    async fn handle_message_command(
279        &self,
280        _frame: &Frame,
281        command: &crate::common::protocol::PayloadCommand,
282        connection_id: &str,
283    ) -> crate::common::error::Result<()> {
284        let message_id = command.message_id.clone();
285
286        use crate::common::protocol::flare::core::commands::payload_command::Type as PayloadType;
287
288        if let Ok(payload_type) = PayloadType::try_from(command.r#type) {
289            let handler_future = match payload_type {
290                PayloadType::Message => self.event_handler.handle_message(command, connection_id),
291                PayloadType::Event => self.event_handler.handle_event(command, connection_id),
292                PayloadType::Ack => self.event_handler.handle_ack(command, connection_id),
293                PayloadType::Data => self.event_handler.handle_data(command, connection_id),
294                PayloadType::Unspecified => {
295                    tracing::warn!(
296                        "[ServerMessageWrapper] handle_message_command: Unspecified payload type, connection_id={}",
297                        connection_id
298                    );
299                    return Ok(());
300                }
301            };
302
303            // 统一处理并发送响应
304            self.handle_and_send_response(
305                handler_future,
306                message_id,
307                connection_id,
308                "handle_message_command",
309            )
310            .await?;
311
312            return Ok(());
313        }
314
315        tracing::error!(
316            "[ServerMessageWrapper] handle_message_command: 无法识别载荷类型, connection_id={}, message_id={}",
317            connection_id,
318            message_id
319        );
320        Err(crate::common::error::FlareError::general_error(
321            "Unknown message type",
322        ))
323    }
324
325    /// 处理通知命令
326    async fn handle_notification_command(
327        &self,
328        frame: &Frame,
329        command: &crate::common::protocol::NotificationCommand,
330        connection_id: &str,
331    ) -> crate::common::error::Result<()> {
332        // 统一处理并发送响应
333        self.handle_and_send_response(
334            self.event_handler
335                .handle_notification_command(command, connection_id),
336            frame.message_id.clone(),
337            connection_id,
338            "handle_notification_command",
339        )
340        .await
341    }
342
343    /// 处理自定义命令
344    async fn handle_custom_command(
345        &self,
346        frame: &Frame,
347        command: &crate::common::protocol::flare::core::commands::CustomCommand,
348        connection_id: &str,
349    ) -> crate::common::error::Result<()> {
350        self.update_connection_active_async(connection_id);
351
352        let cmd_name = command.name.clone();
353        let log_ctx = format!("handle_custom_command[{}]", cmd_name);
354
355        // 统一处理并发送响应
356        self.handle_and_send_response(
357            self.event_handler
358                .handle_custom_command(command, connection_id),
359            frame.message_id.clone(),
360            connection_id,
361            &log_ctx,
362        )
363        .await
364    }
365
366    /// 克隆用于异步任务(只克隆必要的字段)
367    fn clone_for_async(&self) -> Self {
368        Self {
369            event_handler: self.event_handler.clone(),
370            connection_manager: self.connection_manager.clone(),
371            device_manager: self.device_manager.clone(),
372            parser: self.parser.clone(),
373        }
374    }
375}
376
377impl Clone for ServerMessageWrapper {
378    fn clone(&self) -> Self {
379        self.clone_for_async()
380    }
381}
382
383/// 实现连接处理的接口
384#[async_trait]
385impl ConnectionHandler for ServerMessageWrapper {
386    /// 处理消息
387    async fn handle_frame(
388        &self,
389        frame: &Frame,
390        connection_id: &str,
391    ) -> crate::common::error::Result<Option<Frame>> {
392        // 根据命令类型路由到相应的处理方法
393        if let Some(cmd) = &frame.command {
394            match &cmd.r#type {
395                Some(crate::common::protocol::flare::core::commands::command::Type::System(
396                    sys_cmd,
397                )) => {
398                    // 处理系统命令(CONNECT 由 ServerCore 处理,这里只处理 PING/PONG/Event/NEGOTIATION_READY)
399                    let sys_type = sys_cmd.r#type;
400                    // CONNECT 命令由 ServerCore 统一处理,这里跳过
401                    use crate::common::protocol::flare::core::commands::system_command::Type as SysType;
402                    if sys_type != SysType::Connect as i32 {
403                        let wrapper = self.clone_for_async();
404                        let frame_clone = frame.clone();
405                        // 使用 Arc<str> 避免 String clone,减少内存分配
406                        let conn_id: Arc<str> = Arc::from(connection_id);
407                        tokio::spawn(async move {
408                            if let Err(e) = wrapper
409                                .handle_system_command(&frame_clone, sys_type, &conn_id)
410                                .await
411                            {
412                                tracing::error!("[ServerMessageWrapper] 处理系统命令失败: {}", e);
413                            }
414                        });
415                    }
416                }
417                Some(crate::common::protocol::flare::core::commands::command::Type::Payload(
418                    msg_cmd,
419                )) => {
420                    // 处理载荷命令
421                    let wrapper = self.clone_for_async();
422                    let msg_cmd_clone = msg_cmd.clone();
423                    let frame_clone = frame.clone();
424                    // 使用 Arc<str> 避免 String clone,减少内存分配
425                    let conn_id: Arc<str> = Arc::from(connection_id);
426                    tokio::spawn(async move {
427                        if let Err(e) = wrapper
428                            .handle_message_command(&frame_clone, &msg_cmd_clone, &conn_id)
429                            .await
430                        {
431                            tracing::error!("[ServerMessageWrapper] 处理消息命令失败: {}", e);
432                        }
433                    });
434                }
435                Some(
436                    crate::common::protocol::flare::core::commands::command::Type::Notification(
437                        notif_cmd,
438                    ),
439                ) => {
440                    // 处理通知命令
441                    let wrapper = self.clone_for_async();
442                    let notif_cmd_clone = notif_cmd.clone();
443                    let frame_clone = frame.clone();
444                    // 使用 Arc<str> 避免 String clone,减少内存分配
445                    let conn_id: Arc<str> = Arc::from(connection_id);
446                    tokio::spawn(async move {
447                        if let Err(e) = wrapper
448                            .handle_notification_command(&frame_clone, &notif_cmd_clone, &conn_id)
449                            .await
450                        {
451                            tracing::error!("[ServerMessageWrapper] 处理通知命令失败: {}", e);
452                        }
453                    });
454                }
455                Some(crate::common::protocol::flare::core::commands::command::Type::Custom(
456                    custom_cmd,
457                )) => {
458                    // 处理自定义命令
459                    let wrapper = self.clone_for_async();
460                    let custom_cmd_clone = custom_cmd.clone();
461                    let frame_clone = frame.clone();
462                    // 使用 Arc<str> 避免 String clone,减少内存分配
463                    let conn_id: Arc<str> = Arc::from(connection_id);
464                    tokio::spawn(async move {
465                        if let Err(e) = wrapper
466                            .handle_custom_command(&frame_clone, &custom_cmd_clone, &conn_id)
467                            .await
468                        {
469                            tracing::error!("[ServerMessageWrapper] 处理自定义命令失败: {}", e);
470                        }
471                    });
472                }
473                None => {
474                    tracing::debug!("[ServerMessageWrapper] 未处理的命令类型");
475                }
476            }
477        }
478
479        // 消息处理是异步的,这里不返回响应
480        Ok(None)
481    }
482
483    async fn on_connect(&self, connection_id: &str) -> crate::common::error::Result<()> {
484        info!("[ServerMessageWrapper] ✅ 新连接: {}", connection_id);
485        self.event_handler.on_connect(connection_id).await
486    }
487
488    async fn on_disconnect(&self, connection_id: &str) -> crate::common::error::Result<()> {
489        info!("[ServerMessageWrapper] ❌ 连接断开: {}", connection_id);
490
491        // 通知事件处理器
492        let _ = self.event_handler.on_disconnect(connection_id, None).await;
493
494        // 清理设备(如果有设备管理器)
495        if let (Some(device_mgr), Some(manager)) = (&self.device_manager, &self.connection_manager)
496        {
497            let manager_trait = Arc::clone(manager) as Arc<dyn ConnectionManagerTrait>;
498            let device_mgr_clone = device_mgr.clone();
499            // 使用 Arc<str> 避免 String clone,减少内存分配
500            let conn_id: Arc<str> = Arc::from(connection_id);
501
502            tokio::spawn(async move {
503                // 获取连接信息(包括 user_id)
504                if let Some((_, conn_info)) = manager_trait.get_connection(&conn_id).await
505                    && let Some(user_id) = conn_info.user_id
506                {
507                    if let Err(e) = device_mgr_clone.remove_device(&user_id, &conn_id).await {
508                        tracing::debug!(
509                            "[ServerMessageWrapper] Failed to remove device from DeviceManager: {}",
510                            e
511                        );
512                    } else {
513                        tracing::info!(
514                            "[ServerMessageWrapper] Successfully removed device from DeviceManager: user_id={}, connection_id={}",
515                            user_id,
516                            conn_id
517                        );
518                    }
519                }
520            });
521        }
522
523        Ok(())
524    }
525}
526
527// 扩展方法(不在 trait 中)
528impl ServerMessageWrapper {
529    /// 处理错误事件
530    ///
531    /// # 参数
532    /// - `connection_id`: 连接 ID
533    /// - `error`: 错误信息
534    pub(crate) async fn on_error(
535        &self,
536        connection_id: &str,
537        error: &str,
538    ) -> crate::common::error::Result<()> {
539        tracing::error!(
540            "[ServerMessageWrapper] ❌ 连接错误: connection_id={}, error={}",
541            connection_id,
542            error
543        );
544
545        // 通知事件处理器
546        if let Err(e) = self.event_handler.on_error(connection_id, error).await {
547            tracing::error!(
548                "[ServerMessageWrapper] 事件处理器处理错误失败: connection_id={}, error={}",
549                connection_id,
550                e
551            );
552        }
553
554        Ok(())
555    }
556}