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    /// only `DeprecationToggled` produces an API call. `MetadataOnly`,
118    /// `UnregisteredInGit`, and `PresentInGitOnly` are all informational
119    /// drift — Braze has no create endpoint for custom attributes (they
120    /// materialize on first `/users/track`), so registry-only entries are
121    /// expected and must not block apply.
122    pub fn is_actionable(&self) -> bool {
123        match self {
124            Self::CustomAttribute(d) => d.is_actionable(),
125            other => other.has_changes(),
126        }
127    }
128
129    pub fn has_destructive(&self) -> bool {
130        match self {
131            Self::CatalogSchema(d) => d.has_destructive(),
132            // Content Block / Email Template have no DELETE API. "Destructive"
133            // for these resources is reframed as orphan tracking (§11.6); the
134            // apply path performs no destructive call.
135            Self::ContentBlock(_) => false,
136            Self::EmailTemplate(_) => false,
137            // Custom Attribute "removal" is only a deprecation flag toggle.
138            Self::CustomAttribute(_) => false,
139        }
140    }
141
142    pub fn is_orphan(&self) -> bool {
143        match self {
144            Self::ContentBlock(d) => d.is_orphan(),
145            Self::EmailTemplate(d) => d.is_orphan(),
146            _ => false,
147        }
148    }
149}
150
151#[derive(Debug, Clone, Default)]
152pub struct DiffSummary {
153    pub diffs: Vec<ResourceDiff>,
154}
155
156impl DiffSummary {
157    pub fn changed_count(&self) -> usize {
158        self.diffs.iter().filter(|d| d.has_changes()).count()
159    }
160
161    /// Count of diffs that `apply` can actually act on. Excludes
162    /// informational-only drift (e.g. Custom Attribute metadata-only).
163    pub fn actionable_count(&self) -> usize {
164        self.diffs.iter().filter(|d| d.is_actionable()).count()
165    }
166
167    pub fn destructive_count(&self) -> usize {
168        self.diffs.iter().filter(|d| d.has_destructive()).count()
169    }
170
171    pub fn orphan_count(&self) -> usize {
172        self.diffs.iter().filter(|d| d.is_orphan()).count()
173    }
174
175    pub fn in_sync_count(&self) -> usize {
176        self.diffs.iter().filter(|d| !d.has_changes()).count()
177    }
178}