ddex_builder/diff/
mod.rs

1//! Semantic diff engine for DDEX messages
2//! 
3//! This module provides intelligent diffing that understands DDEX business semantics,
4//! not just XML structure. It can detect meaningful changes while ignoring formatting
5//! differences, reference variations, and insignificant ordering changes.
6
7pub mod types;
8pub mod formatter;
9
10#[cfg(test)]
11pub mod test_data;
12
13#[cfg(test)]
14mod diff_tests;
15
16use crate::error::BuildError;
17use crate::ast::{AST, Element, Node};
18use types::{ChangeSet, SemanticChange, DiffPath, ChangeType};
19use indexmap::{IndexMap, IndexSet};
20use serde::{Serialize, Deserialize};
21
22/// Configuration for semantic diffing behavior
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct DiffConfig {
25    /// Ignore formatting differences (whitespace, indentation)
26    pub ignore_formatting: bool,
27    
28    /// Ignore reference ID differences if content is same
29    pub ignore_reference_ids: bool,
30    
31    /// Ignore insignificant ordering changes
32    pub ignore_order_changes: bool,
33    
34    /// DDEX version compatibility mode
35    pub version_compatibility: VersionCompatibility,
36    
37    /// Fields to ignore during comparison
38    pub ignored_fields: IndexSet<String>,
39    
40    /// Business-critical fields that should be highlighted
41    pub critical_fields: IndexSet<String>,
42    
43    /// Tolerance for numeric differences (e.g., 0.01 for currency)
44    pub numeric_tolerance: Option<f64>,
45}
46
47impl Default for DiffConfig {
48    fn default() -> Self {
49        let mut critical_fields = IndexSet::new();
50        critical_fields.insert("CommercialModelType".to_string());
51        critical_fields.insert("TerritoryCode".to_string());
52        critical_fields.insert("ValidityPeriod".to_string());
53        critical_fields.insert("ReleaseDate".to_string());
54        critical_fields.insert("UPC".to_string());
55        critical_fields.insert("ISRC".to_string());
56        critical_fields.insert("Price".to_string());
57        
58        let mut ignored_fields = IndexSet::new();
59        ignored_fields.insert("MessageId".to_string());
60        ignored_fields.insert("MessageCreatedDateTime".to_string());
61        
62        Self {
63            ignore_formatting: true,
64            ignore_reference_ids: true,
65            ignore_order_changes: true,
66            version_compatibility: VersionCompatibility::Strict,
67            ignored_fields,
68            critical_fields,
69            numeric_tolerance: Some(0.01),
70        }
71    }
72}
73
74/// Version compatibility modes for DDEX diffing
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
76pub enum VersionCompatibility {
77    /// Strict - versions must match exactly
78    Strict,
79    /// Compatible - allow compatible versions (4.2 <-> 4.3)
80    Compatible,
81    /// Lenient - ignore version differences entirely
82    Lenient,
83}
84
85/// Semantic diff engine for DDEX messages
86pub struct DiffEngine {
87    config: DiffConfig,
88    // Cache for reference resolution
89    reference_cache: IndexMap<String, Element>,
90}
91
92impl DiffEngine {
93    /// Create a new diff engine with default configuration
94    pub fn new() -> Self {
95        Self {
96            config: DiffConfig::default(),
97            reference_cache: IndexMap::new(),
98        }
99    }
100    
101    /// Create a new diff engine with custom configuration
102    pub fn new_with_config(config: DiffConfig) -> Self {
103        Self {
104            config,
105            reference_cache: IndexMap::new(),
106        }
107    }
108    
109    /// Compare two DDEX ASTs and return a semantic diff
110    pub fn diff(&mut self, old: &AST, new: &AST) -> Result<ChangeSet, BuildError> {
111        // Clear reference cache for this comparison
112        self.reference_cache.clear();
113        
114        // Build reference maps for both documents
115        self.build_reference_cache(&old.root, "old");
116        self.build_reference_cache(&new.root, "new");
117        
118        let mut changeset = ChangeSet::new();
119        
120        // Compare root elements
121        self.compare_elements(&old.root, &new.root, DiffPath::root(), &mut changeset)?;
122        
123        // Analyze changes for business impact
124        self.analyze_business_impact(&mut changeset);
125        
126        Ok(changeset)
127    }
128    
129    /// Compare two elements semantically
130    fn compare_elements(
131        &self, 
132        old: &Element, 
133        new: &Element, 
134        path: DiffPath, 
135        changeset: &mut ChangeSet
136    ) -> Result<(), BuildError> {
137        // Check if elements represent the same logical entity
138        if old.name != new.name {
139            changeset.add_change(SemanticChange {
140                path: path.clone(),
141                change_type: ChangeType::ElementRenamed,
142                old_value: Some(old.name.clone()),
143                new_value: Some(new.name.clone()),
144                is_critical: self.is_critical_field(&old.name),
145                description: format!("Element renamed from '{}' to '{}'", old.name, new.name),
146            });
147            return Ok(());
148        }
149        
150        // Compare attributes
151        self.compare_attributes(&old.attributes, &new.attributes, &path, changeset);
152        
153        // Compare children with semantic understanding
154        self.compare_children(&old.children, &new.children, &path, changeset)?;
155        
156        Ok(())
157    }
158    
159    /// Compare attributes with semantic understanding
160    fn compare_attributes(
161        &self,
162        old: &IndexMap<String, String>,
163        new: &IndexMap<String, String>,
164        path: &DiffPath,
165        changeset: &mut ChangeSet,
166    ) {
167        // Find added, removed, and modified attributes
168        let old_keys: IndexSet<_> = old.keys().collect();
169        let new_keys: IndexSet<_> = new.keys().collect();
170        
171        // Removed attributes
172        for &key in old_keys.difference(&new_keys) {
173            if !self.should_ignore_field(key) {
174                changeset.add_change(SemanticChange {
175                    path: path.with_attribute(key),
176                    change_type: ChangeType::AttributeRemoved,
177                    old_value: old.get(key).cloned(),
178                    new_value: None,
179                    is_critical: self.is_critical_field(key),
180                    description: format!("Attribute '{}' removed", key),
181                });
182            }
183        }
184        
185        // Added attributes
186        for &key in new_keys.difference(&old_keys) {
187            if !self.should_ignore_field(key) {
188                changeset.add_change(SemanticChange {
189                    path: path.with_attribute(key),
190                    change_type: ChangeType::AttributeAdded,
191                    old_value: None,
192                    new_value: new.get(key).cloned(),
193                    is_critical: self.is_critical_field(key),
194                    description: format!("Attribute '{}' added", key),
195                });
196            }
197        }
198        
199        // Modified attributes
200        for &key in old_keys.intersection(&new_keys) {
201            if !self.should_ignore_field(key) {
202                let old_val = &old[key];
203                let new_val = &new[key];
204                
205                if !self.are_values_equivalent(old_val, new_val, key) {
206                    changeset.add_change(SemanticChange {
207                        path: path.with_attribute(key),
208                        change_type: ChangeType::AttributeModified,
209                        old_value: Some(old_val.clone()),
210                        new_value: Some(new_val.clone()),
211                        is_critical: self.is_critical_field(key),
212                        description: format!("Attribute '{}' changed from '{}' to '{}'", key, old_val, new_val),
213                    });
214                }
215            }
216        }
217    }
218    
219    /// Compare children with semantic understanding
220    fn compare_children(
221        &self,
222        old: &[Node],
223        new: &[Node],
224        path: &DiffPath,
225        changeset: &mut ChangeSet,
226    ) -> Result<(), BuildError> {
227        // Separate elements from text nodes
228        let old_elements: Vec<&Element> = old.iter()
229            .filter_map(|n| if let Node::Element(e) = n { Some(e) } else { None })
230            .collect();
231        let new_elements: Vec<&Element> = new.iter()
232            .filter_map(|n| if let Node::Element(e) = n { Some(e) } else { None })
233            .collect();
234        
235        // Compare text content
236        let old_text = self.extract_text_content(old);
237        let new_text = self.extract_text_content(new);
238        
239        // Only report text changes if the content actually differs after applying normalization
240        if old_text != new_text && (!old_text.trim().is_empty() || !new_text.trim().is_empty()) {
241            changeset.add_change(SemanticChange {
242                path: path.with_text(),
243                change_type: ChangeType::TextModified,
244                old_value: if old_text.trim().is_empty() { None } else { Some(old_text) },
245                new_value: if new_text.trim().is_empty() { None } else { Some(new_text) },
246                is_critical: false,
247                description: "Text content changed".to_string(),
248            });
249        }
250        
251        // Group elements by semantic identity for comparison
252        let old_groups = self.group_elements_by_identity(&old_elements);
253        let new_groups = self.group_elements_by_identity(&new_elements);
254        
255        // Compare element groups
256        self.compare_element_groups(&old_groups, &new_groups, path, changeset)?;
257        
258        Ok(())
259    }
260    
261    /// Group elements by their semantic identity (name + key attributes)
262    fn group_elements_by_identity<'a>(&self, elements: &[&'a Element]) -> IndexMap<String, Vec<&'a Element>> {
263        let mut groups = IndexMap::new();
264        
265        for element in elements {
266            let identity = self.get_element_identity(element);
267            groups.entry(identity).or_insert_with(Vec::new).push(*element);
268        }
269        
270        groups
271    }
272    
273    /// Get semantic identity key for an element
274    fn get_element_identity(&self, element: &Element) -> String {
275        // Use element name and key identifying attributes
276        let mut identity = element.name.clone();
277        
278        // Add key attributes that identify this element uniquely
279        let key_attrs = match element.name.as_str() {
280            "Release" => vec!["ReleaseId", "ReleaseReference"],
281            "SoundRecording" | "VideoRecording" => vec!["ResourceId", "ResourceReference"],
282            "Deal" => vec!["DealReference"],
283            "Party" => vec!["PartyId", "PartyReference"],
284            _ => vec!["Id", "Reference"], // Generic fallback
285        };
286        
287        for attr in key_attrs {
288            if let Some(value) = element.attributes.get(attr) {
289                identity.push_str(&format!(":{}", value));
290                break; // Use first found key attribute
291            }
292        }
293        
294        identity
295    }
296    
297    /// Compare groups of elements
298    fn compare_element_groups(
299        &self,
300        old_groups: &IndexMap<String, Vec<&Element>>,
301        new_groups: &IndexMap<String, Vec<&Element>>,
302        path: &DiffPath,
303        changeset: &mut ChangeSet,
304    ) -> Result<(), BuildError> {
305        let old_keys: IndexSet<_> = old_groups.keys().collect();
306        let new_keys: IndexSet<_> = new_groups.keys().collect();
307        
308        // Removed element groups
309        for &key in old_keys.difference(&new_keys) {
310            for element in &old_groups[key] {
311                changeset.add_change(SemanticChange {
312                    path: path.with_element(&element.name),
313                    change_type: ChangeType::ElementRemoved,
314                    old_value: Some(self.element_to_string(element)),
315                    new_value: None,
316                    is_critical: self.is_critical_field(&element.name),
317                    description: format!("Element '{}' removed", element.name),
318                });
319            }
320        }
321        
322        // Added element groups
323        for &key in new_keys.difference(&old_keys) {
324            for element in &new_groups[key] {
325                changeset.add_change(SemanticChange {
326                    path: path.with_element(&element.name),
327                    change_type: ChangeType::ElementAdded,
328                    old_value: None,
329                    new_value: Some(self.element_to_string(element)),
330                    is_critical: self.is_critical_field(&element.name),
331                    description: format!("Element '{}' added", element.name),
332                });
333            }
334        }
335        
336        // Compare matching element groups
337        for &key in old_keys.intersection(&new_keys) {
338            let old_elements = &old_groups[key];
339            let new_elements = &new_groups[key];
340            
341            // For now, compare first element of each group
342            // In a more sophisticated implementation, we'd do optimal matching
343            if let (Some(&old_elem), Some(&new_elem)) = (old_elements.first(), new_elements.first()) {
344                self.compare_elements(old_elem, new_elem, path.with_element(&old_elem.name), changeset)?;
345            }
346        }
347        
348        Ok(())
349    }
350    
351    /// Extract text content from nodes, ignoring formatting
352    fn extract_text_content(&self, nodes: &[Node]) -> String {
353        let mut text = String::new();
354        for node in nodes {
355            if let Node::Text(t) = node {
356                if self.config.ignore_formatting {
357                    text.push_str(t.trim());
358                } else {
359                    text.push_str(t);
360                }
361            }
362        }
363        text
364    }
365    
366    /// Check if two values are semantically equivalent
367    fn are_values_equivalent(&self, old: &str, new: &str, field_name: &str) -> bool {
368        // Reference equivalence - if we're ignoring reference IDs
369        if self.config.ignore_reference_ids && self.is_reference_field(field_name) {
370            return self.are_references_equivalent(old, new);
371        }
372        
373        // Numeric tolerance for prices and monetary values
374        if let Some(tolerance) = self.config.numeric_tolerance {
375            if field_name.contains("Price") || field_name.contains("Amount") {
376                if let (Ok(old_num), Ok(new_num)) = (old.parse::<f64>(), new.parse::<f64>()) {
377                    return (old_num - new_num).abs() < tolerance;
378                }
379            }
380        }
381        
382        // Formatting equivalence
383        if self.config.ignore_formatting {
384            return old.trim() == new.trim();
385        }
386        
387        old == new
388    }
389    
390    /// Check if a field represents a reference
391    fn is_reference_field(&self, field_name: &str) -> bool {
392        field_name.ends_with("Reference") || 
393        field_name.ends_with("Ref") ||
394        field_name == "ResourceId" ||
395        field_name == "ReleaseId" ||
396        field_name == "DealId"
397    }
398    
399    /// Check if two references are equivalent by content
400    fn are_references_equivalent(&self, old_ref: &str, new_ref: &str) -> bool {
401        // If they're the same, they're equivalent
402        if old_ref == new_ref {
403            return true;
404        }
405        
406        // Look up referenced content in cache
407        let old_key = format!("old:{}", old_ref);
408        let new_key = format!("new:{}", new_ref);
409        
410        if let (Some(old_elem), Some(new_elem)) = 
411            (self.reference_cache.get(&old_key), self.reference_cache.get(&new_key)) {
412            // Compare the referenced elements for semantic equivalence
413            self.elements_semantically_equal(old_elem, new_elem)
414        } else {
415            false
416        }
417    }
418    
419    /// Check if two elements are semantically equal
420    fn elements_semantically_equal(&self, old: &Element, new: &Element) -> bool {
421        // This is a simplified check - in practice, you'd want recursive comparison
422        // excluding the reference IDs themselves
423        old.name == new.name &&
424        self.text_content_equal(&old.children, &new.children)
425    }
426    
427    /// Compare text content of children for equality
428    fn text_content_equal(&self, old: &[Node], new: &[Node]) -> bool {
429        self.extract_text_content(old) == self.extract_text_content(new)
430    }
431    
432    /// Build reference cache for resolving reference equivalence
433    fn build_reference_cache(&mut self, element: &Element, prefix: &str) {
434        // Store elements that can be referenced
435        if let Some(ref_id) = self.get_reference_id(element) {
436            let cache_key = format!("{}:{}", prefix, ref_id);
437            self.reference_cache.insert(cache_key, element.clone());
438        }
439        
440        // Recursively build cache for children
441        for child in &element.children {
442            if let Node::Element(child_elem) = child {
443                self.build_reference_cache(child_elem, prefix);
444            }
445        }
446    }
447    
448    /// Get reference ID from element if it has one
449    fn get_reference_id(&self, element: &Element) -> Option<String> {
450        // Look for common reference attributes
451        let ref_attrs = ["ResourceReference", "ReleaseReference", "DealReference", 
452                        "PartyReference", "Reference", "ResourceId", "ReleaseId"];
453        
454        for attr in &ref_attrs {
455            if let Some(value) = element.attributes.get(*attr) {
456                return Some(value.clone());
457            }
458        }
459        
460        None
461    }
462    
463    /// Check if a field should be ignored during comparison
464    fn should_ignore_field(&self, field_name: &str) -> bool {
465        self.config.ignored_fields.contains(field_name)
466    }
467    
468    /// Check if a field is business-critical
469    fn is_critical_field(&self, field_name: &str) -> bool {
470        self.config.critical_fields.contains(field_name)
471    }
472    
473    /// Convert element to string representation
474    fn element_to_string(&self, element: &Element) -> String {
475        // Simplified string representation - in practice you'd want proper XML serialization
476        format!("<{}>", element.name)
477    }
478    
479    /// Analyze changes for business impact
480    fn analyze_business_impact(&self, changeset: &mut ChangeSet) {
481        // Count critical changes
482        let critical_changes = changeset.changes.iter()
483            .filter(|c| c.is_critical)
484            .count();
485        
486        changeset.metadata.insert("critical_changes".to_string(), critical_changes.to_string());
487        
488        // Determine overall impact level
489        let impact = if critical_changes > 0 {
490            "HIGH"
491        } else if changeset.changes.len() > 10 {
492            "MEDIUM"
493        } else {
494            "LOW"
495        };
496        
497        changeset.metadata.insert("impact_level".to_string(), impact.to_string());
498    }
499}
500
501impl Default for DiffEngine {
502    fn default() -> Self {
503        Self::new()
504    }
505}
506
507#[cfg(test)]
508mod tests {
509    use super::*;
510    use crate::ast::{Element, Node};
511    
512    fn create_test_element(name: &str, text: &str) -> Element {
513        Element::new(name).with_text(text)
514    }
515    
516    #[test]
517    fn test_basic_diff() {
518        let mut engine = DiffEngine::new();
519        
520        let old_ast = AST {
521            root: create_test_element("Root", "old content"),
522            namespaces: IndexMap::new(),
523            schema_location: None,
524        };
525        
526        let new_ast = AST {
527            root: create_test_element("Root", "new content"),
528            namespaces: IndexMap::new(),
529            schema_location: None,
530        };
531        
532        let changeset = engine.diff(&old_ast, &new_ast).unwrap();
533        assert!(!changeset.changes.is_empty());
534    }
535    
536    #[test]
537    fn test_ignore_formatting() {
538        let mut engine = DiffEngine::new();
539        
540        let old_ast = AST {
541            root: create_test_element("Root", "  content  "),
542            namespaces: IndexMap::new(),
543            schema_location: None,
544        };
545        
546        let new_ast = AST {
547            root: create_test_element("Root", "content"),
548            namespaces: IndexMap::new(),
549            schema_location: None,
550        };
551        
552        let changeset = engine.diff(&old_ast, &new_ast).unwrap();
553        // Should have no changes due to formatting being ignored
554        let text_changes: Vec<_> = changeset.changes.iter()
555            .filter(|c| matches!(c.change_type, ChangeType::TextModified))
556            .collect();
557        assert!(text_changes.is_empty());
558    }
559}