Skip to main content

rustfs_notify/
rule_engine.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::rules::{RulesMap, TargetIdSet};
16use percent_encoding::percent_decode_str;
17use rustfs_s3_types::EventName;
18use rustfs_targets::arn::TargetID;
19use starshard::{AsyncShardedHashMap, DEFAULT_SHARDS, SnapshotMode};
20use std::sync::Arc;
21use tracing::info;
22
23const LOG_COMPONENT_NOTIFY: &str = "notify";
24const LOG_SUBSYSTEM_RULE_ENGINE: &str = "rule_engine";
25const EVENT_NOTIFY_RULES_UPDATED: &str = "notify_bucket_rules_updated";
26
27fn decoded_object_key_for_matching(object_key: &str) -> Option<String> {
28    if !object_key.contains('%') {
29        return None;
30    }
31
32    let decoded = percent_decode_str(object_key).decode_utf8().ok()?;
33    (decoded != object_key).then(|| decoded.into_owned())
34}
35
36#[derive(Clone)]
37pub struct NotifyRuleEngine {
38    bucket_rules_map: Arc<AsyncShardedHashMap<String, RulesMap, rustc_hash::FxBuildHasher>>,
39}
40
41impl NotifyRuleEngine {
42    pub fn new() -> Self {
43        Self {
44            bucket_rules_map: Arc::new(AsyncShardedHashMap::with_snapshot_mode(DEFAULT_SHARDS, SnapshotMode::Cached)),
45        }
46    }
47
48    pub async fn is_target_bound_to_any_bucket(&self, target_id: &TargetID) -> bool {
49        let items = self.bucket_rules_map.iter().await;
50        for (_bucket, rules_map) in items {
51            if rules_map.contains_target_id(target_id) {
52                return true;
53            }
54        }
55        false
56    }
57
58    pub async fn set_bucket_rules(&self, bucket: &str, rules_map: RulesMap) {
59        let event_count = rules_map.iter_events().count();
60        if rules_map.is_empty() {
61            self.bucket_rules_map.remove(&bucket.to_string()).await;
62        } else {
63            self.bucket_rules_map.insert(bucket.to_string(), rules_map).await;
64        }
65        info!(
66            event = EVENT_NOTIFY_RULES_UPDATED,
67            component = LOG_COMPONENT_NOTIFY,
68            subsystem = LOG_SUBSYSTEM_RULE_ENGINE,
69            bucket = %bucket,
70            state = "updated",
71            event_count,
72            "notify bucket rules state"
73        );
74    }
75
76    pub async fn get_bucket_rules(&self, bucket: &str) -> Option<RulesMap> {
77        self.bucket_rules_map.get(&bucket.to_string()).await
78    }
79
80    pub async fn clear_bucket_rules(&self, bucket: &str) {
81        if self.bucket_rules_map.remove(&bucket.to_string()).await.is_some() {
82            info!(
83                event = EVENT_NOTIFY_RULES_UPDATED,
84                component = LOG_COMPONENT_NOTIFY,
85                subsystem = LOG_SUBSYSTEM_RULE_ENGINE,
86                bucket = %bucket,
87                state = "removed",
88                "notify bucket rules state"
89            );
90        }
91    }
92
93    pub async fn has_subscriber(&self, bucket: &str, event: &EventName) -> bool {
94        self.get_bucket_rules(bucket)
95            .await
96            .is_some_and(|rules_map| rules_map.has_subscriber(event))
97    }
98
99    pub async fn match_targets(&self, bucket: &str, event_name: EventName, object_key: &str) -> TargetIdSet {
100        self.get_bucket_rules(bucket)
101            .await
102            .map_or_else(TargetIdSet::new, |rules_map| {
103                let mut target_ids = rules_map.match_rules(event_name, object_key);
104                if let Some(decoded_key) = decoded_object_key_for_matching(object_key) {
105                    target_ids.extend(rules_map.match_rules(event_name, &decoded_key));
106                }
107                target_ids
108            })
109    }
110}
111
112impl Default for NotifyRuleEngine {
113    fn default() -> Self {
114        Self::new()
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::NotifyRuleEngine;
121    use crate::rules::RulesMap;
122    use rustfs_s3_types::EventName;
123    use rustfs_targets::arn::TargetID;
124
125    #[tokio::test]
126    async fn rule_engine_tracks_bucket_rule_lifecycle() {
127        let engine = NotifyRuleEngine::new();
128        let target_id = TargetID::new("primary".to_string(), "webhook".to_string());
129        let mut rules_map = RulesMap::new();
130        rules_map.add_rule_config(&[EventName::ObjectCreatedPut], "*".to_string(), target_id.clone());
131
132        assert!(!engine.has_subscriber("bucket", &EventName::ObjectCreatedPut).await);
133        assert!(!engine.is_target_bound_to_any_bucket(&target_id).await);
134
135        engine.set_bucket_rules("bucket", rules_map).await;
136
137        assert!(engine.has_subscriber("bucket", &EventName::ObjectCreatedPut).await);
138        assert!(engine.is_target_bound_to_any_bucket(&target_id).await);
139        assert_eq!(
140            engine
141                .match_targets("bucket", EventName::ObjectCreatedPut, "object")
142                .await
143                .into_iter()
144                .collect::<Vec<_>>(),
145            vec![target_id.clone()]
146        );
147
148        engine.clear_bucket_rules("bucket").await;
149
150        assert!(!engine.has_subscriber("bucket", &EventName::ObjectCreatedPut).await);
151        assert!(!engine.is_target_bound_to_any_bucket(&target_id).await);
152    }
153}