rewrit_core/normalize/
pipeline.rs1use rewrit_model::{AppliedNormalizer, Observation};
2use thiserror::Error;
3
4#[derive(Debug, Clone, Default)]
5pub struct NormalizeContext {
6 pub project_root: Option<String>,
7}
8
9#[derive(Debug, Clone)]
10pub struct NormalizationResult {
11 pub observation: Observation,
12 pub applied: Vec<AppliedNormalizer>,
13}
14
15#[derive(Debug, Error)]
16pub enum NormalizeError {
17 #[error("normalizer {name} failed: {message}")]
18 Failed { name: String, message: String },
19}
20
21pub trait Normalizer: Send + Sync {
22 fn name(&self) -> &'static str;
23
24 fn paths(&self) -> &[String] {
25 &[]
26 }
27
28 fn normalize(
29 &self,
30 observation: Observation,
31 ctx: &NormalizeContext,
32 ) -> Result<Observation, NormalizeError>;
33}
34
35#[derive(Default)]
36pub struct NormalizationPipeline {
37 normalizers: Vec<Box<dyn Normalizer>>,
38}
39
40impl NormalizationPipeline {
41 #[must_use]
42 pub fn new(normalizers: Vec<Box<dyn Normalizer>>) -> Self {
43 Self { normalizers }
44 }
45
46 pub fn push(&mut self, normalizer: Box<dyn Normalizer>) {
47 self.normalizers.push(normalizer);
48 }
49
50 pub fn normalize(
51 &self,
52 mut observation: Observation,
53 ctx: &NormalizeContext,
54 ) -> Result<NormalizationResult, NormalizeError> {
55 let mut applied = Vec::new();
56 for normalizer in &self.normalizers {
57 let before = observation.clone();
58 observation = normalizer.normalize(observation, ctx)?;
59 if observation != before {
60 if normalizer.paths().is_empty() {
61 applied.push(AppliedNormalizer {
62 case_id: observation.case_id.clone(),
63 name: normalizer.name().to_string(),
64 path: None,
65 });
66 } else {
67 applied.extend(normalizer.paths().iter().cloned().map(|path| {
68 AppliedNormalizer {
69 case_id: observation.case_id.clone(),
70 name: normalizer.name().to_string(),
71 path: Some(path),
72 }
73 }));
74 }
75 }
76 }
77
78 Ok(NormalizationResult {
79 observation,
80 applied,
81 })
82 }
83}
84
85#[cfg(test)]
86mod tests {
87 use super::*;
88 use crate::normalize::regex::RegexNormalizer;
89 use rewrit_model::{CanonicalValue, CapturedText, CaseId, CaseStatus, RuntimeId};
90 use std::collections::BTreeMap;
91
92 #[test]
93 fn applied_normalizer_records_configured_paths() {
94 let pipeline = NormalizationPipeline::new(vec![Box::new(
95 RegexNormalizer::new("test", "token-[0-9]+", "<TOKEN>")
96 .expect("regex")
97 .with_paths(vec!["$.token".to_string()]),
98 )]);
99 let observation = Observation {
100 case_id: CaseId::new("auth.case"),
101 runtime_id: RuntimeId::new("reference"),
102 status: CaseStatus::Passed,
103 value: Some(CanonicalValue::Json {
104 value: serde_json::json!({"token": "token-123"}),
105 }),
106 error: None,
107 stdout: CapturedText::default(),
108 stderr: CapturedText::default(),
109 exit_code: Some(0),
110 duration_ms: 1,
111 effects: Vec::new(),
112 artifacts: Vec::new(),
113 metadata: BTreeMap::new(),
114 };
115
116 let result = pipeline
117 .normalize(observation, &NormalizeContext::default())
118 .expect("normalize");
119
120 assert_eq!(result.applied.len(), 1);
121 assert_eq!(result.applied[0].name, "test");
122 assert_eq!(result.applied[0].path.as_deref(), Some("$.token"));
123 }
124}