Skip to main content

braze_sync/diff/
mod.rs

1//! Pure structural diff layer. No I/O.
2//!
3//! See IMPLEMENTATION.md §6.6 and §11. The shape of [`DiffOp`] and
4//! [`ResourceDiff`] is the central design contract: every diff site in the
5//! crate goes through these types so that adding a resource forces all
6//! match arms to be updated by the compiler.
7
8use crate::resource::ResourceKind;
9use similar::{ChangeTag, TextDiff};
10
11pub mod catalog;
12pub mod content_block;
13pub mod custom_attribute;
14pub mod email_template;
15pub mod orphan;
16
17#[derive(Debug, Clone)]
18pub struct TextDiffSummary {
19    pub additions: usize,
20    pub deletions: usize,
21}
22
23pub(crate) fn compute_text_diff(from: &str, to: &str) -> TextDiffSummary {
24    let diff = TextDiff::from_lines(from, to);
25    let mut additions = 0;
26    let mut deletions = 0;
27    for change in diff.iter_all_changes() {
28        match change.tag() {
29            ChangeTag::Insert => additions += 1,
30            ChangeTag::Delete => deletions += 1,
31            ChangeTag::Equal => {}
32        }
33    }
34    TextDiffSummary {
35        additions,
36        deletions,
37    }
38}
39
40/// Treats `None` and `Some("")` as equal — Braze may omit a field or
41/// return an empty string interchangeably.
42pub(crate) fn opt_str_eq(a: &Option<String>, b: &Option<String>) -> bool {
43    a.as_deref().unwrap_or("") == b.as_deref().unwrap_or("")
44}
45
46/// Multiset equality: same elements after sort, ignoring order.
47pub(crate) fn tags_eq_unordered(a: &[String], b: &[String]) -> bool {
48    if a.len() != b.len() {
49        return false;
50    }
51    let mut a: Vec<&str> = a.iter().map(String::as_str).collect();
52    let mut b: Vec<&str> = b.iter().map(String::as_str).collect();
53    a.sort_unstable();
54    b.sort_unstable();
55    a == b
56}
57
58/// A diff operation on a single entity. Polymorphic over the entity type so
59/// the same vocabulary applies to whole resources, individual fields, etc.
60#[derive(Debug, Clone, PartialEq)]
61pub enum DiffOp<T> {
62    Added(T),
63    Removed(T),
64    Modified { from: T, to: T },
65    Unchanged,
66}
67
68impl<T> DiffOp<T> {
69    pub fn is_change(&self) -> bool {
70        !matches!(self, Self::Unchanged)
71    }
72
73    pub fn is_destructive(&self) -> bool {
74        matches!(self, Self::Removed(_))
75    }
76}
77
78/// Per-resource-kind diff result.
79#[derive(Debug, Clone)]
80pub enum ResourceDiff {
81    CatalogSchema(catalog::CatalogSchemaDiff),
82    ContentBlock(content_block::ContentBlockDiff),
83    EmailTemplate(email_template::EmailTemplateDiff),
84    CustomAttribute(custom_attribute::CustomAttributeDiff),
85}
86
87impl ResourceDiff {
88    pub fn kind(&self) -> ResourceKind {
89        match self {
90            Self::CatalogSchema(_) => ResourceKind::CatalogSchema,
91            Self::ContentBlock(_) => ResourceKind::ContentBlock,
92            Self::EmailTemplate(_) => ResourceKind::EmailTemplate,
93            Self::CustomAttribute(_) => ResourceKind::CustomAttribute,
94        }
95    }
96
97    pub fn name(&self) -> &str {
98        match self {
99            Self::CatalogSchema(d) => &d.name,
100            Self::ContentBlock(d) => &d.name,
101            Self::EmailTemplate(d) => &d.name,
102            Self::CustomAttribute(d) => &d.name,
103        }
104    }
105
106    pub fn has_changes(&self) -> bool {
107        match self {
108            Self::CatalogSchema(d) => d.has_changes(),
109            Self::ContentBlock(d) => d.has_changes(),
110            Self::EmailTemplate(d) => d.has_changes(),
111            Self::CustomAttribute(d) => d.has_changes(),
112        }
113    }
114
115    /// Whether `apply` can act on this diff. For most resource types this
116    /// is the same as `has_changes()`. Custom Attributes are the exception:
117    /// `MetadataOnly` and `UnregisteredInGit` are informational drift
118    /// that `apply` cannot resolve via API. `PresentInGitOnly` is
119    /// actionable so `apply` can surface the unsupported-create error.
120    pub fn is_actionable(&self) -> bool {
121        match self {
122            Self::CustomAttribute(d) => d.is_actionable(),
123            other => other.has_changes(),
124        }
125    }
126
127    pub fn has_destructive(&self) -> bool {
128        match self {
129            Self::CatalogSchema(d) => d.has_destructive(),
130            // Content Block / Email Template have no DELETE API. "Destructive"
131            // for these resources is reframed as orphan tracking (§11.6); the
132            // apply path performs no destructive call.
133            Self::ContentBlock(_) => false,
134            Self::EmailTemplate(_) => false,
135            // Custom Attribute "removal" is only a deprecation flag toggle.
136            Self::CustomAttribute(_) => false,
137        }
138    }
139
140    pub fn is_orphan(&self) -> bool {
141        match self {
142            Self::ContentBlock(d) => d.is_orphan(),
143            Self::EmailTemplate(d) => d.is_orphan(),
144            _ => false,
145        }
146    }
147}
148
149#[derive(Debug, Clone, Default)]
150pub struct DiffSummary {
151    pub diffs: Vec<ResourceDiff>,
152}
153
154impl DiffSummary {
155    pub fn changed_count(&self) -> usize {
156        self.diffs.iter().filter(|d| d.has_changes()).count()
157    }
158
159    /// Count of diffs that `apply` can actually act on. Excludes
160    /// informational-only drift (e.g. Custom Attribute metadata-only).
161    pub fn actionable_count(&self) -> usize {
162        self.diffs.iter().filter(|d| d.is_actionable()).count()
163    }
164
165    pub fn destructive_count(&self) -> usize {
166        self.diffs.iter().filter(|d| d.has_destructive()).count()
167    }
168
169    pub fn orphan_count(&self) -> usize {
170        self.diffs.iter().filter(|d| d.is_orphan()).count()
171    }
172
173    pub fn in_sync_count(&self) -> usize {
174        self.diffs.iter().filter(|d| !d.has_changes()).count()
175    }
176}