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);
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 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 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 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 self.update_connection_active_async(connection_id);
175
176 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 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 let _ = self.event_handler.handle_pong(frame, connection_id).await;
211 self.update_connection_active_async(connection_id);
212 }
213 Ok(SysType::Event) => {
214 self.update_connection_active_async(connection_id);
216
217 let frame_clone = frame.clone();
219 let frame_message_id = frame.message_id.clone();
221 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 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 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 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 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 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 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 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 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#[async_trait]
385impl ConnectionHandler for ServerMessageWrapper {
386 async fn handle_frame(
388 &self,
389 frame: &Frame,
390 connection_id: &str,
391 ) -> crate::common::error::Result<Option<Frame>> {
392 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 let sys_type = sys_cmd.r#type;
400 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 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 let wrapper = self.clone_for_async();
422 let msg_cmd_clone = msg_cmd.clone();
423 let frame_clone = frame.clone();
424 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 let wrapper = self.clone_for_async();
442 let notif_cmd_clone = notif_cmd.clone();
443 let frame_clone = frame.clone();
444 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, ¬if_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 let wrapper = self.clone_for_async();
460 let custom_cmd_clone = custom_cmd.clone();
461 let frame_clone = frame.clone();
462 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 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 let _ = self.event_handler.on_disconnect(connection_id, None).await;
493
494 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 let conn_id: Arc<str> = Arc::from(connection_id);
501
502 tokio::spawn(async move {
503 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
527impl ServerMessageWrapper {
529 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 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}