rustfs_notify/rules/config.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 super::rules_map::RulesMap;
16use super::xml_config::ParseConfigError as BucketNotificationConfigError;
17use crate::rules::NotificationConfiguration;
18use crate::rules::subscriber_snapshot::{BucketRulesSnapshot, DynRulesContainer, RuleEvents, RulesContainer};
19use rustfs_s3_types::EventName;
20use rustfs_targets::arn::TargetID;
21use serde::{Deserialize, Serialize};
22use std::io::Read;
23use std::sync::Arc;
24
25/// A "rule view", only used for snapshot mask/consistency verification.
26/// Here we choose to generate the view by "single event" to ensure that event_mask calculation is reliable and simple.
27#[derive(Debug)]
28struct RuleView {
29 events: Vec<EventName>,
30}
31
32impl RuleEvents for RuleView {
33 fn subscribed_events(&self) -> &[EventName] {
34 &self.events
35 }
36}
37
38/// Adapt RulesMap to RulesContainer.
39/// Key point: The items returned by iter_rules are &dyn RuleEvents, so a RuleView list is cached in the container.
40#[derive(Debug)]
41struct CompiledRules {
42 // Keep RulesMap (can be used later if you want to make more complex judgments during the snapshot reading phase)
43 #[allow(
44 dead_code,
45 reason = "speculative retention: the comment above keeps it for richer snapshot-time judgements that no code performs yet (backlog#1823)"
46 )]
47 rules_map: RulesMap,
48 // for RulesContainer::iter_rules
49 rule_views: Vec<RuleView>,
50}
51
52impl CompiledRules {
53 fn from_rules_map(rules_map: &RulesMap) -> Self {
54 let mut rule_views = Vec::new();
55
56 for ev in rules_map.iter_events() {
57 rule_views.push(RuleView { events: vec![ev] });
58 }
59
60 Self {
61 rules_map: rules_map.clone(),
62 rule_views,
63 }
64 }
65}
66
67impl RulesContainer for CompiledRules {
68 type Rule = dyn RuleEvents;
69
70 fn iter_rules<'a>(&'a self) -> Box<dyn Iterator<Item = &'a Self::Rule> + 'a> {
71 // Key: Convert &RuleView into &dyn RuleEvents
72 Box::new(self.rule_views.iter().map(|v| v as &dyn RuleEvents))
73 }
74}
75
76/// Configuration for bucket notifications.
77/// This struct now holds the parsed and validated rules in the new RulesMap format.
78#[derive(Debug, Clone, Default, Serialize, Deserialize)]
79pub struct BucketNotificationConfig {
80 pub region: String, // Region where this config is applicable
81 pub rules: RulesMap, // The new, more detailed RulesMap
82}
83
84impl BucketNotificationConfig {
85 pub fn new(region: &str) -> Self {
86 BucketNotificationConfig {
87 region: region.to_string(),
88 rules: RulesMap::new(),
89 }
90 }
91
92 /// Adds a rule to the configuration.
93 /// This method allows adding a rule with a specific event and target ID.
94 pub fn add_rule(
95 &mut self,
96 event_names: &[EventName], // Assuming event_names is a list of event names
97 pattern: String, // The object key pattern for the rule
98 target_id: TargetID, // The target ID for the notification
99 ) {
100 self.rules.add_rule_config(event_names, pattern, target_id);
101 }
102
103 /// Parses notification configuration from XML.
104 /// `arn_list` is a list of valid ARN strings for validation.
105 pub fn from_xml<R: Read + std::io::BufRead>(
106 reader: R,
107 current_region: &str,
108 arn_list: &[String],
109 ) -> Result<Self, BucketNotificationConfigError> {
110 let mut parsed_config = NotificationConfiguration::from_reader(reader)?;
111
112 // Set defaults (region in ARNs if empty, xmlns) before validation
113 parsed_config.set_defaults(current_region);
114
115 // Validate the parsed configuration
116 parsed_config.validate(current_region, arn_list)?;
117
118 let mut rules_map = RulesMap::new();
119 for queue_conf in parsed_config.queue_list {
120 // The ARN in queue_conf should now have its region set if it was originally empty.
121 // Ensure TargetID can be cloned or extracted correctly.
122 let target_id = queue_conf.arn.target_id.clone();
123 let pattern_str = queue_conf.filter.pattern();
124 rules_map.add_rule_config(&queue_conf.events, pattern_str, target_id);
125 }
126
127 Ok(BucketNotificationConfig {
128 region: current_region.to_string(), // Config is for the current_region
129 rules: rules_map,
130 })
131 }
132
133 /// Validates the *current* BucketNotificationConfig.
134 /// This might be redundant if construction always implies validation.
135 /// However, Go's Config has a Validate method.
136 /// The primary validation now happens during `from_xml` via `NotificationConfiguration::validate`.
137 /// This method could re-check against an updated arn_list or region if needed.
138 pub fn validate(&self, current_region: &str, arn_list: &[String]) -> Result<(), BucketNotificationConfigError> {
139 if self.region != current_region {
140 return Err(BucketNotificationConfigError::RegionMismatch {
141 config_region: self.region.clone(),
142 current_region: current_region.to_string(),
143 });
144 }
145
146 // Iterate through the rules in self.rules and validate their TargetIDs against arn_list
147 // This requires RulesMap to expose its internal structure or provide an iterator
148 for (_event_name, pattern_rules) in self.rules.inner().iter() {
149 for (_pattern, target_id_set) in pattern_rules.inner().iter() {
150 // Assuming PatternRules has inner()
151 for target_id in target_id_set {
152 // Construct the ARN string for this target_id and self.region
153 let arn_to_check = target_id.to_arn(&self.region); // Assuming TargetID has to_arn
154 if !arn_list.contains(&arn_to_check.to_string()) {
155 return Err(BucketNotificationConfigError::ArnNotFound(arn_to_check.to_string()));
156 }
157 }
158 }
159 }
160 Ok(())
161 }
162
163 // Expose the RulesMap for the notifier
164 pub fn get_rules_map(&self) -> &RulesMap {
165 &self.rules
166 }
167
168 /// Sets the region for the configuration
169 pub fn set_region(&mut self, region: &str) {
170 self.region = region.to_string();
171 }
172
173 /// Compiles the current BucketNotificationConfig into a BucketRulesSnapshot.
174 /// This involves transforming the rules into a format suitable for runtime use,
175 /// and calculating the event mask based on the subscribed events of the rules.
176 ///
177 /// # Returns
178 /// A BucketRulesSnapshot containing the compiled rules and event mask.
179 pub fn compile_snapshot(&self) -> BucketRulesSnapshot<DynRulesContainer> {
180 // 1) Generate container from RulesMap
181 let compiled = CompiledRules::from_rules_map(self.get_rules_map());
182 let rules: Arc<DynRulesContainer> = Arc::new(compiled) as Arc<DynRulesContainer>;
183
184 // 2) Calculate event_mask
185 let mut mask = 0u64;
186 for rule in rules.iter_rules() {
187 for ev in rule.subscribed_events() {
188 mask |= ev.mask();
189 }
190 }
191
192 BucketRulesSnapshot { event_mask: mask, rules }
193 }
194}