Skip to main content

rustfs_notify/
bucket_config_manager.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, NotificationError, config_manager::notify_configuration_hint,
17    notification_system_subscriber::NotificationSystemSubscriberView, notifier::EventNotifier, rule_engine::NotifyRuleEngine,
18    rules::ParseConfigError,
19};
20use rustfs_s3_types::EventName;
21use std::sync::Arc;
22use tracing::{debug, info, warn};
23
24const LOG_COMPONENT_NOTIFY: &str = "notify";
25const LOG_SUBSYSTEM_BUCKET_CONFIG: &str = "bucket_config";
26const EVENT_NOTIFY_BUCKET_CONFIG_VALIDATION: &str = "notify_bucket_config_validation";
27const EVENT_NOTIFY_BUCKET_CONFIG_LOADED: &str = "notify_bucket_config_loaded";
28
29#[derive(Clone)]
30pub struct NotifyBucketConfigManager {
31    notifier: Arc<EventNotifier>,
32    rule_engine: NotifyRuleEngine,
33    subscriber_view: Arc<NotificationSystemSubscriberView>,
34}
35
36impl NotifyBucketConfigManager {
37    pub fn new(
38        notifier: Arc<EventNotifier>,
39        rule_engine: NotifyRuleEngine,
40        subscriber_view: Arc<NotificationSystemSubscriberView>,
41    ) -> Self {
42        Self {
43            notifier,
44            rule_engine,
45            subscriber_view,
46        }
47    }
48
49    pub async fn has_subscriber(&self, bucket: &str, event: &EventName) -> bool {
50        if !self.subscriber_view.has_subscriber(bucket, event) {
51            return false;
52        }
53        self.rule_engine.has_subscriber(bucket, event).await
54    }
55
56    pub async fn load_bucket_notification_config(
57        &self,
58        bucket: &str,
59        cfg: &BucketNotificationConfig,
60    ) -> Result<(), NotificationError> {
61        let arn_list = self.notifier.get_arn_list(&cfg.region).await;
62        if arn_list.is_empty() {
63            return Err(NotificationError::Configuration(notify_configuration_hint()));
64        }
65        debug!(
66            event = EVENT_NOTIFY_BUCKET_CONFIG_VALIDATION,
67            component = LOG_COMPONENT_NOTIFY,
68            subsystem = LOG_SUBSYSTEM_BUCKET_CONFIG,
69            bucket = %bucket,
70            region = %cfg.region,
71            available_arn_count = arn_list.len(),
72            "notify bucket config validation"
73        );
74
75        if let Err(e) = cfg.validate(&cfg.region, &arn_list) {
76            debug!(
77                event = EVENT_NOTIFY_BUCKET_CONFIG_VALIDATION,
78                component = LOG_COMPONENT_NOTIFY,
79                subsystem = LOG_SUBSYSTEM_BUCKET_CONFIG,
80                bucket = %bucket,
81                region = %cfg.region,
82                error = %e,
83                result = "validation_failed",
84                "notify bucket config validation"
85            );
86            if !matches!(e, ParseConfigError::ArnNotFound(_)) {
87                return Err(NotificationError::BucketNotification(e.to_string()));
88            }
89            warn!(
90                event = EVENT_NOTIFY_BUCKET_CONFIG_VALIDATION,
91                component = LOG_COMPONENT_NOTIFY,
92                subsystem = LOG_SUBSYSTEM_BUCKET_CONFIG,
93                bucket = %bucket,
94                region = %cfg.region,
95                error = %e,
96                result = "missing_target_arn",
97                "notify bucket config validation"
98            );
99        }
100
101        self.subscriber_view.apply_bucket_config(bucket, cfg);
102        self.rule_engine.set_bucket_rules(bucket, cfg.get_rules_map().clone()).await;
103        info!(
104            event = EVENT_NOTIFY_BUCKET_CONFIG_LOADED,
105            component = LOG_COMPONENT_NOTIFY,
106            subsystem = LOG_SUBSYSTEM_BUCKET_CONFIG,
107            bucket = %bucket,
108            region = %cfg.region,
109            rule_count = cfg.get_rules_map().inner().len(),
110            "notify bucket config state"
111        );
112        Ok(())
113    }
114
115    pub async fn remove_bucket_notification_config(&self, bucket: &str) {
116        self.subscriber_view.clear_bucket(bucket);
117        self.rule_engine.clear_bucket_rules(bucket).await;
118    }
119}
120
121#[cfg(test)]
122mod tests {
123    use super::NotifyBucketConfigManager;
124    use crate::{
125        BucketNotificationConfig, integration::NotificationMetrics,
126        notification_system_subscriber::NotificationSystemSubscriberView, notifier::EventNotifier, rule_engine::NotifyRuleEngine,
127    };
128    use rustfs_s3_types::EventName;
129    use rustfs_targets::arn::TargetID;
130    use std::sync::Arc;
131
132    fn build_manager() -> NotifyBucketConfigManager {
133        let metrics = Arc::new(NotificationMetrics::new());
134        let rule_engine = NotifyRuleEngine::new();
135        let notifier = Arc::new(EventNotifier::new(metrics, rule_engine.clone()));
136        let subscriber_view = Arc::new(NotificationSystemSubscriberView::new());
137        NotifyBucketConfigManager::new(notifier, rule_engine, subscriber_view)
138    }
139
140    #[tokio::test]
141    async fn bucket_config_manager_reports_no_subscriber_for_empty_state() {
142        let manager = build_manager();
143        assert!(!manager.has_subscriber("bucket", &EventName::ObjectCreatedPut).await);
144    }
145
146    #[tokio::test]
147    async fn bucket_config_manager_clears_bucket_snapshot() {
148        let manager = build_manager();
149        let target_id = TargetID::new("primary".to_string(), "webhook".to_string());
150        let mut cfg = BucketNotificationConfig::new("us-east-1");
151        cfg.add_rule(&[EventName::ObjectCreatedPut], "*".to_string(), target_id);
152
153        manager.subscriber_view.apply_bucket_config("bucket", &cfg);
154        assert!(manager.subscriber_view.has_subscriber("bucket", &EventName::ObjectCreatedPut));
155
156        manager.remove_bucket_notification_config("bucket").await;
157        assert!(!manager.subscriber_view.has_subscriber("bucket", &EventName::ObjectCreatedPut));
158    }
159}