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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! Content Block endpoints.
//!
//! Braze identifies content blocks by `content_block_id` but the templates
//! that consume them reference `name`, so the workflow is always
//! list-then-translate. There is no DELETE endpoint, which is why
//! remote-only blocks are surfaced as orphans rather than `Removed` diffs.

use crate::braze::error::BrazeApiError;
use crate::braze::{
    check_duplicate_names, classify_info_message, BrazeClient, InfoMessageClass,
    LIST_SAFETY_CAP_ITEMS,
};
use crate::resource::{ContentBlock, ContentBlockState};
use serde::{Deserialize, Serialize};

const LIST_LIMIT: u32 = 1000;

#[derive(Debug, Clone, PartialEq)]
pub struct ContentBlockSummary {
    pub content_block_id: String,
    pub name: String,
}

impl BrazeClient {
    /// Braze has no `has_more`/cursor field, so we loop until a short page.
    pub async fn list_content_blocks(&self) -> Result<Vec<ContentBlockSummary>, BrazeApiError> {
        let mut all: Vec<ContentBlockListEntry> = Vec::with_capacity(LIST_LIMIT as usize);
        let mut offset: u32 = 0;
        loop {
            let req = self.get(&["content_blocks", "list"]).query(&[
                ("limit", LIST_LIMIT.to_string()),
                ("offset", offset.to_string()),
            ]);
            let resp: ContentBlockListResponse = self.send_json(req).await?;
            let page_len = resp.content_blocks.len();
            if all.len().saturating_add(page_len) > LIST_SAFETY_CAP_ITEMS {
                return Err(BrazeApiError::PaginationNotImplemented {
                    endpoint: "/content_blocks/list",
                    detail: format!("would exceed {LIST_SAFETY_CAP_ITEMS} item safety cap"),
                });
            }
            all.extend(resp.content_blocks);

            if page_len < LIST_LIMIT as usize {
                break;
            }
            offset += LIST_LIMIT;
        }

        check_duplicate_names(
            all.iter().map(|e| e.name.as_str()),
            all.len(),
            "/content_blocks/list",
        )?;

        Ok(all
            .into_iter()
            .map(|w| ContentBlockSummary {
                content_block_id: w.content_block_id,
                name: w.name,
            })
            .collect())
    }

    /// Braze returns 200 with a non-success `message` field for unknown
    /// ids instead of a 404, so we need to discriminate here rather than
    /// relying on HTTP status. Recognised not-found phrases remap to
    /// `NotFound` so callers can branch cleanly; any other non-"success"
    /// message surfaces verbatim as `UnexpectedApiMessage` so a real
    /// failure is not silently swallowed. The wire shapes are ASSUMED
    /// per IMPLEMENTATION.md §8.3 — a blanket "non-success → NotFound"
    /// rule would misclassify every future surprise as a missing id.
    pub async fn get_content_block(&self, id: &str) -> Result<ContentBlock, BrazeApiError> {
        let req = self
            .get(&["content_blocks", "info"])
            .query(&[("content_block_id", id)]);
        let wire: ContentBlockInfoResponse = self.send_json(req).await?;
        match classify_info_message(wire.message.as_deref(), "no content block") {
            InfoMessageClass::Success => {}
            InfoMessageClass::NotFound => {
                return Err(BrazeApiError::NotFound {
                    resource: format!("content_block id '{id}'"),
                });
            }
            InfoMessageClass::Unexpected(message) => {
                return Err(BrazeApiError::UnexpectedApiMessage {
                    endpoint: "/content_blocks/info",
                    message,
                });
            }
        }
        Ok(ContentBlock {
            name: wire.name,
            description: wire.description,
            content: wire.content,
            tags: wire.tags,
            // Braze /info has no state field; default keeps round-trips
            // stable. See diff/content_block.rs syncable_eq for why this
            // can't drift the diff layer.
            state: ContentBlockState::Active,
        })
    }

    pub async fn create_content_block(&self, cb: &ContentBlock) -> Result<String, BrazeApiError> {
        let body = ContentBlockWriteBody {
            content_block_id: None,
            name: &cb.name,
            description: cb.description.as_deref(),
            content: &cb.content,
            tags: &cb.tags,
            // Create is the one time braze-sync communicates an initial
            // state to Braze. On update we omit state entirely — see the
            // note on update_content_block.
            state: Some(cb.state),
        };
        let req = self.post(&["content_blocks", "create"]).json(&body);
        let resp: ContentBlockCreateResponse = self.send_json(req).await?;
        Ok(resp.content_block_id)
    }

    /// Used both for body changes and for the `--archive-orphans` rename
    /// (same id, `[ARCHIVED-...]` name).
    ///
    /// `state` is intentionally omitted from the request body. The
    /// diff layer excludes it from `syncable_eq` (there is no state
    /// field on `/content_blocks/info`, so we cannot read it back and
    /// cannot compare it), and the README documents it as a local-only
    /// field. Forwarding `cb.state` here would let local edits leak
    /// into Braze piggyback-style whenever another field changed, and
    /// could silently overwrite a real remote state that braze-sync
    /// has no way to observe — the same "infinite drift" trap the
    /// honest-orphan design exists to avoid. Leaving state off makes
    /// the wire-level behavior match the documented semantics.
    pub async fn update_content_block(
        &self,
        id: &str,
        cb: &ContentBlock,
    ) -> Result<(), BrazeApiError> {
        let body = ContentBlockWriteBody {
            content_block_id: Some(id),
            name: &cb.name,
            description: cb.description.as_deref(),
            content: &cb.content,
            tags: &cb.tags,
            state: None,
        };
        let req = self.post(&["content_blocks", "update"]).json(&body);
        self.send_ok(req).await
    }
}

#[derive(Debug, Deserialize)]
struct ContentBlockListResponse {
    #[serde(default)]
    content_blocks: Vec<ContentBlockListEntry>,
}

#[derive(Debug, Deserialize)]
struct ContentBlockListEntry {
    content_block_id: String,
    name: String,
}

#[derive(Debug, Deserialize)]
struct ContentBlockInfoResponse {
    #[serde(default)]
    name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    description: Option<String>,
    #[serde(default)]
    content: String,
    #[serde(default)]
    tags: Vec<String>,
    #[serde(default)]
    message: Option<String>,
}

/// Wire body shared by `/content_blocks/create` and `.../update`. Both
/// endpoints are replace-all on the fields serialized here: `tags` is
/// always sent (an empty array drops every tag server-side) and
/// `content` overwrites the current body. `description` is sent when
/// `Some` (including `Some("")` — see `diff::content_block::desc_eq`
/// for why empty-string is semantically equivalent to no description
/// at diff time but still goes over the wire if present locally).
/// `state` is the one field we intentionally do NOT round-trip on
/// update — see the doc comment on `update_content_block`.
#[derive(Serialize)]
struct ContentBlockWriteBody<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    content_block_id: Option<&'a str>,
    name: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<&'a str>,
    content: &'a str,
    tags: &'a [String],
    #[serde(skip_serializing_if = "Option::is_none")]
    state: Option<ContentBlockState>,
}

#[derive(Debug, Deserialize)]
struct ContentBlockCreateResponse {
    content_block_id: String,
}

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

    #[tokio::test]
    async fn list_happy_path() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/content_blocks/list"))
            .and(header("authorization", "Bearer test-key"))
            .and(query_param("limit", "1000"))
            .and(query_param("offset", "0"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "content_blocks": [
                    {"content_block_id": "id-1", "name": "promo"},
                    {"content_block_id": "id-2", "name": "header"}
                ],
                "message": "success"
            })))
            .mount(&server)
            .await;

        let client = make_client(&server);
        let summaries = client.list_content_blocks().await.unwrap();
        assert_eq!(summaries.len(), 2);
        assert_eq!(summaries[0].content_block_id, "id-1");
        assert_eq!(summaries[0].name, "promo");
    }

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

    #[tokio::test]
    async fn list_ignores_unknown_fields() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/content_blocks/list"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "content_blocks": [{
                    "content_block_id": "id-1",
                    "name": "promo",
                    "content_type": "html",
                    "liquid_tag": "{{content_blocks.${promo}}}",
                    "future_metadata": {"foo": "bar"}
                }]
            })))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let summaries = client.list_content_blocks().await.unwrap();
        assert_eq!(summaries.len(), 1);
        assert_eq!(summaries[0].name, "promo");
    }

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

    #[tokio::test]
    async fn info_happy_path() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/content_blocks/info"))
            .and(query_param("content_block_id", "id-1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "content_block_id": "id-1",
                "name": "promo",
                "description": "Promo banner",
                "content": "Hello {{ user.${first_name} }}",
                "tags": ["pr", "dialog"],
                "content_type": "html",
                "message": "success"
            })))
            .mount(&server)
            .await;

        let client = make_client(&server);
        let cb = client.get_content_block("id-1").await.unwrap();
        assert_eq!(cb.name, "promo");
        assert_eq!(cb.description.as_deref(), Some("Promo banner"));
        assert_eq!(cb.content, "Hello {{ user.${first_name} }}");
        assert_eq!(cb.tags, vec!["pr".to_string(), "dialog".to_string()]);
        // Braze does not return state; we default to Active.
        assert_eq!(cb.state, ContentBlockState::Active);
    }

    #[tokio::test]
    async fn info_with_unrecognised_error_message_surfaces_as_unexpected() {
        // Regression guard: before this change, any non-"success"
        // message was blanket-remapped to NotFound, which would silently
        // mask a real server-side failure as a missing id. The classifier
        // now only remaps known not-found phrases, so a novel message
        // has to come back as `UnexpectedApiMessage`.
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/content_blocks/info"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "message": "Internal server hiccup, please retry"
            })))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let err = client.get_content_block("some-id").await.unwrap_err();
        match err {
            BrazeApiError::UnexpectedApiMessage { endpoint, message } => {
                assert_eq!(endpoint, "/content_blocks/info");
                assert!(
                    message.contains("Internal server hiccup"),
                    "message not preserved verbatim: {message}"
                );
            }
            other => panic!("expected UnexpectedApiMessage, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn info_with_unsuccessful_message_is_not_found() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/content_blocks/info"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "message": "No content block with id 'missing' found"
            })))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let err = client.get_content_block("missing").await.unwrap_err();
        match err {
            BrazeApiError::NotFound { resource } => assert!(resource.contains("missing")),
            other => panic!("expected NotFound, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn create_sends_correct_body_and_returns_id() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/content_blocks/create"))
            .and(header("authorization", "Bearer test-key"))
            .and(body_json(json!({
                "name": "promo",
                "description": "Promo banner",
                "content": "Hello",
                "tags": ["pr"],
                "state": "active"
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "content_block_id": "new-id-123",
                "message": "success"
            })))
            .mount(&server)
            .await;

        let client = make_client(&server);
        let cb = ContentBlock {
            name: "promo".into(),
            description: Some("Promo banner".into()),
            content: "Hello".into(),
            tags: vec!["pr".into()],
            state: ContentBlockState::Active,
        };
        let id = client.create_content_block(&cb).await.unwrap();
        assert_eq!(id, "new-id-123");
    }

    #[tokio::test]
    async fn create_omits_description_when_none() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/content_blocks/create"))
            .and(body_json(json!({
                "name": "minimal",
                "content": "x",
                "tags": [],
                "state": "active"
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "content_block_id": "id-min"
            })))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let cb = ContentBlock {
            name: "minimal".into(),
            description: None,
            content: "x".into(),
            tags: vec![],
            state: ContentBlockState::Active,
        };
        client.create_content_block(&cb).await.unwrap();
    }

    #[tokio::test]
    async fn create_forwards_draft_state_to_request_body() {
        // Counterpart to `update_sends_id_in_body_and_omits_state`: on
        // create, state IS sent. The only difference between Active and
        // Draft round-trips is the body_json matcher, so pinning Draft
        // here locks in both serde variants going over the wire.
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/content_blocks/create"))
            .and(body_json(json!({
                "name": "wip",
                "content": "draft body",
                "tags": [],
                "state": "draft"
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "content_block_id": "id-wip"
            })))
            .expect(1)
            .mount(&server)
            .await;
        let client = make_client(&server);
        let cb = ContentBlock {
            name: "wip".into(),
            description: None,
            content: "draft body".into(),
            tags: vec![],
            state: ContentBlockState::Draft,
        };
        client.create_content_block(&cb).await.unwrap();
    }

    #[tokio::test]
    async fn update_sends_id_in_body_and_omits_state() {
        // Pins two invariants: the update body carries
        // `content_block_id` (so Braze knows which block to modify),
        // and it does NOT carry a `state` field. State is local-only
        // per the README and `diff::content_block::syncable_eq`;
        // sending it here would let a local `state: draft` silently
        // overwrite the remote whenever another field happened to
        // change.
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/content_blocks/update"))
            .and(body_json(json!({
                "content_block_id": "id-1",
                "name": "promo",
                "content": "Updated body",
                "tags": []
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"message": "success"})))
            .mount(&server)
            .await;

        let client = make_client(&server);
        // Deliberately pick Draft here: if the client still forwarded
        // state on update, `body_json` above would fail to match
        // because the body would carry `"state": "draft"`.
        let cb = ContentBlock {
            name: "promo".into(),
            description: None,
            content: "Updated body".into(),
            tags: vec![],
            state: ContentBlockState::Draft,
        };
        client.update_content_block("id-1", &cb).await.unwrap();
    }

    #[tokio::test]
    async fn update_unauthorized_propagates() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/content_blocks/update"))
            .respond_with(ResponseTemplate::new(401).set_body_string("invalid"))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let cb = ContentBlock {
            name: "x".into(),
            description: None,
            content: String::new(),
            tags: vec![],
            state: ContentBlockState::Active,
        };
        let err = client.update_content_block("id", &cb).await.unwrap_err();
        assert!(matches!(err, BrazeApiError::Unauthorized), "got {err:?}");
    }

    #[tokio::test]
    async fn update_server_error_is_http() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/content_blocks/update"))
            .respond_with(ResponseTemplate::new(500).set_body_string("oops"))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let cb = ContentBlock {
            name: "x".into(),
            description: None,
            content: String::new(),
            tags: vec![],
            state: ContentBlockState::Active,
        };
        let err = client.update_content_block("id", &cb).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:?}"),
        }
    }

    #[tokio::test]
    async fn list_short_page_is_treated_as_complete() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/content_blocks/list"))
            .and(query_param("offset", "0"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "content_blocks": [
                    {"content_block_id": "id-1", "name": "a"},
                    {"content_block_id": "id-2", "name": "b"}
                ]
            })))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let summaries = client.list_content_blocks().await.unwrap();
        assert_eq!(summaries.len(), 2);
    }

    #[tokio::test]
    async fn list_offset_pagination_across_three_pages() {
        let server = MockServer::start().await;
        let page1: Vec<serde_json::Value> = (0..1000)
            .map(|i| {
                json!({
                    "content_block_id": format!("id-p1-{i}"),
                    "name": format!("p1_{i}")
                })
            })
            .collect();
        let page2: Vec<serde_json::Value> = (0..1000)
            .map(|i| {
                json!({
                    "content_block_id": format!("id-p2-{i}"),
                    "name": format!("p2_{i}")
                })
            })
            .collect();
        let page3: Vec<serde_json::Value> = (0..234)
            .map(|i| {
                json!({
                    "content_block_id": format!("id-p3-{i}"),
                    "name": format!("p3_{i}")
                })
            })
            .collect();
        Mock::given(method("GET"))
            .and(path("/content_blocks/list"))
            .and(query_param("offset", "2000"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(json!({ "content_blocks": page3 })),
            )
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/content_blocks/list"))
            .and(query_param("offset", "1000"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(json!({ "content_blocks": page2 })),
            )
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/content_blocks/list"))
            .and(query_param("offset", "0"))
            .respond_with(
                ResponseTemplate::new(200).set_body_json(json!({ "content_blocks": page1 })),
            )
            .mount(&server)
            .await;

        let client = make_client(&server);
        let summaries = client.list_content_blocks().await.unwrap();
        assert_eq!(summaries.len(), 2234);
        assert_eq!(summaries[0].name, "p1_0");
        assert_eq!(summaries[999].name, "p1_999");
        assert_eq!(summaries[1000].name, "p2_0");
        assert_eq!(summaries[2233].name, "p3_233");
    }

    #[tokio::test]
    async fn list_errors_on_duplicate_name_in_response() {
        // Regression guard: if Braze ever violates its own name-uniqueness
        // contract, the BTreeMap-based name→id index in
        // `diff::compute_content_block_plan` would silently keep only
        // the last id for a duplicate pair, hiding one of the two blocks
        // from every subsequent list/update/archive op. Fail loud instead.
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/content_blocks/list"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "content_blocks": [
                    {"content_block_id": "id-a", "name": "dup"},
                    {"content_block_id": "id-b", "name": "dup"}
                ]
            })))
            .mount(&server)
            .await;
        let client = make_client(&server);
        let err = client.list_content_blocks().await.unwrap_err();
        match err {
            BrazeApiError::DuplicateNameInListResponse { endpoint, name } => {
                assert_eq!(endpoint, "/content_blocks/list");
                assert_eq!(name, "dup");
            }
            other => panic!("expected DuplicateNameInListResponse, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn list_retries_on_429_then_succeeds() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/content_blocks/list"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "content_blocks": [{"content_block_id": "id-x", "name": "x"}]
            })))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/content_blocks/list"))
            .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "0"))
            .up_to_n_times(1)
            .mount(&server)
            .await;
        let client = make_client(&server);
        let summaries = client.list_content_blocks().await.unwrap();
        assert_eq!(summaries.len(), 1);
        assert_eq!(summaries[0].name, "x");
    }
}