braze-sync 0.8.0

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
//! Custom Attribute endpoints.
//!
//! Custom Attributes are managed in **registry mode**: the only list
//! endpoint is `GET /custom_attributes`, and the only mutation is
//! toggling the `blocklisted` (deprecated) flag.
//!
//! Braze creates Custom Attributes implicitly when `/users/track`
//! receives data containing a previously-unseen attribute name. There
//! is no declarative "create attribute" API.
//!
//! ## Wire contract
//!
//! Pagination is cursor-based via the RFC 5988 `Link: rel="next"` header;
//! the response body does not carry the cursor. `limit` is not a
//! supported query parameter — page size is fixed at 50 server-side.
//! `deprecated` is derived from `status == STATUS_BLOCKLISTED`.

use crate::braze::error::BrazeApiError;
use crate::braze::BrazeClient;
use crate::resource::{CustomAttribute, CustomAttributeType};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;

/// At Braze's fixed 50 items/page this covers 10k attributes.
const SAFETY_CAP_PAGES: usize = 200;

/// Wire value of the `status` field that indicates a deprecated attribute.
const STATUS_BLOCKLISTED: &str = "Blocklisted";

impl BrazeClient {
    /// List all Custom Attributes from Braze. Follows RFC 5988 `Link`
    /// headers through every page until the server stops returning
    /// `rel="next"`.
    pub async fn list_custom_attributes(&self) -> Result<Vec<CustomAttribute>, BrazeApiError> {
        let mut all: Vec<CustomAttribute> = Vec::new();
        let mut seen: HashSet<String> = HashSet::new();
        let mut next_url: Option<String> = None;

        for _ in 0..SAFETY_CAP_PAGES {
            let req = match &next_url {
                None => self.get(&["custom_attributes"]),
                Some(url) => self.get_absolute(url)?,
            };
            let (resp, next): (CustomAttributeListResponse, _) =
                self.send_json_with_next_link(req).await?;

            // Dedup across pages — per-page checks would miss a name that
            // recurs on a later cursor page.
            for w in resp.attributes {
                if !seen.insert(w.name.clone()) {
                    return Err(BrazeApiError::DuplicateNameInListResponse {
                        endpoint: "/custom_attributes",
                        name: w.name,
                    });
                }
                all.push(wire_to_domain(w));
            }

            match next {
                // Guard against a server that echoes the same cursor —
                // without this the safety-cap is the only exit.
                Some(url) if Some(&url) == next_url.as_ref() => {
                    return Err(BrazeApiError::PaginationNotImplemented {
                        endpoint: "/custom_attributes",
                        detail: format!("server returned same next link twice: {url}"),
                    });
                }
                Some(url) => next_url = Some(url),
                None => return Ok(all),
            }
        }

        Err(BrazeApiError::PaginationNotImplemented {
            endpoint: "/custom_attributes",
            detail: format!("exceeded {SAFETY_CAP_PAGES} page safety cap"),
        })
    }

    /// Toggle the `blocklisted` (deprecated) flag on one or more Custom
    /// Attributes. This is the **only** write operation braze-sync
    /// performs for Custom Attributes.
    pub async fn set_custom_attribute_blocklist(
        &self,
        names: &[&str],
        blocklisted: bool,
    ) -> Result<(), BrazeApiError> {
        let body = BlocklistRequest {
            custom_attribute_names: names,
            blocklisted,
        };
        let req = self.post(&["custom_attributes", "blocklist"]).json(&body);
        self.send_ok(req).await
    }
}

fn wire_to_domain(w: CustomAttributeWire) -> CustomAttribute {
    CustomAttribute {
        name: w.name,
        attribute_type: wire_data_type_to_domain(w.data_type.as_deref()),
        description: w.description,
        deprecated: w
            .status
            .as_deref()
            .map(|s| s.eq_ignore_ascii_case(STATUS_BLOCKLISTED))
            .unwrap_or(false),
    }
}

/// Map the Braze wire `data_type` string to our domain enum.
///
/// Braze returns values like `"String (Automatically Detected)"` — we
/// match on the **leading whitespace-delimited token** (case-insensitive)
/// to ignore the suffix. Unknown values default to `String` with a warn.
fn wire_data_type_to_domain(raw: Option<&str>) -> CustomAttributeType {
    let lowered = raw.unwrap_or("").to_ascii_lowercase();

    // `"object array"` must be checked before the leading-token match:
    // `split_whitespace().next()` would return `"object"` alone and
    // mis-classify Object-Array attributes as Object.
    if lowered.starts_with("object array") {
        return CustomAttributeType::ObjectArray;
    }

    let leading = lowered.split_whitespace().next().unwrap_or("");
    match leading {
        "string" => CustomAttributeType::String,
        "number" | "integer" | "float" => CustomAttributeType::Number,
        "boolean" | "bool" => CustomAttributeType::Boolean,
        "time" | "date" => CustomAttributeType::Time,
        "array" => CustomAttributeType::Array,
        "object" => CustomAttributeType::Object,
        "object_array" => CustomAttributeType::ObjectArray,
        "" => {
            tracing::debug!("Braze data_type is absent, defaulting to string");
            CustomAttributeType::String
        }
        unknown => {
            tracing::warn!(
                data_type = unknown,
                raw = ?raw,
                "unknown Braze data_type, defaulting to string"
            );
            CustomAttributeType::String
        }
    }
}

#[derive(Debug, Deserialize)]
struct CustomAttributeListResponse {
    #[serde(default)]
    attributes: Vec<CustomAttributeWire>,
}

#[derive(Debug, Deserialize)]
struct CustomAttributeWire {
    #[serde(default)]
    name: String,
    #[serde(default)]
    description: Option<String>,
    #[serde(default)]
    data_type: Option<String>,
    /// `"Active"` or `"Blocklisted"`. Absent for older workspaces —
    /// treated as not blocklisted.
    #[serde(default)]
    status: Option<String>,
}

#[derive(Debug, Serialize)]
struct BlocklistRequest<'a> {
    custom_attribute_names: &'a [&'a str],
    blocklisted: bool,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::braze::test_client as make_client;
    use serde_json::json;
    use wiremock::matchers::{body_json, header, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    async fn list_happy_path() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/custom_attributes"))
            .and(header("authorization", "Bearer test-key"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "attributes": [
                    {
                        "name": "last_visit_date",
                        "description": "Most recent visit",
                        "data_type": "Date (Automatically Detected)",
                        "array_length": null,
                        "status": "Active",
                        "tag_names": []
                    },
                    {
                        "name": "legacy_segment",
                        "description": null,
                        "data_type": "String",
                        "array_length": null,
                        "status": "Blocklisted",
                        "tag_names": []
                    }
                ],
                "message": "success"
            })))
            .mount(&server)
            .await;

        let client = make_client(&server);
        let attrs = client.list_custom_attributes().await.unwrap();
        assert_eq!(attrs.len(), 2);
        assert_eq!(attrs[0].name, "last_visit_date");
        assert_eq!(attrs[0].attribute_type, CustomAttributeType::Time);
        assert_eq!(attrs[0].description.as_deref(), Some("Most recent visit"));
        assert!(!attrs[0].deprecated);
        assert_eq!(attrs[1].name, "legacy_segment");
        assert!(attrs[1].deprecated);
    }

    #[tokio::test]
    async fn list_empty_array() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/custom_attributes"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"attributes": []})))
            .mount(&server)
            .await;
        let client = make_client(&server);
        assert!(client.list_custom_attributes().await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn list_ignores_unknown_fields() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/custom_attributes"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "attributes": [{
                    "name": "foo",
                    "data_type": "String",
                    "future_field": "ignored"
                }]
            })))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let attrs = client.list_custom_attributes().await.unwrap();
        assert_eq!(attrs.len(), 1);
        assert_eq!(attrs[0].name, "foo");
    }

    #[tokio::test]
    async fn list_unauthorized() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/custom_attributes"))
            .respond_with(ResponseTemplate::new(401).set_body_string("invalid"))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let err = client.list_custom_attributes().await.unwrap_err();
        assert!(matches!(err, BrazeApiError::Unauthorized), "got {err:?}");
    }

    #[tokio::test]
    async fn list_follows_link_header_through_pages() {
        let server = MockServer::start().await;
        let base = server.uri();
        let page_2_link = format!(
            "<{base}/custom_attributes?cursor=p2>; rel=\"next\"",
            base = base
        );

        // Page 2 (mounted first so cursor-bearing requests hit it).
        Mock::given(method("GET"))
            .and(path("/custom_attributes"))
            .and(wiremock::matchers::query_param("cursor", "p2"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "attributes": [
                    {"name": "c", "data_type": "String", "status": "Active"}
                ],
                "message": "success"
            })))
            .mount(&server)
            .await;
        // Page 1 — no cursor query param, carries a Link header to p2.
        Mock::given(method("GET"))
            .and(path("/custom_attributes"))
            .respond_with(
                ResponseTemplate::new(200)
                    .insert_header("link", page_2_link.as_str())
                    .set_body_json(json!({
                        "attributes": [
                            {"name": "a", "data_type": "String", "status": "Active"},
                            {"name": "b", "data_type": "Number", "status": "Active"}
                        ],
                        "message": "success"
                    })),
            )
            .up_to_n_times(1)
            .mount(&server)
            .await;

        let client = make_client(&server);
        let attrs = client.list_custom_attributes().await.unwrap();
        assert_eq!(attrs.len(), 3);
        assert_eq!(attrs[0].name, "a");
        assert_eq!(attrs[2].name, "c");
    }

    #[tokio::test]
    async fn list_maps_data_types_correctly() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/custom_attributes"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "attributes": [
                    {"name": "s", "data_type": "String (Automatically Detected)"},
                    {"name": "n", "data_type": "Number"},
                    {"name": "b", "data_type": "Boolean"},
                    {"name": "t", "data_type": "Date"},
                    {"name": "a", "data_type": "Array"},
                    {"name": "o", "data_type": "Object"},
                    {"name": "oa", "data_type": "Object Array"}
                ]
            })))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let attrs = client.list_custom_attributes().await.unwrap();
        assert_eq!(attrs[0].attribute_type, CustomAttributeType::String);
        assert_eq!(attrs[1].attribute_type, CustomAttributeType::Number);
        assert_eq!(attrs[2].attribute_type, CustomAttributeType::Boolean);
        assert_eq!(attrs[3].attribute_type, CustomAttributeType::Time);
        assert_eq!(attrs[4].attribute_type, CustomAttributeType::Array);
        assert_eq!(attrs[5].attribute_type, CustomAttributeType::Object);
        assert_eq!(attrs[6].attribute_type, CustomAttributeType::ObjectArray);
    }

    #[tokio::test]
    async fn deprecated_is_derived_from_status_blocklisted() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/custom_attributes"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "attributes": [
                    {"name": "active", "data_type": "String", "status": "Active"},
                    {"name": "blocked", "data_type": "String", "status": "Blocklisted"},
                    {"name": "missing", "data_type": "String"}
                ]
            })))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let attrs = client.list_custom_attributes().await.unwrap();
        assert!(!attrs[0].deprecated);
        assert!(attrs[1].deprecated);
        assert!(!attrs[2].deprecated);
    }

    #[tokio::test]
    async fn blocklist_sends_correct_body() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/custom_attributes/blocklist"))
            .and(header("authorization", "Bearer test-key"))
            .and(body_json(json!({
                "custom_attribute_names": ["legacy_segment"],
                "blocklisted": true
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "message": "success"
            })))
            .expect(1)
            .mount(&server)
            .await;

        let client = make_client(&server);
        client
            .set_custom_attribute_blocklist(&["legacy_segment"], true)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn list_errors_on_duplicate_name() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/custom_attributes"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "attributes": [
                    {"name": "dup", "data_type": "String"},
                    {"name": "unique", "data_type": "Number"},
                    {"name": "dup", "data_type": "String"}
                ]
            })))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let err = client.list_custom_attributes().await.unwrap_err();
        match err {
            BrazeApiError::DuplicateNameInListResponse { endpoint, name } => {
                assert_eq!(endpoint, "/custom_attributes");
                assert_eq!(name, "dup");
            }
            other => panic!("expected DuplicateNameInListResponse, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn list_errors_on_duplicate_name_across_pages() {
        // Same name appears on page 1 and page 2 — must be detected even
        // though each individual page is internally unique.
        let server = MockServer::start().await;
        let base = server.uri();
        let page_2_link = format!("<{base}/custom_attributes?cursor=p2>; rel=\"next\"");

        Mock::given(method("GET"))
            .and(path("/custom_attributes"))
            .and(wiremock::matchers::query_param("cursor", "p2"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "attributes": [
                    {"name": "dup", "data_type": "String", "status": "Active"}
                ]
            })))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/custom_attributes"))
            .respond_with(
                ResponseTemplate::new(200)
                    .insert_header("link", page_2_link.as_str())
                    .set_body_json(json!({
                        "attributes": [
                            {"name": "dup", "data_type": "String", "status": "Active"}
                        ]
                    })),
            )
            .up_to_n_times(1)
            .mount(&server)
            .await;

        let client = make_client(&server);
        let err = client.list_custom_attributes().await.unwrap_err();
        match err {
            BrazeApiError::DuplicateNameInListResponse { endpoint, name } => {
                assert_eq!(endpoint, "/custom_attributes");
                assert_eq!(name, "dup");
            }
            other => panic!("expected DuplicateNameInListResponse, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn list_errors_when_cursor_repeats() {
        // Server echoes the same `rel="next"` cursor forever — without
        // cycle detection we'd loop to SAFETY_CAP_PAGES.
        let server = MockServer::start().await;
        let base = server.uri();
        let self_link = format!("<{base}/custom_attributes?cursor=loop>; rel=\"next\"");

        Mock::given(method("GET"))
            .and(path("/custom_attributes"))
            .respond_with(
                ResponseTemplate::new(200)
                    .insert_header("link", self_link.as_str())
                    .set_body_json(json!({ "attributes": [] })),
            )
            .mount(&server)
            .await;

        let client = make_client(&server);
        let err = client.list_custom_attributes().await.unwrap_err();
        assert!(
            matches!(err, BrazeApiError::PaginationNotImplemented { .. }),
            "got {err:?}"
        );
    }

    #[tokio::test]
    async fn blocklist_unblocklist() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/custom_attributes/blocklist"))
            .and(body_json(json!({
                "custom_attribute_names": ["reactivated"],
                "blocklisted": false
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "message": "success"
            })))
            .expect(1)
            .mount(&server)
            .await;

        let client = make_client(&server);
        client
            .set_custom_attribute_blocklist(&["reactivated"], false)
            .await
            .unwrap();
    }
}