rustfs_notify/rules/pattern_rules.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::TargetIdSet;
16use crate::rules::pattern;
17use hashbrown::HashMap;
18use rayon::prelude::*;
19use rustfs_targets::arn::TargetID;
20use serde::{Deserialize, Serialize};
21
22/// PatternRules - Event rule that maps object name patterns to TargetID collections.
23/// `event.Rules` (map[string]TargetIDSet) in the Go code
24#[derive(Debug, Clone, Default, Serialize, Deserialize)]
25pub struct PatternRules {
26 pub(crate) rules: HashMap<String, TargetIdSet>,
27}
28
29impl PatternRules {
30 /// Create a new, empty PatternRules.
31 pub fn new() -> Self {
32 Default::default()
33 }
34
35 /// Add rules: Pattern and Target ID.
36 /// If the schema already exists, add target_id to the existing TargetIdSet.
37 ///
38 /// # Arguments
39 /// * `pattern` - The object name pattern.
40 /// * `target_id` - The TargetID to associate with the pattern.
41 pub fn add(&mut self, pattern: String, target_id: TargetID) {
42 self.rules.entry(pattern).or_default().insert(target_id);
43 }
44
45 /// Checks if there are any rules that match the given object name.
46 ///
47 /// # Arguments
48 /// * `object_name` - The object name to match against the patterns.
49 ///
50 /// # Returns
51 /// `true` if any pattern matches the object name, otherwise `false`.
52 pub fn match_simple(&self, object_name: &str) -> bool {
53 self.rules.keys().any(|p| pattern::match_simple(p, object_name))
54 }
55
56 /// Returns all TargetIDs that match the object name.
57 ///
58 /// Performance optimization points:
59 /// 1) Small collections are serialized directly to avoid rayon scheduling/merging overhead
60 /// 2) When hitting, no longer temporarily allocate TargetIdSet for each rule, but directly extend
61 ///
62 /// # Arguments
63 /// * `object_name` - The object name to match against the patterns.
64 ///
65 /// # Returns
66 /// A TargetIdSet containing all TargetIDs that match the object name.
67 pub fn match_targets(&self, object_name: &str) -> TargetIdSet {
68 let n = self.rules.len();
69 if n == 0 {
70 return TargetIdSet::new();
71 }
72
73 // Experience Threshold: Serial is usually faster below this value (can be adjusted after benchmarking)
74 const PAR_THRESHOLD: usize = 128;
75
76 if n < PAR_THRESHOLD {
77 let mut out = TargetIdSet::new();
78 for (pattern_str, target_set) in self.rules.iter() {
79 if pattern::match_simple(pattern_str, object_name) {
80 out.extend(target_set.iter().cloned());
81 }
82 }
83 return out;
84 }
85 // Parallel path: Each thread accumulates a local set and finally merges it to reduce frequent allocations
86 self.rules
87 .par_iter()
88 .fold(TargetIdSet::new, |mut local, (pattern_str, target_set)| {
89 if pattern::match_simple(pattern_str, object_name) {
90 local.extend(target_set.iter().cloned());
91 }
92 local
93 })
94 .reduce(TargetIdSet::new, |mut acc, set| {
95 acc.extend(set);
96 acc
97 })
98 }
99
100 pub fn is_empty(&self) -> bool {
101 self.rules.is_empty()
102 }
103
104 /// Merge another PatternRules.
105 /// Corresponding to Go's `Rules.Union`.
106 /// # Arguments
107 /// * `other` - The PatternRules to merge with.
108 ///
109 /// # Returns
110 /// A new PatternRules containing the union of both.
111 pub fn union(&self, other: &Self) -> Self {
112 let mut new_rules = self.clone();
113 for (pattern, their_targets) in &other.rules {
114 let our_targets = new_rules.rules.entry(pattern.clone()).or_default();
115 our_targets.extend(their_targets.iter().cloned());
116 }
117 new_rules
118 }
119
120 /// Calculate the difference from another PatternRules.
121 /// Corresponding to Go's `Rules.Difference`.
122 /// The result contains only the patterns and TargetIDs that are in `self` but not in `other`.
123 ///
124 /// # Arguments
125 /// * `other` - The PatternRules to compare against.
126 ///
127 /// # Returns
128 /// A new PatternRules containing the difference.
129 pub fn difference(&self, other: &Self) -> Self {
130 let mut result_rules = HashMap::new();
131 for (pattern, self_targets) in &self.rules {
132 match other.rules.get(pattern) {
133 Some(other_targets) => {
134 let diff_targets: TargetIdSet = self_targets.difference(other_targets).cloned().collect();
135 if !diff_targets.is_empty() {
136 result_rules.insert(pattern.clone(), diff_targets);
137 }
138 }
139 None => {
140 // If there is no pattern in other, self_targets are all retained
141 result_rules.insert(pattern.clone(), self_targets.clone());
142 }
143 }
144 }
145 PatternRules { rules: result_rules }
146 }
147
148 /// Merge another PatternRules into self in place.
149 /// Corresponding to Go's `Rules.UnionInPlace`.
150 /// # Arguments
151 /// * `other` - The PatternRules to merge with.
152 pub fn union_in_place(&mut self, other: &Self) {
153 for (pattern, their_targets) in &other.rules {
154 self.rules
155 .entry(pattern.clone())
156 .or_default()
157 .extend(their_targets.iter().cloned());
158 }
159 }
160
161 /// Calculate the difference from another PatternRules in place.
162 /// Corresponding to Go's `Rules.DifferenceInPlace`.
163 /// The result contains only the patterns and TargetIDs that are in `self` but not in `other`.
164 /// # Arguments
165 /// * `other` - The PatternRules to compare against.
166 pub fn difference_in_place(&mut self, other: &Self) {
167 self.rules.retain(|pattern, self_targets| {
168 if let Some(other_targets) = other.rules.get(pattern) {
169 // Remove other_targets from self_targets
170 self_targets.retain(|tid| !other_targets.contains(tid));
171 }
172 !self_targets.is_empty()
173 });
174 }
175
176 /// Remove a pattern and its associated TargetID set from the PatternRules.
177 ///
178 /// # Arguments
179 /// * `pattern` - The pattern to remove.
180 pub fn remove_pattern(&mut self, pattern: &str) -> bool {
181 self.rules.remove(pattern).is_some()
182 }
183
184 /// Determine whether the current PatternRules contains the specified TargetID (referenced by any pattern).
185 ///
186 /// # Parameters
187 /// * `target_id` - The TargetID to check for existence within the PatternRules
188 ///
189 /// # Returns
190 /// * `true` if the TargetID exists in any of the patterns; `false` otherwise.
191 pub fn contains_target_id(&self, target_id: &TargetID) -> bool {
192 self.rules.values().any(|set| set.contains(target_id))
193 }
194
195 /// Expose the internal rules for use in scenarios such as BucketNotificationConfig::validate.
196 ///
197 /// # Returns
198 /// A reference to the internal HashMap of patterns to TargetIdSets.
199 pub fn inner(&self) -> &HashMap<String, TargetIdSet> {
200 &self.rules
201 }
202}