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;
104
105 fn user_count_snapshot(&self) -> usize;
108
109 async fn cleanup_timeout_connections(&self, timeout: Duration) -> Vec<String>;
111
112 async fn send_to_connection(&self, connection_id: &str, data: &[u8]) -> Result<()>;
116
117 async fn send_to_user(&self, user_id: &str, data: &[u8]) -> Result<()>;
119
120 async fn broadcast(&self, data: &[u8]) -> Result<()>;
122
123 async fn broadcast_except(&self, data: &[u8], exclude_connection_id: &str) -> Result<()>;
125
126 async fn send_frame_to(
141 &self,
142 connection_id: &str,
143 frame: &Frame,
144 parser: Option<&MessageParser>,
145 ) -> Result<()> {
146 let connection_info = self.get_connection(connection_id).await;
147
148 if let Some((_, info)) = &connection_info {
149 if !info.authenticated {
150 let is_system_command = frame.command.as_ref().and_then(|cmd| {
151 if let Some(crate::common::protocol::flare::core::commands::command::Type::System(sys_cmd)) = &cmd.r#type {
152 Some(sys_cmd.r#type == crate::common::protocol::flare::core::commands::system_command::Type::ConnectAck as i32
153 || sys_cmd.r#type == crate::common::protocol::flare::core::commands::system_command::Type::Ping as i32
154 || sys_cmd.r#type == crate::common::protocol::flare::core::commands::system_command::Type::Pong as i32
155 || sys_cmd.r#type == crate::common::protocol::flare::core::commands::system_command::Type::Error as i32
156 || sys_cmd.r#type == crate::common::protocol::flare::core::commands::system_command::Type::Close as i32)
157 } else {
158 None
159 }
160 }).unwrap_or(false);
161
162 if !is_system_command {
163 return Err(crate::common::error::FlareError::authentication_failed(
164 format!("连接 {} 未验证,无法发送消息", connection_id),
165 ));
166 }
167 }
168 } else {
169 return Err(crate::common::error::FlareError::connection_failed(
170 format!("连接 {} 不存在", connection_id),
171 ));
172 }
173
174 let data = if let Some(p) = parser {
175 p.serialize(frame)?
176 } else if let Some((_, info)) = connection_info {
177 let connection_parser =
178 MessageParser::new(info.serialization_format, info.compression, info.encryption);
179 connection_parser.serialize(frame)?
180 } else {
181 use crate::common::message::parser::PRE_NEGOTIATION_PARSER;
182 PRE_NEGOTIATION_PARSER.serialize(frame)?
183 };
184
185 self.send_to_connection(connection_id, &data).await?;
186 self.update_connection_active(connection_id).await?;
187 Ok(())
188 }
189
190 async fn send_frame_to_user(
200 &self,
201 user_id: &str,
202 frame: &Frame,
203 parser: Option<&MessageParser>,
204 ) -> Result<()> {
205 let connection_ids = self.get_user_connections(user_id).await;
206 for conn_id in connection_ids {
207 let _ = self.send_frame_to(&conn_id, frame, parser).await;
209 }
210 Ok(())
211 }
212
213 async fn send_frame_to_connections(
221 &self,
222 connection_ids: &[String],
223 frame: &Frame,
224 ) -> (i32, i32) {
225 let mut success = 0i32;
226 let mut failure = 0i32;
227 for connection_id in connection_ids {
228 match self.send_frame_to(connection_id, frame, None).await {
229 Ok(()) => success += 1,
230 Err(_) => failure += 1,
231 }
232 }
233 (success, failure)
234 }
235
236 async fn broadcast_frame(&self, frame: &Frame, parser: Option<&MessageParser>) -> Result<()> {
245 let connection_ids = self.list_connections().await;
246 for conn_id in connection_ids {
247 let _ = self.send_frame_to(&conn_id, frame, parser).await;
249 }
250 Ok(())
251 }
252
253 async fn broadcast_frame_except(
263 &self,
264 frame: &Frame,
265 exclude_connection_id: &str,
266 parser: Option<&MessageParser>,
267 ) -> Result<()> {
268 let connection_ids = self.list_connections().await;
269 for conn_id in connection_ids {
270 if conn_id != exclude_connection_id {
271 let _ = self.send_frame_to(&conn_id, frame, parser).await;
273 }
274 }
275 Ok(())
276 }
277}
278
279#[derive(Debug, Clone)]
281pub struct ConnectionStats {
282 pub total_connections: usize,
284 pub total_users: usize,
286}