1use crate::{
16 BucketNotificationConfig, Event, EventArgs, LifecycleError, NotificationError, NotificationMetricSnapshot,
17 NotificationSystem, NotificationTargetMetricSnapshot, error::transition_join_error,
18};
19use rustfs_config::server_config::Config;
20use rustfs_s3_types::EventName;
21use rustfs_targets::arn::TargetID;
22use std::sync::{Arc, LazyLock, Mutex, OnceLock, Weak};
23use tracing::error;
24
25static NOTIFICATION_SYSTEM: OnceLock<Arc<NotificationSystem>> = OnceLock::new();
26static LEGACY_INITIALIZATION: LazyLock<Mutex<Option<LegacyInitialization>>> = LazyLock::new(|| Mutex::new(None));
27
28enum LegacyInitialization {
29 Initializing(Weak<NotificationSystem>),
30 Retryable(Weak<NotificationSystem>),
31 Initialized,
32}
33const LOG_COMPONENT_NOTIFY: &str = "notify";
34const LOG_SUBSYSTEM_GLOBAL: &str = "global";
35const EVENT_NOTIFY_GLOBAL_STATE: &str = "notify_global_state";
36
37fn notification_system_or_init(config: Config) -> Arc<NotificationSystem> {
38 NOTIFICATION_SYSTEM
39 .get_or_init(|| Arc::new(NotificationSystem::new(config)))
40 .clone()
41}
42
43pub async fn initialize(config: Config) -> Result<(), NotificationError> {
48 let system = {
49 let mut legacy = LEGACY_INITIALIZATION.lock().unwrap_or_else(|err| err.into_inner());
50 match legacy.as_ref() {
51 Some(LegacyInitialization::Retryable(system)) => {
52 let Some(system) = system.upgrade() else {
53 return Err(NotificationError::Lifecycle(LifecycleError::AlreadyInitialized));
54 };
55 if !NOTIFICATION_SYSTEM.get().is_some_and(|global| Arc::ptr_eq(global, &system)) {
56 return Err(NotificationError::Lifecycle(LifecycleError::AlreadyInitialized));
57 }
58 *legacy = Some(LegacyInitialization::Initializing(Arc::downgrade(&system)));
59 system
60 }
61 Some(LegacyInitialization::Initializing(_)) | Some(LegacyInitialization::Initialized) => {
62 return Err(NotificationError::Lifecycle(LifecycleError::AlreadyInitialized));
63 }
64 None => {
65 if NOTIFICATION_SYSTEM.get().is_some() {
66 return Err(NotificationError::Lifecycle(LifecycleError::AlreadyInitialized));
67 }
68 let system = Arc::new(NotificationSystem::new(config.clone()));
69 if NOTIFICATION_SYSTEM.set(system.clone()).is_err() {
70 return Err(NotificationError::Lifecycle(LifecycleError::AlreadyInitialized));
71 }
72 *legacy = Some(LegacyInitialization::Initializing(Arc::downgrade(&system)));
73 system
74 }
75 }
76 };
77
78 let task_system = system.clone();
79 tokio::spawn(async move {
80 let result = task_system.set_targets_enabled(true, Some(config)).await;
81 let mut legacy = LEGACY_INITIALIZATION.lock().unwrap_or_else(|err| err.into_inner());
82 if matches!(
83 legacy.as_ref(),
84 Some(LegacyInitialization::Initializing(current))
85 if current.upgrade().is_some_and(|current| Arc::ptr_eq(¤t, &task_system))
86 ) {
87 *legacy = Some(if result.is_ok() {
88 LegacyInitialization::Initialized
89 } else {
90 LegacyInitialization::Retryable(Arc::downgrade(&task_system))
91 });
92 }
93 result
94 })
95 .await
96 .map_err(transition_join_error)?
97}
98
99pub fn initialize_live_events() -> Result<(), NotificationError> {
105 if NOTIFICATION_SYSTEM
106 .set(Arc::new(NotificationSystem::new(Config::new())))
107 .is_err()
108 {
109 return Err(NotificationError::Lifecycle(LifecycleError::AlreadyInitialized));
110 }
111 Ok(())
112}
113
114pub fn ensure_live_events() -> Arc<NotificationSystem> {
116 notification_system_or_init(Config::new())
117}
118
119pub async fn reconcile(config: Config) -> Result<(), NotificationError> {
121 let system = notification_system_or_init(config.clone());
122 system.set_targets_enabled(true, Some(config)).await
123}
124
125pub fn notification_system() -> Option<Arc<NotificationSystem>> {
128 NOTIFICATION_SYSTEM.get().cloned()
129}
130
131pub fn notification_metrics_snapshot() -> NotificationMetricSnapshot {
133 NOTIFICATION_SYSTEM
134 .get()
135 .map(|system| system.snapshot_metrics())
136 .unwrap_or_default()
137}
138
139pub async fn notification_target_metrics() -> Vec<NotificationTargetMetricSnapshot> {
141 if let Some(system) = notification_system() {
142 system.snapshot_target_metrics().await
143 } else {
144 Vec::new()
145 }
146}
147
148pub fn is_notification_system_initialized() -> bool {
150 NOTIFICATION_SYSTEM.get().is_some()
151}
152
153pub mod notifier_global {
155 use super::*;
156 use tracing::instrument;
157
158 #[instrument(skip(args))]
169 pub async fn notify(args: EventArgs) {
170 let notification_sys = match notification_system() {
172 Some(sys) => sys,
174 None => {
175 error!(
176 event = EVENT_NOTIFY_GLOBAL_STATE,
177 component = LOG_COMPONENT_NOTIFY,
178 subsystem = LOG_SUBSYSTEM_GLOBAL,
179 state = "uninitialized",
180 "notify global state"
181 );
182 return;
183 }
184 };
185
186 if args.is_replication_request() {
188 return;
189 }
190
191 let event = Arc::new(Event::new(args));
193 notification_sys.send_event(event).await;
194 }
195
196 pub async fn add_bucket_notification_rule(
211 bucket_name: &str,
212 region: &str,
213 event_names: &[EventName],
214 prefix: &str,
215 suffix: &str,
216 target_ids: &[TargetID],
217 ) -> Result<(), NotificationError> {
218 let pattern = crate::rules::pattern::new_pattern(
220 if prefix.is_empty() { None } else { Some(prefix) },
221 if suffix.is_empty() { None } else { Some(suffix) },
222 );
223
224 let mut bucket_config = BucketNotificationConfig::new(region);
226 for target_id in target_ids {
227 bucket_config.add_rule(event_names, pattern.clone(), target_id.clone());
228 }
229
230 let notification_sys = match notification_system() {
232 Some(sys) => sys,
233 None => return Err(NotificationError::Lifecycle(LifecycleError::NotInitialized)),
234 };
235
236 notification_sys
238 .load_bucket_notification_config(bucket_name, &bucket_config)
239 .await
240 }
241
242 fn bucket_notification_config_for_rules(
243 region: &str,
244 event_rules: &[(Vec<EventName>, String, String, Vec<TargetID>)],
245 ) -> BucketNotificationConfig {
246 let mut bucket_config = BucketNotificationConfig::new(region);
247
248 for (event_names, prefix, suffix, target_ids) in event_rules {
249 let pattern = crate::rules::pattern::new_pattern(Some(prefix.as_str()), Some(suffix.as_str()));
251
252 for target_id in target_ids {
253 bucket_config.add_rule(event_names, pattern.clone(), target_id.clone());
254 }
255 }
256
257 bucket_config
258 }
259
260 pub async fn validate_event_specific_rules(
264 bucket_name: &str,
265 region: &str,
266 event_rules: &[(Vec<EventName>, String, String, Vec<TargetID>)],
267 ) -> Result<(), NotificationError> {
268 let bucket_config = bucket_notification_config_for_rules(region, event_rules);
269
270 let notification_sys = notification_system().ok_or(NotificationError::Lifecycle(LifecycleError::NotInitialized))?;
272
273 notification_sys
274 .validate_bucket_notification_config(bucket_name, &bucket_config)
275 .await
276 }
277
278 pub async fn add_event_specific_rules(
291 bucket_name: &str,
292 region: &str,
293 event_rules: &[(Vec<EventName>, String, String, Vec<TargetID>)],
294 ) -> Result<(), NotificationError> {
295 let bucket_config = bucket_notification_config_for_rules(region, event_rules);
296
297 let notification_sys = notification_system().ok_or(NotificationError::Lifecycle(LifecycleError::NotInitialized))?;
299
300 notification_sys
302 .load_bucket_notification_config(bucket_name, &bucket_config)
303 .await
304 }
305
306 pub async fn clear_bucket_notification_rules(bucket_name: &str) -> Result<(), NotificationError> {
316 let notification_sys = notification_system().ok_or(NotificationError::Lifecycle(LifecycleError::NotInitialized))?;
318
319 notification_sys.remove_bucket_notification_config(bucket_name).await;
321 Ok(())
322 }
323}