1use 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
78pub type Message = Bytes;
89
90pub const DEFAULT_GROUP: &str = "wordval-workers";
92
93#[derive(Debug, Clone)]
97pub struct BusConfig {
98 pub driver: String,
100 pub capacity: usize,
102 pub default_group: String,
104 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#[derive(Clone)]
130pub struct Bus {
131 backend: Arc<dyn BusBackend>,
132 config: BusConfig,
133}
134
135impl Bus {
136 pub fn new(driver: &str) -> Result<Self> {
138 Self::with_config(BusConfig {
139 driver: driver.to_string(),
140 ..Default::default()
141 })
142 }
143
144 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 pub fn driver_name(&self) -> &str {
153 &self.config.driver
154 }
155
156 pub async fn publish(&self, topic: &str, payload: impl Into<Bytes>) -> Result<()> {
161 self.backend.publish(topic, payload.into()).await
162 }
163
164 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 pub fn topic_len(&self, topic: &str) -> Option<usize> {
177 self.backend.topic_len(topic)
178 }
179
180 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 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 pub async fn shutdown(&self) -> Result<()> {
206 self.backend.shutdown().await
207 }
208
209 pub async fn shutdown_timeout(&self, timeout: Duration) -> Result<()> {
212 self.backend.shutdown_timeout(Some(timeout)).await
213 }
214
215 pub async fn unsubscribe(&self, topic: &str) -> Result<()> {
221 self.backend.unsubscribe(topic).await
222 }
223
224 pub fn counters(&self) -> Vec<(&'static str, u64)> {
226 self.backend.counters()
227 }
228
229 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 f.debug_struct("Bus")
239 .field("driver", &self.config.driver)
240 .field("backend", &self.backend.name())
241 .finish()
242 }
243}
244
245static GLOBAL_BUS: RwLock<Option<Arc<Bus>>> = RwLock::new(None);
248
249pub fn bus() -> Arc<Bus> {
255 try_bus().expect("Bus 未初始化,请确保 BusPlugin 已启动")
256}
257
258pub fn try_bus() -> Option<Arc<Bus>> {
260 GLOBAL_BUS.read().clone()
261}
262
263pub struct BusPlugin {
273 driver: String,
274 capacity: usize,
275 default_group: String,
276 jetstream_persist: bool,
277}
278
279impl BusPlugin {
280 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 pub fn with_driver(mut self, driver: &str) -> Self {
292 self.driver = driver.to_string();
293 self
294 }
295
296 pub fn with_capacity(mut self, capacity: usize) -> Self {
298 self.capacity = capacity;
299 self
300 }
301
302 pub fn with_default_group(mut self, group: &str) -> Self {
304 self.default_group = group.to_string();
305 self
306 }
307
308 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 let old = GLOBAL_BUS.write().replace(Arc::new(bus));
351 if let Some(old) = old {
352 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 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#[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 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(); plugin.stop().await.unwrap();
476 assert!(try_bus().is_none());
477 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}