event_notification/
global.rs1use crate::{ChannelAdapter, Error, Event, NotificationConfig, NotificationSystem};
2use std::sync::Arc;
3use tokio::sync::{Mutex, OnceCell};
4
5static GLOBAL_SYSTEM: OnceCell<Arc<Mutex<NotificationSystem>>> = OnceCell::const_new();
6static INITIALIZED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
7
8pub async fn initialize(config: NotificationConfig) -> Result<(), Error> {
10 if INITIALIZED.swap(true, std::sync::atomic::Ordering::SeqCst) {
11 return Err(Error::custom("notify the system has been initialized"));
12 }
13
14 let system = Arc::new(Mutex::new(NotificationSystem::new(config).await?));
15 GLOBAL_SYSTEM
16 .set(system)
17 .map_err(|_| Error::custom("unable to set up global notification system"))?;
18 Ok(())
19}
20
21pub async fn start(adapters: Vec<Arc<dyn ChannelAdapter>>) -> Result<(), Error> {
23 let system = get_system().await?;
24
25 let system_clone = Arc::clone(&system);
27 tokio::spawn(async move {
28 let mut system_guard = system_clone.lock().await;
29 if let Err(e) = system_guard.start(adapters).await {
30 tracing::error!("notify the system to start failed: {}", e);
31 }
32 });
33
34 Ok(())
35}
36
37pub async fn initialize_and_start(config: NotificationConfig) -> Result<(), Error> {
63 initialize(config.clone()).await?;
65
66 let adapters = crate::create_adapters(&config.adapters).expect("failed to create adapters");
68
69 start(adapters).await?;
71
72 Ok(())
73}
74
75pub async fn send_event(event: Event) -> Result<(), Error> {
77 let system = get_system().await?;
78 let system_guard = system.lock().await;
79 system_guard.send_event(event).await
80}
81
82pub fn shutdown() -> Result<(), Error> {
84 if let Some(system) = GLOBAL_SYSTEM.get() {
85 let system_guard = system.blocking_lock();
86 system_guard.shutdown();
87 Ok(())
88 } else {
89 Err(Error::custom("notification system not initialized"))
90 }
91}
92
93async fn get_system() -> Result<Arc<Mutex<NotificationSystem>>, Error> {
95 GLOBAL_SYSTEM
96 .get()
97 .cloned()
98 .ok_or_else(|| Error::custom("notification system not initialized"))
99}