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    /// Dynamically add notification rules according to different event types.
243    ///
244    /// # Parameter
245    /// - `bucket_name`: The name of the target bucket.
246    /// - `region`: The area where bucket is located.
247    /// - `event_rules`: Each rule contains a list of event types, prefixes, suffixes, and target IDs.
248    ///
249    /// # Return value
250    /// Returns `Result<(), NotificationError>`, Ok on success, and an error on failure.
251    ///
252    /// # Using
253    /// Supports notification rules for adding multiple event types, prefixes, suffixes, and targets to the same bucket in batches.
254    pub async fn add_event_specific_rules(
255        bucket_name: &str,
256        region: &str,
257        event_rules: &[(Vec<EventName>, String, String, Vec<TargetID>)],
258    ) -> Result<(), NotificationError> {
259        let mut bucket_config = BucketNotificationConfig::new(region);
260
261        for (event_names, prefix, suffix, target_ids) in event_rules {
262            // Use `new_pattern` to construct a matching pattern
263            let pattern = crate::rules::pattern::new_pattern(Some(prefix.as_str()), Some(suffix.as_str()));
264
265            for target_id in target_ids {
266                bucket_config.add_rule(event_names, pattern.clone(), target_id.clone());
267            }
268        }
269
270        // Get global NotificationSystem instance
271        let notification_sys = notification_system().ok_or(NotificationError::Lifecycle(LifecycleError::NotInitialized))?;
272
273        // Loading configuration
274        notification_sys
275            .load_bucket_notification_config(bucket_name, &bucket_config)
276            .await
277    }
278
279    /// Clear all notification rules for the specified bucket.
280    /// # Parameter
281    /// - `bucket_name`: The name of the target bucket.
282    /// # Return value
283    /// Returns `Result<(), NotificationError>`, Ok on success, and an error on failure.
284    /// # Using
285    /// This function allows you to clear all notification rules for a specific bucket.
286    /// This is useful when you want to reset the notification configuration for a bucket.
287    ///
288    pub async fn clear_bucket_notification_rules(bucket_name: &str) -> Result<(), NotificationError> {
289        // Get global NotificationSystem instance
290        let notification_sys = notification_system().ok_or(NotificationError::Lifecycle(LifecycleError::NotInitialized))?;
291
292        // Clear configuration
293        notification_sys.remove_bucket_notification_config(bucket_name).await;
294        Ok(())
295    }
296}