Skip to main content

braze_sync/cli/
apply.rs

1//! `braze-sync apply` — the only command that mutates remote state.
2//!
3//! Recomputes the diff via the same code path as `diff`, prints it,
4//! then short-circuits unless `--confirm` is set. Pre-validates
5//! unsupported/destructive ops before any API call, then walks the
6//! plan and aborts on the first write failure. Braze has no
7//! cross-resource transaction, so a mid-loop failure can still leave
8//! earlier writes applied — the pre-validation prevents *known-bad*
9//! plans from firing any writes at all, but it does not promise
10//! cross-write atomicity.
11
12use crate::braze::BrazeClient;
13use crate::config::ResolvedConfig;
14use crate::diff::catalog::CatalogSchemaDiff;
15use crate::diff::content_block::{ContentBlockDiff, ContentBlockIdIndex};
16use crate::diff::custom_attribute::CustomAttributeOp;
17use crate::diff::email_template::{EmailTemplateDiff, EmailTemplateIdIndex};
18use crate::diff::orphan;
19use crate::diff::{DiffOp, DiffSummary, ResourceDiff};
20use crate::error::Error;
21use crate::format::OutputFormat;
22use crate::resource::ResourceKind;
23use anyhow::{anyhow, Context as _};
24use clap::Args;
25use std::path::Path;
26
27use super::diff::{
28    compute_catalog_schema_diffs, compute_content_block_plan, compute_custom_attribute_diffs,
29    compute_email_template_plan,
30};
31use super::{selected_kinds, warn_if_name_excluded};
32
33#[derive(Args, Debug)]
34pub struct ApplyArgs {
35    /// Limit apply to a specific resource kind.
36    #[arg(long, value_enum)]
37    pub resource: Option<ResourceKind>,
38
39    /// When `--resource` is given, optionally restrict to a single named
40    /// resource. Requires `--resource`.
41    #[arg(long, requires = "resource")]
42    pub name: Option<String>,
43
44    /// Actually apply changes. Without this, runs in dry-run mode and
45    /// makes zero write calls to Braze. This is the default for safety.
46    #[arg(long)]
47    pub confirm: bool,
48
49    /// Permit destructive operations (field deletes, etc.). Required in
50    /// addition to `--confirm` for any change that would lose data on
51    /// the Braze side.
52    #[arg(long)]
53    pub allow_destructive: bool,
54
55    /// Archive orphan Content Blocks / Email Templates by prefixing the
56    /// remote name with `[ARCHIVED-YYYY-MM-DD]`. Inert for resource
57    /// kinds that have no orphan concept (e.g. catalog schema).
58    #[arg(long)]
59    pub archive_orphans: bool,
60}
61
62pub async fn run(
63    args: &ApplyArgs,
64    resolved: ResolvedConfig,
65    config_dir: &Path,
66    format: OutputFormat,
67) -> anyhow::Result<()> {
68    let catalogs_root = config_dir.join(&resolved.resources.catalog_schema.path);
69    let content_blocks_root = config_dir.join(&resolved.resources.content_block.path);
70    let email_templates_root = config_dir.join(&resolved.resources.email_template.path);
71    let custom_attributes_path = config_dir.join(&resolved.resources.custom_attribute.path);
72    let client = BrazeClient::from_resolved(&resolved);
73    let kinds = selected_kinds(args.resource, &resolved.resources);
74
75    let mut summary = DiffSummary::default();
76    let mut content_block_id_index: Option<ContentBlockIdIndex> = None;
77    let mut email_template_id_index: Option<EmailTemplateIdIndex> = None;
78    for kind in kinds {
79        if warn_if_name_excluded(kind, args.name.as_deref(), resolved.excludes_for(kind)) {
80            continue;
81        }
82        match kind {
83            ResourceKind::CatalogSchema => {
84                let diffs = compute_catalog_schema_diffs(
85                    &client,
86                    &catalogs_root,
87                    args.name.as_deref(),
88                    resolved.excludes_for(ResourceKind::CatalogSchema),
89                )
90                .await
91                .context("computing catalog_schema plan")?;
92                summary.diffs.extend(diffs);
93            }
94            ResourceKind::ContentBlock => {
95                let (diffs, idx) = compute_content_block_plan(
96                    &client,
97                    &content_blocks_root,
98                    args.name.as_deref(),
99                    resolved.excludes_for(ResourceKind::ContentBlock),
100                )
101                .await
102                .context("computing content_block plan")?;
103                summary.diffs.extend(diffs);
104                content_block_id_index = Some(idx);
105            }
106            ResourceKind::EmailTemplate => {
107                let (diffs, idx) = compute_email_template_plan(
108                    &client,
109                    &email_templates_root,
110                    args.name.as_deref(),
111                    resolved.excludes_for(ResourceKind::EmailTemplate),
112                )
113                .await
114                .context("computing email_template plan")?;
115                summary.diffs.extend(diffs);
116                email_template_id_index = Some(idx);
117            }
118            ResourceKind::CustomAttribute => {
119                let diffs = compute_custom_attribute_diffs(
120                    &client,
121                    &custom_attributes_path,
122                    args.name.as_deref(),
123                    resolved.excludes_for(ResourceKind::CustomAttribute),
124                )
125                .await
126                .context("computing custom_attribute plan")?;
127                summary.diffs.extend(diffs);
128            }
129        }
130    }
131
132    let mode_label = if args.confirm {
133        "Plan:"
134    } else {
135        "Plan (dry-run, pass --confirm to apply):"
136    };
137    eprintln!("{mode_label}");
138    print!("{}", format.formatter().format(&summary));
139
140    if summary.actionable_count() == 0 {
141        if summary.changed_count() > 0 {
142            eprintln!(
143                "No actionable changes to apply \
144                 (informational drift above can be reconciled with `export`)."
145            );
146        } else {
147            eprintln!("No changes to apply.");
148        }
149        return Ok(());
150    }
151
152    if !args.confirm {
153        eprintln!("DRY RUN — pass --confirm to apply these changes.");
154        return Ok(());
155    }
156
157    if summary.destructive_count() > 0 && !args.allow_destructive {
158        return Err(Error::DestructiveBlocked.into());
159    }
160
161    check_for_unsupported_ops(&summary)?;
162
163    // One canonical archive timestamp per run, even across multiple
164    // orphans. UTC (not Local) so two operators running the same archive
165    // on the same wall-clock day from different timezones produce the
166    // same `[ARCHIVED-YYYY-MM-DD]` prefix — determinism across a team
167    // matters more than matching the operator's local calendar.
168    let today = chrono::Utc::now().date_naive();
169
170    let mut applied = 0;
171    let mut ca_deprecate: Vec<&str> = Vec::new();
172    let mut ca_reactivate: Vec<&str> = Vec::new();
173    for diff in &summary.diffs {
174        match diff {
175            ResourceDiff::CatalogSchema(d) => {
176                applied += apply_catalog_schema(&client, d).await?;
177            }
178            ResourceDiff::ContentBlock(d) => {
179                applied += apply_content_block(
180                    &client,
181                    d,
182                    content_block_id_index.as_ref(),
183                    args.archive_orphans,
184                    today,
185                )
186                .await?;
187            }
188            ResourceDiff::EmailTemplate(d) => {
189                applied += apply_email_template(
190                    &client,
191                    d,
192                    email_template_id_index.as_ref(),
193                    args.archive_orphans,
194                    today,
195                )
196                .await?;
197            }
198            ResourceDiff::CustomAttribute(d) => {
199                if let CustomAttributeOp::DeprecationToggled { to, .. } = &d.op {
200                    if *to {
201                        ca_deprecate.push(&d.name);
202                    } else {
203                        ca_reactivate.push(&d.name);
204                    }
205                }
206            }
207        }
208    }
209
210    if !ca_deprecate.is_empty() || !ca_reactivate.is_empty() {
211        applied += apply_custom_attribute_batch(&client, &ca_deprecate, &ca_reactivate).await?;
212    }
213
214    eprintln!("✓ Applied {applied} change(s).");
215    Ok(())
216}
217
218/// Reject ops the API can't actually perform. Runs before any write
219/// call so a statically-known-bad plan cannot fire a partial apply;
220/// runtime write failures can still leave earlier writes in place.
221///
222/// ContentBlock diffs are deliberately not inspected here: every shape
223/// the diff layer can produce (`Added` → create, `Modified` → update,
224/// `orphan` → archive-or-noop) maps to a supported API call, so there
225/// is nothing to statically reject. If a future diff shape is added
226/// (e.g. content-type change with no in-place update), re-evaluate.
227fn check_for_unsupported_ops(summary: &DiffSummary) -> anyhow::Result<()> {
228    for diff in &summary.diffs {
229        if let ResourceDiff::CatalogSchema(d) = diff {
230            match &d.op {
231                DiffOp::Added(_) => {}
232                DiffOp::Removed(_) => {
233                    return Err(anyhow!(
234                        "deleting catalog '{}' (top-level) is not supported by braze-sync; \
235                         only field-level changes can be applied",
236                        d.name
237                    ));
238                }
239                _ => {}
240            }
241            // Field type change would require delete-then-add, which is
242            // data-losing on the field — refuse rather than silently drop.
243            for fd in &d.field_diffs {
244                if let DiffOp::Modified { from, to } = fd {
245                    return Err(anyhow!(
246                        "modifying field '{}' on catalog '{}' (type {} → {}) \
247                         is not supported by braze-sync; the change would be \
248                         data-losing on the field. Drop the field manually \
249                         in the Braze dashboard and re-run `braze-sync apply`",
250                        to.name,
251                        d.name,
252                        from.field_type.as_str(),
253                        to.field_type.as_str(),
254                    ));
255                }
256            }
257        }
258    }
259    Ok(())
260}
261
262async fn apply_content_block(
263    client: &BrazeClient,
264    d: &ContentBlockDiff,
265    id_index: Option<&ContentBlockIdIndex>,
266    archive_orphans: bool,
267    today: chrono::NaiveDate,
268) -> anyhow::Result<usize> {
269    // Orphans only mutate remote state when --archive-orphans is set;
270    // otherwise the plan-print is the entire effect.
271    if d.orphan {
272        if !archive_orphans {
273            return Ok(0);
274        }
275        let id_index = id_index.ok_or_else(|| {
276            anyhow!("internal: content_block id index missing for orphan apply path")
277        })?;
278        let id = id_index.get(&d.name).ok_or_else(|| {
279            anyhow!(
280                "internal: orphan '{}' missing from id index — list/diff drift",
281                d.name
282            )
283        })?;
284        let archived = orphan::archive_name(today, &d.name);
285        if archived == d.name {
286            return Ok(0);
287        }
288        // Update endpoint requires the full body, not a partial. Safe
289        // re: state — `get_content_block` defaults state to Active
290        // (Braze /info has no state field) and `update_content_block`
291        // omits state from the wire body, so this rename can never
292        // toggle the remote state as a side effect. If either of those
293        // invariants ever changes, the orphan path needs revisiting.
294        let mut cb = client
295            .get_content_block(id)
296            .await
297            .with_context(|| format!("fetching content block '{}' for archive rename", d.name))?;
298        cb.name = archived;
299        tracing::info!(
300            content_block = %d.name,
301            new_name = %cb.name,
302            "archiving orphan content block"
303        );
304        client.update_content_block(id, &cb).await?;
305        return Ok(1);
306    }
307
308    match &d.op {
309        DiffOp::Added(cb) => {
310            tracing::info!(content_block = %cb.name, "creating content block");
311            let _ = client.create_content_block(cb).await?;
312            Ok(1)
313        }
314        DiffOp::Modified { to, .. } => {
315            let id_index = id_index.ok_or_else(|| {
316                anyhow!("internal: content_block id index missing for modified apply path")
317            })?;
318            let id = id_index.get(&to.name).ok_or_else(|| {
319                anyhow!(
320                    "internal: modified content block '{}' missing from id index",
321                    to.name
322                )
323            })?;
324            tracing::info!(content_block = %to.name, "updating content block");
325            client.update_content_block(id, to).await?;
326            Ok(1)
327        }
328        // The diff layer routes remote-only blocks through the orphan
329        // flag, never as a Removed op.
330        DiffOp::Removed(_) => {
331            unreachable!("diff layer routes content block removals through orphan")
332        }
333        DiffOp::Unchanged => Ok(0),
334    }
335}
336
337async fn apply_catalog_schema(
338    client: &BrazeClient,
339    d: &CatalogSchemaDiff,
340) -> anyhow::Result<usize> {
341    // `POST /catalogs` carries the full schema, so the per-field loop
342    // below is skipped for `Added` to avoid duplicate field POSTs.
343    if let DiffOp::Added(cat) = &d.op {
344        tracing::info!(catalog = %d.name, "creating new catalog");
345        client
346            .create_catalog(cat)
347            .await
348            .with_context(|| format!("creating catalog '{}'", d.name))?;
349        return Ok(1);
350    }
351
352    let mut count = 0;
353    for fd in &d.field_diffs {
354        match fd {
355            DiffOp::Added(f) => {
356                tracing::info!(
357                    catalog = %d.name,
358                    field = %f.name,
359                    field_type = f.field_type.as_str(),
360                    "adding catalog field"
361                );
362                client.add_catalog_field(&d.name, f).await?;
363                count += 1;
364            }
365            DiffOp::Removed(f) => {
366                tracing::info!(
367                    catalog = %d.name,
368                    field = %f.name,
369                    "deleting catalog field"
370                );
371                client.delete_catalog_field(&d.name, &f.name).await?;
372                count += 1;
373            }
374            DiffOp::Modified { .. } => {
375                return Err(anyhow!(
376                    "internal: Modified field op should have been rejected \
377                     by check_for_unsupported_ops"
378                ));
379            }
380            DiffOp::Unchanged => {}
381        }
382    }
383    Ok(count)
384}
385
386async fn apply_email_template(
387    client: &BrazeClient,
388    d: &EmailTemplateDiff,
389    id_index: Option<&EmailTemplateIdIndex>,
390    archive_orphans: bool,
391    today: chrono::NaiveDate,
392) -> anyhow::Result<usize> {
393    if d.orphan {
394        if !archive_orphans {
395            return Ok(0);
396        }
397        let id_index = id_index.ok_or_else(|| {
398            anyhow!("internal: email_template id index missing for orphan apply path")
399        })?;
400        let id = id_index.get(&d.name).ok_or_else(|| {
401            anyhow!(
402                "internal: orphan '{}' missing from id index — list/diff drift",
403                d.name
404            )
405        })?;
406        let archived = orphan::archive_name(today, &d.name);
407        if archived == d.name {
408            return Ok(0);
409        }
410        let mut et = client
411            .get_email_template(id)
412            .await
413            .with_context(|| format!("fetching email template '{}' for archive rename", d.name))?;
414        et.name = archived;
415        tracing::info!(
416            email_template = %d.name,
417            new_name = %et.name,
418            "archiving orphan email template"
419        );
420        client.update_email_template(id, &et).await?;
421        return Ok(1);
422    }
423
424    match &d.op {
425        DiffOp::Added(et) => {
426            tracing::info!(email_template = %et.name, "creating email template");
427            let _ = client.create_email_template(et).await?;
428            Ok(1)
429        }
430        DiffOp::Modified { to, .. } => {
431            let id_index = id_index.ok_or_else(|| {
432                anyhow!("internal: email_template id index missing for modified apply path")
433            })?;
434            let id = id_index.get(&to.name).ok_or_else(|| {
435                anyhow!(
436                    "internal: modified email template '{}' missing from id index",
437                    to.name
438                )
439            })?;
440            tracing::info!(email_template = %to.name, "updating email template");
441            client.update_email_template(id, to).await?;
442            Ok(1)
443        }
444        DiffOp::Removed(_) => {
445            unreachable!("diff layer routes email template removals through orphan")
446        }
447        DiffOp::Unchanged => Ok(0),
448    }
449}
450
451/// Batch custom attribute deprecation toggles by direction so we issue
452/// at most two API calls. Each batch is reported to stderr on success so
453/// the user can tell what was committed if a later batch fails.
454async fn apply_custom_attribute_batch(
455    client: &BrazeClient,
456    to_deprecate: &[&str],
457    to_reactivate: &[&str],
458) -> anyhow::Result<usize> {
459    let mut applied = 0;
460    for (names, blocklisted, verb) in [
461        (to_deprecate, true, "deprecating"),
462        (to_reactivate, false, "reactivating"),
463    ] {
464        if names.is_empty() {
465            continue;
466        }
467        tracing::info!(attributes = ?names, "{verb} custom attributes");
468        client
469            .set_custom_attribute_blocklist(names, blocklisted)
470            .await
471            .with_context(|| format!("{verb} custom attributes"))?;
472        let n = names.len();
473        let past = if blocklisted {
474            "deprecated"
475        } else {
476            "reactivated"
477        };
478        eprintln!("  ✓ {past} {n} custom attribute(s)");
479        applied += n;
480    }
481
482    Ok(applied)
483}