Skip to main content

rewrit_core/normalize/
regex.rs

1use crate::normalize::{NormalizeContext, NormalizeError, Normalizer};
2use regex::Regex;
3use rewrit_model::{CanonicalError, CanonicalValue, Observation};
4
5#[derive(Debug, Clone)]
6pub struct RegexNormalizer {
7    name: &'static str,
8    regex: Regex,
9    replacement: String,
10    paths: Vec<String>,
11}
12
13impl RegexNormalizer {
14    pub fn new(
15        name: &'static str,
16        pattern: &str,
17        replacement: impl Into<String>,
18    ) -> Result<Self, regex::Error> {
19        Ok(Self {
20            name,
21            regex: Regex::new(pattern)?,
22            replacement: replacement.into(),
23            paths: Vec::new(),
24        })
25    }
26
27    pub fn uuid() -> Self {
28        Self::new(
29            "uuid",
30            r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b",
31            "<UUID>",
32        )
33        .expect("built-in UUID regex is valid")
34    }
35
36    #[must_use]
37    pub fn with_paths(mut self, paths: Vec<String>) -> Self {
38        self.paths = paths;
39        self
40    }
41}
42
43impl Normalizer for RegexNormalizer {
44    fn name(&self) -> &'static str {
45        self.name
46    }
47
48    fn paths(&self) -> &[String] {
49        &self.paths
50    }
51
52    fn normalize(
53        &self,
54        mut observation: Observation,
55        _ctx: &NormalizeContext,
56    ) -> Result<Observation, NormalizeError> {
57        if self.paths.is_empty() {
58            observation.stdout.text = self.replace(&observation.stdout.text);
59            observation.stderr.text = self.replace(&observation.stderr.text);
60            if let Some(value) = &mut observation.value {
61                self.normalize_value(value);
62            }
63            if let Some(error) = &mut observation.error {
64                self.normalize_error(error);
65            }
66        } else if let Some(value) = &mut observation.value {
67            self.normalize_value_at_paths(value, "$");
68        }
69        Ok(observation)
70    }
71}
72
73impl RegexNormalizer {
74    fn replace(&self, value: &str) -> String {
75        self.regex
76            .replace_all(value, self.replacement.as_str())
77            .into_owned()
78    }
79
80    fn normalize_error(&self, error: &mut CanonicalError) {
81        if let Some(message) = &mut error.message {
82            *message = self.replace(message);
83        }
84        if let Some(message) = &mut error.normalized_message {
85            *message = self.replace(message);
86        }
87    }
88
89    fn normalize_value(&self, value: &mut CanonicalValue) {
90        match value {
91            CanonicalValue::String { value }
92            | CanonicalValue::Integer { value }
93            | CanonicalValue::Decimal { value }
94            | CanonicalValue::Float { value }
95            | CanonicalValue::DateTime { rfc3339: value } => {
96                *value = self.replace(value);
97            }
98            CanonicalValue::Array { items } => {
99                for item in items {
100                    self.normalize_value(item);
101                }
102            }
103            CanonicalValue::Object { fields } => {
104                for field in fields.values_mut() {
105                    self.normalize_value(field);
106                }
107            }
108            CanonicalValue::Json { value } => normalize_json(value, &|s| self.replace(s)),
109            CanonicalValue::Null
110            | CanonicalValue::Absent
111            | CanonicalValue::Bool { .. }
112            | CanonicalValue::Bytes { .. } => {}
113        }
114    }
115
116    fn normalize_value_at_paths(&self, value: &mut CanonicalValue, path: &str) {
117        if self.path_matches(path) {
118            self.normalize_value(value);
119            return;
120        }
121
122        match value {
123            CanonicalValue::Array { items } => {
124                for (index, item) in items.iter_mut().enumerate() {
125                    self.normalize_value_at_paths(item, &format!("{path}[{index}]"));
126                }
127            }
128            CanonicalValue::Object { fields } => {
129                for (key, value) in fields {
130                    self.normalize_value_at_paths(value, &format!("{path}.{}", escape_path(key)));
131                }
132            }
133            CanonicalValue::Json { value } => self.normalize_json_at_paths(value, path),
134            CanonicalValue::Null
135            | CanonicalValue::Absent
136            | CanonicalValue::Bool { .. }
137            | CanonicalValue::Integer { .. }
138            | CanonicalValue::Decimal { .. }
139            | CanonicalValue::Float { .. }
140            | CanonicalValue::String { .. }
141            | CanonicalValue::Bytes { .. }
142            | CanonicalValue::DateTime { .. } => {}
143        }
144    }
145
146    fn normalize_json_at_paths(&self, value: &mut serde_json::Value, path: &str) {
147        if self.path_matches(path) {
148            normalize_json(value, &|s| self.replace(s));
149            return;
150        }
151
152        match value {
153            serde_json::Value::Array(items) => {
154                for (index, item) in items.iter_mut().enumerate() {
155                    self.normalize_json_at_paths(item, &format!("{path}[{index}]"));
156                }
157            }
158            serde_json::Value::Object(fields) => {
159                for (key, value) in fields {
160                    self.normalize_json_at_paths(value, &format!("{path}.{}", escape_path(key)));
161                }
162            }
163            serde_json::Value::Null
164            | serde_json::Value::Bool(_)
165            | serde_json::Value::Number(_)
166            | serde_json::Value::String(_) => {}
167        }
168    }
169
170    fn path_matches(&self, path: &str) -> bool {
171        candidate_policy_paths(path).iter().any(|candidate| {
172            self.paths.iter().any(|configured| {
173                candidate == configured || wildcard_path_matches(candidate, configured)
174            })
175        })
176    }
177}
178
179fn normalize_json(value: &mut serde_json::Value, replace: &dyn Fn(&str) -> String) {
180    match value {
181        serde_json::Value::String(text) => *text = replace(text),
182        serde_json::Value::Array(items) => {
183            for item in items {
184                normalize_json(item, replace);
185            }
186        }
187        serde_json::Value::Object(fields) => {
188            for item in fields.values_mut() {
189                normalize_json(item, replace);
190            }
191        }
192        serde_json::Value::Null | serde_json::Value::Bool(_) | serde_json::Value::Number(_) => {}
193    }
194}
195
196fn candidate_policy_paths(path: &str) -> Vec<String> {
197    let mut paths = vec![path.to_string()];
198    if let Some(suffix) = path.strip_prefix("$.body") {
199        if suffix.is_empty() {
200            paths.push("$".to_string());
201        } else if let Some(suffix) = suffix.strip_prefix('.') {
202            paths.push(format!("$.{suffix}"));
203        } else if suffix.starts_with('[') {
204            paths.push(format!("${suffix}"));
205        }
206    }
207    if let Some(suffix) = path.strip_prefix("$.value.body") {
208        if suffix.is_empty() {
209            paths.push("$".to_string());
210        } else if let Some(suffix) = suffix.strip_prefix('.') {
211            paths.push(format!("$.{suffix}"));
212        } else if suffix.starts_with('[') {
213            paths.push(format!("${suffix}"));
214        }
215    }
216    if let Some(suffix) = path.strip_prefix("$.value") {
217        if suffix.is_empty() {
218            paths.push("$".to_string());
219        } else if let Some(suffix) = suffix.strip_prefix('.') {
220            paths.push(format!("$.{suffix}"));
221        } else if suffix.starts_with('[') {
222            paths.push(format!("${suffix}"));
223        }
224    }
225    paths
226}
227
228fn wildcard_path_matches(path: &str, configured: &str) -> bool {
229    if !configured.contains("[*]") {
230        return false;
231    }
232    let prefix = configured.split("[*]").next().unwrap_or_default();
233    let suffix = configured.split("[*]").nth(1).unwrap_or_default();
234    path.starts_with(prefix) && path.ends_with(suffix)
235}
236
237fn escape_path(segment: &str) -> String {
238    if segment
239        .chars()
240        .all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '-')
241    {
242        segment.to_string()
243    } else {
244        format!("[{}]", serde_json::to_string(segment).unwrap_or_default())
245    }
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251    use rewrit_model::{CapturedText, CaseId, CaseStatus, RuntimeId};
252    use std::collections::BTreeMap;
253
254    #[test]
255    fn scoped_regex_normalizes_only_configured_json_paths() {
256        let normalizer = RegexNormalizer::new("test", r"\bid-[0-9]+\b", "<ID>")
257            .expect("regex")
258            .with_paths(vec!["$.items[*].id".to_string()]);
259        let mut observation = observation_with_value(CanonicalValue::Json {
260            value: serde_json::json!({
261                "items": [
262                    {"id": "id-123", "label": "id-123"},
263                    {"id": "id-456", "label": "id-456"}
264                ],
265                "id": "id-789"
266            }),
267        });
268
269        observation = normalizer
270            .normalize(observation, &NormalizeContext::default())
271            .expect("normalize");
272
273        assert_eq!(
274            observation.value,
275            Some(CanonicalValue::Json {
276                value: serde_json::json!({
277                    "items": [
278                        {"id": "<ID>", "label": "id-123"},
279                        {"id": "<ID>", "label": "id-456"}
280                    ],
281                    "id": "id-789"
282                })
283            })
284        );
285    }
286
287    fn observation_with_value(value: CanonicalValue) -> Observation {
288        Observation {
289            case_id: CaseId::new("case"),
290            runtime_id: RuntimeId::new("runtime"),
291            status: CaseStatus::Passed,
292            value: Some(value),
293            error: None,
294            stdout: CapturedText::default(),
295            stderr: CapturedText::default(),
296            exit_code: Some(0),
297            duration_ms: 1,
298            effects: Vec::new(),
299            artifacts: Vec::new(),
300            metadata: BTreeMap::new(),
301        }
302    }
303}