Skip to main content

rustfs_notify/
global.rs

1// Copyright 2024 RustFS Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use 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
43/// Initialize the global notification system with the given configuration.
44///
45/// This preserves the historical one-shot API contract. Server lifecycle code
46/// that needs idempotent reconciliation should use [`reconcile`] instead.
47pub 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(&current, &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
99/// Initialize the global notification system only for live in-process consumers.
100///
101/// This does not load configured notification targets or bucket rules. It exists so
102/// ListenBucketNotification clients can receive live events even when external
103/// notification targets are disabled.
104pub 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
114/// Ensures the stable process-wide live-event container exists.
115pub fn ensure_live_events() -> Arc<NotificationSystem> {
116    notification_system_or_init(Config::new())
117}
118
119/// Ensures the stable singleton exists and reconciles its target runtime.
120pub 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
125/// Returns a handle to the global NotificationSystem instance.
126/// Return None if the system has not been initialized.
127pub fn notification_system() -> Option<Arc<NotificationSystem>> {
128    NOTIFICATION_SYSTEM.get().cloned()
129}
130
131/// Returns aggregate notification delivery metrics for Prometheus collection.
132pub fn notification_metrics_snapshot() -> NotificationMetricSnapshot {
133    NOTIFICATION_SYSTEM
134        .get()
135        .map(|system| system.snapshot_metrics())
136        .unwrap_or_default()
137}
138
139/// Returns per-target notification delivery metrics for Prometheus collection.
140pub 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
148/// Check if the notification system has been initialized.
149pub fn is_notification_system_initialized() -> bool {
150    NOTIFICATION_SYSTEM.get().is_some()
151}
152
153/// A module providing the public API for event notification.
154pub mod notifier_global {
155    use super::*;
156    use tracing::instrument;
157
158    /// Notify an event asynchronously.
159    /// This is the only entry point for all event notifications in the system.
160    /// # Parameter
161    /// - `args`: The event arguments containing details about the event to be notified.
162    ///
163    /// # Return value
164    /// Returns `()`, indicating that the notification has been sent.
165    ///
166    /// # Using
167    /// This function is used to notify events in the system, such as object creation, deletion, or updates.
168    #[instrument(skip(args))]
169    pub async fn notify(args: EventArgs) {
170        // Dependency injection or service positioning mode obtain NotificationSystem instance
171        let notification_sys = match notification_system() {
172            // If the notification system itself cannot be retrieved, it will be returned directly
173            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        // Avoid generating notifications for replica creation events
187        if args.is_replication_request() {
188            return;
189        }
190
191        // Create an event and send it
192        let event = Arc::new(Event::new(args));
193        notification_sys.send_event(event).await;
194    }
195
196    /// Add notification rules for the specified bucket and load configuration
197    /// # Parameter
198    /// - `bucket_name`: The name of the target bucket.
199    /// - `region`: The area where bucket is located.
200    /// - `event_names`: A list of event names that trigger notifications.
201    /// - `prefix`: The prefix of the object key that triggers notifications.
202    /// - `suffix`: The suffix of the object key that triggers notifications.
203    /// - `target_ids`: A list of target IDs that will receive notifications.
204    ///
205    /// # Return value
206    /// Returns `Result<(), NotificationError>`, Ok on success, and an error on failure
207    ///
208    /// # Using
209    /// This function allows you to dynamically add notification rules for a specific bucket.
210    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        // Construct pattern using proper pattern function
219        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        // Create BucketNotificationConfig
225        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        // Get global NotificationSystem
231        let notification_sys = match notification_system() {
232            Some(sys) => sys,
233            None => return Err(NotificationError::Lifecycle(LifecycleError::NotInitialized)),
234        };
235
236        // Loading configuration
237        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            // Use `new_pattern` to construct a matching pattern
250            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    /// Checks that the runtime can accept `event_rules` for `region` without
261    /// publishing them. Callers use this to fail before persisting a bucket
262    /// notification configuration the notify subsystem would reject.
263    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        // Get global NotificationSystem instance
271        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    /// Dynamically add notification rules according to different event types.
279    ///
280    /// # Parameter
281    /// - `bucket_name`: The name of the target bucket.
282    /// - `region`: The area where bucket is located.
283    /// - `event_rules`: Each rule contains a list of event types, prefixes, suffixes, and target IDs.
284    ///
285    /// # Return value
286    /// Returns `Result<(), NotificationError>`, Ok on success, and an error on failure.
287    ///
288    /// # Using
289    /// Supports notification rules for adding multiple event types, prefixes, suffixes, and targets to the same bucket in batches.
290    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        // Get global NotificationSystem instance
298        let notification_sys = notification_system().ok_or(NotificationError::Lifecycle(LifecycleError::NotInitialized))?;
299
300        // Loading configuration
301        notification_sys
302            .load_bucket_notification_config(bucket_name, &bucket_config)
303            .await
304    }
305
306    /// Clear all notification rules for the specified bucket.
307    /// # Parameter
308    /// - `bucket_name`: The name of the target bucket.
309    /// # Return value
310    /// Returns `Result<(), NotificationError>`, Ok on success, and an error on failure.
311    /// # Using
312    /// This function allows you to clear all notification rules for a specific bucket.
313    /// This is useful when you want to reset the notification configuration for a bucket.
314    ///
315    pub async fn clear_bucket_notification_rules(bucket_name: &str) -> Result<(), NotificationError> {
316        // Get global NotificationSystem instance
317        let notification_sys = notification_system().ok_or(NotificationError::Lifecycle(LifecycleError::NotInitialized))?;
318
319        // Clear configuration
320        notification_sys.remove_bucket_notification_config(bucket_name).await;
321        Ok(())
322    }
323}