use crate::{
BucketNotificationConfig, Event, EventArgs, LifecycleError, NotificationError, NotificationMetricSnapshot,
NotificationSystem, NotificationTargetMetricSnapshot, error::transition_join_error,
};
use rustfs_config::server_config::Config;
use rustfs_s3_types::EventName;
use rustfs_targets::arn::TargetID;
use std::sync::{Arc, LazyLock, Mutex, OnceLock, Weak};
use tracing::error;
static NOTIFICATION_SYSTEM: OnceLock<Arc<NotificationSystem>> = OnceLock::new();
static LEGACY_INITIALIZATION: LazyLock<Mutex<Option<LegacyInitialization>>> = LazyLock::new(|| Mutex::new(None));
enum LegacyInitialization {
Initializing(Weak<NotificationSystem>),
Retryable(Weak<NotificationSystem>),
Initialized,
}
const LOG_COMPONENT_NOTIFY: &str = "notify";
const LOG_SUBSYSTEM_GLOBAL: &str = "global";
const EVENT_NOTIFY_GLOBAL_STATE: &str = "notify_global_state";
fn notification_system_or_init(config: Config) -> Arc<NotificationSystem> {
NOTIFICATION_SYSTEM
.get_or_init(|| Arc::new(NotificationSystem::new(config)))
.clone()
}
pub async fn initialize(config: Config) -> Result<(), NotificationError> {
let system = {
let mut legacy = LEGACY_INITIALIZATION.lock().unwrap_or_else(|err| err.into_inner());
match legacy.as_ref() {
Some(LegacyInitialization::Retryable(system)) => {
let Some(system) = system.upgrade() else {
return Err(NotificationError::Lifecycle(LifecycleError::AlreadyInitialized));
};
if !NOTIFICATION_SYSTEM.get().is_some_and(|global| Arc::ptr_eq(global, &system)) {
return Err(NotificationError::Lifecycle(LifecycleError::AlreadyInitialized));
}
*legacy = Some(LegacyInitialization::Initializing(Arc::downgrade(&system)));
system
}
Some(LegacyInitialization::Initializing(_)) | Some(LegacyInitialization::Initialized) => {
return Err(NotificationError::Lifecycle(LifecycleError::AlreadyInitialized));
}
None => {
if NOTIFICATION_SYSTEM.get().is_some() {
return Err(NotificationError::Lifecycle(LifecycleError::AlreadyInitialized));
}
let system = Arc::new(NotificationSystem::new(config.clone()));
if NOTIFICATION_SYSTEM.set(system.clone()).is_err() {
return Err(NotificationError::Lifecycle(LifecycleError::AlreadyInitialized));
}
*legacy = Some(LegacyInitialization::Initializing(Arc::downgrade(&system)));
system
}
}
};
let task_system = system.clone();
tokio::spawn(async move {
let result = task_system.set_targets_enabled(true, Some(config)).await;
let mut legacy = LEGACY_INITIALIZATION.lock().unwrap_or_else(|err| err.into_inner());
if matches!(
legacy.as_ref(),
Some(LegacyInitialization::Initializing(current))
if current.upgrade().is_some_and(|current| Arc::ptr_eq(¤t, &task_system))
) {
*legacy = Some(if result.is_ok() {
LegacyInitialization::Initialized
} else {
LegacyInitialization::Retryable(Arc::downgrade(&task_system))
});
}
result
})
.await
.map_err(transition_join_error)?
}
pub fn initialize_live_events() -> Result<(), NotificationError> {
if NOTIFICATION_SYSTEM
.set(Arc::new(NotificationSystem::new(Config::new())))
.is_err()
{
return Err(NotificationError::Lifecycle(LifecycleError::AlreadyInitialized));
}
Ok(())
}
pub fn ensure_live_events() -> Arc<NotificationSystem> {
notification_system_or_init(Config::new())
}
pub async fn reconcile(config: Config) -> Result<(), NotificationError> {
let system = notification_system_or_init(config.clone());
system.set_targets_enabled(true, Some(config)).await
}
pub fn notification_system() -> Option<Arc<NotificationSystem>> {
NOTIFICATION_SYSTEM.get().cloned()
}
pub fn notification_metrics_snapshot() -> NotificationMetricSnapshot {
NOTIFICATION_SYSTEM
.get()
.map(|system| system.snapshot_metrics())
.unwrap_or_default()
}
pub async fn notification_target_metrics() -> Vec<NotificationTargetMetricSnapshot> {
if let Some(system) = notification_system() {
system.snapshot_target_metrics().await
} else {
Vec::new()
}
}
pub fn is_notification_system_initialized() -> bool {
NOTIFICATION_SYSTEM.get().is_some()
}
pub mod notifier_global {
use super::*;
use tracing::instrument;
#[instrument(skip(args))]
pub async fn notify(args: EventArgs) {
let notification_sys = match notification_system() {
Some(sys) => sys,
None => {
error!(
event = EVENT_NOTIFY_GLOBAL_STATE,
component = LOG_COMPONENT_NOTIFY,
subsystem = LOG_SUBSYSTEM_GLOBAL,
state = "uninitialized",
"notify global state"
);
return;
}
};
if args.is_replication_request() {
return;
}
let event = Arc::new(Event::new(args));
notification_sys.send_event(event).await;
}
pub async fn add_bucket_notification_rule(
bucket_name: &str,
region: &str,
event_names: &[EventName],
prefix: &str,
suffix: &str,
target_ids: &[TargetID],
) -> Result<(), NotificationError> {
let pattern = crate::rules::pattern::new_pattern(
if prefix.is_empty() { None } else { Some(prefix) },
if suffix.is_empty() { None } else { Some(suffix) },
);
let mut bucket_config = BucketNotificationConfig::new(region);
for target_id in target_ids {
bucket_config.add_rule(event_names, pattern.clone(), target_id.clone());
}
let notification_sys = match notification_system() {
Some(sys) => sys,
None => return Err(NotificationError::Lifecycle(LifecycleError::NotInitialized)),
};
notification_sys
.load_bucket_notification_config(bucket_name, &bucket_config)
.await
}
pub async fn add_event_specific_rules(
bucket_name: &str,
region: &str,
event_rules: &[(Vec<EventName>, String, String, Vec<TargetID>)],
) -> Result<(), NotificationError> {
let mut bucket_config = BucketNotificationConfig::new(region);
for (event_names, prefix, suffix, target_ids) in event_rules {
let pattern = crate::rules::pattern::new_pattern(Some(prefix.as_str()), Some(suffix.as_str()));
for target_id in target_ids {
bucket_config.add_rule(event_names, pattern.clone(), target_id.clone());
}
}
let notification_sys = notification_system().ok_or(NotificationError::Lifecycle(LifecycleError::NotInitialized))?;
notification_sys
.load_bucket_notification_config(bucket_name, &bucket_config)
.await
}
pub async fn clear_bucket_notification_rules(bucket_name: &str) -> Result<(), NotificationError> {
let notification_sys = notification_system().ok_or(NotificationError::Lifecycle(LifecycleError::NotInitialized))?;
notification_sys.remove_bucket_notification_config(bucket_name).await;
Ok(())
}
}