Skip to main content

wordval_foxglove/
lib.rs

1//! wordval-foxglove:面向 wordval 框架的 Foxglove WebSocket 协议客户端,
2//! 用于将机器人数据流式接入 wordval 框架。
3//!
4//! 提供高弹性的 [`FoxgloveClient`],以
5//! [`foxglove.websocket.v1`](https://github.com/foxglove/ws-protocol) 协议
6//! 对接 foxglove-sdk WebSocket 服务端,特性包括:
7//!
8//! - **高性能** — 全链路零拷贝 `Bytes` 载荷;入站分发仅是一次 DashMap
9//!   查找 + `try_send`,绝不因慢消费者而阻塞 socket。
10//! - **低内存** — 所有队列均有界(出站帧、每订阅通道、事件广播);
11//!   `max_message_size` / `max_frame_size` / `max_write_buffer_size`
12//!   均显式配置。
13//! - **高稳定** — 由监督任务持有连接生命周期,指数退避重连
14//!   (±25 % 抖动);订阅、客户端广播与 watch 在每次重连后自动重放;
15//!   断连时在途请求立即以 [`FoxgloveError::NotConnected`] 快速失败。
16//! - **CDR / ROS 2 支持** — `cdr` 编码通道既可通用解码
17//!   ([`MessageData::decode_cdr`],由广播的 `ros2msg` schema 驱动),
18//!   也可解码为类型化的 serde 结构体([`MessageData::decode_cdr_as`]);
19//!   发布通过 [`PublishChannel::publish_cdr`] 完成。
20//!
21//! [`FoxglovePlugin`](`plugin` feature,默认启用)实现了
22//! `wordval_core::Plugin` 用于生命周期管理,
23//! 全局访问器(`foxglove()` / `try_foxglove()`)遵循 wordval 单例模式
24//! (可安全重启,与 `wordval_nats::nats()` 一致)。不使用 wordval 框架的
25//! 宿主可 `default-features = false` 只引入独立客户端 API。
26//!
27//! # 快速上手
28//!
29//! ```ignore
30//! use wordval_foxglove::{foxglove, FoxglovePlugin};
31//! use wordval_core::PluginManager;
32//!
33//! let mgr = PluginManager::new()
34//!     .add(FoxglovePlugin::new().with_url("ws://127.0.0.1:8765"));
35//! mgr.start_all().await?;
36//!
37//! // 订阅(等待主题被广播,重连后依然有效)
38//! let mut sub = foxglove().subscribe_topic("/camera/image").await?;
39//! while let Some(msg) = sub.recv().await {
40//!     println!("{}: {} bytes", msg.topic(), msg.payload().len());
41//! }
42//! ```
43
44#[cfg(feature = "plugin")]
45use async_trait::async_trait;
46#[cfg(feature = "plugin")]
47use parking_lot::RwLock;
48#[cfg(feature = "plugin")]
49use std::sync::Arc;
50#[cfg(feature = "plugin")]
51use wordval_core::{Plugin, Result};
52
53mod client;
54mod subscription;
55
56// 协议层(JSON / 二进制编解码、CDR / ROS 2 schema 解析)已抽取到
57// wordval-foxglove-protocol crate,由本客户端与 wordval-ws 服务端共享。
58// 整体 re-export 以保持 `crate::protocol` / `crate::cdr` 内部路径与
59// `wordval_foxglove::protocol` / `wordval_foxglove::cdr` 公开路径不变。
60pub use wordval_foxglove_protocol::cdr;
61pub use wordval_foxglove_protocol::protocol;
62
63/// Foxglove 客户端错误。
64pub mod error {
65    use std::time::Duration;
66
67    use crate::protocol::ProtocolError;
68
69    /// foxglove 客户端操作中可能发生的错误。
70    #[derive(Debug, thiserror::Error)]
71    pub enum FoxgloveError {
72        /// 配置的服务端 URL 格式错误或不受支持。
73        #[error("invalid url: {0}")]
74        InvalidUrl(String),
75
76        /// 连接时发生 TCP 层 IO 失败。
77        #[error("io error: {0}")]
78        Io(String),
79
80        /// WebSocket 协议 / 传输层故障。
81        #[error("websocket error: {0}")]
82        Ws(String),
83
84        /// 二进制帧解码失败。
85        #[error("protocol decode error: {0}")]
86        Codec(#[from] ProtocolError),
87
88        /// JSON 控制消息(反)序列化失败。
89        #[error("json error: {0}")]
90        Serde(#[from] serde_json::Error),
91
92        /// 操作超出时限。
93        #[error("timeout after {0:?}")]
94        Timeout(Duration),
95
96        /// 无活动连接(已断开或处于重连间隙)。
97        #[error("not connected")]
98        NotConnected,
99
100        /// 对端关闭了连接。
101        #[error("connection closed by peer")]
102        Closed,
103
104        /// 在订阅截止时间前主题未被广播。
105        #[error("topic not advertised: {0}")]
106        TopicNotAdvertised(String),
107
108        /// 请求的通道 id 未被当前会话广播(
109        /// [`FoxgloveClient::subscribe_channel`](crate::FoxgloveClient::subscribe_channel))。
110        #[error("channel not advertised: {0}")]
111        ChannelNotAdvertised(u32),
112
113        /// 该主题已存在活动订阅(协议规定每个客户端对每个通道只能有一个订阅)。
114        #[error("topic already subscribed: {0}")]
115        AlreadySubscribed(String),
116
117        /// 服务名未被服务端广播。
118        #[error("service not advertised: {0}")]
119        ServiceNotAdvertised(String),
120
121        /// 服务端报告服务调用失败。
122        #[error("service call failed: {0}")]
123        ServiceFailed(String),
124
125        /// 服务端获取请求的资源失败。
126        #[error("fetch asset failed: {0}")]
127        FetchAssetFailed(String),
128
129        /// 操作所需的服务端能力未被声明。
130        #[error("server capability not supported: {0}")]
131        CapabilityUnsupported(&'static str),
132
133        /// 出站队列已满;消息未发送。
134        #[error("outbound queue full")]
135        QueueFull,
136
137        /// CDR(反)序列化失败(例如发生在
138        /// [`PublishChannel::publish_cdr`](crate::PublishChannel::publish_cdr) 中)。
139        #[error("cdr error: {0}")]
140        Cdr(#[from] cdr::Error),
141    }
142}
143
144pub use cdr::{CdrError, CdrValue};
145pub use client::{
146    ClientChannelSpec, ClientConfig, ConnectionState, ConnectionStatus, FoxgloveClient,
147    FoxgloveEvent, PublishChannel, ServiceCall, ServiceResponse, TrafficSnapshot,
148};
149pub use error::FoxgloveError;
150pub use protocol::{
151    Channel, ConnectionGraphUpdate, Parameter, ServerInfo, Service, StatusLevel, CAP_ASSETS,
152    CAP_CLIENT_PUBLISH, CAP_CONNECTION_GRAPH, CAP_PARAMETERS, CAP_PARAMETERS_SUBSCRIBE, CAP_SERVICES,
153    CAP_TIME, SUBPROTOCOL, SUBPROTOCOL_SDK,
154};
155pub use subscription::{MessageData, Subscription};
156
157// ── 测试辅助 ──────────────────────────────────────────────────────────
158
159/// 连接注入接缝(`test-utils` feature)。
160///
161/// 暴露 [`Connector`] trait 与流类型别名,让下游能以内存双工流
162/// (如 `tokio::io::duplex`)驱动 [`FoxgloveClient`] 做端到端测试,
163/// 无需真实 TCP / WebSocket 服务端;配合
164/// [`FoxgloveClient::with_connector`](crate::FoxgloveClient::with_connector)
165/// 使用。
166#[cfg(feature = "test-utils")]
167pub mod test_utils {
168    pub use crate::client::{BoxIo, Connector, Io, WsStream};
169}
170
171// ── 全局单例(plugin feature)──────────────────────────────────────────
172//
173// wordval 框架专属的插件与全局单例放在 `plugin` feature 后面(默认启用)。
174// 只使用独立客户端 API 的宿主(如嵌入式 / 非 wordval 框架)可
175// `default-features = false` 引入,省去 wordval-core 依赖与二进制体积。
176
177/// 全局 [`FoxgloveClient`] 单例,由 [`FoxglovePlugin`] 管理。
178///
179/// `RwLock<Option<..>>`:支持插件停止后再次启动(例如 `PluginManager`
180/// 回滚 / 重启)而不触发"已初始化"错误,且 `try_foxglove()` 能观察到
181/// `stop()` 之后的状态,而不是拿到一个已被清空的僵尸客户端。
182#[cfg(feature = "plugin")]
183static FOXGLOVE_CLIENT: RwLock<Option<Arc<FoxgloveClient>>> = RwLock::new(None);
184
185/// 返回全局 [`FoxgloveClient`]。
186///
187/// # 恐慌
188///
189/// 若客户端尚未初始化(即 `FoxglovePlugin` 尚未启动,或已被停止)则 panic。
190/// 可失败的变体请使用 [`try_foxglove`]。
191#[cfg(feature = "plugin")]
192pub fn foxglove() -> Arc<FoxgloveClient> {
193    try_foxglove().expect("foxglove not initialized")
194}
195
196/// 返回全局 [`FoxgloveClient`] 的 `Some`,未初始化时返回 `None`。
197#[cfg(feature = "plugin")]
198pub fn try_foxglove() -> Option<Arc<FoxgloveClient>> {
199    FOXGLOVE_CLIENT.read().clone()
200}
201
202// ── 插件(plugin feature)─────────────────────────────────────────────
203
204/// 管理 foxglove 客户端连接生命周期的 Foxglove 插件。
205///
206/// `start()` 时派生后台监督任务(负责持续连接 / 重连),并将客户端句柄
207/// 存入全局单例;`stop()` 时优雅地关闭监督任务。
208///
209/// 客户端在后台连接,因此即使服务端尚不可达,`start()` 也会成功;
210/// 可用 [`FoxgloveClient::wait_active`] 等待首个会话。
211///
212/// # 配置
213///
214/// 配置从环境变量(前缀 `FOXGLOVE_`)读取,并可通过 builder 方法覆盖:
215///
216/// | 环境变量               | Builder 方法          | 默认值                |
217/// |------------------------|-----------------------|-----------------------|
218/// | `FOXGLOVE_URL`         | `with_url()`          | `ws://127.0.0.1:8765` |
219/// | `FOXGLOVE_RECONNECT`   | `with_reconnect()`    | `true`                |
220///
221/// # 示例
222///
223/// ```ignore
224/// use wordval_foxglove::FoxglovePlugin;
225/// use wordval_core::PluginManager;
226///
227/// let plugin = FoxglovePlugin::new()
228///     .with_url("ws://robot.local:8765")
229///     .with_reconnect(true);
230///
231/// let mgr = PluginManager::new().add(plugin);
232/// mgr.start_all().await?;
233/// // ... 应用逻辑 ...
234/// mgr.stop_all().await;
235/// ```
236#[cfg(feature = "plugin")]
237pub struct FoxglovePlugin {
238    config: ClientConfig,
239}
240
241#[cfg(feature = "plugin")]
242impl FoxglovePlugin {
243    /// 使用 `FOXGLOVE_*` 环境变量创建插件配置。
244    pub fn new() -> Self {
245        let mut config = ClientConfig::default();
246        if let Ok(url) = std::env::var("FOXGLOVE_URL") {
247            config.url = url;
248        }
249        if let Ok(v) = std::env::var("FOXGLOVE_RECONNECT") {
250            config.reconnect = v == "1" || v.eq_ignore_ascii_case("true");
251        }
252        Self { config }
253    }
254
255    /// 覆盖服务端 URL,例如 `ws://127.0.0.1:8765`。
256    ///
257    /// `wss://` URL 需要启用本 crate 的 `tls` feature。
258    pub fn with_url(mut self, url: &str) -> Self {
259        self.config.url = url.to_string();
260        self
261    }
262
263    /// 启用或禁用自动重连(默认:启用)。
264    pub fn with_reconnect(mut self, reconnect: bool) -> Self {
265        self.config.reconnect = reconnect;
266        self
267    }
268
269    /// 覆盖完整的客户端配置。
270    pub fn with_config(mut self, config: ClientConfig) -> Self {
271        self.config = config;
272        self
273    }
274}
275
276#[cfg(feature = "plugin")]
277impl Default for FoxglovePlugin {
278    fn default() -> Self {
279        Self::new()
280    }
281}
282
283#[cfg(feature = "plugin")]
284#[async_trait]
285impl Plugin for FoxglovePlugin {
286    fn name(&self) -> &str {
287        "foxglove"
288    }
289
290    fn priority(&self) -> i32 {
291        30
292    }
293
294    async fn start(&self) -> Result<()> {
295        // 幂等替换:重启插件时先取出旧客户端。若不 shutdown,残留的
296        // Subscription/PublishChannel 句柄会让旧 ClientInner 存活,
297        // 监督任务继续后台重连(与"可安全重启"的文档承诺不符)。
298        let old = FOXGLOVE_CLIENT.write().take();
299        if let Some(old) = old {
300            // 不阻塞启动:旧客户端的关闭在网络超时场景可能耗时,
301            // 后台完成即可(新客户端已接管)。
302            tokio::spawn(async move { old.shutdown().await });
303        }
304
305        let client = FoxgloveClient::connect(self.config.clone());
306        *FOXGLOVE_CLIENT.write() = Some(Arc::new(client));
307
308        tracing::info!(
309            "foxglove plugin started url={} reconnect={}",
310            self.config.url,
311            self.config.reconnect
312        );
313        Ok(())
314    }
315
316    async fn stop(&self) -> Result<()> {
317        // 先取出再 await:关闭进行期间全局状态表现为"未初始化",
318        // 且锁守卫不会跨 `.await` 持有。
319        let client = FOXGLOVE_CLIENT.write().take();
320        if let Some(client) = client {
321            client.shutdown().await;
322        }
323        tracing::info!("foxglove plugin stopped");
324        Ok(())
325    }
326}
327
328// ── 测试 ─────────────────────────────────────────────────────────────
329
330#[cfg(all(test, feature = "plugin"))]
331mod tests {
332    use super::*;
333
334    #[test]
335    fn test_plugin_default_name() {
336        let plugin = FoxglovePlugin::new();
337        assert_eq!(plugin.name(), "foxglove");
338    }
339
340    #[test]
341    fn test_plugin_no_dependencies() {
342        let plugin = FoxglovePlugin::new();
343        assert!(plugin.depends_on().is_empty());
344    }
345
346    #[test]
347    fn test_plugin_builder() {
348        let plugin = FoxglovePlugin::new()
349            .with_url("ws://robot.local:8765")
350            .with_reconnect(false);
351        assert_eq!(plugin.config.url, "ws://robot.local:8765");
352        assert!(!plugin.config.reconnect);
353    }
354
355    #[test]
356    fn test_not_initialised() {
357        // 本测试二进制中没有任何测试会启动插件,
358        // 因此这里全局单例必须读取为未初始化。
359        assert!(try_foxglove().is_none());
360    }
361
362    #[test]
363    #[should_panic(expected = "foxglove not initialized")]
364    fn test_panics_when_not_initialised() {
365        let _ = foxglove();
366    }
367
368    /// 验证 `FoxgloveError` 实现了 `std::error::Error`,
369    /// 从而可作为 `wordval_core::Error::Plugin` 中的 `source` 使用。
370    #[test]
371    fn test_error_is_std_error() {
372        fn _assert_error<T: std::error::Error + Send + Sync>() {}
373        _assert_error::<FoxgloveError>();
374    }
375}