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> {
62 initialize(config.clone()).await?;
64
65 let adapters = crate::create_adapters(&config.adapters).expect("failed to create adapters");
67
68 start(adapters).await?;
70
71 Ok(())
72}
73
74pub async fn send_event(event: Event) -> Result<(), Error> {
76 let system = get_system().await?;
77 let system_guard = system.lock().await;
78 system_guard.send_event(event).await
79}
80
81pub fn shutdown() -> Result<(), Error> {
83 if let Some(system) = GLOBAL_SYSTEM.get() {
84 let system_guard = system.blocking_lock();
85 system_guard.shutdown();
86 Ok(())
87 } else {
88 Err(Error::custom("notification system not initialized"))
89 }
90}
91
92async fn get_system() -> Result<Arc<Mutex<NotificationSystem>>, Error> {
94 GLOBAL_SYSTEM
95 .get()
96 .cloned()
97 .ok_or_else(|| Error::custom("notification system not initialized"))
98}