Skip to main content

opensms/
client.rs

1//! The OpenSMS client: validates configuration and wires the resources to
2//! the shared transport.
3
4use std::future::Future;
5use std::sync::Arc;
6use std::time::Duration;
7
8use crate::error::{OpensmsError, Result};
9use crate::http::{
10    HttpClient, ReqwestTransport, Sleeper, TokioSleeper, Transport, DEFAULT_BASE_URL,
11};
12use crate::models::Page;
13use crate::pagination::{paginate, Paginator};
14use crate::resources::{
15    Analytics, Batches, Compliance, ContactGroups, Contacts, Countries, Inbound, Lookups, Messages,
16    Numbers, Otp, Pricing, Sandbox, SenderIds, Suppressions, Templates, Wallet, Webhooks,
17};
18
19const DEFAULT_TIMEOUT_SECS: u64 = 30;
20const DEFAULT_MAX_RETRIES: u32 = 2;
21const MIN_SECRET_LEN: usize = 12;
22
23/// Builder for [`Client`]. Construct with [`Client::builder`].
24pub struct ClientBuilder {
25    api_key: String,
26    base_url: String,
27    timeout: Duration,
28    max_retries: u32,
29    transport: Option<Arc<dyn Transport>>,
30    sleeper: Option<Arc<dyn Sleeper>>,
31}
32
33impl ClientBuilder {
34    /// Override the API base URL (default `https://opensms.io`). Trailing
35    /// slashes are stripped.
36    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
37        self.base_url = base_url.into();
38        self
39    }
40
41    /// Per-attempt timeout covering connect and read. Default 30 s.
42    pub fn timeout(mut self, timeout: Duration) -> Self {
43        self.timeout = timeout;
44        self
45    }
46
47    /// Retries after the first attempt. Default 2 (3 attempts). `0` disables
48    /// retries.
49    pub fn max_retries(mut self, max_retries: u32) -> Self {
50        self.max_retries = max_retries;
51        self
52    }
53
54    /// Replace the HTTP transport (for tests or custom networking).
55    pub fn transport(mut self, transport: Arc<dyn Transport>) -> Self {
56        self.transport = Some(transport);
57        self
58    }
59
60    /// Replace the sleeper used between retries (tests inject a no-op).
61    pub fn sleeper(mut self, sleeper: Arc<dyn Sleeper>) -> Self {
62        self.sleeper = Some(sleeper);
63        self
64    }
65
66    /// Validate the key and build the client. No network call is made.
67    pub fn build(self) -> Result<Client> {
68        let environment = environment_of(&self.api_key).ok_or_else(|| {
69            OpensmsError::invalid_argument(
70                "api_key must start with sk_test_ or sk_live_ followed by more than 12 characters",
71            )
72        })?;
73        let transport: Arc<dyn Transport> = match self.transport {
74            Some(t) => t,
75            None => Arc::new(ReqwestTransport::new()?),
76        };
77        let sleeper = self.sleeper.unwrap_or_else(|| Arc::new(TokioSleeper));
78        let http = HttpClient::new(
79            self.api_key,
80            self.base_url,
81            self.timeout,
82            self.max_retries,
83            transport,
84            sleeper,
85        );
86        Ok(Client {
87            environment,
88            messages: Messages::new(http.clone()),
89            batches: Batches::new(http.clone()),
90            otp: Otp::new(http.clone()),
91            lookups: Lookups::new(http.clone()),
92            contacts: Contacts::new(http.clone()),
93            contact_groups: ContactGroups::new(http.clone()),
94            templates: Templates::new(http.clone()),
95            webhooks: Webhooks::new(http.clone()),
96            inbound: Inbound::new(http.clone()),
97            numbers: Numbers::new(http.clone()),
98            sender_ids: SenderIds::new(http.clone()),
99            suppressions: Suppressions::new(http.clone()),
100            compliance: Compliance::new(http.clone()),
101            wallet: Wallet::new(http.clone()),
102            pricing: Pricing::new(http.clone()),
103            analytics: Analytics::new(http.clone()),
104            sandbox: Sandbox::new(http.clone()),
105            countries: Countries::new(http.clone()),
106            http,
107        })
108    }
109}
110
111/// `sandbox` for `sk_test_` keys, `live` for `sk_live_`, `None` if invalid.
112fn environment_of(key: &str) -> Option<&'static str> {
113    let (env, rest) = match key.strip_prefix("sk_test_") {
114        Some(rest) => ("sandbox", rest),
115        None => ("live", key.strip_prefix("sk_live_")?),
116    };
117    (rest.len() > MIN_SECRET_LEN).then_some(env)
118}
119
120/// OpenSMS API client. Cheap to clone; clones share one connection pool.
121///
122/// ```no_run
123/// use opensms::{Client, SendMessage};
124///
125/// # async fn run() -> Result<(), opensms::OpensmsError> {
126/// let client = Client::new("sk_test_...")?;
127/// let message = client.messages().send(&SendMessage::new("+254700000012", "Hello")).await?;
128/// println!("{} is {:?}", message.id, message.status);
129/// # Ok(())
130/// # }
131/// ```
132#[derive(Debug, Clone)]
133pub struct Client {
134    http: HttpClient,
135    environment: &'static str,
136    messages: Messages,
137    batches: Batches,
138    otp: Otp,
139    lookups: Lookups,
140    contacts: Contacts,
141    contact_groups: ContactGroups,
142    templates: Templates,
143    webhooks: Webhooks,
144    inbound: Inbound,
145    numbers: Numbers,
146    sender_ids: SenderIds,
147    suppressions: Suppressions,
148    compliance: Compliance,
149    wallet: Wallet,
150    pricing: Pricing,
151    analytics: Analytics,
152    sandbox: Sandbox,
153    countries: Countries,
154}
155
156impl Client {
157    /// A client with default settings. The key must start with `sk_test_` or
158    /// `sk_live_` and have more than 12 characters after the prefix.
159    pub fn new(api_key: impl Into<String>) -> Result<Self> {
160        Self::builder(api_key).build()
161    }
162
163    /// Start configuring a client.
164    pub fn builder(api_key: impl Into<String>) -> ClientBuilder {
165        ClientBuilder {
166            api_key: api_key.into(),
167            base_url: DEFAULT_BASE_URL.to_string(),
168            timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
169            max_retries: DEFAULT_MAX_RETRIES,
170            transport: None,
171            sleeper: None,
172        }
173    }
174
175    /// `"sandbox"` for `sk_test_` keys, `"live"` for `sk_live_` keys.
176    pub fn environment(&self) -> &'static str {
177        self.environment
178    }
179
180    /// The base URL requests go to.
181    pub fn base_url(&self) -> &str {
182        self.http.base_url()
183    }
184
185    /// Walk every page of a cursor list. See [`Paginator`].
186    pub fn paginate<T, F, Fut>(&self, fetch: F) -> Paginator<T, F>
187    where
188        F: FnMut(Option<String>) -> Fut,
189        Fut: Future<Output = Result<Page<T>>>,
190    {
191        paginate(fetch)
192    }
193
194    /// Send, list, fetch and cancel messages.
195    pub fn messages(&self) -> &Messages {
196        &self.messages
197    }
198    /// Bulk batches.
199    pub fn batches(&self) -> &Batches {
200        &self.batches
201    }
202    /// One-time passcodes.
203    pub fn otp(&self) -> &Otp {
204        &self.otp
205    }
206    /// Number lookups.
207    pub fn lookups(&self) -> &Lookups {
208        &self.lookups
209    }
210    /// Contacts.
211    pub fn contacts(&self) -> &Contacts {
212        &self.contacts
213    }
214    /// Contact groups.
215    pub fn contact_groups(&self) -> &ContactGroups {
216        &self.contact_groups
217    }
218    /// Message templates.
219    pub fn templates(&self) -> &Templates {
220        &self.templates
221    }
222    /// Webhook endpoints and signature verification.
223    pub fn webhooks(&self) -> &Webhooks {
224        &self.webhooks
225    }
226    /// Inbound messages.
227    pub fn inbound(&self) -> &Inbound {
228        &self.inbound
229    }
230    /// Virtual numbers.
231    pub fn numbers(&self) -> &Numbers {
232        &self.numbers
233    }
234    /// Sender IDs, drafts and documents.
235    pub fn sender_ids(&self) -> &SenderIds {
236        &self.sender_ids
237    }
238    /// Suppression list.
239    pub fn suppressions(&self) -> &Suppressions {
240        &self.suppressions
241    }
242    /// Compliance rules.
243    pub fn compliance(&self) -> &Compliance {
244        &self.compliance
245    }
246    /// Wallet balances, ledger and top-ups.
247    pub fn wallet(&self) -> &Wallet {
248        &self.wallet
249    }
250    /// Price lists.
251    pub fn pricing(&self) -> &Pricing {
252        &self.pricing
253    }
254    /// Delivery analytics.
255    pub fn analytics(&self) -> &Analytics {
256        &self.analytics
257    }
258    /// Sandbox message viewer.
259    pub fn sandbox(&self) -> &Sandbox {
260        &self.sandbox
261    }
262    /// Public country catalog.
263    pub fn countries(&self) -> &Countries {
264        &self.countries
265    }
266}