braze-sync 0.2.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
518
519
520
521
522
523
524
525
526
527
//! Catalog Schema endpoints. See IMPLEMENTATION.md §8.3.

use crate::braze::error::BrazeApiError;
use crate::braze::BrazeClient;
use crate::resource::{Catalog, CatalogField, CatalogFieldType};
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};

/// Wire shape of `GET /catalogs` and `GET /catalogs/{name}` responses.
///
/// **ASSUMED** based on IMPLEMENTATION.md §8.3 and Braze public docs.
/// If the actual shape differs, only this struct and the wrapping
/// logic in this file need to change.
///
/// Fields use serde defaults so an unexpected-but-related shape from
/// Braze (e.g. an extra status field) doesn't break parsing.
#[derive(Debug, Deserialize)]
struct CatalogsResponse {
    #[serde(default)]
    catalogs: Vec<Catalog>,
    /// Pagination cursor returned by Braze when more pages exist.
    /// Its presence is the signal we use to fail closed — see
    /// `list_catalogs`.
    #[serde(default)]
    next_cursor: Option<String>,
}

impl BrazeClient {
    /// `GET /catalogs` — list every catalog schema in the workspace.
    ///
    /// Fails closed on `next_cursor` rather than returning page 1: a
    /// partial view would let `apply` re-create page-2 catalogs and
    /// mis-report drift. Mirrors `list_content_blocks`.
    pub async fn list_catalogs(&self) -> Result<Vec<Catalog>, BrazeApiError> {
        let req = self.get(&["catalogs"]);
        let resp: CatalogsResponse = self.send_json(req).await?;
        if let Some(cursor) = resp.next_cursor.as_deref() {
            if !cursor.is_empty() {
                return Err(BrazeApiError::PaginationNotImplemented {
                    endpoint: "/catalogs",
                    detail: format!(
                        "got {} catalog(s) plus a non-empty next_cursor; \
                         aborting to prevent silent truncation",
                        resp.catalogs.len()
                    ),
                });
            }
        }
        Ok(resp.catalogs)
    }

    /// `GET /catalogs/{name}` — fetch a single catalog schema.
    ///
    /// 404 from Braze and an empty `catalogs` array in the response are
    /// both mapped to [`BrazeApiError::NotFound`] so callers can branch
    /// on "this catalog doesn't exist" without string matching on the
    /// HTTP body.
    pub async fn get_catalog(&self, name: &str) -> Result<Catalog, BrazeApiError> {
        let req = self.get(&["catalogs", name]);
        match self.send_json::<CatalogsResponse>(req).await {
            Ok(resp) => resp
                .catalogs
                .into_iter()
                .next()
                .ok_or_else(|| BrazeApiError::NotFound {
                    resource: format!("catalog '{name}'"),
                }),
            Err(BrazeApiError::Http { status, .. }) if status == StatusCode::NOT_FOUND => {
                Err(BrazeApiError::NotFound {
                    resource: format!("catalog '{name}'"),
                })
            }
            Err(e) => Err(e),
        }
    }

    /// `POST /catalogs/{name}/fields` — add one field to a catalog schema.
    ///
    /// **ASSUMED** wire format `{"fields": [{"name": "...", "type": "..."}]}`
    /// per IMPLEMENTATION.md §8.3 + Braze public docs. v0.1.0 sends one
    /// POST per added field.
    pub async fn add_catalog_field(
        &self,
        catalog_name: &str,
        field: &CatalogField,
    ) -> Result<(), BrazeApiError> {
        let body = AddFieldsRequest {
            fields: vec![WireField {
                name: &field.name,
                field_type: field.field_type,
            }],
        };
        let req = self.post(&["catalogs", catalog_name, "fields"]).json(&body);
        self.send_ok(req).await
    }

    /// `DELETE /catalogs/{name}/fields/{field}` — remove a field. **Destructive**.
    ///
    /// 404 from Braze stays as `Http { status: 404, .. }` rather than
    /// being mapped to `NotFound`. The use case is different from
    /// get_catalog: a 404 here means "the field you wanted to delete is
    /// already gone", which is a state-drift signal the user should see
    /// rather than silently no-op. A future `--ignore-missing` flag in
    /// `apply` can opt into idempotent behavior.
    pub async fn delete_catalog_field(
        &self,
        catalog_name: &str,
        field_name: &str,
    ) -> Result<(), BrazeApiError> {
        let req = self.delete(&["catalogs", catalog_name, "fields", field_name]);
        self.send_ok(req).await
    }
}

#[derive(Serialize)]
struct AddFieldsRequest<'a> {
    fields: Vec<WireField<'a>>,
}

#[derive(Serialize)]
struct WireField<'a> {
    name: &'a str,
    /// Reuses the domain type's snake_case `Serialize` impl so the
    /// wire string stays in sync with `CatalogFieldType` automatically.
    #[serde(rename = "type")]
    field_type: CatalogFieldType,
}

#[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_catalogs_happy_path() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .and(header("authorization", "Bearer test-key"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "catalogs": [
                    {
                        "name": "cardiology",
                        "description": "Cardiology catalog",
                        "fields": [
                            {"name": "id", "type": "string"},
                            {"name": "score", "type": "number"}
                        ]
                    },
                    {
                        "name": "dermatology",
                        "fields": [
                            {"name": "id", "type": "string"}
                        ]
                    }
                ],
                "message": "success"
            })))
            .mount(&server)
            .await;

        let client = make_client(&server);
        let cats = client.list_catalogs().await.unwrap();
        assert_eq!(cats.len(), 2);
        assert_eq!(cats[0].name, "cardiology");
        assert_eq!(cats[0].description.as_deref(), Some("Cardiology catalog"));
        assert_eq!(cats[0].fields.len(), 2);
        assert_eq!(cats[0].fields[1].field_type, CatalogFieldType::Number);
        assert_eq!(cats[1].name, "dermatology");
        assert_eq!(cats[1].description, None);
    }

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

    #[tokio::test]
    async fn list_catalogs_sets_user_agent() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .and(header(
                "user-agent",
                concat!("braze-sync/", env!("CARGO_PKG_VERSION")),
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"catalogs": []})))
            .mount(&server)
            .await;
        let client = make_client(&server);
        client.list_catalogs().await.unwrap();
    }

    #[tokio::test]
    async fn list_catalogs_ignores_unknown_fields_in_response() {
        // Forward compat: a future Braze response with extra fields
        // (top-level and inside catalog entries) should still parse
        // because no struct in the chain uses deny_unknown_fields.
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "catalogs": [
                    {
                        "name": "future",
                        "description": "tomorrow",
                        "future_metadata": {"foo": "bar"},
                        "num_items": 1234,
                        "fields": [
                            {"name": "id", "type": "string", "extra": "ignored"}
                        ]
                    }
                ],
                "future_top_level": {"whatever": true},
                "message": "success"
            })))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let cats = client.list_catalogs().await.unwrap();
        assert_eq!(cats.len(), 1);
        assert_eq!(cats[0].name, "future");
    }

    #[tokio::test]
    async fn list_catalogs_errors_when_next_cursor_present() {
        // Regression guard: v0.2.0 silently returned page 1 here.
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "catalogs": [
                    {"name": "cardiology", "fields": [{"name": "id", "type": "string"}]}
                ],
                "next_cursor": "abc123"
            })))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let err = client.list_catalogs().await.unwrap_err();
        match err {
            BrazeApiError::PaginationNotImplemented { endpoint, detail } => {
                assert_eq!(endpoint, "/catalogs");
                assert!(detail.contains("next_cursor"), "detail: {detail}");
                assert!(detail.contains("1 catalog"), "detail: {detail}");
            }
            other => panic!("expected PaginationNotImplemented, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn list_catalogs_empty_string_cursor_is_treated_as_no_more_pages() {
        // Some paginated APIs return `next_cursor: ""` on the last
        // page instead of omitting the field. Treat that as "no more
        // pages" rather than tripping the fail-closed guard — the
        // alternative would turn every workspace under one page into
        // an error.
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "catalogs": [{"name": "only", "fields": []}],
                "next_cursor": ""
            })))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let cats = client.list_catalogs().await.unwrap();
        assert_eq!(cats.len(), 1);
        assert_eq!(cats[0].name, "only");
    }

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

    #[tokio::test]
    async fn server_error_carries_status_and_body() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(500).set_body_string("internal explosion"))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let err = client.list_catalogs().await.unwrap_err();
        match err {
            BrazeApiError::Http { status, body } => {
                assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
                assert!(body.contains("internal explosion"));
            }
            other => panic!("expected Http, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn retries_on_429_and_succeeds() {
        let server = MockServer::start().await;
        // wiremock matches the *most recently mounted* mock first; the
        // limited 429 mock is mounted second so it preempts until used
        // up, after which the success mock takes over.
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "catalogs": [{"name": "after_retry", "fields": []}]
            })))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "0"))
            .up_to_n_times(1)
            .mount(&server)
            .await;

        let client = make_client(&server);
        let cats = client.list_catalogs().await.unwrap();
        assert_eq!(cats.len(), 1);
        assert_eq!(cats[0].name, "after_retry");
    }

    #[tokio::test]
    async fn retries_exhausted_returns_rate_limit_exhausted() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs"))
            .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "0"))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let err = client.list_catalogs().await.unwrap_err();
        assert!(
            matches!(err, BrazeApiError::RateLimitExhausted),
            "got {err:?}"
        );
    }

    #[tokio::test]
    async fn get_catalog_happy_path() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs/cardiology"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "catalogs": [
                    {"name": "cardiology", "fields": [{"name": "id", "type": "string"}]}
                ]
            })))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let cat = client.get_catalog("cardiology").await.unwrap();
        assert_eq!(cat.name, "cardiology");
        assert_eq!(cat.fields.len(), 1);
    }

    #[tokio::test]
    async fn get_catalog_404_is_mapped_to_not_found() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs/missing"))
            .respond_with(ResponseTemplate::new(404).set_body_string("not found"))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let err = client.get_catalog("missing").await.unwrap_err();
        match err {
            BrazeApiError::NotFound { resource } => assert!(resource.contains("missing")),
            other => panic!("expected NotFound, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn get_catalog_empty_response_array_is_not_found() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/catalogs/ghost"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"catalogs": []})))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let err = client.get_catalog("ghost").await.unwrap_err();
        assert!(matches!(err, BrazeApiError::NotFound { .. }), "got {err:?}");
    }

    #[tokio::test]
    async fn debug_does_not_leak_api_key() {
        let server = MockServer::start().await;
        let client = make_client(&server);
        let dbg = format!("{client:?}");
        assert!(!dbg.contains("test-key"), "leaked api key in: {dbg}");
        assert!(dbg.contains("<redacted>"));
    }

    #[tokio::test]
    async fn add_catalog_field_happy_path_sends_correct_body() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/catalogs/cardiology/fields"))
            .and(header("authorization", "Bearer test-key"))
            .and(body_json(json!({
                "fields": [{"name": "severity_level", "type": "number"}]
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"message": "success"})))
            .mount(&server)
            .await;

        let client = make_client(&server);
        let field = CatalogField {
            name: "severity_level".into(),
            field_type: CatalogFieldType::Number,
        };
        client
            .add_catalog_field("cardiology", &field)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn add_catalog_field_unauthorized_propagates() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/catalogs/cardiology/fields"))
            .respond_with(ResponseTemplate::new(401).set_body_string("invalid key"))
            .mount(&server)
            .await;

        let client = make_client(&server);
        let field = CatalogField {
            name: "x".into(),
            field_type: CatalogFieldType::String,
        };
        let err = client
            .add_catalog_field("cardiology", &field)
            .await
            .unwrap_err();
        assert!(matches!(err, BrazeApiError::Unauthorized), "got {err:?}");
    }

    #[tokio::test]
    async fn add_catalog_field_retries_on_429_then_succeeds() {
        let server = MockServer::start().await;
        // Success mounted first; the limited 429 mock is mounted second
        // and wiremock matches the most-recently-mounted one until it
        // exhausts its `up_to_n_times` budget.
        Mock::given(method("POST"))
            .and(path("/catalogs/cardiology/fields"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"message": "ok"})))
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/catalogs/cardiology/fields"))
            .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "0"))
            .up_to_n_times(1)
            .mount(&server)
            .await;

        let client = make_client(&server);
        let field = CatalogField {
            name: "x".into(),
            field_type: CatalogFieldType::String,
        };
        client
            .add_catalog_field("cardiology", &field)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn delete_catalog_field_happy_path_uses_segment_encoded_path() {
        let server = MockServer::start().await;
        Mock::given(method("DELETE"))
            .and(path("/catalogs/cardiology/fields/legacy_code"))
            .and(header("authorization", "Bearer test-key"))
            .respond_with(ResponseTemplate::new(204))
            .mount(&server)
            .await;

        let client = make_client(&server);
        client
            .delete_catalog_field("cardiology", "legacy_code")
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn delete_catalog_field_server_error_returns_http() {
        let server = MockServer::start().await;
        Mock::given(method("DELETE"))
            .and(path("/catalogs/cardiology/fields/x"))
            .respond_with(ResponseTemplate::new(500).set_body_string("oops"))
            .mount(&server)
            .await;

        let client = make_client(&server);
        let err = client
            .delete_catalog_field("cardiology", "x")
            .await
            .unwrap_err();
        match err {
            BrazeApiError::Http { status, body } => {
                assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
                assert!(body.contains("oops"));
            }
            other => panic!("expected Http, got {other:?}"),
        }
    }
}