braze-sync 0.14.1

GitOps CLI for managing Braze configuration as code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! YAML schema types for `values/<env>.yaml` per RFC §2.2.
//!
//! Phase 1 scope: deserialize the file and validate built-in shapes
//! (lid: `[a-z0-9]{8,}`, cb_id: `cb[0-9]+`). Resolution wiring per
//! resource/field comes in Phase 2 / Phase 3.
//!
//! Forward-compat policy: `#[serde(deny_unknown_fields)]` is intentionally
//! NOT applied here — values files are user-edited and the RFC permits
//! omitting empty namespaces (e.g. `preheader: {}`). The strict shape
//! check happens via `validate()` after parsing.

use regex_lite::Regex;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

use crate::error::{Error, Result};

/// Currently supported values file schema version (RFC §5 Edge cases).
pub const SUPPORTED_VERSION: u32 = 1;

/// Top-level `values/<env>.yaml` document.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ValuesFile {
    pub version: u32,
    #[serde(default, skip_serializing_if = "Globals::is_empty")]
    pub globals: Globals,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub content_block: BTreeMap<String, ContentBlockValues>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub email_template: BTreeMap<String, EmailTemplateValues>,
}

/// Cross-resource per-env values. Currently only `custom` is populated;
/// future extension may add `globals.lid` / `globals.cb_id` (RFC §2.2).
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct Globals {
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub custom: BTreeMap<String, CustomEntry>,
}

impl Globals {
    fn is_empty(&self) -> bool {
        self.custom.is_empty()
    }
}

/// Resource-scoped values for a content_block. content_block bodies are
/// single-body so `lid` / `cb_id` / `custom` live directly under the
/// resource (RFC §2.2).
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ContentBlockValues {
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub lid: BTreeMap<String, LidEntry>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub cb_id: BTreeMap<String, CbIdEntry>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub custom: BTreeMap<String, CustomEntry>,
}

/// Resource-scoped values for an email_template. `lid` / `cb_id` are
/// field-scoped because lid is a per-occurrence ID tied to in-field
/// position. `custom` lives at the resource root only (RFC §2.2).
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct EmailTemplateValues {
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub custom: BTreeMap<String, CustomEntry>,
    #[serde(default, skip_serializing_if = "FieldValues::is_empty")]
    pub subject: FieldValues,
    #[serde(default, skip_serializing_if = "FieldValues::is_empty")]
    pub preheader: FieldValues,
    #[serde(default, skip_serializing_if = "FieldValues::is_empty")]
    pub body_html: FieldValues,
    #[serde(default, skip_serializing_if = "FieldValues::is_empty")]
    pub body_plaintext: FieldValues,
}

/// lid / cb_id namespaces for one email_template field.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct FieldValues {
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub lid: BTreeMap<String, LidEntry>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub cb_id: BTreeMap<String, CbIdEntry>,
}

impl FieldValues {
    fn is_empty(&self) -> bool {
        self.lid.is_empty() && self.cb_id.is_empty()
    }
}

/// A lid value with its correlation anchor. `url` is set for fields that
/// have a hyperlink context (HTML / plaintext bodies); `anchor` is set
/// for URL-less fields (subject / preheader). Either may be absent for
/// skeletons generated by `templatize` (RFC §2.7).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct LidEntry {
    /// `null` is allowed for skeletons (RFC §2.7) and is preserved on
    /// save so the skeleton marker survives the round trip.
    pub value: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub anchor: Option<String>,
}

/// A cb_id value. Key = referenced content_block name slug (RFC §3 Q3).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CbIdEntry {
    pub value: Option<String>,
}

/// User-managed custom value; opaque string. No shape validation per
/// RFC §9 Q3 (custom is left to user).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CustomEntry {
    pub value: Option<String>,
}

fn lid_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| Regex::new(r"^[a-z0-9]{8,}$").expect("lid regex is valid"))
}

fn cb_id_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| Regex::new(r"^cb[0-9]+$").expect("cb_id regex is valid"))
}

fn key_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| Regex::new(r"^[a-z][a-z0-9_]*$").expect("key regex is valid"))
}

impl ValuesFile {
    /// Load and validate a values file from disk.
    ///
    /// Errors:
    /// - I/O failure → `Error::Io`
    /// - YAML parse failure → `Error::YamlParse`
    /// - Unsupported `version` or built-in shape violation →
    ///   `Error::InvalidFormat` (RFC §5 Edge cases)
    pub fn load(path: &Path) -> Result<Self> {
        let raw = std::fs::read_to_string(path)?;
        let parsed: ValuesFile =
            serde_norway::from_str(&raw).map_err(|source| Error::YamlParse {
                path: path.to_path_buf(),
                source,
            })?;
        parsed.validate(path)?;
        Ok(parsed)
    }

    /// Serialize and atomically write to `path` (tmp + `rename(2)`).
    /// Used by `export` (Phase 3) to write back updated values entries.
    ///
    /// Note: this round-trips through `serde_norway` and therefore does
    /// NOT preserve user comments or quoting style. Phase 3 accepts this
    /// trade-off; a comment-preserving editor is out of scope for v0.14.
    pub fn save(&self, path: &Path) -> Result<()> {
        self.validate(path)?;
        let yaml = serde_norway::to_string(self).map_err(|e| Error::InvalidFormat {
            path: path.to_path_buf(),
            message: format!("serializing values file: {e}"),
        })?;
        crate::fs::write_atomic(path, yaml.as_bytes())
    }

    /// Validate version + built-in value shapes. Skeleton entries
    /// (`value: null`) are skipped (RFC §2.7 / §5).
    pub fn validate(&self, path: &Path) -> Result<()> {
        if self.version != SUPPORTED_VERSION {
            return Err(Error::InvalidFormat {
                path: path.to_path_buf(),
                message: format!(
                    "values file requires schema version {} (found: {})",
                    SUPPORTED_VERSION, self.version
                ),
            });
        }

        let mut errors: Vec<String> = Vec::new();

        // globals.custom — only key shape; values are opaque.
        for key in self.globals.custom.keys() {
            check_key(key, "globals.custom", &mut errors);
        }

        for (cb_name, cb) in &self.content_block {
            let scope = format!("content_block.{}", cb_name);
            check_lid_map(&cb.lid, &scope, &mut errors);
            check_cb_id_map(&cb.cb_id, &scope, &mut errors);
            for key in cb.custom.keys() {
                check_key(key, &format!("{scope}.custom"), &mut errors);
            }
        }

        for (et_name, et) in &self.email_template {
            let root = format!("email_template.{}", et_name);
            for key in et.custom.keys() {
                check_key(key, &format!("{root}.custom"), &mut errors);
            }
            for (field_name, field) in [
                ("subject", &et.subject),
                ("preheader", &et.preheader),
                ("body_html", &et.body_html),
                ("body_plaintext", &et.body_plaintext),
            ] {
                let field_scope = format!("{root}.{field_name}");
                check_lid_map(&field.lid, &field_scope, &mut errors);
                check_cb_id_map(&field.cb_id, &field_scope, &mut errors);
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(Error::InvalidFormat {
                path: path.to_path_buf(),
                message: errors.join("; "),
            })
        }
    }
}

fn check_key(key: &str, scope: &str, errors: &mut Vec<String>) {
    if !key_re().is_match(key) {
        errors.push(format!("{scope}: key '{key}' must match [a-z][a-z0-9_]*"));
    }
}

fn check_lid_map(map: &BTreeMap<String, LidEntry>, scope: &str, errors: &mut Vec<String>) {
    for (key, entry) in map {
        check_key(key, &format!("{scope}.lid"), errors);
        if let Some(value) = &entry.value {
            if !lid_re().is_match(value) {
                errors.push(format!(
                    "{scope}.lid.{key}: value '{value}' must match ^[a-z0-9]{{8,}}$"
                ));
            }
        }
    }
}

fn check_cb_id_map(map: &BTreeMap<String, CbIdEntry>, scope: &str, errors: &mut Vec<String>) {
    for (key, entry) in map {
        check_key(key, &format!("{scope}.cb_id"), errors);
        if let Some(value) = &entry.value {
            if !cb_id_re().is_match(value) {
                errors.push(format!(
                    "{scope}.cb_id.{key}: value '{value}' must match ^cb[0-9]+$"
                ));
            }
        }
    }
}

/// Default location resolver. RFC §2.1: `values_file` config field wins,
/// otherwise `values/<env>.yaml` relative to the config dir.
pub fn default_values_path(config_dir: &Path, env: &str) -> PathBuf {
    config_dir.join("values").join(format!("{env}.yaml"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    fn write_temp(contents: &str) -> NamedTempFile {
        let mut f = NamedTempFile::new().unwrap();
        f.write_all(contents.as_bytes()).unwrap();
        f
    }

    #[test]
    fn parses_minimal_valid_file() {
        let f = write_temp("version: 1\n");
        let parsed = ValuesFile::load(f.path()).unwrap();
        assert_eq!(parsed.version, 1);
        assert!(parsed.content_block.is_empty());
        assert!(parsed.email_template.is_empty());
    }

    #[test]
    fn parses_full_shape() {
        let f = write_temp(
            r#"
version: 1
globals:
  custom:
    api_host:
      value: api-prod.example.com
content_block:
  cb_promo_banner:
    lid:
      spring_sale:
        value: ai8kexrxcp03
        url: https://example.com/spring-sale
    cb_id:
      cb_promo_image:
        value: cb42
    custom:
      banner_variant:
        value: A
email_template:
  welcome:
    custom:
      user_segment_id:
        value: seg_prod_42
    subject:
      lid:
        promo_subject:
          value: lidsubj42
          anchor: "{{promo_code}}"
    body_html:
      lid:
        cta:
          value: lidhtml42
          url: https://example.com/welcome/cta
      cb_id:
        cb_promo_image:
          value: cb42
"#,
        );
        let parsed = ValuesFile::load(f.path()).unwrap();
        assert_eq!(parsed.version, 1);
        assert_eq!(
            parsed.globals.custom["api_host"].value.as_deref(),
            Some("api-prod.example.com")
        );
        let cb = &parsed.content_block["cb_promo_banner"];
        assert_eq!(cb.lid["spring_sale"].value.as_deref(), Some("ai8kexrxcp03"));
        assert_eq!(
            cb.lid["spring_sale"].url.as_deref(),
            Some("https://example.com/spring-sale")
        );
        assert_eq!(cb.cb_id["cb_promo_image"].value.as_deref(), Some("cb42"));
        let et = &parsed.email_template["welcome"];
        assert_eq!(
            et.custom["user_segment_id"].value.as_deref(),
            Some("seg_prod_42")
        );
        assert_eq!(
            et.subject.lid["promo_subject"].anchor.as_deref(),
            Some("{{promo_code}}")
        );
        assert_eq!(et.body_html.lid["cta"].value.as_deref(), Some("lidhtml42"));
    }

    #[test]
    fn rejects_unsupported_version() {
        let f = write_temp("version: 2\n");
        let err = ValuesFile::load(f.path()).unwrap_err();
        match err {
            Error::InvalidFormat { message, .. } => {
                assert!(message.contains("schema version"));
            }
            other => panic!("expected InvalidFormat, got {other:?}"),
        }
    }

    #[test]
    fn rejects_bad_lid_shape() {
        let f = write_temp(
            r#"
version: 1
content_block:
  cb:
    lid:
      foo:
        value: TOO_SHORT
"#,
        );
        let err = ValuesFile::load(f.path()).unwrap_err();
        match err {
            Error::InvalidFormat { message, .. } => {
                assert!(message.contains("content_block.cb.lid.foo"));
                assert!(message.contains("TOO_SHORT"));
            }
            other => panic!("expected InvalidFormat, got {other:?}"),
        }
    }

    #[test]
    fn rejects_bad_cb_id_shape() {
        let f = write_temp(
            r#"
version: 1
content_block:
  cb:
    cb_id:
      target:
        value: not_cb_form
"#,
        );
        let err = ValuesFile::load(f.path()).unwrap_err();
        match err {
            Error::InvalidFormat { message, .. } => {
                assert!(message.contains("cb_id.target"));
            }
            other => panic!("expected InvalidFormat, got {other:?}"),
        }
    }

    #[test]
    fn accepts_null_value_skeleton() {
        // RFC §2.7: templatize-generated skeleton uses `value: null` to
        // signal "needs export". Shape check must skip these.
        let f = write_temp(
            r#"
version: 1
content_block:
  cb:
    lid:
      foo:
        value: null
        url: https://example.com/foo
"#,
        );
        let parsed = ValuesFile::load(f.path()).unwrap();
        assert!(parsed.content_block["cb"].lid["foo"].value.is_none());
    }

    #[test]
    fn rejects_bad_key_shape() {
        let f = write_temp(
            r#"
version: 1
content_block:
  cb:
    custom:
      BadKey:
        value: x
"#,
        );
        let err = ValuesFile::load(f.path()).unwrap_err();
        match err {
            Error::InvalidFormat { message, .. } => {
                assert!(message.contains("BadKey"));
            }
            other => panic!("expected InvalidFormat, got {other:?}"),
        }
    }

    #[test]
    fn yaml_parse_error_surfaces() {
        let f = write_temp(":\n  unbalanced");
        let err = ValuesFile::load(f.path()).unwrap_err();
        assert!(matches!(err, Error::YamlParse { .. }));
    }

    #[test]
    fn save_omits_empty_namespaces_and_none_anchors() {
        // Regression: without skip_serializing_if, exporting a single
        // content_block bloated the file with `globals.custom: {}`,
        // every empty field on every email_template, and `anchor: null`
        // on every lid entry. Pin the lean output shape so users don't
        // see noisy diffs after their first export.
        let mut vf = ValuesFile {
            version: 1,
            ..Default::default()
        };
        let mut cb = ContentBlockValues::default();
        cb.lid.insert(
            "cta".to_string(),
            LidEntry {
                value: Some("newlidvalue1".into()),
                url: Some("https://example.com/cta".into()),
                anchor: None,
            },
        );
        vf.content_block.insert("promo".into(), cb);

        let s = serde_norway::to_string(&vf).unwrap();
        assert!(!s.contains("globals"), "empty globals leaked: {s}");
        assert!(
            !s.contains("email_template"),
            "empty email_template leaked: {s}"
        );
        assert!(!s.contains("cb_id"), "empty cb_id leaked: {s}");
        assert!(!s.contains("custom"), "empty custom leaked: {s}");
        assert!(!s.contains("anchor"), "None anchor leaked: {s}");
        assert!(s.contains("value: newlidvalue1"));
        assert!(s.contains("url: https://example.com/cta"));
    }

    #[test]
    fn skeleton_null_value_survives_round_trip() {
        // RFC §2.7 skeletons use `value: null` as the "needs export"
        // marker. The save path must preserve it (not omit it).
        let f = write_temp(
            r#"version: 1
content_block:
  cb:
    lid:
      foo:
        value: null
        url: https://example.com/foo
"#,
        );
        let parsed = ValuesFile::load(f.path()).unwrap();
        let s = serde_norway::to_string(&parsed).unwrap();
        assert!(
            s.contains("value: null") || s.contains("value: ~"),
            "skeleton null marker must survive save, got: {s}"
        );
    }

    #[test]
    fn default_path_uses_env_name() {
        let p = default_values_path(Path::new("/tmp/repo"), "prod");
        assert_eq!(p, PathBuf::from("/tmp/repo/values/prod.yaml"));
    }
}