Skip to main content

rustfs_notify/rules/
rules_map.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::{PatternRules, TargetIdSet};
16use hashbrown::HashMap;
17use rustfs_s3_types::EventName;
18use rustfs_targets::arn::TargetID;
19use serde::{Deserialize, Serialize};
20
21/// RulesMap - Rule mapping organized by event name。
22/// `event.RulesMap` (map[Name]Rules) in the corresponding Go code
23#[derive(Debug, Clone, Default, Serialize, Deserialize)]
24pub struct RulesMap {
25    map: HashMap<EventName, PatternRules>,
26    /// A bitmask that represents the union of all event types in this map.
27    /// Used for quick checks in `has_subscriber`.
28    total_events_mask: u64,
29}
30
31impl RulesMap {
32    /// Create a new, empty RulesMap.
33    ///
34    /// # Returns
35    /// A new instance of RulesMap with an empty map and a total_events_mask set to 0.
36    pub fn new() -> Self {
37        Default::default()
38    }
39
40    /// Add a rule configuration to the map.
41    ///
42    /// This method handles composite event names (such as `s3:ObjectCreated:*`), expanding them as
43    /// Multiple specific event types and add rules for each event type.
44    ///
45    /// # Parameters
46    /// * `event_names` - List of event names associated with this rule.
47    /// * `pattern` - Matching pattern for object keys. If empty, the default is `*` (match all).
48    /// * `target_id` - The target ID of the notification.
49    pub fn add_rule_config(&mut self, event_names: &[EventName], pattern: String, target_id: TargetID) {
50        let effective_pattern = if pattern.is_empty() {
51            "*".to_string() // Match all by default
52        } else {
53            pattern
54        };
55
56        for event_name_spec in event_names {
57            // Expand compound event types, for example ObjectCreatedAll -> [ObjectCreatedPut, ObjectCreatedPost, ...]
58            for expanded_event_name in event_name_spec.expand() {
59                // Make sure EventName::expand() returns Vec<EventName>
60                self.map
61                    .entry(expanded_event_name)
62                    .or_default()
63                    .add(effective_pattern.clone(), target_id.clone());
64                // Update the total_events_mask to include this event type
65                self.total_events_mask |= expanded_event_name.mask();
66            }
67        }
68    }
69
70    /// Merge another RulesMap.
71    /// `RulesMap.Add(rulesMap2 RulesMap) corresponding to Go
72    ///
73    /// # Parameters
74    /// * `other_map` - The other RulesMap to be merged into the current one.
75    pub fn add_map(&mut self, other_map: &Self) {
76        for (event_name, other_pattern_rules) in &other_map.map {
77            self.map.entry(*event_name).or_default().union_in_place(other_pattern_rules);
78        }
79        // Directly merge two masks.
80        self.total_events_mask |= other_map.total_events_mask;
81    }
82
83    /// Remove another rule defined in the RulesMap from the current RulesMap.
84    ///
85    /// After the rule is removed, `total_events_mask` is recalculated to ensure its accuracy.
86    ///
87    /// # Parameters
88    /// * `other_map` - The other RulesMap containing rules to be removed from the current one.
89    pub fn remove_map(&mut self, other_map: &Self) {
90        let mut events_to_remove = Vec::new();
91        for (event_name, self_pattern_rules) in &mut self.map {
92            if let Some(other_pattern_rules) = other_map.map.get(event_name) {
93                self_pattern_rules.difference_in_place(other_pattern_rules);
94                if self_pattern_rules.is_empty() {
95                    events_to_remove.push(*event_name);
96                }
97            }
98        }
99        for event_name in events_to_remove {
100            self.map.remove(&event_name);
101        }
102        // After removing the rule, recalculate total_events_mask.
103        self.recalculate_mask();
104    }
105
106    /// Checks whether any configured rules exist for a given event type.
107    ///
108    /// This method uses a bitmask for a quick check of O(1) complexity.
109    /// `event_name` can be a compound type, such as `ObjectCreatedAll`.
110    ///
111    /// # Parameters
112    /// * `event_name` - The event name to check for subscribers.
113    pub fn has_subscriber(&self, event_name: &EventName) -> bool {
114        // event_name.mask() will handle compound events correctly
115        (self.total_events_mask & event_name.mask()) != 0
116    }
117
118    /// Rules matching the given event and object keys and return all matching target IDs.
119    ///
120    /// # Notice
121    /// The `event_name` parameter should be a specific, non-compound event type.
122    /// Because this is taken from the `Event` object that actually occurs.
123    ///
124    /// # Parameters
125    /// * `event_name` - The specific event name to match against.
126    /// * `object_key` - The object key to match against the patterns in the rules.
127    ///
128    /// # Returns
129    /// * A set of TargetIDs that match the given event and object key.
130    pub fn match_rules(&self, event_name: EventName, object_key: &str) -> TargetIdSet {
131        // Use bitmask to quickly determine whether there is a matching rule
132        if (self.total_events_mask & event_name.mask()) == 0 {
133            return TargetIdSet::new(); // No matching rules
134        }
135
136        // In Go, RulesMap[eventName] returns empty rules if the key doesn't exist.
137        // Rust's HashMap::get returns Option, so missing key means no rules.
138        // Compound events like ObjectCreatedAll are expanded into specific events during add_rule_config.
139        // Thus, queries should use specific event names.
140        // If event_name is compound, expansion happens at addition time.
141        // match_rules assumes event_name is already a specific event for lookup.
142        // Callers should expand compound events before calling this method.
143        self.map
144            .get(&event_name)
145            .map_or_else(TargetIdSet::new, |pr| pr.match_targets(object_key))
146    }
147
148    /// Check if RulesMap is empty.
149    ///
150    /// # Returns
151    /// * `true` if there are no rules in the map; `false` otherwise
152    pub fn is_empty(&self) -> bool {
153        self.map.is_empty()
154    }
155
156    /// Determine whether the current RulesMap contains the specified TargetID (referenced by any event / pattern).
157    ///
158    /// # Parameters
159    /// * `target_id` - The TargetID to check for existence within the RulesMap
160    ///
161    /// # Returns
162    /// * `true` if the TargetID exists in any of the PatternRules; `false` otherwise.
163    pub fn contains_target_id(&self, target_id: &TargetID) -> bool {
164        self.map.values().any(|pr| pr.contains_target_id(target_id))
165    }
166
167    /// Returns a clone of internal rules for use in scenarios such as BucketNotificationConfig::validate.
168    ///
169    /// # Returns
170    /// A reference to the internal HashMap of EventName to PatternRules.
171    pub fn inner(&self) -> &HashMap<EventName, PatternRules> {
172        &self.map
173    }
174
175    /// A private helper function that recalculates `total_events_mask` based on the content of the current `map`.
176    /// Called after the removal operation to ensure the accuracy of the mask.
177    fn recalculate_mask(&mut self) {
178        let mut new_mask = 0u64;
179        for event_name in self.map.keys() {
180            new_mask |= event_name.mask();
181        }
182        self.total_events_mask = new_mask;
183    }
184
185    /// Remove rules and optimize performance
186    ///
187    /// # Parameters
188    /// * `event_name` - The EventName from which to remove the rule.
189    /// * `pattern` - The pattern of the rule to be removed.
190    pub fn remove_rule(&mut self, event_name: &EventName, pattern: &str) {
191        let mut remove_event = false;
192
193        if let Some(pattern_rules) = self.map.get_mut(event_name) {
194            pattern_rules.remove_pattern(pattern);
195            if pattern_rules.is_empty() {
196                remove_event = true;
197            }
198        }
199
200        if remove_event {
201            self.map.remove(event_name);
202        }
203
204        self.recalculate_mask(); // Delay calculation mask
205    }
206
207    /// Batch Delete Rules and Optimize Performance
208    ///
209    /// # Parameters
210    /// * `event_names` - A slice of EventNames to be removed.
211    pub fn remove_rules(&mut self, event_names: &[EventName]) {
212        for event_name in event_names {
213            self.map.remove(event_name);
214        }
215        self.recalculate_mask(); // Unified calculation of mask after batch processing
216    }
217
218    /// Update rules and optimize performance
219    ///
220    /// # Parameters
221    /// * `event_name` - The EventName to update.
222    /// * `pattern` - The pattern of the rule to be updated.
223    /// * `target_id` - The TargetID to be added.
224    pub fn update_rule(&mut self, event_name: EventName, pattern: String, target_id: TargetID) {
225        self.map.entry(event_name).or_default().add(pattern, target_id);
226        self.total_events_mask |= event_name.mask(); // Update only the relevant bitmask
227    }
228
229    /// Iterate all EventName keys contained in this RulesMap.
230    ///
231    /// Used by snapshot compilation to compute bucket event_mask.
232    ///
233    /// # Returns
234    /// An iterator over all EventName keys in the RulesMap.
235    #[inline]
236    pub fn iter_events(&self) -> impl Iterator<Item = EventName> + '_ {
237        // `inner()` is already used by config.rs, so we reuse it here.
238        // If the key type is `EventName`, `.copied()` is the cheapest way to return values.
239        self.inner().keys().copied()
240    }
241}