Skip to main content

wordval_nats/
lib.rs

1//! wordval-nats:面向服务间通信的 NATS 消息队列集成。
2//!
3//! 提供高层级的 [`NatsClient`] 封装,涵盖发布/订阅、请求-响应、
4//! 队列组负载均衡与 JetStream 持久化。[`NatsPlugin`] 实现了
5//! `wordval_core::Plugin` trait 用于生命周期管理,全局资源访问器
6//! (`nats()` / `try_nats()`)遵循 wordval 单例模式
7//! (可安全重启,与 `wordval_bus::bus()` 一致)。
8//!
9//! # 快速开始
10//!
11//! ```ignore
12//! use wordval_nats::nats;
13//!
14//! // 发布消息
15//! nats().publish_json("game.auth.login", &serde_json::json!({
16//!     "username": "alice",
17//!     "password": "secret",
18//! })).await?;
19//!
20//! // 订阅
21//! let mut sub = nats().subscribe("game.chat.lobby").await?;
22//! ```
23
24use std::sync::Arc;
25
26use async_trait::async_trait;
27use parking_lot::RwLock;
28use wordval_core::{Plugin, Result};
29
30mod client;
31
32/// NATS 操作错误。
33pub mod error {
34    use std::time::Duration;
35
36    /// NATS 操作期间可能发生的错误。
37    ///
38    /// 封装底层 `async_nats` 错误(以其 `Display` 表示)、JSON 序列化
39    /// 失败、超时以及其它杂项问题。
40    #[derive(Debug, thiserror::Error)]
41    pub enum NatsError {
42        /// 来自 NATS 客户端或服务端的错误。
43        #[error("NATS error: {0}")]
44        Nats(String),
45
46        /// 请求-响应操作失败,因为没有服务监听该 subject。
47        /// 与 [`Timeout`](Self::Timeout) 不同:该失败会被立即检测到,
48        /// 而不用等满截止时间。
49        #[error("no responders for request subject")]
50        NoResponders,
51
52        /// JSON 序列化或反序列化错误。
53        #[error("Serialization error: {0}")]
54        Serde(#[from] serde_json::Error),
55
56        /// 请求-响应或 JetStream 确认操作超时。
57        #[error("Timeout after {0:?}")]
58        Timeout(Duration),
59
60        /// 尝试执行 JetStream 操作,但构造客户端时未启用 JetStream。
61        #[error("JetStream is not enabled")]
62        JetStreamDisabled,
63    }
64}
65
66pub use client::NatsClient;
67pub use error::NatsError;
68
69// 重新导出常用的 async_nats 类型,下游 crate 无需为了获取类型
70// 而在自己的 Cargo.toml 中添加 async_nats 依赖。
71pub use async_nats::jetstream::context::PublishAckFuture;
72pub use async_nats::jetstream::publish::PublishAck;
73pub use async_nats::subject::ToSubject;
74pub use async_nats::{Message, Subject, Subscriber};
75
76// ── 全局单例 ──────────────────────────────────────────────────────────
77
78/// 由 [`NatsPlugin`] 管理的全局 `NatsClient` 单例。
79///
80/// 使用 `RwLock<Option<..>>` 而非 `OnceLock`,使插件可以被停止后
81/// 再次启动(例如 `PluginManager` 回滚 / 重启)而不会撞上
82/// "already initialised" 错误,同时 `try_nats()` 观察到的是
83/// `stop()` 之后的状态,而不是被排空的"僵尸"客户端。
84static NATS_CLIENT: RwLock<Option<Arc<NatsClient>>> = RwLock::new(None);
85
86/// 返回全局 [`NatsClient`]。
87///
88/// # 恐慌
89///
90/// 当 NATS 客户端尚未初始化(即 `NatsPlugin` 尚未启动,或已经停止)
91/// 时恐慌。可失败版本请使用 [`try_nats`]。
92pub fn nats() -> Arc<NatsClient> {
93    try_nats().expect("NATS not initialized")
94}
95
96/// 返回全局 [`NatsClient`] 的 `Some`,未初始化时返回 `None`。
97pub fn try_nats() -> Option<Arc<NatsClient>> {
98    NATS_CLIENT.read().clone()
99}
100
101// ── 插件 ──────────────────────────────────────────────────────────────
102
103/// 管理 NATS 客户端连接生命周期的 NATS 插件。
104///
105/// `start()` 时连接 NATS 服务端并把客户端存入全局单例
106/// (幂等:重新启动会替换上一个客户端)。`stop()` 时优雅排空并断开。
107///
108/// # 配置
109///
110/// 插件从环境变量(前缀 `NATS_`)读取配置,可通过构建器方法覆盖:
111///
112/// | 环境变量          | 构建器方法            | 默认值                     |
113/// |-------------------|-----------------------|----------------------------|
114/// | `NATS_URL`        | `with_url()`          | `nats://localhost:4222`    |
115/// | `NATS_USER`       | `with_credentials()`  | 无(不认证)               |
116/// | `NATS_PASSWORD`   | `with_credentials()`  | 无                         |
117/// | `NATS_TOKEN`      | `with_token()`        | 无(不认证)               |
118/// | `NATS_JETSTREAM`  | `with_jetstream()`    | `false`                    |
119///
120/// # 示例
121///
122/// ```ignore
123/// use wordval_nats::NatsPlugin;
124/// use wordval_core::PluginManager;
125///
126/// let plugin = NatsPlugin::new()
127///     .with_url("nats://demo.nats.io:4222")
128///     .with_token("my-token")
129///     .with_jetstream(true);
130///
131/// let mgr = PluginManager::new().add(plugin);
132/// mgr.start_all().await?;
133/// // ... 应用逻辑 ...
134/// mgr.stop_all().await;
135/// ```
136pub struct NatsPlugin {
137    /// NATS 服务端 URL
138    url: String,
139    /// 是否创建 JetStream 上下文
140    enable_jetstream: bool,
141    /// 用于密码认证的用户名(可选)
142    user: Option<String>,
143    /// 用于密码认证的密码(可选)
144    password: Option<String>,
145    /// 用于 token 认证的 token(可选,优先)
146    token: Option<String>,
147}
148
149impl NatsPlugin {
150    /// 创建新的 `NatsPlugin`,设置项从环境变量读取。
151    ///
152    /// 读取 `NATS_URL`、`NATS_USER`、`NATS_PASSWORD`、`NATS_TOKEN` 与
153    /// `NATS_JETSTREAM`(设为 `"1"` 或 `"true"` 以启用)。
154    pub fn new() -> Self {
155        Self {
156            url: std::env::var("NATS_URL").unwrap_or_else(|_| "nats://localhost:4222".to_string()),
157            enable_jetstream: std::env::var("NATS_JETSTREAM")
158                .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
159                .unwrap_or(false),
160            user: std::env::var("NATS_USER").ok(),
161            password: std::env::var("NATS_PASSWORD").ok(),
162            token: std::env::var("NATS_TOKEN").ok(),
163        }
164    }
165
166    /// 覆盖 NATS 服务端 URL。
167    pub fn with_url(mut self, url: &str) -> Self {
168        self.url = url.to_string();
169        self
170    }
171
172    /// 启用或禁用 JetStream。
173    pub fn with_jetstream(mut self, enable: bool) -> Self {
174        self.enable_jetstream = enable;
175        self
176    }
177
178    /// 设置用于认证的用户名和密码。
179    pub fn with_credentials(mut self, user: &str, password: &str) -> Self {
180        self.user = Some(user.to_string());
181        self.password = Some(password.to_string());
182        self
183    }
184
185    /// 设置用于 token 认证的 token。
186    ///
187    /// 同时设置时,token 认证优先于用户名+密码。
188    pub fn with_token(mut self, token: &str) -> Self {
189        self.token = Some(token.to_string());
190        self
191    }
192}
193
194impl Default for NatsPlugin {
195    fn default() -> Self {
196        Self::new()
197    }
198}
199
200#[async_trait]
201impl Plugin for NatsPlugin {
202    fn name(&self) -> &str {
203        "nats"
204    }
205
206    fn priority(&self) -> i32 {
207        30
208    }
209
210    async fn start(&self) -> Result<()> {
211        let client = NatsClient::connect(
212            &self.url,
213            self.user.as_deref(),
214            self.password.as_deref(),
215            self.token.as_deref(),
216            self.enable_jetstream,
217        )
218        .await
219        .map_err(|e| wordval_core::Error::Plugin {
220            name: "nats".into(),
221            source: Box::new(e),
222        })?;
223
224        // 幂等替换:重启插件会换入新客户端。
225        *NATS_CLIENT.write() = Some(Arc::new(client));
226
227        tracing::info!(
228            "NATS plugin started url={} jetstream={}",
229            self.url,
230            self.enable_jetstream
231        );
232        Ok(())
233    }
234
235    async fn stop(&self) -> Result<()> {
236        // 先取出再等待:排空进行期间全局状态呈现"未初始化",
237        // 且锁保护不会跨越 `.await` 持有。
238        let client = NATS_CLIENT.write().take();
239        if let Some(client) = client {
240            client
241                .drain()
242                .await
243                .map_err(|e| wordval_core::Error::Plugin {
244                    name: "nats".into(),
245                    source: Box::new(e),
246                })?;
247        }
248        tracing::info!("NATS plugin stopped");
249        Ok(())
250    }
251}
252
253// ── 测试 ──────────────────────────────────────────────────────────────
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258
259    #[test]
260    fn test_nats_plugin_default_name() {
261        let plugin = NatsPlugin::new();
262        assert_eq!(plugin.name(), "nats");
263    }
264
265    #[test]
266    fn test_nats_plugin_no_dependencies() {
267        let plugin = NatsPlugin::new();
268        assert!(plugin.depends_on().is_empty());
269    }
270
271    #[test]
272    fn test_nats_plugin_builder() {
273        let plugin = NatsPlugin::new()
274            .with_url("nats://demo.nats.io:4222")
275            .with_credentials("admin", "secret")
276            .with_jetstream(true);
277
278        assert_eq!(plugin.url, "nats://demo.nats.io:4222");
279        assert_eq!(plugin.user.as_deref(), Some("admin"));
280        assert_eq!(plugin.password.as_deref(), Some("secret"));
281        assert!(plugin.enable_jetstream);
282    }
283
284    #[test]
285    fn test_nats_not_initialised() {
286        // 本二进制中没有任何测试会启动插件,
287        // 因此这里的全局单例必须表现为未初始化。
288        assert!(try_nats().is_none());
289    }
290
291    #[test]
292    #[should_panic(expected = "NATS not initialized")]
293    fn test_nats_panics_when_not_initialised() {
294        let _ = nats();
295    }
296
297    /// 验证 `NatsError` 实现了 `std::error::Error`,
298    /// 从而可作为 `wordval_core::Error::Plugin` 的 `source` 使用。
299    #[test]
300    fn test_nats_error_is_std_error() {
301        fn _assert_error<T: std::error::Error + Send + Sync>() {}
302        _assert_error::<NatsError>();
303    }
304
305    /// 零分配保证:`&'static str` subject 经由 `Subject::from_static`
306    /// 转换,不触碰堆。
307    #[test]
308    fn test_static_subject_is_zero_alloc() {
309        let subject = "game.auth.login".to_subject();
310        assert_eq!(subject.as_str(), "game.auth.login");
311    }
312}