vibemail 1.2.0

Official VibeMail SDK for transactional email
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
//! Official Rust SDK for the [VibeMail](https://vibemail.ai) transactional
//! email API.
//!
//! The surface here is limited to endpoints the API actually serves. Methods
//! for analytics and listing existed in an earlier draft and returned 404
//! against every deployment; they are absent rather than broken, and will
//! return when the endpoints do.
//!
//! ```no_run
//! # async fn run() -> Result<(), vibemail::Error> {
//! use vibemail::{SendRequest, VibeMail};
//!
//! let client = VibeMail::new(std::env::var("VIBEMAIL_API_KEY").unwrap());
//!
//! let sent = client
//!     .send(
//!         SendRequest::new("ada@example.com")
//!             .subject("Welcome")
//!             .text("Glad you're here."),
//!     )
//!     .await?;
//!
//! println!("{} {}", sent.id, sent.status);
//! # Ok(())
//! # }
//! ```

#![forbid(unsafe_code)]
#![warn(missing_docs)]

use std::collections::HashMap;
use std::time::Duration;

use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;

/// Version of this SDK, reported in the User-Agent.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

const DEFAULT_BASE_URL: &str = "https://vibemail.ai";
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
const DEFAULT_MAX_RETRIES: u32 = 2;

/// Anything that can go wrong talking to the API.
#[derive(Debug, Error)]
pub enum Error {
    /// A non-2xx response.
    #[error("vibemail: api {status}: {message}")]
    Api {
        /// HTTP status code.
        status: u16,
        /// The API's `error` field when the body was JSON, otherwise the raw body.
        message: String,
        /// The full response body.
        body: String,
        /// The server's requested wait on a 429, if it sent one.
        retry_after: Option<Duration>,
    },

    /// The request never completed, connection refused, DNS failure, timeout.
    #[error("vibemail: request failed: {0}")]
    Request(#[from] reqwest::Error),

    /// The response was not the shape we expected.
    #[error("vibemail: decoding response: {0}")]
    Decode(#[from] serde_json::Error),

    /// `to` held something other than exactly one address.
    ///
    /// The API delivers to a single recipient and derives per-domain rate
    /// limiting from it; silently taking the first of several would drop the
    /// rest with no error anywhere.
    #[error("vibemail: {0}")]
    InvalidRecipient(String),
}

impl Error {
    /// Whether repeating the request could plausibly succeed.
    pub fn is_retryable(&self) -> bool {
        match self {
            Error::Api { status, .. } => *status == 429 || *status >= 500,
            Error::Request(err) => err.is_timeout() || err.is_connect(),
            _ => false,
        }
    }

    /// The HTTP status, when the failure came from the API.
    pub fn status(&self) -> Option<u16> {
        match self {
            Error::Api { status, .. } => Some(*status),
            _ => None,
        }
    }
}

/// One outbound message.
///
/// Built fluently; only `to` is required, though the API also needs a subject
/// unless a template supplies one.
#[derive(Debug, Clone, Serialize, Default)]
pub struct SendRequest {
    /// Recipient. Exactly one, see [`VibeMail::batch`] for several.
    pub to: String,
    /// Sender. Must be an address your account owns.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Subject line.
    pub subject: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Plain-text body. Always send one alongside `html`.
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// HTML body.
    pub html: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Name or id of a stored template. Explicit fields win over it.
    pub template: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Values substituted into the template.
    pub variables: Option<HashMap<String, String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Labels recorded with the send.
    pub tags: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Open tracking for HTML sends. Defaults to on.
    pub track_opens: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Click tracking for HTML sends. Defaults to on.
    pub track_clicks: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// RFC 3339 timestamp or a relative offset such as `"in 2 hours"`.
    pub scheduled_at: Option<String>,
}

impl SendRequest {
    /// A message to one recipient.
    pub fn new(to: impl Into<String>) -> Self {
        Self {
            to: to.into(),
            ..Default::default()
        }
    }

    /// Set the sender. Must be an address your account owns.
    pub fn from(mut self, from: impl Into<String>) -> Self {
        self.from = Some(from.into());
        self
    }

    /// Set the subject.
    pub fn subject(mut self, subject: impl Into<String>) -> Self {
        self.subject = Some(subject.into());
        self
    }

    /// Set the plain-text body.
    pub fn text(mut self, text: impl Into<String>) -> Self {
        self.text = Some(text.into());
        self
    }

    /// Set the HTML body.
    pub fn html(mut self, html: impl Into<String>) -> Self {
        self.html = Some(html.into());
        self
    }

    /// Send using a stored template.
    pub fn template(mut self, template: impl Into<String>) -> Self {
        self.template = Some(template.into());
        self
    }

    /// Substitute a value into the template.
    pub fn variable(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.variables
            .get_or_insert_with(HashMap::new)
            .insert(key.into(), value.into());
        self
    }

    /// Attach labels to the send.
    pub fn tags(mut self, tags: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.tags = Some(tags.into_iter().map(Into::into).collect());
        self
    }

    /// Turn open tracking on or off.
    pub fn track_opens(mut self, on: bool) -> Self {
        self.track_opens = Some(on);
        self
    }

    /// Turn click tracking on or off.
    pub fn track_clicks(mut self, on: bool) -> Self {
        self.track_clicks = Some(on);
        self
    }

    /// Schedule the send, up to 30 days ahead.
    ///
    /// Takes an RFC 3339 timestamp or a relative offset such as `"in 2 hours"`.
    pub fn scheduled_at(mut self, when: impl Into<String>) -> Self {
        self.scheduled_at = Some(when.into());
        self
    }

    fn validate(&self, index: Option<usize>) -> Result<(), Error> {
        let where_ = index.map_or(String::new(), |i| format!("emails[{i}]: "));
        if self.to.trim().is_empty() {
            return Err(Error::InvalidRecipient(format!(
                "{where_}`to` must contain a recipient address"
            )));
        }
        if self.to.contains(',') {
            return Err(Error::InvalidRecipient(format!(
                "{where_}`to` takes a single address, use batch() to send to several \
                 recipients, since one message addressed to many would disclose the list \
                 to all of them"
            )));
        }
        Ok(())
    }
}

/// The API's acknowledgement. Means the message was accepted, not delivered.
#[derive(Debug, Clone, Deserialize)]
pub struct SendResponse {
    /// Identifier for the send.
    pub id: String,
    /// `queued`, `sent`, `scheduled`, `delayed`, ...
    pub status: String,
    /// When a scheduled send is due.
    #[serde(default)]
    pub scheduled_at: Option<String>,
}

/// One entry per submitted message, in order.
#[derive(Debug, Clone, Deserialize)]
pub struct BatchResponse {
    /// Per-message outcomes.
    pub data: Vec<BatchResult>,
}

/// An accepted message, or the reason it was rejected.
#[derive(Debug, Clone, Deserialize)]
pub struct BatchResult {
    /// Identifier, when the message was accepted.
    #[serde(default)]
    pub id: Option<String>,
    /// Outcome for this entry.
    pub status: String,
    /// Why this entry was rejected, when it was.
    #[serde(default)]
    pub error: Option<String>,
}

/// A template stored on the account.
#[derive(Debug, Clone, Deserialize)]
pub struct Template {
    /// Identifier.
    pub id: i64,
    /// Name used to reference it from a send.
    pub name: String,
    /// Subject line, before variable substitution.
    pub subject: String,
    /// HTML body, before variable substitution.
    #[serde(default)]
    pub html_body: Option<String>,
    /// Plain-text body, before variable substitution.
    #[serde(default)]
    pub text_body: Option<String>,
}

/// A page of results. `total` counts everything matching, not just this page.
#[derive(Debug, Clone, Deserialize)]
pub struct Page<T> {
    /// Always `"list"`.
    #[serde(default)]
    pub object: String,
    /// Total matching records, across all pages.
    #[serde(default)]
    pub total: i64,
    /// Page size that was applied.
    #[serde(default)]
    pub limit: i64,
    /// Offset that was applied.
    #[serde(default)]
    pub offset: i64,
    /// This page of records.
    #[serde(default = "Vec::new")]
    pub data: Vec<T>,
}

/// Paging for the list endpoints.
#[derive(Debug, Clone, Default)]
pub struct ListOptions {
    /// Defaults to 50, capped at 100.
    pub limit: Option<u32>,
    /// Records to skip.
    pub offset: Option<u32>,
    /// Matches address or name. Only honoured by contacts.
    pub search: Option<String>,
}

impl ListOptions {
    /// Empty options: server defaults apply.
    pub fn new() -> Self {
        Self::default()
    }

    /// Page size.
    pub fn limit(mut self, n: u32) -> Self {
        self.limit = Some(n);
        self
    }

    /// Records to skip.
    pub fn offset(mut self, n: u32) -> Self {
        self.offset = Some(n);
        self
    }

    /// Match address or name.
    pub fn search(mut self, term: impl Into<String>) -> Self {
        self.search = Some(term.into());
        self
    }

    fn to_query(&self) -> String {
        let mut parts: Vec<String> = Vec::new();
        if let Some(n) = self.limit {
            parts.push(format!("limit={n}"));
        }
        if let Some(n) = self.offset {
            parts.push(format!("offset={n}"));
        }
        if let Some(term) = &self.search {
            parts.push(format!("search={}", urlencode(term)));
        }
        if parts.is_empty() {
            String::new()
        } else {
            format!("?{}", parts.join("&"))
        }
    }
}

/// A DNS record to publish so a domain can be verified.
#[derive(Debug, Clone, Deserialize)]
pub struct DnsRecord {
    /// Record type, such as `TXT` or `MX`.
    pub r#type: String,
    /// The record name to create, fully qualified.
    pub host: String,
    /// Record value.
    pub value: String,
    /// Priority, for record types that take one.
    #[serde(default)]
    pub priority: Option<i32>,
}

/// A sending domain on the account.
#[derive(Debug, Clone, Deserialize)]
pub struct Domain {
    /// Identifier.
    pub id: i64,
    /// The domain itself.
    pub domain: String,
    /// Whether the DNS records have been seen to resolve.
    #[serde(default)]
    pub is_verified: bool,
    /// Token embedded in the verification record.
    #[serde(default)]
    pub verification_token: Option<String>,
    /// When it was added.
    #[serde(default)]
    pub created_at: Option<String>,
    /// Records to publish, keyed by purpose: `verification`, `mx`, `spf`,
    /// `dmarc`. Returned by `domain` and `create_domain`.
    #[serde(default)]
    pub dns_records: Option<HashMap<String, DnsRecord>>,
}

/// A stored contact.
#[derive(Debug, Clone, Deserialize)]
pub struct Contact {
    /// Identifier.
    pub id: i64,
    /// Address.
    pub email: String,
    /// Display name.
    #[serde(default)]
    pub name: Option<String>,
    /// Free-form notes.
    #[serde(default)]
    pub notes: Option<String>,
    /// When it was stored.
    #[serde(default)]
    pub created_at: Option<String>,
}

/// An address that will not be sent to.
#[derive(Debug, Clone, Deserialize)]
pub struct Suppression {
    /// Address.
    pub email: String,
    /// Why it was suppressed, such as `hard_bounce` or `complaint`.
    #[serde(default)]
    pub reason: Option<String>,
    /// When it was suppressed.
    #[serde(default)]
    pub created_at: Option<String>,
}

/// The outcome of a delete.
#[derive(Debug, Clone, Deserialize)]
pub struct Deleted {
    /// Always true when the call succeeded.
    #[serde(default)]
    pub deleted: bool,
    /// The domain that was removed, when it was a domain.
    #[serde(default)]
    pub domain: Option<String>,
    /// The address that was removed, when it was a contact.
    #[serde(default)]
    pub email: Option<String>,
}

/// Client for the VibeMail API.
///
/// Cloning is cheap: the underlying connection pool is shared.
#[derive(Clone)]
pub struct VibeMail {
    client: reqwest::Client,
    base_url: String,
    api_key: String,
    max_retries: u32,
}

impl VibeMail {
    /// A client for the given API key.
    ///
    /// # Panics
    /// If the HTTP client cannot be built, which in practice means the platform
    /// TLS backend is unavailable. Use [`VibeMail::try_new`] to handle that.
    pub fn new(api_key: impl Into<String>) -> Self {
        Self::try_new(api_key).expect("failed to build the HTTP client")
    }

    /// A client for the given API key, surfacing HTTP-client construction errors.
    pub fn try_new(api_key: impl Into<String>) -> Result<Self, Error> {
        Ok(Self {
            client: reqwest::Client::builder()
                .timeout(DEFAULT_TIMEOUT)
                .build()?,
            base_url: DEFAULT_BASE_URL.to_string(),
            api_key: api_key.into(),
            max_retries: DEFAULT_MAX_RETRIES,
        })
    }

    /// Point the client at a different deployment.
    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = base_url.into().trim_end_matches('/').to_string();
        self
    }

    /// How many times a 429 or 5xx is retried. Zero disables retrying.
    pub fn with_max_retries(mut self, retries: u32) -> Self {
        self.max_retries = retries;
        self
    }

    /// Supply your own [`reqwest::Client`], for a custom transport, proxy or
    /// timeout.
    pub fn with_http_client(mut self, client: reqwest::Client) -> Self {
        self.client = client;
        self
    }

    /// Send one message.
    pub async fn send(&self, request: SendRequest) -> Result<SendResponse, Error> {
        request.validate(None)?;
        self.request(reqwest::Method::POST, "/v1/emails", Some(&request), None)
            .await
    }

    /// Send one message with an idempotency key.
    ///
    /// A retry carrying the same key returns the original result instead of
    /// sending a second copy, which matters because a client that times out
    /// cannot otherwise tell whether the message went out.
    pub async fn send_idempotent(
        &self,
        request: SendRequest,
        idempotency_key: impl AsRef<str>,
    ) -> Result<SendResponse, Error> {
        request.validate(None)?;
        self.request(
            reqwest::Method::POST,
            "/v1/emails",
            Some(&request),
            Some(idempotency_key.as_ref()),
        )
        .await
    }

    /// Send several messages in one request, one recipient each.
    pub async fn batch(&self, emails: Vec<SendRequest>) -> Result<BatchResponse, Error> {
        for (index, email) in emails.iter().enumerate() {
            email.validate(Some(index))?;
        }

        #[derive(Serialize)]
        struct Body {
            emails: Vec<SendRequest>,
        }

        self.request(
            reqwest::Method::POST,
            "/v1/emails/batch",
            Some(&Body { emails }),
            None,
        )
        .await
    }

    /// Look up a send by the id returned from [`VibeMail::send`].
    pub async fn get(&self, id: &str) -> Result<SendResponse, Error> {
        let path = format!("/v1/emails/{}", urlencode(id));
        self.request::<(), _>(reqwest::Method::GET, &path, None, None)
            .await
    }

    /// Withdraw a scheduled send, while it is still scheduled.
    pub async fn cancel(&self, id: &str) -> Result<SendResponse, Error> {
        let path = format!("/v1/emails/{}/cancel", urlencode(id));
        self.request::<(), _>(reqwest::Method::POST, &path, None, None)
            .await
    }

    /// Templates stored on the account.
    pub async fn templates(&self) -> Result<Vec<Template>, Error> {
        self.request::<(), _>(reqwest::Method::GET, "/v1/templates", None, None)
            .await
    }

    /// A page of sending domains.
    pub async fn domains(&self, opts: ListOptions) -> Result<Page<Domain>, Error> {
        let path = format!("/v1/domains{}", opts.to_query());
        self.request::<(), _>(reqwest::Method::GET, &path, None, None)
            .await
    }

    /// One domain, including the DNS records that verify it.
    pub async fn domain(&self, id: &str) -> Result<Domain, Error> {
        let path = format!("/v1/domains/{}", urlencode(id));
        self.request::<(), _>(reqwest::Method::GET, &path, None, None)
            .await
    }

    /// Add a domain. The reply carries the records to publish; it stays
    /// unverified until they resolve.
    pub async fn create_domain(&self, domain: &str) -> Result<Domain, Error> {
        #[derive(Serialize)]
        struct Body<'a> {
            domain: &'a str,
        }
        self.request(
            reqwest::Method::POST,
            "/v1/domains",
            Some(&Body { domain }),
            None,
        )
        .await
    }

    /// Remove a domain. Mail already sent from it is unaffected.
    pub async fn delete_domain(&self, id: &str) -> Result<Deleted, Error> {
        let path = format!("/v1/domains/{}", urlencode(id));
        self.request::<(), _>(reqwest::Method::DELETE, &path, None, None)
            .await
    }

    /// A page of contacts. Set [`ListOptions::search`] to match address or name.
    pub async fn contacts(&self, opts: ListOptions) -> Result<Page<Contact>, Error> {
        let path = format!("/v1/contacts{}", opts.to_query());
        self.request::<(), _>(reqwest::Method::GET, &path, None, None)
            .await
    }

    /// Store a contact.
    pub async fn create_contact(
        &self,
        email: &str,
        name: Option<&str>,
        notes: Option<&str>,
    ) -> Result<Contact, Error> {
        #[derive(Serialize)]
        struct Body<'a> {
            email: &'a str,
            #[serde(skip_serializing_if = "Option::is_none")]
            name: Option<&'a str>,
            #[serde(skip_serializing_if = "Option::is_none")]
            notes: Option<&'a str>,
        }
        self.request(
            reqwest::Method::POST,
            "/v1/contacts",
            Some(&Body { email, name, notes }),
            None,
        )
        .await
    }

    /// Forget a contact.
    pub async fn delete_contact(&self, id: &str) -> Result<Deleted, Error> {
        let path = format!("/v1/contacts/{}", urlencode(id));
        self.request::<(), _>(reqwest::Method::DELETE, &path, None, None)
            .await
    }

    /// Addresses that will not be sent to: hard bounces, complaints and manual
    /// blocks. A send to one of these is dropped rather than attempted.
    pub async fn suppressions(&self, opts: ListOptions) -> Result<Page<Suppression>, Error> {
        let path = format!("/v1/suppressions{}", opts.to_query());
        self.request::<(), _>(reqwest::Method::GET, &path, None, None)
            .await
    }

    async fn request<B, T>(
        &self,
        method: reqwest::Method,
        path: &str,
        body: Option<&B>,
        idempotency_key: Option<&str>,
    ) -> Result<T, Error>
    where
        B: Serialize + ?Sized,
        T: for<'de> Deserialize<'de>,
    {
        let url = format!("{}{path}", self.base_url);
        let mut attempt = 0;

        loop {
            let mut req = self
                .client
                .request(method.clone(), &url)
                .bearer_auth(&self.api_key)
                .header("Accept", "application/json")
                .header("User-Agent", format!("vibemail-rust/{VERSION}"));
            if let Some(key) = idempotency_key {
                req = req.header("Idempotency-Key", key);
            }
            if let Some(payload) = body {
                req = req.json(payload);
            }

            let outcome = req.send().await;
            let error = match outcome {
                Ok(res) => {
                    let status = res.status();
                    let retry_after = res
                        .headers()
                        .get(reqwest::header::RETRY_AFTER)
                        .and_then(|v| v.to_str().ok())
                        .and_then(|v| v.parse::<u64>().ok())
                        .map(Duration::from_secs);
                    let text = res.text().await?;

                    if status.is_success() {
                        // A 200 with no body is a valid acknowledgement; give
                        // serde an empty object rather than failing on "".
                        let raw = if text.trim().is_empty() { "{}" } else { &text };
                        return Ok(serde_json::from_str(raw)?);
                    }

                    let message = serde_json::from_str::<Value>(&text)
                        .ok()
                        .and_then(|v| v.get("error")?.as_str().map(str::to_owned))
                        .unwrap_or_else(|| text.chars().take(200).collect());

                    Error::Api {
                        status: status.as_u16(),
                        message,
                        body: text,
                        retry_after,
                    }
                }
                Err(err) => Error::Request(err),
            };

            if !error.is_retryable() || attempt >= self.max_retries {
                return Err(error);
            }

            // Honour Retry-After when the server sets it, capped so a long hint
            // cannot stall a caller who did not choose that.
            let delay = match &error {
                Error::Api {
                    retry_after: Some(d),
                    ..
                } => (*d).min(Duration::from_secs(30)),
                _ => backoff(attempt),
            };
            tokio::time::sleep(delay).await;
            attempt += 1;
        }
    }
}

fn backoff(attempt: u32) -> Duration {
    Duration::from_millis((500u64 << attempt).min(8_000))
}

/// Percent-encode a path segment. Ids come from the API, but an id echoed back
/// from user input must not be able to reshape the path.
fn urlencode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for byte in s.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(byte as char);
            }
            _ => out.push_str(&format!("%{byte:02X}")),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn builder_only_sets_what_was_asked_for() {
        let req = SendRequest::new("a@example.com").subject("Hi");
        let json = serde_json::to_value(&req).unwrap();

        assert_eq!(json["to"], "a@example.com");
        assert_eq!(json["subject"], "Hi");
        assert!(json.get("html").is_none());
        assert!(json.get("tags").is_none());
        assert!(json.get("scheduled_at").is_none());
    }

    #[test]
    fn explicit_false_tracking_is_serialized() {
        let json = serde_json::to_value(SendRequest::new("a@e.com").track_opens(false)).unwrap();
        assert_eq!(json["track_opens"], false);
    }

    #[test]
    fn variables_accumulate() {
        let req = SendRequest::new("a@e.com")
            .variable("name", "Ada")
            .variable("plan", "pro");
        let vars = req.variables.unwrap();
        assert_eq!(vars.get("name").map(String::as_str), Some("Ada"));
        assert_eq!(vars.get("plan").map(String::as_str), Some("pro"));
    }

    #[test]
    fn empty_recipient_is_rejected() {
        let err = SendRequest::new("   ").validate(None).unwrap_err();
        assert!(matches!(err, Error::InvalidRecipient(_)));
    }

    #[test]
    fn comma_joined_recipients_are_rejected() {
        let err = SendRequest::new("a@e.com,b@e.com")
            .validate(None)
            .unwrap_err();
        assert!(err.to_string().contains("batch()"), "{err}");
    }

    #[test]
    fn batch_validation_names_the_offending_entry() {
        let err = SendRequest::new("").validate(Some(3)).unwrap_err();
        assert!(err.to_string().contains("emails[3]"), "{err}");
    }

    #[test]
    fn retryable_classification() {
        let api = |status| Error::Api {
            status,
            message: String::new(),
            body: String::new(),
            retry_after: None,
        };
        assert!(api(429).is_retryable());
        assert!(api(500).is_retryable());
        assert!(api(503).is_retryable());
        assert!(!api(400).is_retryable());
        assert!(!api(422).is_retryable());
        assert!(!Error::InvalidRecipient("x".into()).is_retryable());
    }

    #[test]
    fn status_is_exposed_for_api_errors_only() {
        let api = Error::Api {
            status: 422,
            message: String::new(),
            body: String::new(),
            retry_after: None,
        };
        assert_eq!(api.status(), Some(422));
        assert_eq!(Error::InvalidRecipient("x".into()).status(), None);
    }

    #[test]
    fn backoff_grows_then_caps() {
        assert_eq!(backoff(0), Duration::from_millis(500));
        assert_eq!(backoff(1), Duration::from_millis(1000));
        assert_eq!(backoff(2), Duration::from_millis(2000));
        assert_eq!(backoff(20), Duration::from_millis(8000));
    }

    #[test]
    fn path_segments_are_escaped() {
        assert_eq!(urlencode("a/b"), "a%2Fb");
        assert_eq!(urlencode("plain-id_1.2~3"), "plain-id_1.2~3");
        assert_eq!(urlencode("../etc"), "..%2Fetc");
    }

    #[test]
    fn base_url_trailing_slash_is_trimmed() {
        let c = VibeMail::new("k").with_base_url("http://localhost:8080///");
        assert_eq!(c.base_url, "http://localhost:8080");
    }
}