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
//! Blocking mirror of [`crate::client`].
//!
//! Uses [`reqwest::blocking`] under the hood — no tokio runtime required at
//! the call site. The API matches [`crate::Client`] one-to-one.

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

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

use crate::{
    client::{decode_envelope, ErasedSerialize, RetryConfig},
    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"));

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

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

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

impl BlockingClient {
    /// New blocking client with default settings. Panics on empty creds —
    /// use [`BlockingClientBuilder::build`] for fallible construction.
    pub fn new(username: impl Into<String>, api_key: impl Into<String>) -> Self {
        BlockingClientBuilder::new(username, api_key).build().expect("default builds")
    }

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

    /// `/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 }
    }

    /// Pre-authenticated [`RequestBuilder`] for any path. See
    /// [`crate::Client::raw_request`].
    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))
    }

    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.blocking", %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.raw_request(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();
            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");
                        thread::sleep(backoff);
                        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");
                    thread::sleep(wait);
                    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");
                thread::sleep(backoff);
                backoff = next_backoff(backoff, &self.inner.retry);
                continue;
            }

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

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
    }
}

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

/// Builder for [`BlockingClient`]. Mirrors [`crate::ClientBuilder`].
pub struct BlockingClientBuilder {
    username: String,
    api_key: String,
    base_url: String,
    timeout: Duration,
    connect_timeout: Duration,
    user_agent: String,
    retry: RetryConfig,
    http: Option<HttpClient>,
}

impl BlockingClientBuilder {
    /// Start a builder with credentials.
    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.
    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.
    pub fn user_agent(mut self, v: impl Into<String>) -> Self {
        self.user_agent = v.into();
        self
    }
    /// Configure retry behavior.
    pub fn retry(mut self, v: RetryConfig) -> Self {
        self.retry = v;
        self
    }
    /// Plug your own `reqwest::blocking::Client`.
    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<BlockingClient, 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(BlockingClient {
            inner: Arc::new(Inner {
                username: self.username,
                api_key: self.api_key,
                base_url: self.base_url,
                http,
                retry: self.retry,
            }),
        })
    }
}

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

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

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

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

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

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

    /// `GET /sms/history` with optional query params (`page`, `limit`, etc).
    pub fn history(
        &self,
        query: &[(&str, &str)],
    ) -> Result<ApiEnvelope<Paginated<SmsHistoryItem>>, ClickSendError> {
        self.c
            .execute::<Paginated<SmsHistoryItem>>(Method::GET, "/sms/history", Some(query), None)
    }

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

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

    /// `PUT /sms/{id}/cancel` — cancel a scheduled message.
    pub 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)
    }

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

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

impl<'a> MmsApi<'a> {
    /// `POST /mms/send`.
    pub fn send(
        &self,
        messages: &MmsMessageCollection,
    ) -> Result<ApiEnvelope<serde_json::Value>, ClickSendError> {
        self.c
            .execute::<serde_json::Value>(Method::POST, "/mms/send", None, Some(messages))
    }
}

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

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

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

impl<'a> EmailApi<'a> {
    /// `POST /email/send` — transactional email.
    pub fn send(
        &self,
        email: &Email,
    ) -> Result<ApiEnvelope<serde_json::Value>, ClickSendError> {
        self.c
            .execute::<serde_json::Value>(Method::POST, "/email/send", None, Some(email))
    }
}