clicksend-rs 0.1.1

Unofficial ClickSend SDK for Rust (async + optional blocking).
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
//! Async API client.
//!
//! Construct with [`Client::new`] for defaults, or [`Client::builder`] for
//! tunables (timeout, retry, custom HTTP client). Then dispatch through
//! one of the namespace handles ([`Client::sms`], [`Client::account`], …).

use std::{fmt, sync::Arc, time::Duration};

use reqwest::{Client as HttpClient, Method, RequestBuilder};
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::{
    errors::ClickSendError,
    types::{
        AccountData, ApiEnvelope, Email, MmsMessageCollection, Paginated, SmsHistoryItem,
        SmsInboundItem, SmsMessageCollection, SmsReceiptItem, SmsSendData, VoiceMessageCollection,
    },
};

const DEFAULT_BASE_URL: &str = "https://rest.clicksend.com/v3";
const DEFAULT_USER_AGENT: &str = concat!("clicksend-rs/", env!("CARGO_PKG_VERSION"));

/// Retry policy for transient errors (429, 5xx, request timeouts).
///
/// Default is **no retry** (`max_attempts = 1`). Build with
/// [`RetryConfig::enabled`] to opt in.
///
/// Honors `Retry-After` on 429s when present; otherwise uses exponential
/// backoff capped at `max_backoff`.
#[derive(Debug, Clone, Copy)]
pub struct RetryConfig {
    /// Total attempts (1 = no retry, 3 = original + 2 retries).
    pub max_attempts: u32,
    /// First retry delay.
    pub initial_backoff: Duration,
    /// Multiplier between retries.
    pub backoff_multiplier: f64,
    /// Cap on backoff.
    pub max_backoff: Duration,
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            max_attempts: 1,
            initial_backoff: Duration::from_millis(500),
            backoff_multiplier: 2.0,
            max_backoff: Duration::from_secs(30),
        }
    }
}

impl RetryConfig {
    /// Quick-config with N attempts and otherwise default backoff.
    pub fn enabled(max_attempts: u32) -> Self {
        Self {
            max_attempts,
            ..Default::default()
        }
    }
}

pub(crate) struct Inner {
    pub username: String,
    pub api_key: String,
    pub base_url: String,
    pub http: HttpClient,
    pub retry: RetryConfig,
}

/// Async ClickSend client. Cheap to clone (`Arc` inside).
///
/// `Debug` redacts the api key.
#[derive(Clone)]
pub struct Client {
    pub(crate) inner: Arc<Inner>,
}

/// Custom Debug — never leak the api_key.
impl fmt::Debug for Client {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Client")
            .field("username", &self.inner.username)
            .field("api_key", &"<redacted>")
            .field("base_url", &self.inner.base_url)
            .field("retry", &self.inner.retry)
            .finish()
    }
}

impl Client {
    /// New client with default settings (30s timeout, 10s connect, no retry,
    /// `clicksend-rs/<version>` UA). Use [`Client::builder`] for more control.
    ///
    /// # Panics
    /// If `username` or `api_key` is empty. For non-panicking construction,
    /// use [`ClientBuilder::build`].
    pub fn new(username: impl Into<String>, api_key: impl Into<String>) -> Self {
        ClientBuilder::new(username, api_key).build().expect("default client builds")
    }

    /// Configurable builder — set timeout, retry, custom HTTP client, base URL.
    pub fn builder(
        username: impl Into<String>,
        api_key: impl Into<String>,
    ) -> ClientBuilder {
        ClientBuilder::new(username, api_key)
    }

    // ───────── namespace handles ─────────

    /// `/account` endpoints.
    pub fn account(&self) -> AccountApi<'_> {
        AccountApi { c: self }
    }
    /// `/sms/*` endpoints.
    pub fn sms(&self) -> SmsApi<'_> {
        SmsApi { c: self }
    }
    /// `/mms/*` endpoints.
    pub fn mms(&self) -> MmsApi<'_> {
        MmsApi { c: self }
    }
    /// `/voice/*` endpoints.
    pub fn voice(&self) -> VoiceApi<'_> {
        VoiceApi { c: self }
    }
    /// `/email/*` endpoints.
    pub fn email(&self) -> EmailApi<'_> {
        EmailApi { c: self }
    }

    // ───────── escape hatch ─────────

    /// Pre-authenticated [`RequestBuilder`] for any path, for endpoints not
    /// yet wrapped by this crate. `path` is appended to the base URL.
    ///
    /// ```no_run
    /// # async fn run(client: clicksend_rs::Client) -> Result<(), Box<dyn std::error::Error>> {
    /// let resp: serde_json::Value = client
    ///     .raw_request(reqwest::Method::GET, "/contacts/lists")
    ///     .send().await?
    ///     .json().await?;
    /// # Ok(()) }
    /// ```
    pub fn raw_request(&self, method: Method, path: &str) -> RequestBuilder {
        self.inner
            .http
            .request(method, format!("{}{}", self.inner.base_url, path))
            .basic_auth(&self.inner.username, Some(&self.inner.api_key))
    }

    // ───────── private plumbing ─────────

    fn req(&self, method: Method, path: &str) -> RequestBuilder {
        self.raw_request(method, path)
    }

    pub(crate) async fn execute<T: DeserializeOwned>(
        &self,
        method: Method,
        path: &str,
        query: Option<&[(&str, &str)]>,
        body: Option<&dyn ErasedSerialize>,
    ) -> Result<ApiEnvelope<T>, ClickSendError> {
        let span = tracing::debug_span!("clicksend", %method, path);
        let _g = span.enter();

        let mut attempt = 0u32;
        let mut backoff = self.inner.retry.initial_backoff;

        loop {
            attempt += 1;

            let mut rb = self.req(method.clone(), path);
            if let Some(q) = query {
                rb = rb.query(q);
            }
            if let Some(b) = body {
                rb = rb.json(&b.as_value()?);
            }

            let resp = rb.send().await;
            let resp = match resp {
                Ok(r) => r,
                Err(e) => {
                    if attempt < self.inner.retry.max_attempts && e.is_timeout() {
                        tracing::warn!(?e, attempt, "transient send error, retrying");
                        sleep(backoff).await;
                        backoff = next_backoff(backoff, &self.inner.retry);
                        continue;
                    }
                    return Err(ClickSendError::Http(e));
                }
            };

            let status = resp.status();

            if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
                if attempt < self.inner.retry.max_attempts {
                    let retry_after = resp
                        .headers()
                        .get("retry-after")
                        .and_then(|v| v.to_str().ok())
                        .and_then(|v| v.parse::<u64>().ok());
                    let wait = retry_after
                        .map(Duration::from_secs)
                        .unwrap_or(backoff);
                    tracing::warn!(attempt, ?wait, "429, retrying");
                    sleep(wait).await;
                    backoff = next_backoff(backoff, &self.inner.retry);
                    continue;
                }
                let retry_after = resp
                    .headers()
                    .get("retry-after")
                    .and_then(|v| v.to_str().ok())
                    .and_then(|v| v.parse::<u64>().ok());
                return Err(ClickSendError::RateLimited {
                    retry_after_secs: retry_after,
                });
            }

            if status.is_server_error() && attempt < self.inner.retry.max_attempts {
                tracing::warn!(?status, attempt, "5xx, retrying");
                sleep(backoff).await;
                backoff = next_backoff(backoff, &self.inner.retry);
                continue;
            }

            let text = resp.text().await.map_err(ClickSendError::Http)?;
            return decode_envelope(status, &text);
        }
    }
}

pub(crate) fn decode_envelope<T: DeserializeOwned>(
    status: reqwest::StatusCode,
    text: &str,
) -> Result<ApiEnvelope<T>, ClickSendError> {
    if status == reqwest::StatusCode::UNAUTHORIZED {
        return Err(ClickSendError::Unauthorized);
    }
    if status == reqwest::StatusCode::NOT_FOUND {
        return Err(ClickSendError::NotFound(text.to_string()));
    }
    if status.is_client_error() || status.is_server_error() {
        return Err(ClickSendError::Http4xx5xx {
            code: status.as_u16(),
            message: text.to_string(),
        });
    }

    let env: ApiEnvelope<T> = serde_json::from_str(text).map_err(|e| ClickSendError::Decode {
        message: e.to_string(),
        body: text.to_string(),
    })?;

    if env.response_code != "SUCCESS" {
        return Err(ClickSendError::Api {
            code: env.response_code.clone(),
            message: env.response_msg.clone().unwrap_or_default(),
            body: text.to_string(),
        });
    }

    Ok(env)
}

fn next_backoff(current: Duration, cfg: &RetryConfig) -> Duration {
    let next = current.mul_f64(cfg.backoff_multiplier);
    if next > cfg.max_backoff {
        cfg.max_backoff
    } else {
        next
    }
}

async fn sleep(d: Duration) {
    tokio::time::sleep(d).await;
}

// ───────── erased serializer (so execute() isn't generic over body type) ─────────

pub(crate) trait ErasedSerialize: Send + Sync {
    fn as_value(&self) -> Result<serde_json::Value, ClickSendError>;
}

impl<T: Serialize + Send + Sync> ErasedSerialize for T {
    fn as_value(&self) -> Result<serde_json::Value, ClickSendError> {
        serde_json::to_value(self).map_err(|e| ClickSendError::Decode {
            message: e.to_string(),
            body: String::new(),
        })
    }
}

// ───────── builder ─────────

/// Builder for [`Client`]. Tunes timeouts, retry, UA, base URL, custom HTTP.
pub struct ClientBuilder {
    username: String,
    api_key: String,
    base_url: String,
    timeout: Duration,
    connect_timeout: Duration,
    user_agent: String,
    retry: RetryConfig,
    http: Option<HttpClient>,
}

impl ClientBuilder {
    /// Start a builder with credentials. Call [`Self::build`] to finalize.
    pub fn new(username: impl Into<String>, api_key: impl Into<String>) -> Self {
        Self {
            username: username.into(),
            api_key: api_key.into(),
            base_url: DEFAULT_BASE_URL.to_string(),
            timeout: Duration::from_secs(30),
            connect_timeout: Duration::from_secs(10),
            user_agent: DEFAULT_USER_AGENT.to_string(),
            retry: RetryConfig::default(),
            http: None,
        }
    }

    /// Override the API base URL (useful for mock servers).
    pub fn base_url(mut self, v: impl Into<String>) -> Self {
        self.base_url = v.into();
        self
    }
    /// Total request timeout (default 30s).
    pub fn timeout(mut self, v: Duration) -> Self {
        self.timeout = v;
        self
    }
    /// TCP connect timeout (default 10s).
    pub fn connect_timeout(mut self, v: Duration) -> Self {
        self.connect_timeout = v;
        self
    }
    /// Override the User-Agent header (default `clicksend-rs/<version>`).
    pub fn user_agent(mut self, v: impl Into<String>) -> Self {
        self.user_agent = v.into();
        self
    }
    /// Configure retry behavior. Default is no retry.
    pub fn retry(mut self, v: RetryConfig) -> Self {
        self.retry = v;
        self
    }
    /// Plug your own `reqwest::Client` — timeout/connect/UA on the builder are
    /// then ignored.
    pub fn http_client(mut self, http: HttpClient) -> Self {
        self.http = Some(http);
        self
    }

    /// Finalize. Errors with [`ClickSendError::InvalidConfig`] on empty creds.
    pub fn build(self) -> Result<Client, ClickSendError> {
        if self.username.is_empty() {
            return Err(ClickSendError::InvalidConfig("username is empty".into()));
        }
        if self.api_key.is_empty() {
            return Err(ClickSendError::InvalidConfig("api_key is empty".into()));
        }

        let http = match self.http {
            Some(h) => h,
            None => HttpClient::builder()
                .timeout(self.timeout)
                .connect_timeout(self.connect_timeout)
                .user_agent(self.user_agent)
                .build()
                .map_err(ClickSendError::Http)?,
        };

        Ok(Client {
            inner: Arc::new(Inner {
                username: self.username,
                api_key: self.api_key,
                base_url: self.base_url,
                http,
                retry: self.retry,
            }),
        })
    }
}

// ═════════════════════════════════════════════════════════════════
//                          NAMESPACES
// ═════════════════════════════════════════════════════════════════

/// `/account` namespace. Get from [`Client::account`].
#[derive(Debug)]
pub struct AccountApi<'a> {
    c: &'a Client,
}

impl<'a> AccountApi<'a> {
    /// `GET /account` — fetch account info, balance, currency.
    pub async fn get(&self) -> Result<ApiEnvelope<AccountData>, ClickSendError> {
        self.c
            .execute::<AccountData>(Method::GET, "/account", None, None)
            .await
    }
}

/// `/sms/*` namespace. Get from [`Client::sms`].
#[derive(Debug)]
pub struct SmsApi<'a> {
    c: &'a Client,
}

impl<'a> SmsApi<'a> {
    /// `POST /sms/send` — actually send SMS. Each message in the collection
    /// is billed.
    pub async fn send(
        &self,
        messages: &SmsMessageCollection,
    ) -> Result<ApiEnvelope<SmsSendData>, ClickSendError> {
        self.c
            .execute::<SmsSendData>(Method::POST, "/sms/send", None, Some(messages))
            .await
    }

    /// `POST /sms/price` — free price estimate; nothing is sent.
    pub async fn price(
        &self,
        messages: &SmsMessageCollection,
    ) -> Result<ApiEnvelope<SmsSendData>, ClickSendError> {
        self.c
            .execute::<SmsSendData>(Method::POST, "/sms/price", None, Some(messages))
            .await
    }

    /// `GET /sms/history` — list previously sent SMS with delivery status.
    /// Common query keys: `q`, `date_from`, `date_to`, `page`, `limit`.
    pub async fn history(
        &self,
        query: &[(&str, &str)],
    ) -> Result<ApiEnvelope<Paginated<SmsHistoryItem>>, ClickSendError> {
        self.c
            .execute::<Paginated<SmsHistoryItem>>(Method::GET, "/sms/history", Some(query), None)
            .await
    }

    /// `GET /sms/receipts` — delivery receipts only.
    pub async fn receipts(
        &self,
        query: &[(&str, &str)],
    ) -> Result<ApiEnvelope<Paginated<SmsReceiptItem>>, ClickSendError> {
        self.c
            .execute::<Paginated<SmsReceiptItem>>(Method::GET, "/sms/receipts", Some(query), None)
            .await
    }

    /// `GET /sms/inbound` — incoming SMS to your numbers.
    pub async fn inbound(
        &self,
        query: &[(&str, &str)],
    ) -> Result<ApiEnvelope<Paginated<SmsInboundItem>>, ClickSendError> {
        self.c
            .execute::<Paginated<SmsInboundItem>>(Method::GET, "/sms/inbound", Some(query), None)
            .await
    }

    /// `PUT /sms/{id}/cancel` — cancel a scheduled message that hasn't sent yet.
    pub async fn cancel(
        &self,
        message_id: &str,
    ) -> Result<ApiEnvelope<serde_json::Value>, ClickSendError> {
        let path = format!("/sms/{message_id}/cancel");
        self.c
            .execute::<serde_json::Value>(Method::PUT, &path, None, None)
            .await
    }

    /// `PUT /sms/cancel-all` — cancel every scheduled message at once.
    pub async fn cancel_all(&self) -> Result<ApiEnvelope<serde_json::Value>, ClickSendError> {
        self.c
            .execute::<serde_json::Value>(Method::PUT, "/sms/cancel-all", None, None)
            .await
    }
}

/// `/mms/*` namespace. Get from [`Client::mms`].
#[derive(Debug)]
pub struct MmsApi<'a> {
    c: &'a Client,
}

impl<'a> MmsApi<'a> {
    /// `POST /mms/send` — send MMS. The collection's `media_file` must be a
    /// publicly reachable URL.
    pub async fn send(
        &self,
        messages: &MmsMessageCollection,
    ) -> Result<ApiEnvelope<serde_json::Value>, ClickSendError> {
        self.c
            .execute::<serde_json::Value>(Method::POST, "/mms/send", None, Some(messages))
            .await
    }
}

/// `/voice/*` namespace. Get from [`Client::voice`].
#[derive(Debug)]
pub struct VoiceApi<'a> {
    c: &'a Client,
}

impl<'a> VoiceApi<'a> {
    /// `POST /voice/send` — place TTS voice calls.
    pub async fn send(
        &self,
        messages: &VoiceMessageCollection,
    ) -> Result<ApiEnvelope<serde_json::Value>, ClickSendError> {
        self.c
            .execute::<serde_json::Value>(Method::POST, "/voice/send", None, Some(messages))
            .await
    }
}

/// `/email/*` namespace. Get from [`Client::email`].
#[derive(Debug)]
pub struct EmailApi<'a> {
    c: &'a Client,
}

impl<'a> EmailApi<'a> {
    /// `POST /email/send` — send a transactional email. Requires a
    /// pre-verified sender (see [`crate::EmailFrom`]).
    pub async fn send(
        &self,
        email: &Email,
    ) -> Result<ApiEnvelope<serde_json::Value>, ClickSendError> {
        self.c
            .execute::<serde_json::Value>(Method::POST, "/email/send", None, Some(email))
            .await
    }
}