flare_core/server/connection/
trait.rs1use crate::common::MessageParser;
7use crate::common::error::Result;
8use crate::common::protocol::Frame;
9use crate::transport::connection::Connection;
10use async_trait::async_trait;
11use std::sync::Arc;
12use std::time::Duration;
13use tokio::sync::Mutex;
14
15#[derive(Clone)]
17pub struct ConnectionInfo {
18 pub connection_id: String,
20 pub user_id: Option<String>,
22 pub created_at: u64,
24 pub last_active: u64,
26 pub metadata: std::collections::HashMap<String, String>,
28 pub device_info: Option<crate::common::device::DeviceInfo>,
30 pub serialization_format: crate::common::protocol::SerializationFormat,
32 pub compression: crate::common::compression::CompressionAlgorithm,
34 pub encryption: crate::common::encryption::EncryptionAlgorithm,
36 pub authenticated: bool,
38 pub authenticated_at: Option<u64>,
40 pub negotiation_completed: bool,
42 pub negotiation_confirmed: bool,
45 pub cached_parser: Option<std::sync::Arc<crate::common::MessageParser>>,
47 pub cached_pipeline: Option<std::sync::Arc<crate::common::message::pipeline::MessagePipeline>>,
50}
51
52#[async_trait]
57pub trait ConnectionManagerTrait: Send + Sync + std::any::Any {
58 fn as_any(&self) -> &dyn std::any::Any;
60 async fn add_connection(
62 &self,
63 connection_id: String,
64 connection: Arc<Mutex<Box<dyn Connection>>>,
65 user_id: Option<String>,
66 ) -> Result<()>;
67
68 async fn remove_connection(&self, connection_id: &str) -> Result<()>;
70
71 async fn get_connection(
73 &self,
74 connection_id: &str,
75 ) -> Option<(Arc<Mutex<Box<dyn Connection>>>, ConnectionInfo)>;
76
77 async fn get_user_connections(&self, user_id: &str) -> Vec<String>;
79
80 async fn bind_user(&self, connection_id: &str, user_id: String) -> Result<()>;
82
83 async fn update_connection_active(&self, connection_id: &str) -> Result<()>;
85
86 async fn set_connection_authenticated(
88 &self,
89 connection_id: &str,
90 user_id: Option<String>,
91 ) -> Result<()>;
92
93 async fn list_connections(&self) -> Vec<String>;
95
96 async fn connection_count(&self) -> usize;
98
99 fn connection_count_snapshot(&self) -> usize;
103
104 fn user_count_snapshot(&self) -> usize;
106
107 async fn cleanup_timeout_connections(&self, timeout: Duration) -> Vec<String>;
109
110 async fn send_to_connection(&self, connection_id: &str, data: &[u8]) -> Result<()>;
114
115 async fn send_to_user(&self, user_id: &str, data: &[u8]) -> Result<()>;
117
118 async fn broadcast(&self, data: &[u8]) -> Result<()>;
120
121 async fn broadcast_except(&self, data: &[u8], exclude_connection_id: &str) -> Result<()>;
123
124 async fn send_frame_to(
139 &self,
140 connection_id: &str,
141 frame: &Frame,
142 parser: Option<&MessageParser>,
143 ) -> Result<()> {
144 let connection_info = self.get_connection(connection_id).await;
145
146 if let Some((_, info)) = &connection_info {
147 if !info.authenticated {
148 let is_system_command = frame.command.as_ref().and_then(|cmd| {
149 if let Some(crate::common::protocol::flare::core::commands::command::Type::System(sys_cmd)) = &cmd.r#type {
150 Some(sys_cmd.r#type == crate::common::protocol::flare::core::commands::system_command::Type::ConnectAck as i32
151 || sys_cmd.r#type == crate::common::protocol::flare::core::commands::system_command::Type::Ping as i32
152 || sys_cmd.r#type == crate::common::protocol::flare::core::commands::system_command::Type::Pong as i32
153 || sys_cmd.r#type == crate::common::protocol::flare::core::commands::system_command::Type::Error as i32
154 || sys_cmd.r#type == crate::common::protocol::flare::core::commands::system_command::Type::Close as i32)
155 } else {
156 None
157 }
158 }).unwrap_or(false);
159
160 if !is_system_command {
161 return Err(crate::common::error::FlareError::authentication_failed(
162 format!("连接 {} 未验证,无法发送消息", connection_id),
163 ));
164 }
165 }
166 } else {
167 return Err(crate::common::error::FlareError::connection_failed(
168 format!("连接 {} 不存在", connection_id),
169 ));
170 }
171
172 let data = if let Some(p) = parser {
173 p.serialize(frame)?
174 } else if let Some((_, info)) = connection_info {
175 let connection_parser =
176 MessageParser::new(info.serialization_format, info.compression, info.encryption);
177 connection_parser.serialize(frame)?
178 } else {
179 use crate::common::message::parser::PRE_NEGOTIATION_PARSER;
180 PRE_NEGOTIATION_PARSER.serialize(frame)?
181 };
182
183 self.send_to_connection(connection_id, &data).await?;
184 self.update_connection_active(connection_id).await?;
185 Ok(())
186 }
187
188 async fn send_frame_to_user(
198 &self,
199 user_id: &str,
200 frame: &Frame,
201 parser: Option<&MessageParser>,
202 ) -> Result<()> {
203 let connection_ids = self.get_user_connections(user_id).await;
204 for conn_id in connection_ids {
205 let _ = self.send_frame_to(&conn_id, frame, parser).await;
207 }
208 Ok(())
209 }
210
211 async fn broadcast_frame(&self, frame: &Frame, parser: Option<&MessageParser>) -> Result<()> {
220 let connection_ids = self.list_connections().await;
221 for conn_id in connection_ids {
222 let _ = self.send_frame_to(&conn_id, frame, parser).await;
224 }
225 Ok(())
226 }
227
228 async fn broadcast_frame_except(
238 &self,
239 frame: &Frame,
240 exclude_connection_id: &str,
241 parser: Option<&MessageParser>,
242 ) -> Result<()> {
243 let connection_ids = self.list_connections().await;
244 for conn_id in connection_ids {
245 if conn_id != exclude_connection_id {
246 let _ = self.send_frame_to(&conn_id, frame, parser).await;
248 }
249 }
250 Ok(())
251 }
252}
253
254#[derive(Debug, Clone)]
256pub struct ConnectionStats {
257 pub total_connections: usize,
259 pub total_users: usize,
261}