Skip to main content

flare_core/server/events/
observer.rs

1//! 服务端连接观察者实现
2//!
3//! 将 `ConnectionHandler` 适配为 `ConnectionObserver`,处理连接事件和消息
4
5use crate::common::MessageParser;
6use crate::common::message::parser::PRE_NEGOTIATION_PARSER;
7use crate::server::connection::ConnectionManager;
8use crate::server::events::ServerMessageWrapper;
9use crate::transport::events::{ConnectionEvent, ConnectionObserver};
10use std::sync::Arc;
11use tracing::{debug, error, warn};
12
13/// 连接状态信息(用于消息处理)
14struct ConnectionState {
15    info: crate::server::connection::ConnectionInfo,
16    negotiation_completed: bool,
17    negotiation_confirmed: bool,
18    cached_parser: Option<Arc<MessageParser>>,
19    cached_pipeline: Option<Arc<crate::common::message::pipeline::MessagePipeline>>,
20}
21
22/// ConnectionHandler 到 ConnectionObserver 的适配器
23///
24/// 将实现了 `ConnectionHandler` 的 `ServerMessageWrapper` 适配为 `ConnectionObserver`
25/// 这样可以在需要 `ConnectionObserver` 的地方使用 `ServerMessageWrapper`
26///
27/// 注意:每个连接都有自己的协商结果,parser 应该根据连接信息动态创建,而不是固定存储
28pub struct ConnectionHandlerObserverAdapter {
29    /// 内部的 ConnectionHandler(ServerMessageWrapper)
30    handler: Arc<ServerMessageWrapper>,
31    /// 连接 ID
32    connection_id: String,
33    /// 连接管理器(用于查询连接信息,获取协商结果)
34    connection_manager: Arc<ConnectionManager>,
35    /// ServerCore 引用(用于处理 CONNECT 消息)
36    server_core: Option<Arc<crate::server::transports::server_core::ServerCore>>,
37}
38
39impl ConnectionHandlerObserverAdapter {
40    /// 创建适配器
41    pub fn new(
42        handler: Arc<ServerMessageWrapper>,
43        connection_id: String,
44        connection_manager: Arc<ConnectionManager>,
45        server_core: Option<Arc<crate::server::transports::server_core::ServerCore>>,
46    ) -> Self {
47        Self {
48            handler,
49            connection_id,
50            connection_manager,
51            server_core,
52        }
53    }
54
55    /// 处理消息事件
56    async fn handle_message_event(
57        handler: &Arc<ServerMessageWrapper>,
58        data: Vec<u8>,
59        conn_id: Arc<str>,
60        manager: Arc<ConnectionManager>,
61        server_core: Option<Arc<crate::server::transports::server_core::ServerCore>>,
62    ) {
63        // **关键修复**:在处理消息时立即更新连接活跃时间,防止连接被心跳检测器清理
64        // 这必须在处理消息之前更新,因为消息处理可能耗时较长
65        let manager_trait =
66            Arc::clone(&manager) as Arc<dyn crate::server::connection::ConnectionManagerTrait>;
67        let conn_id_clone = Arc::clone(&conn_id);
68        if let Err(e) = manager_trait.update_connection_active(&conn_id_clone).await {
69            // 如果连接不存在,记录警告但不阻塞处理(可能是连接刚被清理)
70            tracing::warn!(
71                "[ConnectionHandlerObserverAdapter] 更新连接活跃时间失败(连接可能不存在): connection_id={}, error={}",
72                conn_id,
73                e
74            );
75        }
76
77        // 获取连接信息以检查协商状态和获取缓存的 parser/pipeline
78        let connection_state = Self::get_connection_state(&manager, &conn_id);
79
80        // 根据协商状态路由到不同的处理逻辑
81        if connection_state.negotiation_completed {
82            Self::handle_negotiated_message(
83                handler,
84                data,
85                conn_id,
86                manager,
87                connection_state.info,
88                connection_state.negotiation_confirmed,
89                connection_state.cached_parser,
90                connection_state.cached_pipeline,
91            )
92            .await;
93        } else {
94            // 协商未完成,使用全局共享的协商前 parser
95            Self::handle_pre_negotiation_message(handler, data, conn_id, manager, server_core)
96                .await;
97        }
98    }
99
100    /// 获取连接状态信息
101    fn get_connection_state(manager: &Arc<ConnectionManager>, conn_id: &str) -> ConnectionState {
102        manager
103            .get_connection(conn_id)
104            .map(|(_, info)| ConnectionState {
105                negotiation_completed: info.negotiation_completed,
106                negotiation_confirmed: info.negotiation_confirmed,
107                cached_parser: info.cached_parser.clone(),
108                cached_pipeline: info.cached_pipeline.clone(),
109                info: info.clone(),
110            })
111            .unwrap_or_else(|| {
112                // 如果连接不存在,使用默认值
113                let default_info =
114                    crate::server::connection::ConnectionInfo::new(conn_id.to_string(), true);
115                ConnectionState {
116                    info: default_info,
117                    negotiation_completed: false,
118                    negotiation_confirmed: false,
119                    cached_parser: None,
120                    cached_pipeline: None,
121                }
122            })
123    }
124
125    /// 处理已协商完成的消息
126    ///
127    /// 处理流程:
128    /// 1. 解析消息得到 Frame(由 MessageParser 统一处理,支持容错标记)
129    /// 2. 如果有 pipeline,执行中间件(before)和处理器(processor)
130    /// 3. **无论 pipeline 是否返回响应,都继续调用 handle_frame 让 event_wrapper.rs 处理业务逻辑**
131    /// 4. event_wrapper.rs 处理后会发送响应(如果有)
132    ///
133    /// # 容错策略
134    /// - 如果 `negotiation_confirmed = false`:使用容错模式(允许解密失败时作为未加密数据处理)
135    /// - 如果 `negotiation_confirmed = true`:使用严格模式(解密失败直接返回错误)
136    /// - 在客户端确认之前,除了加密、压缩和序列化,其他都使用默认值(JSON、不压缩、不加密)
137    #[allow(clippy::too_many_arguments)]
138    async fn handle_negotiated_message(
139        handler: &Arc<ServerMessageWrapper>,
140        data: Vec<u8>,
141        conn_id: Arc<str>,
142        manager: Arc<ConnectionManager>,
143        connection_info: crate::server::connection::ConnectionInfo,
144        negotiation_confirmed: bool,
145        cached_parser: Option<Arc<MessageParser>>,
146        cached_pipeline: Option<Arc<crate::common::message::pipeline::MessagePipeline>>,
147    ) {
148        // 1. 先尝试使用 PRE_NEGOTIATION_PARSER 解析,检查是否是 NEGOTIATION_READY 消息
149        // NEGOTIATION_READY 消息必须使用 PRE_NEGOTIATION_PARSER(JSON、不压缩、不加密)
150        // 这样客户端和服务端都统一使用 PRE_NEGOTIATION_PARSER 处理,确保兼容性
151        // 服务端收到 NEGOTIATION_READY 后才会严格使用协商后的 parser(不允许 fallback)
152        if let Ok(frame) = PRE_NEGOTIATION_PARSER.parse(&data)
153            && Self::is_negotiation_ready_message(&frame)
154        {
155            // 这是 NEGOTIATION_READY 消息,使用 PRE_NEGOTIATION_PARSER 解析成功
156            // 标记协商已确认,之后服务端将严格使用协商后的 parser(不允许 fallback)
157            if let Err(e) = (*manager).mark_negotiation_confirmed(&conn_id) {
158                error!(
159                    "[ConnectionHandlerObserverAdapter] 标记协商确认失败: connection_id={}, error={}",
160                    conn_id, e
161                );
162            } else {
163                debug!(
164                    "[ConnectionHandlerObserverAdapter] ✅ 协商已确认: connection_id={},之后将严格使用协商后的 parser",
165                    conn_id
166                );
167            }
168            // 协商确认消息不需要进一步处理
169            return;
170        }
171
172        // 2. 如果不是 NEGOTIATION_READY 消息,使用协商后的 parser 解析
173        // 在客户端确认之前(negotiation_confirmed = false),如果协商已完成但未确认,使用容错模式
174        // 这样可以兼容客户端在收到 CONNECT_ACK 之前发送的未加密消息
175        // 在客户端确认之后(negotiation_confirmed = true),严格使用协商后的 parser,不允许 fallback
176        let allow_fallback = !negotiation_confirmed;
177
178        // 先克隆,避免在创建 parser 时移动
179        let compression = connection_info.compression.clone();
180        let encryption = connection_info.encryption.clone();
181
182        let parser = cached_parser.unwrap_or_else(|| {
183            error!(
184                "[ConnectionHandlerObserverAdapter] 协商已完成但缓存 parser 不存在,回退到动态创建: connection_id={}",
185                conn_id
186            );
187            std::sync::Arc::new(crate::common::MessageParser::new(
188                connection_info.serialization_format,
189                compression.clone(),
190                encryption.clone(),
191            ))
192        });
193
194        // 在解析前验证加密器是否已注册(如果协商了加密)
195        if encryption != crate::common::encryption::EncryptionAlgorithm::None {
196            let encryptor_name = encryption.as_str();
197            if !crate::common::encryption::EncryptionUtil::is_registered(&encryptor_name) {
198                let registered = crate::common::encryption::EncryptionUtil::list_registered();
199                error!(
200                    "[ConnectionHandlerObserverAdapter] 加密器未注册: connection_id={}, encryption={:?}, registered={:?}",
201                    conn_id, encryption, registered
202                );
203                return;
204            }
205        }
206
207        // 使用 MessageParser 的统一解析方法,支持容错标记
208        // negotiation_confirmed = false 时允许 fallback(容错模式)
209        // negotiation_confirmed = true 时不允许 fallback(严格模式)
210        let frame = match parser.parse_with_fallback(&data, allow_fallback) {
211            Ok(frame) => frame,
212            Err(e) => {
213                // 提供更详细的错误信息,包括加密器注册状态
214                let encryptor_status = if encryption
215                    != crate::common::encryption::EncryptionAlgorithm::None
216                {
217                    let encryptor_name = encryption.as_str();
218                    if crate::common::encryption::EncryptionUtil::is_registered(&encryptor_name) {
219                        "registered".to_string()
220                    } else {
221                        format!(
222                            "NOT registered (registered: {:?})",
223                            crate::common::encryption::EncryptionUtil::list_registered()
224                        )
225                    }
226                } else {
227                    "none".to_string()
228                };
229
230                // 添加数据预览,帮助调试
231                let data_preview: Vec<u8> = data.iter().take(16).cloned().collect();
232                error!(
233                    "[ConnectionHandlerObserverAdapter] 解析消息失败(协商后): connection_id={}, format={:?}, compression={:?}, encryption={:?} ({}), confirmed={}, allow_fallback={}, error={}, data_len={}, data_preview={:?}",
234                    conn_id,
235                    connection_info.serialization_format,
236                    compression,
237                    encryption,
238                    encryptor_status,
239                    negotiation_confirmed,
240                    allow_fallback,
241                    e,
242                    data.len(),
243                    data_preview
244                );
245                return;
246            }
247        };
248
249        // 3. 如果有 pipeline,执行中间件(before)和处理器(processor)
250        // 注意:Pipeline 的处理器(processor)只用于额外的处理,不应该替代 handle_frame
251        // 无论 pipeline 是否返回响应,都继续调用 handle_frame 让 event_wrapper.rs 处理业务逻辑
252        if let Some(pipeline) = cached_pipeline {
253            // 执行 pipeline 的中间件(before)和处理器
254            // 这里只执行中间件和处理器,不处理响应(响应由 event_wrapper.rs 处理)
255            match pipeline.process_frame(&frame, Some(&conn_id)).await {
256                Ok(pipeline_response) => {
257                    // Pipeline 可能返回了响应,但我们仍然继续调用 handle_frame
258                    // Pipeline 的响应可以用于中间件处理(如日志、监控),但不替代业务逻辑处理
259                    if pipeline_response.is_some() {
260                        debug!(
261                            "[ConnectionHandlerObserverAdapter] Pipeline 返回了响应,但继续调用 handle_frame: connection_id={}",
262                            conn_id
263                        );
264                    }
265                }
266                Err(e) => {
267                    error!(
268                        "[ConnectionHandlerObserverAdapter] Pipeline 处理失败: connection_id={}, error={}",
269                        conn_id, e
270                    );
271                    // Pipeline 失败不影响继续处理,继续调用 handle_frame
272                }
273            }
274        }
275
276        // 4. 继续调用 handle_frame 让 event_wrapper.rs 处理业务逻辑
277        // 这是必须的,因为所有消息最终都需要经过 event_wrapper.rs 处理
278        Self::handle_frame_safely(handler, &frame, &conn_id).await;
279    }
280
281    /// 处理协商前的消息
282    async fn handle_pre_negotiation_message(
283        handler: &Arc<ServerMessageWrapper>,
284        data: Vec<u8>,
285        conn_id: Arc<str>,
286        manager: Arc<ConnectionManager>,
287        server_core: Option<Arc<crate::server::transports::server_core::ServerCore>>,
288    ) {
289        // 使用全局共享的协商前 parser(避免每次创建)
290        match PRE_NEGOTIATION_PARSER.parse(&data) {
291            Ok(frame) => {
292                // 检查是否是 CONNECT 消息
293                if Self::is_connect_message(&frame) {
294                    // CONNECT 消息:调用 ServerCore 的 handle_connect_complete
295                    Self::handle_connect_message(handler, &frame, &conn_id, manager, server_core)
296                        .await; // CONNECT 消息处理完成
297                } else {
298                    // 非 CONNECT 消息但在协商完成前收到,记录警告并继续处理
299                    // 检查连接信息,确认协商状态
300                    if let Some((_, conn_info)) = (*manager).get_connection(&conn_id) {
301                        warn!(
302                            "[ConnectionHandlerObserverAdapter] 收到非 CONNECT 消息但协商未完成: connection_id={}, negotiation_completed={}, negotiation_confirmed={}, format={:?}, compression={:?}, encryption={:?}",
303                            conn_id,
304                            conn_info.negotiation_completed,
305                            conn_info.negotiation_confirmed,
306                            conn_info.serialization_format,
307                            conn_info.compression,
308                            conn_info.encryption
309                        );
310                    } else {
311                        warn!(
312                            "[ConnectionHandlerObserverAdapter] 收到非 CONNECT 消息但协商未完成: connection_id={}, 连接不存在",
313                            conn_id
314                        );
315                    }
316                    // 继续使用 handle_frame 处理
317                    Self::handle_frame_safely(handler, &frame, &conn_id).await;
318                }
319            }
320            Err(e) => {
321                error!(
322                    "[ConnectionHandlerObserverAdapter] 解析消息失败(协商前): connection_id={}, error={}",
323                    conn_id, e
324                );
325            }
326        }
327    }
328
329    /// 安全地调用 handle_frame(统一错误处理)
330    async fn handle_frame_safely(
331        handler: &Arc<ServerMessageWrapper>,
332        frame: &crate::common::protocol::Frame,
333        conn_id: &str,
334    ) {
335        use crate::server::ConnectionHandler;
336        if let Err(e) = ConnectionHandler::handle_frame(handler.as_ref(), frame, conn_id).await {
337            error!(
338                "[ConnectionHandlerObserverAdapter] 处理消息失败: connection_id={}, error={}",
339                conn_id, e
340            );
341        }
342    }
343
344    /// 处理 CONNECT 消息
345    async fn handle_connect_message(
346        _handler: &Arc<ServerMessageWrapper>,
347        frame: &crate::common::protocol::Frame,
348        conn_id: &Arc<str>,
349        manager: Arc<ConnectionManager>,
350        server_core: Option<Arc<crate::server::transports::server_core::ServerCore>>,
351    ) {
352        // 获取连接实例
353        let Some((connection, _)) = manager.get_connection(conn_id) else {
354            error!(
355                "[ConnectionHandlerObserverAdapter] 连接不存在,无法处理 CONNECT: connection_id={}",
356                conn_id
357            );
358            return;
359        };
360
361        // 获取 ServerCore 引用
362        let Some(server_core) = &server_core else {
363            error!(
364                "[ConnectionHandlerObserverAdapter] ServerCore 未初始化,无法处理 CONNECT: connection_id={}",
365                conn_id
366            );
367            return;
368        };
369
370        if let Err(e) = server_core
371            .handle_connect_complete(frame, conn_id, connection)
372            .await
373        {
374            error!(
375                "[ConnectionHandlerObserverAdapter] 处理 CONNECT 消息失败: connection_id={}, error={}",
376                conn_id, e
377            );
378        }
379        // CONNECT 消息已由 handle_connect_complete 处理,不需要再调用 handle_frame
380    }
381
382    /// 检查是否是 CONNECT 消息
383    fn is_connect_message(frame: &crate::common::protocol::Frame) -> bool {
384        frame.command.as_ref().and_then(|cmd| {
385            if let Some(crate::common::protocol::flare::core::commands::command::Type::System(sys_cmd)) = &cmd.r#type {
386                use crate::common::protocol::flare::core::commands::system_command::Type as SysType;
387                Some(sys_cmd.r#type == SysType::Connect as i32)
388            } else {
389                None
390            }
391        }).unwrap_or(false)
392    }
393
394    /// 检查是否是 NEGOTIATION_READY 消息
395    fn is_negotiation_ready_message(frame: &crate::common::protocol::Frame) -> bool {
396        frame.command.as_ref().and_then(|cmd| {
397            if let Some(crate::common::protocol::flare::core::commands::command::Type::System(sys_cmd)) = &cmd.r#type {
398                use crate::common::protocol::flare::core::commands::system_command::Type as SysType;
399                Some(sys_cmd.r#type == SysType::NegotiationReady as i32)
400            } else {
401                None
402            }
403        }).unwrap_or(false)
404    }
405}
406
407impl ConnectionObserver for ConnectionHandlerObserverAdapter {
408    fn on_event(&self, event: &ConnectionEvent) {
409        match event {
410            ConnectionEvent::Message(data) => {
411                let handler = Arc::clone(&self.handler);
412                let conn_id: Arc<str> = Arc::from(self.connection_id.as_str());
413                let manager = Arc::clone(&self.connection_manager);
414                let server_core = self.server_core.clone();
415                // 克隆 data 以便在异步任务中使用
416                let data = data.to_vec();
417
418                tokio::spawn(async move {
419                    Self::handle_message_event(&handler, data, conn_id, manager, server_core).await;
420                });
421            }
422            ConnectionEvent::Connected => {
423                // 物理连接建立不等于 IM 会话建立。业务 on_connect 必须等 CONNECT
424                // 认证、协商、CONNECT_ACK 发送完成后由 ServerCore 统一触发。
425                debug!(
426                    "[ConnectionHandlerObserverAdapter] transport connected; wait for CONNECT negotiation: connection_id={}",
427                    self.connection_id
428                );
429            }
430            ConnectionEvent::Disconnected(reason) => {
431                // 调用 on_disconnect
432                let handler = Arc::clone(&self.handler);
433                // 使用 Arc<str> 避免 String clone,减少内存分配
434                let conn_id: Arc<str> = Arc::from(self.connection_id.as_str());
435                // 使用 Arc<str> 避免 String clone,减少内存分配
436                let reason_str: Arc<str> = Arc::from(reason.as_str());
437                tokio::spawn(async move {
438                    use crate::server::ConnectionHandler;
439                    if let Err(e) =
440                        ConnectionHandler::on_disconnect(handler.as_ref(), &conn_id).await
441                    {
442                        warn!(
443                            "[ConnectionHandlerObserverAdapter] 处理断开事件失败: connection_id={}, reason={}, error={}",
444                            conn_id, reason_str, e
445                        );
446                    }
447                });
448            }
449            ConnectionEvent::Error(err) => {
450                // 处理错误事件
451                let handler = Arc::clone(&self.handler);
452                let conn_id: Arc<str> = Arc::from(self.connection_id.as_str());
453                let error_msg = err.to_string();
454                let error_str: Arc<str> = Arc::from(error_msg.as_str());
455
456                tokio::spawn(async move {
457                    if let Err(e) = handler.on_error(&conn_id, &error_str).await {
458                        error!(
459                            "[ConnectionHandlerObserverAdapter] 处理错误事件失败: connection_id={}, error={}",
460                            conn_id, e
461                        );
462                    }
463                });
464            }
465        }
466    }
467}