Skip to main content

wordval_bus/
lib.rs

1//! # wordval-bus
2//!
3//! Wordval 事件总线(Bus):以统一 API 封装进程内事件分发与 NATS 扇出,
4//! 并可通过 [`register_backend`] 接入任意第三方消息中间件(Kafka / Redis / RabbitMQ …),
5//! 单机部署零依赖、分布式部署换驱动即可,业务代码不变。
6//!
7//! > **更名说明**:本 crate 原名 `wordval-queue`(历史遗留),2026-09-28 起
8//! > 更名为 `wordval-bus`——它封装的是**发布-订阅事件总线**
9//! >(at-most-once,见下),并非可靠消息队列——无 ack、无重投、无留存。
10//! > 需要可靠队列请使用中间件原生能力(如 NATS JetStream consumer)。
11//!
12//! ## 驱动选择
13//!
14//! - `local` — 进程内事件分发(默认,零依赖,有界通道)
15//!   - 每主题单订阅者;无订阅者的事件直接丢弃;
16//!   - 处理失败仅记录日志,不重投(at-most-once)。
17//! - `nats`  — NATS(需启用 `nats` feature 且 `NatsPlugin` 已启动)
18//!   - 同主题不同消费组各收一份(扇出),同组内负载均衡。
19//! - 其他    — 由 [`register_backend`] 注册的自定义后端
20//!
21//! ## 语义契约
22//!
23//! - **at-most-once**:无消费者的事件直接丢弃,处理失败仅记录日志,
24//!   不重投、不留存;
25//! - **顺序**:`local` 驱动同一主题内事件按发布顺序**严格 FIFO 串行**处理
26//!   (每主题单任务);NATS 驱动单服务器部署按送达序串行处理,集群部署
27//!   无全局顺序保证;跨主题、跨消费组无顺序保证;
28//! - **handler 约束**:处理函数应快速返回——慢 handler 会拖死该主题并使
29//!   通道积压(`local` 触发发布背压 / [`Bus::try_publish`] 满即拒);
30//!   阻塞型工作请用 [`tokio::task::spawn_blocking`] 包装或拆分主题并行消费。
31//!
32//! ## 快速开始
33//!
34//! ```ignore
35//! use wordval_bus::{Bus, Message};
36//!
37//! let bus = Bus::new("local")?;
38//! bus.subscribe("topic", |msg: Message| async move {
39//!     println!("收到事件: {:?}", msg);
40//!     Ok(())
41//! }).await?;
42//! bus.publish("topic", b"hello").await?;
43//! ```
44//!
45//! ## 插件模式
46//!
47//! ```ignore
48//! use wordval_bus::BusPlugin;
49//! use wordval_core::PluginManager;
50//!
51//! let mgr = PluginManager::new()
52//!     .add(NatsPlugin::new())
53//!     .add(BusPlugin::new().with_driver("nats"));
54//! mgr.start_all().await?;
55//!
56//! wordval_bus::bus().publish("topic", b"hello").await?;
57//! ```
58
59use std::future::Future;
60use std::sync::Arc;
61use std::time::Duration;
62
63use async_trait::async_trait;
64use bytes::Bytes;
65use parking_lot::RwLock;
66use wordval_core::{Plugin, Result};
67
68pub mod backend;
69mod local;
70#[cfg(feature = "nats")]
71mod nats_impl;
72
73pub use backend::{boxed_handler, register_backend, BusBackend, Handler};
74pub use local::LocalBus;
75#[cfg(feature = "nats")]
76pub use nats_impl::NatsBus;
77
78// ── 事件类型 ─────────────────────────────────────────────────────
79
80/// 总线事件体,基于 [`Bytes`] 的零拷贝引用计数切片。
81///
82/// 从 `Vec<u8>`、`&[u8]`、`&str` 构造均为 O(1)(除首次拷贝外无额外分配):
83///
84/// ```ignore
85/// bus.publish("t", b"hello".to_vec()).await?; // Vec<u8> → Bytes,零拷贝
86/// bus.publish("t", b"hello").await?;          // &[u8] → Bytes,一次拷贝
87/// ```
88pub type Message = Bytes;
89
90/// 默认消费组名([`BusConfig::default_group`] 与 [`BusPlugin`] 共用)
91pub const DEFAULT_GROUP: &str = "wordval-workers";
92
93// ── 总线配置 ─────────────────────────────────────────────────────
94
95/// 总线配置,驱动名 + 可选参数
96#[derive(Debug, Clone)]
97pub struct BusConfig {
98    /// 驱动名:`local`、`nats`,或已注册的自定义后端名
99    pub driver: String,
100    /// 本地驱动单主题有界通道容量;其他后端忽略此值
101    pub capacity: usize,
102    /// 默认消费组名(NATS 使用 queue group,本地驱动忽略)
103    pub default_group: String,
104    /// 发布时是否优先 JetStream 持久化(仅 NATS 后端使用,其他后端忽略)
105    ///
106    /// 默认 `true`:publish 经 JetStream 等待服务端 ack(最长 10s),
107    /// 留存供外部工具 / 补录消费——**前提是已在服务端为发布主题配置流覆盖**。
108    /// 若未配置流覆盖,建议置 `false`:普通 publish 无 ack 往返,
109    /// 避免存在 core 订阅者时每条发布阻塞至 ack 超时。
110    pub jetstream_persist: bool,
111}
112
113impl Default for BusConfig {
114    fn default() -> Self {
115        Self {
116            driver: std::env::var("BUS_DRIVER").unwrap_or_else(|_| "local".to_string()),
117            capacity: local::DEFAULT_CAPACITY,
118            default_group: DEFAULT_GROUP.to_string(),
119            jetstream_persist: true,
120        }
121    }
122}
123
124// ── 总线外观 ─────────────────────────────────────────────────────
125
126/// 统一事件总线外观:持有一个 [`BusBackend`] 并暴露高级 API
127///
128/// 克隆为 `Arc` 引用计数,廉价且线程安全。
129#[derive(Clone)]
130pub struct Bus {
131    backend: Arc<dyn BusBackend>,
132    config: BusConfig,
133}
134
135impl Bus {
136    /// 按驱动名构造总线(使用默认配置)
137    pub fn new(driver: &str) -> Result<Self> {
138        Self::with_config(BusConfig {
139            driver: driver.to_string(),
140            ..Default::default()
141        })
142    }
143
144    /// 按完整配置构造总线
145    pub fn with_config(config: BusConfig) -> Result<Self> {
146        let factory = backend::lookup_factory(&config.driver)?;
147        let backend = factory(&config)?;
148        Ok(Self { backend, config })
149    }
150
151    /// 当前驱动名
152    pub fn driver_name(&self) -> &str {
153        &self.config.driver
154    }
155
156    /// 发布事件到指定主题
157    ///
158    /// `payload` 接受 `Vec<u8>` / `&[u8]` / `Bytes`,内部统一转为 [`Bytes`]。
159    /// 无订阅者的主题事件被丢弃(总线语义),返回 `Ok`。
160    pub async fn publish(&self, topic: &str, payload: impl Into<Bytes>) -> Result<()> {
161        self.backend.publish(topic, payload.into()).await
162    }
163
164    /// 非阻塞发布:本地驱动总线积压满时立即返回 `Err` 而非等待空位,
165    /// 适合"宁可丢弃不可阻塞"的场景(如高频心跳);无订阅者主题与
166    /// [`Bus::publish`] 语义一致(丢弃 + warn + `Ok`)。
167    /// NATS 等无本地有界缓冲的后端等价于 [`Bus::publish`]。
168    pub async fn try_publish(&self, topic: &str, payload: impl Into<Bytes>) -> Result<()> {
169        self.backend.try_publish(topic, payload.into()).await
170    }
171
172    /// 主题当前积压深度(已发布未消费的事件数)
173    ///
174    /// 返回 `None` 表示该主题无订阅者,或当前后端不支持观测
175    /// (NATS 驱动始终返回 `None`)。
176    pub fn topic_len(&self, topic: &str) -> Option<usize> {
177        self.backend.topic_len(topic)
178    }
179
180    /// 注册订阅者到默认消费组(`BusConfig::default_group`)
181    pub async fn subscribe<F, Fut>(&self, topic: &str, handler: F) -> Result<()>
182    where
183        F: Fn(Message) -> Fut + Send + Sync + 'static,
184        Fut: Future<Output = Result<()>> + Send + 'static,
185    {
186        self.subscribe_on(topic, &self.config.default_group, handler)
187            .await
188    }
189
190    /// 注册订阅者到指定消费组
191    ///
192    /// - NATS:同主题不同消费组各收一份(扇出语义),同组内负载均衡;
193    /// - 本地:忽略组名,单订阅者,重复注册报错。
194    pub async fn subscribe_on<F, Fut>(&self, topic: &str, group: &str, handler: F) -> Result<()>
195    where
196        F: Fn(Message) -> Fut + Send + Sync + 'static,
197        Fut: Future<Output = Result<()>> + Send + 'static,
198    {
199        self.backend
200            .subscribe_on(topic, group, boxed_handler(handler))
201            .await
202    }
203
204    /// 优雅关闭:停止所有订阅者并释放资源
205    pub async fn shutdown(&self) -> Result<()> {
206        self.backend.shutdown().await
207    }
208
209    /// 带超时的优雅关闭:超时后中止(abort)残余订阅者任务,防止
210    /// handler 挂死导致 shutdown / 插件停止流程永久阻塞
211    pub async fn shutdown_timeout(&self, timeout: Duration) -> Result<()> {
212        self.backend.shutdown_timeout(Some(timeout)).await
213    }
214
215    /// 退订主题:取消该主题全部订阅者并等待其在途事件处理完成
216    ///
217    /// - local:单订阅者退订,返回后可立即重新 [`Bus::subscribe_on`] 替换处理器;
218    /// - nats:取消该主题所有消费组的订阅(扇出语义下每组一份);
219    /// - 其他后端:不支持时返回 `Err`。
220    pub async fn unsubscribe(&self, topic: &str) -> Result<()> {
221        self.backend.unsubscribe(topic).await
222    }
223
224    /// 诊断计数器快照(后端可选支持,见 [`BusBackend::counters`])
225    pub fn counters(&self) -> Vec<(&'static str, u64)> {
226        self.backend.counters()
227    }
228
229    /// 当前驱动后端名称(诊断/日志用)
230    pub fn backend_name(&self) -> &'static str {
231        self.backend.name()
232    }
233}
234
235impl std::fmt::Debug for Bus {
236    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
237        // backend 是 dyn trait object(无 Debug supertrait),手动打印驱动名
238        f.debug_struct("Bus")
239            .field("driver", &self.config.driver)
240            .field("backend", &self.backend.name())
241            .finish()
242    }
243}
244
245// ── 全局单例 ─────────────────────────────────────────────────────
246
247static GLOBAL_BUS: RwLock<Option<Arc<Bus>>> = RwLock::new(None);
248
249/// 获取全局 [`Bus`] 引用
250///
251/// # Panics
252///
253/// 若 `BusPlugin` 尚未启动将 panic;可用 [`try_bus`] 做可落败版本。
254pub fn bus() -> Arc<Bus> {
255    try_bus().expect("Bus 未初始化,请确保 BusPlugin 已启动")
256}
257
258/// 尝试获取全局 [`Bus`] 引用(不 panic)
259pub fn try_bus() -> Option<Arc<Bus>> {
260    GLOBAL_BUS.read().clone()
261}
262
263// ── 插件 ─────────────────────────────────────────────────────────
264
265/// 总线插件:管理全局 [`Bus`] 的生命周期
266///
267/// 驱动从环境变量 `BUS_DRIVER` 读取(默认 `local`),
268/// 也可用 [`BusPlugin::with_driver`] 显式指定。
269///
270/// 选择 `nats` 驱动时自动声明对 `nats` 插件的依赖,
271/// `PluginManager` 会保证 `wordval_nats::NatsPlugin` 先启动。
272pub struct BusPlugin {
273    driver: String,
274    capacity: usize,
275    default_group: String,
276    jetstream_persist: bool,
277}
278
279impl BusPlugin {
280    /// 创建总线插件,驱动从环境变量 `BUS_DRIVER` 读取,默认 `local`
281    pub fn new() -> Self {
282        Self {
283            driver: std::env::var("BUS_DRIVER").unwrap_or_else(|_| "local".to_string()),
284            capacity: local::DEFAULT_CAPACITY,
285            default_group: DEFAULT_GROUP.to_string(),
286            jetstream_persist: true,
287        }
288    }
289
290    /// 显式指定驱动:`"local"` 或 `"nats"`,或已注册的自定义后端名
291    pub fn with_driver(mut self, driver: &str) -> Self {
292        self.driver = driver.to_string();
293        self
294    }
295
296    /// 本地驱动单主题通道容量(默认 1024)
297    pub fn with_capacity(mut self, capacity: usize) -> Self {
298        self.capacity = capacity;
299        self
300    }
301
302    /// 默认消费组名(默认 `wordval-workers`)
303    pub fn with_default_group(mut self, group: &str) -> Self {
304        self.default_group = group.to_string();
305        self
306    }
307
308    /// 是否优先 JetStream 持久化(仅 NATS 驱动使用,
309    /// 详见 [`BusConfig::jetstream_persist`];默认 `true`)
310    pub fn with_jetstream_persist(mut self, persist: bool) -> Self {
311        self.jetstream_persist = persist;
312        self
313    }
314}
315
316impl Default for BusPlugin {
317    fn default() -> Self {
318        Self::new()
319    }
320}
321
322#[async_trait]
323impl Plugin for BusPlugin {
324    fn name(&self) -> &str {
325        "bus"
326    }
327
328    fn depends_on(&self) -> &[&str] {
329        if self.driver == "nats" {
330            &["nats"]
331        } else {
332            &[]
333        }
334    }
335
336    fn priority(&self) -> i32 {
337        40
338    }
339
340    async fn start(&self) -> Result<()> {
341        let config = BusConfig {
342            driver: self.driver.clone(),
343            capacity: self.capacity,
344            default_group: self.default_group.clone(),
345            jetstream_persist: self.jetstream_persist,
346        };
347        let bus = Bus::with_config(config)?;
348        // 热重启:替换前先优雅关闭旧实例,避免旧总线的订阅者任务
349        // 永久空闲驻留(任务泄漏)。
350        let old = GLOBAL_BUS.write().replace(Arc::new(bus));
351        if let Some(old) = old {
352            // 新实例已上线:旧实例回收失败只告警不上抛——若让 start 返回
353            // Err,返回值与全局状态(新总线已生效)不一致。
354            if let Err(e) = old.shutdown().await {
355                tracing::warn!("[BusPlugin] 旧 Bus 实例 shutdown 失败(已忽略): {e}");
356            }
357        }
358        tracing::info!("Bus 插件已启动 driver={}", self.driver);
359        Ok(())
360    }
361
362    async fn stop(&self) -> Result<()> {
363        // 先取出再 await,避免持锁跨 await(锁守卫非 Send)
364        let bus = GLOBAL_BUS.write().take();
365        if let Some(bus) = bus {
366            bus.shutdown().await?;
367            tracing::info!("Bus 插件已停止 driver={}", self.driver);
368        }
369        Ok(())
370    }
371}
372
373// ── Tests ─────────────────────────────────────────────────────────
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378    use std::sync::atomic::{AtomicU32, Ordering};
379    use std::time::Duration;
380
381    #[test]
382    fn test_bus_plugin_name() {
383        let plugin = BusPlugin::new().with_driver("local");
384        assert_eq!(plugin.name(), "bus");
385    }
386
387    #[test]
388    fn test_bus_debug_and_default_group() {
389        let bus = Bus::new("local").unwrap();
390        assert!(format!("{bus:?}").contains("local"));
391        assert_eq!(DEFAULT_GROUP, "wordval-workers");
392        assert_eq!(BusConfig::default().default_group, DEFAULT_GROUP);
393    }
394
395    #[test]
396    fn test_bus_plugin_jetstream_persist_flag() {
397        assert!(BusPlugin::new().jetstream_persist);
398        assert!(!BusPlugin::new().with_jetstream_persist(false).jetstream_persist);
399    }
400
401    #[test]
402    fn test_bus_plugin_local_no_dependencies() {
403        let plugin = BusPlugin::new().with_driver("local");
404        assert!(plugin.depends_on().is_empty());
405    }
406
407    #[cfg(feature = "nats")]
408    #[test]
409    fn test_bus_plugin_nats_depends_on_nats() {
410        let plugin = BusPlugin::new().with_driver("nats");
411        assert_eq!(plugin.depends_on(), &["nats"]);
412    }
413
414    #[test]
415    fn test_bus_unknown_driver_fails() {
416        assert!(Bus::new("redis").is_err());
417    }
418
419    #[tokio::test]
420    async fn test_bus_roundtrip() {
421        let bus = Bus::new("local").unwrap();
422        let count = Arc::new(AtomicU32::new(0));
423        let c = count.clone();
424
425        bus.subscribe("t", move |msg| {
426            let c = c.clone();
427            async move {
428                assert_eq!(&msg[..], b"hello");
429                c.fetch_add(1, Ordering::SeqCst);
430                Ok(())
431            }
432        })
433        .await
434        .unwrap();
435
436        bus.publish("t", b"hello".to_vec()).await.unwrap();
437        tokio::time::sleep(Duration::from_millis(100)).await;
438        assert_eq!(count.load(Ordering::SeqCst), 1);
439        bus.shutdown().await.unwrap();
440    }
441
442    #[tokio::test]
443    async fn test_bus_try_publish_and_topic_len() {
444        let bus = Bus::new("local").unwrap();
445        bus.subscribe("t", |_| async { Ok(()) }).await.unwrap();
446        assert_eq!(bus.topic_len("t"), Some(0));
447        assert_eq!(bus.topic_len("missing"), None);
448
449        bus.try_publish("t", b"x".to_vec()).await.unwrap();
450
451        bus.shutdown().await.unwrap();
452        assert_eq!(bus.topic_len("t"), None);
453    }
454
455    #[tokio::test]
456    async fn test_bus_unsubscribe_and_counters_facade() {
457        let bus = Bus::new("local").unwrap();
458        bus.subscribe("t", |_| async { Ok(()) }).await.unwrap();
459        assert_eq!(bus.topic_len("t"), Some(0));
460
461        bus.unsubscribe("t").await.unwrap();
462        assert_eq!(bus.topic_len("t"), None);
463        // 退订后发布 → 无订阅者丢弃,counters 可观测
464        bus.publish("t", b"x".to_vec()).await.unwrap();
465        assert!(bus.counters().contains(&("no_subscriber_dropped", 1)));
466        bus.shutdown().await.unwrap();
467    }
468
469    #[tokio::test]
470    async fn test_plugin_start_stop_idempotent() {
471        let plugin = BusPlugin::new().with_driver("local");
472        plugin.start().await.unwrap();
473        assert!(try_bus().is_some());
474        bus().publish("t", Bytes::from_static(b"x")).await.unwrap(); // 无订阅者也安全(丢弃)
475        plugin.stop().await.unwrap();
476        assert!(try_bus().is_none());
477        // 可重复启动
478        plugin.start().await.unwrap();
479        assert!(try_bus().is_some());
480        plugin.stop().await.unwrap();
481    }
482
483    #[tokio::test]
484    async fn test_custom_backend_registration() {
485        use std::sync::atomic::AtomicUsize;
486
487        struct EchoBackend(Arc<AtomicUsize>);
488
489        #[async_trait]
490        impl BusBackend for EchoBackend {
491            fn name(&self) -> &'static str {
492                "echo"
493            }
494            async fn publish(&self, _topic: &str, _payload: Bytes) -> Result<()> {
495                self.0.fetch_add(1, Ordering::SeqCst);
496                Ok(())
497            }
498            async fn subscribe_on(&self, _topic: &str, _group: &str, _h: Handler) -> Result<()> {
499                Ok(())
500            }
501        }
502
503        let counter = Arc::new(AtomicUsize::new(0));
504        let c = counter.clone();
505        register_backend(
506            "echo",
507            Arc::new(move |_cfg| Ok(Arc::new(EchoBackend(c.clone())) as Arc<dyn BusBackend>)),
508        );
509
510        let bus = Bus::new("echo").unwrap();
511        bus.publish("a", Bytes::from_static(b"1")).await.unwrap();
512        bus.publish("b", Bytes::from_static(b"2")).await.unwrap();
513        assert_eq!(counter.load(Ordering::SeqCst), 2);
514    }
515}