Skip to main content

flare_core/server/connection/manager/
trait_impl.rs

1use super::*;
2
3#[async_trait]
4impl ConnectionManagerTrait for ConnectionManager {
5    fn as_any(&self) -> &dyn std::any::Any {
6        self
7    }
8
9    async fn add_connection(
10        &self,
11        connection_id: String,
12        connection: Arc<Mutex<Box<dyn Connection>>>,
13        user_id: Option<String>,
14    ) -> Result<()> {
15        // 注意:trait 方法不能直接传递 requires_auth,我们需要从 ServerCore 获取
16        // 但这里我们暂时使用 true(需要认证),实际值应该在调用时通过 ServerCore 的 auth_enabled() 获取
17        // 由于 ConnectionManager 不知道 ServerCore,我们暂时使用 true
18        // 实际应用中,连接会在 CONNECT 消息处理时被标记为已验证
19        let requires_auth = true; // 默认需要认证,如果不需要认证,连接会在 CONNECT 消息处理时被标记为已验证
20
21        // 将 Arc<Mutex<Box<dyn Connection>>> 转换为 Box<dyn Connection>
22        // 注意:这需要从 Arc 中取出,但 Arc 可能被多个地方引用
23        // 对于默认实现,我们需要一个不同的方式
24        // 由于 ConnectionManager 内部使用 Arc<Mutex<Box<dyn Connection>>>,
25        // 我们需要保持一致性
26        self.reserve_connection_slot(usize::MAX)?;
27
28        let mut shard = match self.connection_shard(&connection_id).write() {
29            Ok(shard) => shard,
30            Err(_) => {
31                self.release_connection_slot();
32                return Err(FlareError::general_error("Failed to lock connection shard"));
33            }
34        };
35
36        if shard.contains_key(&connection_id) {
37            self.release_connection_slot();
38            return Err(FlareError::protocol_error(format!(
39                "Connection {} already exists",
40                connection_id
41            )));
42        }
43
44        let mut info = ConnectionInfo::new(connection_id.clone(), requires_auth);
45        info.user_id = user_id.clone();
46
47        let entry = self.new_connection_entry(&connection_id, Arc::clone(&connection), info);
48        shard.insert(connection_id.clone(), entry);
49
50        // 如果提供了用户 ID,添加到用户连接映射
51        if let Some(user_id) = user_id
52            && let Err(err) = self.insert_user_connection(user_id, &connection_id)
53        {
54            shard.remove(&connection_id);
55            self.release_connection_slot();
56            return Err(err);
57        }
58
59        Ok(())
60    }
61
62    async fn remove_connection(&self, connection_id: &str) -> Result<()> {
63        ConnectionManager::remove_connection(self, connection_id)
64    }
65
66    async fn get_connection(
67        &self,
68        connection_id: &str,
69    ) -> Option<(
70        Arc<Mutex<Box<dyn Connection>>>,
71        crate::server::connection::r#trait::ConnectionInfo,
72    )> {
73        ConnectionManager::get_connection(self, connection_id).map(|(conn, info)| {
74            // 转换 ConnectionInfo 格式(从 Instant 转换为 Unix 时间戳)
75            let now = std::time::SystemTime::now()
76                .duration_since(std::time::UNIX_EPOCH)
77                .unwrap_or_default()
78                .as_secs();
79            let created_at_secs = now.saturating_sub(info.created_at.elapsed().as_secs());
80            let last_active_secs = now.saturating_sub(info.last_active.elapsed().as_secs());
81
82            let trait_info = crate::server::connection::r#trait::ConnectionInfo {
83                connection_id: info.connection_id,
84                user_id: info.user_id,
85                created_at: created_at_secs,
86                last_active: last_active_secs,
87                metadata: info.metadata,
88                device_info: info.device_info.clone(),
89                serialization_format: info.serialization_format,
90                compression: info.compression,
91                encryption: info.encryption,
92                authenticated: info.authenticated,
93                authenticated_at: info.authenticated_at,
94                negotiation_completed: info.negotiation_completed,
95                negotiation_confirmed: info.negotiation_confirmed,
96                cached_parser: info.cached_parser.clone(),
97                cached_pipeline: info.cached_pipeline.clone(),
98            };
99            (conn, trait_info)
100        })
101    }
102
103    async fn get_user_connections(&self, user_id: &str) -> Vec<String> {
104        ConnectionManager::get_user_connections(self, user_id)
105    }
106
107    async fn bind_user(&self, connection_id: &str, user_id: String) -> Result<()> {
108        ConnectionManager::bind_user(self, connection_id, user_id)
109    }
110
111    async fn update_connection_active(&self, connection_id: &str) -> Result<()> {
112        ConnectionManager::update_connection_active(self, connection_id)
113    }
114
115    async fn set_connection_authenticated(
116        &self,
117        connection_id: &str,
118        user_id: Option<String>,
119    ) -> Result<()> {
120        // ConnectionManager::set_connection_authenticated 是同步方法,直接调用
121        ConnectionManager::set_connection_authenticated(self, connection_id, user_id)
122    }
123
124    async fn list_connections(&self) -> Vec<String> {
125        ConnectionManager::list_connections(self)
126    }
127
128    async fn connection_count(&self) -> usize {
129        ConnectionManager::connection_count(self)
130    }
131
132    fn connection_count_snapshot(&self) -> usize {
133        ConnectionManager::connection_count(self)
134    }
135
136    fn user_count_snapshot(&self) -> usize {
137        ConnectionManager::user_count(self)
138    }
139
140    async fn cleanup_timeout_connections(&self, timeout: Duration) -> Vec<String> {
141        let timeout_connections = self.timeout_connection_snapshots(timeout);
142
143        for (_, connection, _) in &timeout_connections {
144            let mut conn = connection.lock().await;
145            let _ = conn.close().await;
146        }
147
148        self.remove_connection_snapshots(
149            timeout_connections
150                .iter()
151                .map(|(connection_id, _, _)| connection_id.clone()),
152        )
153    }
154
155    async fn send_to_connection(&self, connection_id: &str, data: &[u8]) -> Result<()> {
156        let (_, connection, _) = self.get_connection_snapshot(connection_id).ok_or_else(|| {
157            FlareError::protocol_error(format!("Connection {} not found", connection_id))
158        })?;
159
160        self.send_to_connection_handle(connection_id, connection, data)
161            .await
162    }
163
164    async fn send_to_user(&self, user_id: &str, data: &[u8]) -> Result<()> {
165        let connections =
166            self.connection_handles_for_ids(ConnectionManager::get_user_connections(self, user_id));
167
168        stream::iter(connections)
169            .for_each_concurrent(
170                self.fanout_concurrency,
171                |(connection_id, connection)| async move {
172                    if let Err(e) = self
173                        .send_to_connection_handle(&connection_id, connection, data)
174                        .await
175                    {
176                        tracing::warn!("Failed to send to connection {}: {:?}", connection_id, e);
177                    }
178                },
179            )
180            .await;
181
182        Ok(())
183    }
184
185    async fn broadcast(&self, data: &[u8]) -> Result<()> {
186        let connections = self.connection_handles();
187
188        stream::iter(connections)
189            .for_each_concurrent(
190                self.fanout_concurrency,
191                |(connection_id, connection)| async move {
192                    if let Err(e) = self
193                        .send_to_connection_handle(&connection_id, connection, data)
194                        .await
195                    {
196                        tracing::warn!(
197                            "Failed to broadcast to connection {}: {:?}",
198                            connection_id,
199                            e
200                        );
201                    }
202                },
203            )
204            .await;
205
206        Ok(())
207    }
208
209    async fn broadcast_except(&self, data: &[u8], exclude_connection_id: &str) -> Result<()> {
210        let connections = self.connection_handles_except(exclude_connection_id);
211
212        stream::iter(connections)
213            .for_each_concurrent(
214                self.fanout_concurrency,
215                |(connection_id, connection)| async move {
216                    if let Err(e) = self
217                        .send_to_connection_handle(&connection_id, connection, data)
218                        .await
219                    {
220                        tracing::warn!(
221                            "Failed to broadcast to connection {}: {:?}",
222                            connection_id,
223                            e
224                        );
225                    }
226                },
227            )
228            .await;
229
230        Ok(())
231    }
232
233    async fn send_frame_to(
234        &self,
235        connection_id: &str,
236        frame: &crate::common::protocol::Frame,
237        parser: Option<&crate::common::MessageParser>,
238    ) -> Result<()> {
239        let snapshot = self.get_connection_snapshot(connection_id).ok_or_else(|| {
240            FlareError::connection_failed(format!("连接 {} 不存在", connection_id))
241        })?;
242
243        self.send_frame_to_snapshot(snapshot, frame, parser).await
244    }
245
246    async fn send_frame_to_connections(
247        &self,
248        connection_ids: &[String],
249        frame: &crate::common::protocol::Frame,
250    ) -> (i32, i32) {
251        self.fanout_frame_grouped_by_encoding(connection_ids.to_vec(), frame)
252            .await
253    }
254
255    async fn send_frame_to_user(
256        &self,
257        user_id: &str,
258        frame: &crate::common::protocol::Frame,
259        parser: Option<&crate::common::MessageParser>,
260    ) -> Result<()> {
261        let connection_ids = ConnectionManager::get_user_connections(self, user_id);
262
263        if let Some(parser) = parser {
264            let connections = self.connection_auth_snapshots_for_ids(connection_ids);
265            let data = match parser.serialize(frame) {
266                Ok(data) => data,
267                Err(e) => {
268                    tracing::warn!("Failed to serialize frame for user {}: {:?}", user_id, e);
269                    return Ok(());
270                }
271            };
272
273            let successful_ids = self
274                .fanout_serialized_frame_to_auth_snapshots(
275                    connections,
276                    frame,
277                    &data,
278                    "send_frame_to_user",
279                )
280                .await;
281            self.update_connections_active(successful_ids);
282
283            return Ok(());
284        }
285
286        let connections = self.connection_snapshots_for_ids(connection_ids);
287        let successful_ids = self
288            .fanout_frame_to_snapshots(connections, frame, parser, "send_frame_to_user")
289            .await;
290        self.update_connections_active(successful_ids);
291
292        Ok(())
293    }
294
295    async fn broadcast_frame(
296        &self,
297        frame: &crate::common::protocol::Frame,
298        parser: Option<&crate::common::MessageParser>,
299    ) -> Result<()> {
300        if let Some(parser) = parser {
301            let connections = self.connection_auth_snapshots();
302            let data = match parser.serialize(frame) {
303                Ok(data) => data,
304                Err(e) => {
305                    tracing::warn!("Failed to serialize broadcast frame: {:?}", e);
306                    return Ok(());
307                }
308            };
309
310            let successful_ids = self
311                .fanout_serialized_frame_to_auth_snapshots(
312                    connections,
313                    frame,
314                    &data,
315                    "broadcast_frame",
316                )
317                .await;
318            self.update_connections_active(successful_ids);
319
320            return Ok(());
321        }
322
323        let connections = self.connection_snapshots();
324        let successful_ids = self
325            .fanout_frame_to_snapshots(connections, frame, parser, "broadcast_frame")
326            .await;
327        self.update_connections_active(successful_ids);
328
329        Ok(())
330    }
331
332    async fn broadcast_frame_except(
333        &self,
334        frame: &crate::common::protocol::Frame,
335        exclude_connection_id: &str,
336        parser: Option<&crate::common::MessageParser>,
337    ) -> Result<()> {
338        if let Some(parser) = parser {
339            let connections = self.connection_auth_snapshots_except(exclude_connection_id);
340            let data = match parser.serialize(frame) {
341                Ok(data) => data,
342                Err(e) => {
343                    tracing::warn!("Failed to serialize broadcast frame: {:?}", e);
344                    return Ok(());
345                }
346            };
347
348            let successful_ids = self
349                .fanout_serialized_frame_to_auth_snapshots(
350                    connections,
351                    frame,
352                    &data,
353                    "broadcast_frame_except",
354                )
355                .await;
356            self.update_connections_active(successful_ids);
357
358            return Ok(());
359        }
360
361        let connections = self.connection_snapshots_except(exclude_connection_id);
362        let successful_ids = self
363            .fanout_frame_to_snapshots(connections, frame, parser, "broadcast_frame_except")
364            .await;
365        self.update_connections_active(successful_ids);
366
367        Ok(())
368    }
369}