Skip to main content

wordval_ws/
lib.rs

1//! wordval-ws:wordval 游戏服务器框架的 WebSocket 传输层。
2//!
3//! 提供连接管理、会话跟踪,以及与 axum 集成的 WebSocket 升级助手。
4//! 基于主题的发布/订阅见 [`foxglove`] 模块(feature `foxglove`)。
5//!
6//! # 快速上手
7//!
8//! ```ignore
9//! use wordval_ws::{ws_upgrade, ws_conns, ws_sessions, WsPlugin, WsMessage};
10//!
11//! // 注册插件
12//! let plugin_manager = PluginManager::new().add(WsPlugin);
13//! plugin_manager.start_all().await?;
14//!
15//! // 在 axum 路由中升级 WebSocket:
16//! async fn ws_route(ws: WebSocketUpgrade, user_id: Query<u64>) -> impl IntoResponse {
17//!     ws_upgrade(ws, user_id.0)
18//! }
19//!
20//! // 在任意位置向用户发消息:
21//! ws_conns().send_to_user(user_id, &WsMessage::text("hello"));
22//! ```
23
24pub mod connection;
25pub mod message;
26pub mod session;
27
28use async_trait::async_trait;
29use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
30use axum::http::StatusCode;
31use axum::response::IntoResponse;
32use futures::future::BoxFuture;
33use futures::sink::SinkExt;
34use futures::stream::StreamExt;
35use std::sync::atomic::{AtomicU64, Ordering};
36use std::sync::{Arc, OnceLock};
37use tokio::sync::{mpsc, watch, Semaphore};
38use tracing::{debug, error, info, warn};
39use wordval_core::Result;
40
41// Re-exports
42pub use connection::ConnectionManager;
43#[cfg(feature = "foxglove")]
44pub use foxglove::{
45    AuthCtx, AuthHandler, AuthIdentity, AuthRejection, ClientPublishHandler, ConnCtx,
46    ConnectHandler, DisconnectHandler, FoxgloveServer, FoxgloveServerConfig,
47    FoxgloveServerError, RateLimit, ServiceCallHandler, SubscribeHandler,
48};
49pub use message::Connection;
50pub use message::WsMessage;
51#[cfg(feature = "cluster")]
52pub use cluster::ClusterConfig;
53pub use session::SessionExpiredHandler;
54pub use session::SessionInfo;
55pub use session::SessionManager;
56
57// ──── Foxglove 服务端模块 ───────────────────────────────────────────
58
59/// Foxglove WebSocket 协议 v1 服务端(feature `foxglove`)。
60///
61/// 让 Foxglove Studio / wordval-foxglove 客户端连接本应用的 axum 端口,
62/// 订阅服务端广播的通道进行可视化。详见 [`foxglove`] 模块文档。
63#[cfg(feature = "foxglove")]
64pub mod foxglove;
65
66/// 多节点集群支持(feature `cluster`):总线跨节点转发 + 缓存(Redis)
67/// 跨节点在线状态。见 [`cluster`] 模块文档。
68#[cfg(feature = "cluster")]
69pub mod cluster;
70
71// ──── 资源访问器 ─────────────────────────────────────────────────────
72
73/// 全局 ConnectionManager 单例的便捷访问器。
74///
75/// 等价于 [`connection::get()`]。
76///
77/// # Panics
78///
79/// 若 `ws` 插件尚未启动则 panic。
80pub fn ws_conns() -> &'static Arc<ConnectionManager> {
81    connection::get()
82}
83
84/// 尝试获取全局连接管理器的引用(未初始化时返回 `None`)。
85pub fn try_ws_conns() -> Option<&'static Arc<ConnectionManager>> {
86    connection::try_get()
87}
88
89/// 全局 SessionManager 单例的便捷访问器。
90///
91/// 等价于 [`session::get()`]。
92///
93/// # Panics
94///
95/// 若 `ws` 插件尚未启动则 panic。
96pub fn ws_sessions() -> &'static Arc<SessionManager> {
97    session::get()
98}
99
100/// 尝试获取全局会话管理器的引用(未初始化时返回 `None`)。
101pub fn try_ws_sessions() -> Option<&'static Arc<SessionManager>> {
102    session::try_get()
103}
104
105// ──── 消息处理器类型 ─────────────────────────────────────────────────
106
107/// 入站 WebSocket 消息的应用层处理器。
108///
109/// 接收解析后的消息与用户 ID。在 WebSocket 读任务内调用;返回的 future
110/// 会被 spawn 到 runtime 上,因此长时间的异步工作(如调用 LLM、写库)不会阻塞读循环。
111pub type MessageHandler = Arc<dyn Fn(WsMessage, u64) -> BoxFuture<'static, ()> + Send + Sync>;
112
113// ──── WebSocket 升级助手 ─────────────────────────────────────────────
114
115/// 出站消息通道容量。
116///
117/// 限制每条连接在施加背压前可排队的消息数。
118/// 缓冲满时新消息被丢弃(`try_send` 失败),慢消费者随后因心跳超时被
119/// [`ConnectionManager::purge_stale`] 回收,防止 OOM。
120const WS_CHANNEL_CAPACITY: usize = 1024;
121
122/// 单连接允许的最大并发消息处理任务数。
123///
124/// 每条入站消息会 spawn 一个处理任务;若处理器缓慢(如调用 LLM)而客户端
125/// 持续洪泛,无界 spawn 会让任务无限堆积耗尽内存。超过该上限的新消息直接
126/// 丢弃并计数(与出站方向的慢消费者丢弃策略一致)。
127const WS_MAX_IN_FLIGHT_HANDLERS: usize = 256;
128
129/// 单条入站 WebSocket 消息的最大字节数(防洪泛,默认 4 MiB)。
130///
131/// 入站消息会占用有界处理器并发额度(每连接 [`WS_MAX_IN_FLIGHT_HANDLERS`]
132/// 个在途任务),不限制单条消息体积时,恶意客户端可用少量连接占满内存
133/// (256 在途 × 64 MiB = 16 GiB)。如需传输更大帧,请基于 axum 自行封装
134/// upgrade 并放宽该限制。
135pub const WS_MAX_MESSAGE_SIZE: usize = 4 * 1024 * 1024;
136
137/// 心跳/会话活跃触摸的去抖间隔。
138///
139/// 入站消息风暴下每连接每秒至多触发一次 DashMap 写(原本每条消息一次,
140/// 纯热路径浪费);`purge_stale` 的超时阈值(默认 90 s)远大于该粒度,
141/// 不影响过期判定精度。
142const TOUCH_DEBOUNCE: std::time::Duration = std::time::Duration::from_secs(1);
143
144/// 后台维护任务默认间隔(秒)
145pub const DEFAULT_MAINTENANCE_INTERVAL_SECS: u64 = 30;
146/// 连接被视为过期(无心跳)的超时(秒),应大于维护间隔以容忍至少一次心跳往返
147pub const DEFAULT_STALE_TIMEOUT_SECS: u64 = 90;
148
149/// 把 HTTP 请求升级为 WebSocket 连接。
150///
151/// **安全警告**: 此函数假设 `user_id` 已由调用方完成认证。
152/// 对于面向公网的应用,请自行在路由层(如通过认证中间件注入的 `Extension`)
153/// 安全提取已认证用户,避免伪造 `user_id`。
154///
155/// 在全局 [`ConnectionManager`] 中登记连接,spawn 读写循环的后台任务,
156/// 并自动处理 ping/pong 保活。连接数达到上限时握手期直接返回 503
157/// (软检查,与 foxglove 路由行为一致;硬上限由 [`handle_socket`] 的
158/// CAS 占位兜底)。
159///
160/// # 参数
161///
162/// * `ws` - axum 的 WebSocket 升级提取器。
163/// * `user_id` - 已认证的用户 ID(0 表示未认证 / 游客)。
164///
165/// # 示例
166///
167/// ```ignore
168/// // 内部受信任路由使用(如管理后台内部调用)
169/// async fn ws_internal(ws: WebSocketUpgrade, user_id: Extension<u64>) -> impl IntoResponse {
170///     wordval_ws::ws_upgrade(ws, user_id.0)
171/// }
172/// ```
173pub async fn ws_upgrade(ws: WebSocketUpgrade, user_id: u64) -> impl IntoResponse {
174    if let Some(mgr) = connection::try_get() {
175        if mgr.count() as u64 >= mgr.max_connections() {
176            return (StatusCode::SERVICE_UNAVAILABLE, "too many connections").into_response();
177        }
178    }
179    ws.max_message_size(WS_MAX_MESSAGE_SIZE)
180        .max_frame_size(WS_MAX_MESSAGE_SIZE)
181        .on_upgrade(move |socket| handle_socket(socket, user_id, None))
182}
183
184/// 把 HTTP 请求升级为 WebSocket 连接,并挂载自定义消息处理器。
185///
186/// **安全警告**: 同 [`ws_upgrade`],`user_id` 须已由调用方认证。
187/// 连接数软 / 硬上限行为亦同 [`ws_upgrade`]。
188pub async fn ws_upgrade_with_handler(
189    ws: WebSocketUpgrade,
190    user_id: u64,
191    handler: MessageHandler,
192) -> impl IntoResponse {
193    if let Some(mgr) = connection::try_get() {
194        if mgr.count() as u64 >= mgr.max_connections() {
195            return (StatusCode::SERVICE_UNAVAILABLE, "too many connections").into_response();
196        }
197    }
198    ws.max_message_size(WS_MAX_MESSAGE_SIZE)
199        .max_frame_size(WS_MAX_MESSAGE_SIZE)
200        .on_upgrade(move |socket| handle_socket(socket, user_id, Some(handler)))
201}
202
203// ──── WebSocket 生命周期 ────────────────────────────────────────────
204
205/// 内部处理器:管理单条 WebSocket 连接的完整生命周期。
206async fn handle_socket(socket: WebSocket, user_id: u64, handler: Option<MessageHandler>) {
207    // 分配唯一连接 ID
208    let conn_mgr = match connection::try_get() {
209        Some(mgr) => mgr,
210        None => {
211            error!("ConnectionManager 未初始化,无法处理 WebSocket 连接");
212            return;
213        }
214    };
215
216    let conn_id = conn_mgr.next_conn_id();
217
218    // 把 WebSocket 拆分为发送与接收两半
219    let (mut ws_sender, mut ws_receiver) = socket.split();
220
221    // 为出站消息(外部 → WebSocket)创建有界 mpsc 通道。
222    // 有界通道施加背压:客户端过慢时发送失败、消息被丢弃,
223    // 防止内存无限增长。
224    let (tx, rx) = mpsc::channel::<WsMessage>(WS_CHANNEL_CAPACITY);
225
226    // 连接数硬上限:CAS 原子占位,超限直接拒绝(无 TOCTOU 窗口)
227    if conn_mgr.try_add(conn_id, user_id, tx).is_none() {
228        warn!(
229            conn_id,
230            user_id,
231            "WebSocket 连接数已达上限 {},拒绝新连接",
232            conn_mgr.max_connections()
233        );
234        // HTTP 101 已发出:以 Close 帧礼貌收尾,而非静默断开
235        let _ = ws_sender.send(Message::Close(None)).await;
236        return;
237    }
238
239    // 若 user_id 非零,登记到会话管理器(多端 / 跨协议引用计数:
240    // 每条连接 attach 一个计数)
241    if user_id != 0 {
242        if let Some(sess_mgr) = session::try_get() {
243            sess_mgr.attach_conn(user_id, conn_id);
244        }
245        // 集群在线状态:把本节点登记到用户的在线节点集合
246        #[cfg(feature = "cluster")]
247        crate::cluster::on_conn_attached(user_id).await;
248    }
249
250    info!(conn_id, user_id, "WebSocket 连接已建立");
251
252    // 写任务退出信号:连接被管理器摘除(purge_stale / close_all)后发送端
253    // drop,写任务排空缓冲退出并置位;读循环据此及时终止——否则被摘除的
254    // 连接会变成"僵尸":socket 不关、会话引用不释放,客户端只要持续发帧
255    // 读循环就永远存活。写任务因发送失败退出(对端已死)时同样会触发。
256    let (write_done_tx, mut write_done_rx) = watch::channel(false);
257
258    // Spawn 写任务:把 mpsc 消息转发到 WebSocket
259    let mut write_ws_sender = ws_sender;
260    let mut write_task = tokio::spawn(async move {
261        let mut rx = rx;
262        while let Some(msg) = rx.recv().await {
263            let ws_msg = ws_message_to_axum(msg);
264            match write_ws_sender.send(ws_msg).await {
265                Ok(()) => {}
266                Err(e) => {
267                    warn!(error = %e, "WebSocket 写入失败,结束写任务");
268                    break;
269                }
270            }
271        }
272        // tungstenite 0.26+ 读到对端 Close 时自动排队回显帧并转入 Closed,
273        // 应用层显式 echo 会被 SendAfterClosing 拒绝;退出前排空底层缓冲,
274        // 把库内自动回显真正写出去——否则对端只能收到异常断链
275        // (ResetWithoutClosingHandshake)而非干净的关闭握手。
276        let _ = write_ws_sender.flush().await;
277        debug!(conn_id, "写任务结束");
278        let _ = write_done_tx.send(true);
279    });
280
281    // 入站处理器并发额度:有界派发,满则丢弃新消息(防洪泛耗尽内存)
282    let handler_slots = Arc::new(Semaphore::new(WS_MAX_IN_FLIGHT_HANDLERS));
283    let dropped_inbound = AtomicU64::new(0);
284    // 心跳/会话触摸去抖:上次触摸时刻;None 表示尚未触摸过
285    let mut last_touch: Option<std::time::Instant> = None;
286    loop {
287        let msg = tokio::select! {
288            _ = write_done_rx.changed() => {
289                info!(conn_id, user_id, "连接已被移除或写任务已退出,读循环终止");
290                break;
291            }
292            msg = ws_receiver.next() => msg,
293        };
294
295        // 任何成功接收的入站帧都视为活跃信号(Text/Binary/Ping/Pong 均刷新心跳),
296        // 避免"不配合 Pong 但持续发消息"的客户端被 purge_stale 误杀。
297        // 去抖:每秒至多触摸一次,热路径不再逐消息抢 DashMap 分片写锁。
298        if matches!(msg, Some(Ok(_))) {
299            let now = std::time::Instant::now();
300            if last_touch.map_or(true, |t| now.duration_since(t) >= TOUCH_DEBOUNCE) {
301                last_touch = Some(now);
302                conn_mgr.touch_heartbeat(conn_id);
303                if user_id != 0 {
304                    if let Some(sess_mgr) = session::try_get() {
305                        sess_mgr.touch(user_id);
306                    }
307                }
308            }
309        }
310
311        match msg {
312            Some(Ok(Message::Text(text))) => {
313                if let Some(ref h) = handler {
314                    dispatch_handler(h, WsMessage::Text(text), user_id, &handler_slots, &dropped_inbound, conn_id);
315                }
316            }
317            Some(Ok(Message::Binary(data))) => {
318                if let Some(ref h) = handler {
319                    dispatch_handler(h, WsMessage::Binary(data), user_id, &handler_slots, &dropped_inbound, conn_id);
320                }
321            }
322            Some(Ok(Message::Ping(payload))) => {
323                // 仅向当前连接回应 Pong。
324                // 注意:不能走 send_to_user —— 那会误投到该用户的所有设备,
325                // 且游客 user_id=0 时会广播给全部游客连接。
326                conn_mgr.send_to_conn(conn_id, &WsMessage::Pong(payload.to_vec()));
327            }
328            Some(Ok(Message::Pong(_payload))) => {
329                debug!(conn_id, user_id, "收到 pong");
330            }
331            Some(Ok(Message::Close(_frame))) => {
332                info!(conn_id, user_id, "客户端请求关闭连接");
333                // 回显 Close 完成关闭握手(此刻连接仍在表中,入队后由写任务
334                // 按序发出),客户端收到干净关闭而非 TCP FIN(1006 异常关闭);
335                // 队列满则放弃,退化为原有的 best-effort 行为
336                conn_mgr.send_to_conn(conn_id, &WsMessage::Close);
337                break;
338            }
339            Some(Err(e)) => {
340                warn!(conn_id, user_id, error = %e, "WebSocket 读取错误");
341                break;
342            }
343            None => {
344                info!(conn_id, user_id, "WebSocket 流已结束");
345                break;
346            }
347        }
348    }
349
350    // ── 连接清理 ──────────────────────────────────────────────────
351    let dropped_inbound_total = dropped_inbound.load(Ordering::Relaxed);
352    if dropped_inbound_total > 0 {
353        warn!(
354            conn_id,
355            user_id,
356            dropped_inbound_total, "连接关闭:入站处理超限累计丢弃的消息数"
357        );
358    }
359    info!(conn_id, user_id, "WebSocket 连接关闭中");
360
361    // 从连接管理器移除(同时 drop 发送端,写任务 drain 后会自行退出)
362    conn_mgr.remove(conn_id);
363
364    // 解绑会话:引用计数 detach。
365    // 仅当用户(跨所有协议的)最后一条活跃连接断开时,
366    // 会话才进入宽限期。
367    if user_id != 0 {
368        if let Some(sess_mgr) = session::try_get() {
369            let fully_disconnected = sess_mgr.detach_conn(user_id);
370            if fully_disconnected {
371                debug!(user_id, "用户全部连接已断开,会话进入宽限期");
372                // 集群在线状态:本节点已无该用户的连接,从在线集合移除
373                #[cfg(feature = "cluster")]
374                crate::cluster::on_conn_detached(user_id).await;
375            }
376        }
377    }
378
379    // remove() 已 drop 发送端:写任务 drain 完缓冲消息(含 Close 帧)后自行退出。
380    // 给短暂窗口完成收尾,超时再兜底 abort,避免丢弃已排队的消息。
381    if tokio::time::timeout(std::time::Duration::from_secs(2), &mut write_task)
382        .await
383        .is_err()
384    {
385        write_task.abort();
386    }
387}
388
389// ──── 转换助手 ───────────────────────────────────────────────────────
390
391/// 把入站消息有界地派发给应用处理器:信号量占坑成功才 spawn,
392/// 额度耗尽(慢处理器 + 洪泛客户端)则丢弃新消息并计数,绝不阻塞读循环。
393fn dispatch_handler(
394    handler: &MessageHandler,
395    msg: WsMessage,
396    user_id: u64,
397    slots: &Arc<Semaphore>,
398    dropped: &AtomicU64,
399    conn_id: u64,
400) {
401    match slots.clone().try_acquire_owned() {
402        Ok(permit) => {
403            let h = Arc::clone(handler);
404            tokio::spawn(async move {
405                h(msg, user_id).await;
406                drop(permit);
407            });
408        }
409        Err(_) => {
410            let n = dropped.fetch_add(1, Ordering::Relaxed) + 1;
411            // 仅周期性告警,避免日志被洪泛打满
412            if n == 1 || n % 1024 == 0 {
413                warn!(conn_id, user_id, dropped = n, "入站处理任务已达上限,丢弃消息");
414            }
415        }
416    }
417}
418
419/// 把内部 [`WsMessage`] 转换为 axum [`Message`]。
420///
421/// 零拷贝:Utf8Bytes / Bytes 直接传入 axum,克隆仅递增引用计数。
422fn ws_message_to_axum(msg: WsMessage) -> Message {
423    match msg {
424        WsMessage::Text(s) => Message::Text(s),
425        WsMessage::Binary(data) => Message::Binary(data),
426        WsMessage::Close => Message::Close(None),
427        WsMessage::Ping(payload) => Message::Ping(payload.into()),
428        WsMessage::Pong(payload) => Message::Pong(payload.into()),
429    }
430}
431
432// ──── 插件 ───────────────────────────────────────────────────────────
433
434/// wordval 的 WebSocket 插件。
435///
436/// 实现 [`wordval_core::Plugin`]。`start()` 时初始化全局连接与会话管理器;
437/// `stop()` 时拆除所有连接并清理资源。
438///
439/// 依赖 `cache` 插件以支持会话持久化集成。
440pub struct WsPlugin {
441    /// 最大并发 WebSocket 连接数上限
442    max_connections: u64,
443    /// 后台维护任务间隔(秒):心跳 Ping 下发 + 过期清理周期
444    maintenance_interval_secs: u64,
445    /// 无心跳连接的过期超时(秒)
446    stale_timeout_secs: u64,
447    /// 多节点集群配置(feature `cluster`)
448    #[cfg(feature = "cluster")]
449    cluster: Option<cluster::ClusterConfig>,
450}
451
452impl WsPlugin {
453    pub fn new() -> Self {
454        Self {
455            max_connections: connection::DEFAULT_MAX_WS_CONNECTIONS,
456            maintenance_interval_secs: DEFAULT_MAINTENANCE_INTERVAL_SECS,
457            stale_timeout_secs: DEFAULT_STALE_TIMEOUT_SECS,
458            #[cfg(feature = "cluster")]
459            cluster: None,
460        }
461    }
462
463    /// 设置最大并发连接数上限(至少 1)
464    pub fn with_max_connections(mut self, n: u64) -> Self {
465        self.max_connections = n.max(1);
466        self
467    }
468
469    /// 设置后台维护任务间隔(秒,至少 1):每该时长向所有连接下发心跳
470    /// Ping 并执行过期连接 / 会话清理。
471    ///
472    /// 全局仅允许一个维护任务:若 `WsPlugin::start()` 之前已有其他组件
473    /// 初始化了 ws 基础设施(如 [`foxglove::FoxgloveServer::new`]),
474    /// 以先启动者为准,此处配置被忽略。
475    pub fn with_maintenance_interval(mut self, secs: u64) -> Self {
476        self.maintenance_interval_secs = secs.max(1);
477        self
478    }
479
480    /// 设置无心跳连接的过期超时(秒,至少 1),应大于维护间隔以容忍
481    /// 至少一次心跳往返。
482    pub fn with_stale_timeout(mut self, secs: u64) -> Self {
483        self.stale_timeout_secs = secs.max(1);
484        self
485    }
486
487    /// 启用多节点集群:跨节点 `send_to_user` / `broadcast` 转发(wordval-bus)
488    /// 与跨节点在线状态(缓存 / Redis)。投递语义与边界见 [`cluster`]
489    /// 模块文档。
490    #[cfg(feature = "cluster")]
491    pub fn with_cluster(mut self, config: cluster::ClusterConfig) -> Self {
492        self.cluster = Some(config);
493        self
494    }
495}
496
497impl Default for WsPlugin {
498    fn default() -> Self {
499        Self::new()
500    }
501}
502
503/// 独立初始化 WebSocket 基础设施(连接/会话管理器 + 后台维护任务)。
504///
505/// 供不通过 `WsPlugin`(无 cache 插件依赖的场景)直接使用 wordval-ws 的
506/// 业务模块调用;全局仅生效一次,重复调用安全忽略。
507/// [`foxglove::FoxgloveServer::new`] 内部会自动调用本函数。
508///
509/// 后台维护任务需要 tokio runtime;在无 runtime 的上下文(如全局静态构造)
510/// 调用时管理器仍会初始化,但维护任务不会启动(打印 warn),请在 runtime
511/// 内尽早调用一次本函数以补启动。
512pub fn init_ws_infrastructure() {
513    static STARTED: OnceLock<()> = OnceLock::new();
514    let first = STARTED.set(()).is_ok();
515    if first {
516        connection::init();
517        session::init();
518        if tokio::runtime::Handle::try_current().is_err() {
519            warn!(
520                "init_ws_infrastructure 在无 tokio runtime 的上下文调用:\
521                 后台维护任务将在下一次(runtime 内)调用时补启动"
522            );
523        }
524    }
525    // 维护任务与全局管理器解耦:首次调用若缺 runtime,后续调用(如
526    // WsPlugin::start 或 FoxgloveServer::new 在 runtime 内)可补启动。
527    // spawn_maintenance_task 自带全局去重,重复调用无害。
528    if tokio::runtime::Handle::try_current().is_ok() {
529        spawn_maintenance_task(
530            DEFAULT_MAINTENANCE_INTERVAL_SECS,
531            DEFAULT_STALE_TIMEOUT_SECS,
532        );
533    }
534}
535
536#[async_trait]
537impl wordval_core::Plugin for WsPlugin {
538    fn name(&self) -> &str {
539        "ws"
540    }
541
542    async fn start(&self) -> Result<()> {
543        info!("WsPlugin 启动中...");
544        // 先按插件配置抢占全局唯一的维护任务(若被其他组件抢先则其配置
545        // 生效,本次调用被 OnceLock 忽略),再初始化管理器。
546        spawn_maintenance_task(self.maintenance_interval_secs, self.stale_timeout_secs);
547        init_ws_infrastructure();
548        if let Some(mgr) = connection::try_get() {
549            mgr.set_max_connections(self.max_connections);
550        }
551        // 集群转发与在线状态(feature `cluster`)
552        #[cfg(feature = "cluster")]
553        if let Some(cfg) = &self.cluster {
554            cluster::enable(cfg.clone())?;
555        }
556        info!("WsPlugin 已启动 (连接管理器 + 会话管理器)");
557        Ok(())
558    }
559
560    async fn stop(&self) -> Result<()> {
561        info!("WsPlugin 停止中...");
562
563        // 关闭所有连接(向每个客户端发送 Close 帧)
564        if let Some(mgr) = connection::try_get() {
565            mgr.close_all();
566        }
567
568        // 清空所有会话
569        if let Some(mgr) = session::try_get() {
570            mgr.clear_all();
571        }
572
573        info!("WsPlugin 已停止");
574        Ok(())
575    }
576}
577
578// ──── 后台维护 ───────────────────────────────────────────────────────
579
580/// 启动后台任务:周期性清理过期连接与过期会话。
581///
582/// 在插件启动后调用(如应用初始化阶段)。
583///
584/// # 参数
585///
586/// * `interval_secs` - 清理周期(秒)。
587/// * `stale_timeout_secs` - 空闲超过该时长的连接将被移除。
588pub fn spawn_maintenance_task(interval_secs: u64, stale_timeout_secs: u64) {
589    // 全局仅允许启动一个维护任务:插件自动启动与用户显式调用只会生效一次
590    static STARTED: OnceLock<()> = OnceLock::new();
591    if STARTED.set(()).is_err() {
592        return;
593    }
594
595    let interval = std::time::Duration::from_secs(interval_secs);
596    let timeout = std::time::Duration::from_secs(stale_timeout_secs);
597
598    tokio::spawn(async move {
599        loop {
600            tokio::time::sleep(interval).await;
601
602            // 整拍防御性隔离:任何一处 panic(框架缺陷或业务回调)都不应
603            // 终止维护循环——否则心跳与过期清理将永久停摆,僵尸连接再无回收。
604            let tick = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
605                // 向所有连接下发 Ping 心跳:存活客户端会回应 Pong 刷新 last_heartbeat,
606                // 使得下方 purge_stale 只清理真正无响应的死连接,不会误杀空闲但存活的连接。
607                if let Some(conn_mgr) = connection::try_get() {
608                    conn_mgr.send_heartbeat_pings();
609                }
610
611                if let Some(conn_mgr) = connection::try_get() {
612                    let purged = conn_mgr.purge_stale(timeout);
613                    if purged > 0 {
614                        info!(purged, "后台清理了 {} 个过期连接", purged);
615                    }
616                }
617
618                if let Some(sess_mgr) = session::try_get() {
619                    let cleaned = sess_mgr.cleanup_expired();
620                    if cleaned > 0 {
621                        info!(cleaned, "后台清理了 {} 个过期会话", cleaned);
622                    }
623                }
624            }));
625            if tick.is_err() {
626                error!("ws 维护任务本拍 panic(已隔离,循环继续)");
627            }
628
629            // 集群在线状态 TTL 续期:保证长连接用户不因 TTL 到期而"假离线"。
630            // 经 spawn + JoinHandle 收割 panic:续期若 panic 仅记录并继续,
631            // 维护循环(心跳 / 过期清理)不受波及;串行 await 保持逐拍节奏。
632            #[cfg(feature = "cluster")]
633            match tokio::spawn(crate::cluster::refresh_presence()).await {
634                Ok(()) => {}
635                Err(e) if e.is_panic() => {
636                    error!("ws 集群 presence 续期 panic(已隔离,循环继续)");
637                }
638                Err(e) => {
639                    error!(error = %e, "ws 集群 presence 续期任务异常取消");
640                }
641            }
642        }
643    });
644}
645
646#[cfg(test)]
647mod tests {
648    use super::*;
649
650    #[test]
651    fn test_ws_message_conversion_text() {
652        let ws_msg = WsMessage::text("hello");
653        let axum_msg = ws_message_to_axum(ws_msg);
654        assert!(matches!(axum_msg, Message::Text(ref s) if *s == "hello"));
655    }
656
657    #[test]
658    fn test_ws_message_conversion_binary() {
659        let ws_msg = WsMessage::binary(vec![1, 2, 3]);
660        let axum_msg = ws_message_to_axum(ws_msg);
661        assert!(matches!(axum_msg, Message::Binary(ref b) if **b == [1, 2, 3]));
662    }
663
664    #[test]
665    fn test_ws_message_conversion_close() {
666        let ws_msg = WsMessage::Close;
667        let axum_msg = ws_message_to_axum(ws_msg);
668        assert!(matches!(axum_msg, Message::Close(None)));
669    }
670
671    #[test]
672    fn test_ws_message_conversion_ping_pong() {
673        let ws_msg = WsMessage::Ping(vec![4, 5, 6]);
674        let axum_msg = ws_message_to_axum(ws_msg);
675        assert!(matches!(axum_msg, Message::Ping(ref b) if **b == [4, 5, 6]));
676
677        let ws_msg = WsMessage::Pong(vec![7, 8, 9]);
678        let axum_msg = ws_message_to_axum(ws_msg);
679        assert!(matches!(axum_msg, Message::Pong(ref b) if **b == [7, 8, 9]));
680    }
681
682    #[test]
683    fn test_ws_message_json_constructor() {
684        let data = serde_json::json!({"type": "chat", "content": "hi"});
685        let msg = WsMessage::json(&data).unwrap();
686        assert!(matches!(msg, WsMessage::Text(ref s) if s.contains("chat")));
687    }
688
689    #[test]
690    fn test_ws_message_from_string() {
691        let msg: WsMessage = "hello".into();
692        assert!(matches!(msg, WsMessage::Text(ref s) if s.as_str() == "hello"));
693
694        let msg: WsMessage = String::from("world").into();
695        assert!(matches!(msg, WsMessage::Text(ref s) if s.as_str() == "world"));
696    }
697
698    #[test]
699    fn test_ws_message_clone_shares_payload() {
700        // 引用计数共享负载:克隆不复制底层字节,指向同一分配
701        let msg = WsMessage::text("shared payload");
702        let cloned = msg.clone();
703        match (&msg, &cloned) {
704            (WsMessage::Text(a), WsMessage::Text(b)) => {
705                // Utf8Bytes 底层是 Bytes(Arc 管理),比较数据指针验证零拷贝
706                assert_eq!(a.as_ptr(), b.as_ptr());
707            }
708            _ => panic!("expected text messages"),
709        }
710    }
711}