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        if old_text != new_text && !old_text.trim().is_empty() || !new_text.trim().is_empty() {
239            changeset.add_change(SemanticChange {
240                path: path.with_text(),
241                change_type: ChangeType::TextModified,
242                old_value: if old_text.trim().is_empty() { None } else { Some(old_text) },
243                new_value: if new_text.trim().is_empty() { None } else { Some(new_text) },
244                is_critical: false,
245                description: "Text content changed".to_string(),
246            });
247        }
248        
249        // Group elements by semantic identity for comparison
250        let old_groups = self.group_elements_by_identity(&old_elements);
251        let new_groups = self.group_elements_by_identity(&new_elements);
252        
253        // Compare element groups
254        self.compare_element_groups(&old_groups, &new_groups, path, changeset)?;
255        
256        Ok(())
257    }
258    
259    /// Group elements by their semantic identity (name + key attributes)
260    fn group_elements_by_identity<'a>(&self, elements: &[&'a Element]) -> IndexMap<String, Vec<&'a Element>> {
261        let mut groups = IndexMap::new();
262        
263        for element in elements {
264            let identity = self.get_element_identity(element);
265            groups.entry(identity).or_insert_with(Vec::new).push(*element);
266        }
267        
268        groups
269    }
270    
271    /// Get semantic identity key for an element
272    fn get_element_identity(&self, element: &Element) -> String {
273        // Use element name and key identifying attributes
274        let mut identity = element.name.clone();
275        
276        // Add key attributes that identify this element uniquely
277        let key_attrs = match element.name.as_str() {
278            "Release" => vec!["ReleaseId", "ReleaseReference"],
279            "SoundRecording" | "VideoRecording" => vec!["ResourceId", "ResourceReference"],
280            "Deal" => vec!["DealReference"],
281            "Party" => vec!["PartyId", "PartyReference"],
282            _ => vec!["Id", "Reference"], // Generic fallback
283        };
284        
285        for attr in key_attrs {
286            if let Some(value) = element.attributes.get(attr) {
287                identity.push_str(&format!(":{}", value));
288                break; // Use first found key attribute
289            }
290        }
291        
292        identity
293    }
294    
295    /// Compare groups of elements
296    fn compare_element_groups(
297        &self,
298        old_groups: &IndexMap<String, Vec<&Element>>,
299        new_groups: &IndexMap<String, Vec<&Element>>,
300        path: &DiffPath,
301        changeset: &mut ChangeSet,
302    ) -> Result<(), BuildError> {
303        let old_keys: IndexSet<_> = old_groups.keys().collect();
304        let new_keys: IndexSet<_> = new_groups.keys().collect();
305        
306        // Removed element groups
307        for &key in old_keys.difference(&new_keys) {
308            for element in &old_groups[key] {
309                changeset.add_change(SemanticChange {
310                    path: path.with_element(&element.name),
311                    change_type: ChangeType::ElementRemoved,
312                    old_value: Some(self.element_to_string(element)),
313                    new_value: None,
314                    is_critical: self.is_critical_field(&element.name),
315                    description: format!("Element '{}' removed", element.name),
316                });
317            }
318        }
319        
320        // Added element groups
321        for &key in new_keys.difference(&old_keys) {
322            for element in &new_groups[key] {
323                changeset.add_change(SemanticChange {
324                    path: path.with_element(&element.name),
325                    change_type: ChangeType::ElementAdded,
326                    old_value: None,
327                    new_value: Some(self.element_to_string(element)),
328                    is_critical: self.is_critical_field(&element.name),
329                    description: format!("Element '{}' added", element.name),
330                });
331            }
332        }
333        
334        // Compare matching element groups
335        for &key in old_keys.intersection(&new_keys) {
336            let old_elements = &old_groups[key];
337            let new_elements = &new_groups[key];
338            
339            // For now, compare first element of each group
340            // In a more sophisticated implementation, we'd do optimal matching
341            if let (Some(&old_elem), Some(&new_elem)) = (old_elements.first(), new_elements.first()) {
342                self.compare_elements(old_elem, new_elem, path.with_element(&old_elem.name), changeset)?;
343            }
344        }
345        
346        Ok(())
347    }
348    
349    /// Extract text content from nodes, ignoring formatting
350    fn extract_text_content(&self, nodes: &[Node]) -> String {
351        let mut text = String::new();
352        for node in nodes {
353            if let Node::Text(t) = node {
354                if self.config.ignore_formatting {
355                    text.push_str(t.trim());
356                } else {
357                    text.push_str(t);
358                }
359            }
360        }
361        text
362    }
363    
364    /// Check if two values are semantically equivalent
365    fn are_values_equivalent(&self, old: &str, new: &str, field_name: &str) -> bool {
366        // Reference equivalence - if we're ignoring reference IDs
367        if self.config.ignore_reference_ids && self.is_reference_field(field_name) {
368            return self.are_references_equivalent(old, new);
369        }
370        
371        // Numeric tolerance for prices and monetary values
372        if let Some(tolerance) = self.config.numeric_tolerance {
373            if field_name.contains("Price") || field_name.contains("Amount") {
374                if let (Ok(old_num), Ok(new_num)) = (old.parse::<f64>(), new.parse::<f64>()) {
375                    return (old_num - new_num).abs() < tolerance;
376                }
377            }
378        }
379        
380        // Formatting equivalence
381        if self.config.ignore_formatting {
382            return old.trim() == new.trim();
383        }
384        
385        old == new
386    }
387    
388    /// Check if a field represents a reference
389    fn is_reference_field(&self, field_name: &str) -> bool {
390        field_name.ends_with("Reference") || 
391        field_name.ends_with("Ref") ||
392        field_name == "ResourceId" ||
393        field_name == "ReleaseId" ||
394        field_name == "DealId"
395    }
396    
397    /// Check if two references are equivalent by content
398    fn are_references_equivalent(&self, old_ref: &str, new_ref: &str) -> bool {
399        // If they're the same, they're equivalent
400        if old_ref == new_ref {
401            return true;
402        }
403        
404        // Look up referenced content in cache
405        let old_key = format!("old:{}", old_ref);
406        let new_key = format!("new:{}", new_ref);
407        
408        if let (Some(old_elem), Some(new_elem)) = 
409            (self.reference_cache.get(&old_key), self.reference_cache.get(&new_key)) {
410            // Compare the referenced elements for semantic equivalence
411            self.elements_semantically_equal(old_elem, new_elem)
412        } else {
413            false
414        }
415    }
416    
417    /// Check if two elements are semantically equal
418    fn elements_semantically_equal(&self, old: &Element, new: &Element) -> bool {
419        // This is a simplified check - in practice, you'd want recursive comparison
420        // excluding the reference IDs themselves
421        old.name == new.name &&
422        self.text_content_equal(&old.children, &new.children)
423    }
424    
425    /// Compare text content of children for equality
426    fn text_content_equal(&self, old: &[Node], new: &[Node]) -> bool {
427        self.extract_text_content(old) == self.extract_text_content(new)
428    }
429    
430    /// Build reference cache for resolving reference equivalence
431    fn build_reference_cache(&mut self, element: &Element, prefix: &str) {
432        // Store elements that can be referenced
433        if let Some(ref_id) = self.get_reference_id(element) {
434            let cache_key = format!("{}:{}", prefix, ref_id);
435            self.reference_cache.insert(cache_key, element.clone());
436        }
437        
438        // Recursively build cache for children
439        for child in &element.children {
440            if let Node::Element(child_elem) = child {
441                self.build_reference_cache(child_elem, prefix);
442            }
443        }
444    }
445    
446    /// Get reference ID from element if it has one
447    fn get_reference_id(&self, element: &Element) -> Option<String> {
448        // Look for common reference attributes
449        let ref_attrs = ["ResourceReference", "ReleaseReference", "DealReference", 
450                        "PartyReference", "Reference", "ResourceId", "ReleaseId"];
451        
452        for attr in &ref_attrs {
453            if let Some(value) = element.attributes.get(*attr) {
454                return Some(value.clone());
455            }
456        }
457        
458        None
459    }
460    
461    /// Check if a field should be ignored during comparison
462    fn should_ignore_field(&self, field_name: &str) -> bool {
463        self.config.ignored_fields.contains(field_name)
464    }
465    
466    /// Check if a field is business-critical
467    fn is_critical_field(&self, field_name: &str) -> bool {
468        self.config.critical_fields.contains(field_name)
469    }
470    
471    /// Convert element to string representation
472    fn element_to_string(&self, element: &Element) -> String {
473        // Simplified string representation - in practice you'd want proper XML serialization
474        format!("<{}>", element.name)
475    }
476    
477    /// Analyze changes for business impact
478    fn analyze_business_impact(&self, changeset: &mut ChangeSet) {
479        // Count critical changes
480        let critical_changes = changeset.changes.iter()
481            .filter(|c| c.is_critical)
482            .count();
483        
484        changeset.metadata.insert("critical_changes".to_string(), critical_changes.to_string());
485        
486        // Determine overall impact level
487        let impact = if critical_changes > 0 {
488            "HIGH"
489        } else if changeset.changes.len() > 10 {
490            "MEDIUM"
491        } else {
492            "LOW"
493        };
494        
495        changeset.metadata.insert("impact_level".to_string(), impact.to_string());
496    }
497}
498
499impl Default for DiffEngine {
500    fn default() -> Self {
501        Self::new()
502    }
503}
504
505#[cfg(test)]
506mod tests {
507    use super::*;
508    use crate::ast::{Element, Node};
509    
510    fn create_test_element(name: &str, text: &str) -> Element {
511        Element::new(name).with_text(text)
512    }
513    
514    #[test]
515    fn test_basic_diff() {
516        let mut engine = DiffEngine::new();
517        
518        let old_ast = AST {
519            root: create_test_element("Root", "old content"),
520            namespaces: IndexMap::new(),
521            schema_location: None,
522        };
523        
524        let new_ast = AST {
525            root: create_test_element("Root", "new content"),
526            namespaces: IndexMap::new(),
527            schema_location: None,
528        };
529        
530        let changeset = engine.diff(&old_ast, &new_ast).unwrap();
531        assert!(!changeset.changes.is_empty());
532    }
533    
534    #[test]
535    fn test_ignore_formatting() {
536        let mut engine = DiffEngine::new();
537        
538        let old_ast = AST {
539            root: create_test_element("Root", "  content  "),
540            namespaces: IndexMap::new(),
541            schema_location: None,
542        };
543        
544        let new_ast = AST {
545            root: create_test_element("Root", "content"),
546            namespaces: IndexMap::new(),
547            schema_location: None,
548        };
549        
550        let changeset = engine.diff(&old_ast, &new_ast).unwrap();
551        // Should have no changes due to formatting being ignored
552        let text_changes: Vec<_> = changeset.changes.iter()
553            .filter(|c| matches!(c.change_type, ChangeType::TextModified))
554            .collect();
555        assert!(text_changes.is_empty());
556    }
557}