Skip to main content

loops_so/client/
mod.rs

1//! The high-level [`LoopsClient`].
2//!
3//! Requests are dispatched here rather than through the generated
4//! `LoopsOpenApiSpecClient`, which discards the status code and headers of any
5//! response its spec does not list. The client needs both to report rate
6//! limits, so it sends the request itself and hands successful responses to
7//! the generated `parse_response` functions for typed decoding.
8
9mod campaigns;
10mod contacts;
11mod email_messages;
12mod events;
13mod groups;
14mod params;
15mod segments;
16mod templates;
17mod transactional;
18mod workflow_nodes;
19mod workflows;
20
21use std::fmt;
22use std::future::Future;
23use std::sync::{Arc, PoisonError, RwLock};
24
25use bytes::Bytes;
26use http::{HeaderMap, HeaderValue, StatusCode};
27use reqwest::Url;
28use serde_json::Value;
29
30use crate::config::get_config;
31use crate::error::{LoopsError, Result};
32use crate::generated::{LoopsOpenApiSpecClient, TestApiKeyRequest, TestApiKeyResponse};
33use crate::routes::Route;
34
35pub use params::{
36    ContactFields, ContactId, DeleteNodeOptions, EmailFormat, EmailMessageUpdate, EventOptions,
37    NodePlacement, Page, PreviewOptions, TransactionalOptions,
38};
39
40const USER_AGENT: &str = concat!("loops-so-rust/", env!("CARGO_PKG_VERSION"));
41
42/// High-level client for the Loops API.
43///
44/// Wraps every Loops endpoint with typed arguments, maps failures to
45/// [`LoopsError`], and enforces safe mode. Cloning is cheap: clones share the
46/// underlying connection pool.
47///
48/// ```no_run
49/// # async fn run() -> loops_so::Result<()> {
50/// use loops_so::{ContactFields, ContactId, LoopsClient};
51///
52/// let client = LoopsClient::builder().api_key("your_api_key").build()?;
53/// client
54///     .upsert_contact(
55///         ContactId::email("user@example.com"),
56///         ContactFields::new().first_name("John"),
57///     )
58///     .await?;
59/// # Ok(())
60/// # }
61/// ```
62#[derive(Clone)]
63pub struct LoopsClient {
64    http: reqwest::Client,
65    base_url: Url,
66    authorization: HeaderValue,
67    safe_mode: bool,
68    safe_mode_allowed_domains: Vec<String>,
69}
70
71impl fmt::Debug for LoopsClient {
72    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73        f.debug_struct("LoopsClient")
74            .field("base_url", &self.base_url.as_str())
75            .field("safe_mode", &self.safe_mode)
76            .field("safe_mode_allowed_domains", &self.safe_mode_allowed_domains)
77            .finish_non_exhaustive()
78    }
79}
80
81/// Builds a [`LoopsClient`]. Every setting left unset falls back to the
82/// process-wide defaults from [`configure`](crate::configure).
83#[derive(Debug, Default)]
84#[must_use]
85pub struct LoopsClientBuilder {
86    api_key: Option<String>,
87    base_url: Option<String>,
88    safe_mode: Option<bool>,
89    safe_mode_allowed_domains: Option<Vec<String>>,
90    http_client: Option<reqwest::Client>,
91}
92
93impl LoopsClientBuilder {
94    /// The Loops API key. Defaults to the configured key, then the
95    /// `LOOPS_API_KEY` environment variable.
96    pub fn api_key(mut self, api_key: impl Into<String>) -> Self {
97        self.api_key = Some(api_key.into());
98        self
99    }
100
101    /// The base URL of the Loops API (default `https://app.loops.so/api`).
102    /// Do not include the `/v1` version segment; a trailing `/v1` is stripped.
103    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
104        self.base_url = Some(base_url.into());
105        self
106    }
107
108    /// When `true`, every recipient address must end in one of the
109    /// [allowed domains](Self::safe_mode_allowed_domains) or the call fails
110    /// with [`LoopsError::UnsafeEmail`] before anything is sent.
111    pub fn safe_mode(mut self, safe_mode: bool) -> Self {
112        self.safe_mode = Some(safe_mode);
113        self
114    }
115
116    /// The domains allowed in safe mode, each starting with `@`
117    /// (e.g. `["@test.com", "@example.com"]`).
118    pub fn safe_mode_allowed_domains<I, S>(mut self, domains: I) -> Self
119    where
120        I: IntoIterator<Item = S>,
121        S: Into<String>,
122    {
123        self.safe_mode_allowed_domains = Some(domains.into_iter().map(Into::into).collect());
124        self
125    }
126
127    /// Send requests through this `reqwest` client, e.g. to set timeouts or a
128    /// proxy. The API key is added per request, so the client needs no
129    /// default headers.
130    pub fn http_client(mut self, client: reqwest::Client) -> Self {
131        self.http_client = Some(client);
132        self
133    }
134
135    /// Build the client.
136    ///
137    /// # Errors
138    ///
139    /// [`LoopsError::Configuration`] when no API key is available or the base
140    /// URL does not parse.
141    pub fn build(self) -> Result<LoopsClient> {
142        let config = get_config();
143        let api_key = self
144            .api_key
145            .filter(|key| !key.is_empty())
146            .or(config.api_key)
147            .ok_or_else(|| {
148                LoopsError::Configuration(
149                    "API key not configured. Set the LOOPS_API_KEY environment variable or call \
150                 loops_so::configure(ConfigureOptions::new().api_key(\"...\"))"
151                        .to_owned(),
152                )
153            })?;
154        let base_url = self.base_url.unwrap_or(config.base_url);
155        let normalized = normalize_base_url(&base_url);
156        let base_url = Url::parse(&normalized)
157            .ok()
158            .filter(|url| !url.cannot_be_a_base())
159            .ok_or_else(|| LoopsError::Configuration(format!("Invalid base_url: {base_url:?}")))?;
160        let mut authorization =
161            HeaderValue::try_from(format!("Bearer {api_key}")).map_err(|_| {
162                LoopsError::Configuration(
163                    "API key contains characters not allowed in an HTTP header".to_owned(),
164                )
165            })?;
166        authorization.set_sensitive(true);
167        let http = match self.http_client {
168            Some(client) => client,
169            None => reqwest::Client::builder().user_agent(USER_AGENT).build()?,
170        };
171        Ok(LoopsClient {
172            http,
173            base_url,
174            authorization,
175            safe_mode: self.safe_mode.unwrap_or(config.safe_mode),
176            safe_mode_allowed_domains: self
177                .safe_mode_allowed_domains
178                .unwrap_or(config.safe_mode_allowed_domains),
179        })
180    }
181}
182
183/// Strip trailing slashes and a trailing `/v1` from a base URL. The version
184/// segment is part of every endpoint path, so leaving it on the base URL
185/// would produce `/v1/v1/...` paths.
186pub(crate) fn normalize_base_url(base_url: &str) -> String {
187    let trimmed = base_url.trim_end_matches('/');
188    trimmed.strip_suffix("/v1").unwrap_or(trimmed).to_owned()
189}
190
191impl LoopsClient {
192    /// A client built entirely from the process-wide defaults.
193    ///
194    /// # Errors
195    ///
196    /// See [`LoopsClientBuilder::build`].
197    pub fn new() -> Result<Self> {
198        Self::builder().build()
199    }
200
201    /// Start building a client.
202    pub fn builder() -> LoopsClientBuilder {
203        LoopsClientBuilder::default()
204    }
205
206    /// The normalized base URL requests are sent to.
207    pub fn base_url(&self) -> &str {
208        self.base_url.as_str()
209    }
210
211    /// Whether safe mode is on for this client.
212    pub fn safe_mode(&self) -> bool {
213        self.safe_mode
214    }
215
216    /// A low-level generated client that shares this client's base URL and
217    /// API key. Use it for endpoints or options the high-level methods do not
218    /// expose. Each call builds a new connection pool, so keep the result
219    /// rather than calling this per request.
220    ///
221    /// # Errors
222    ///
223    /// [`LoopsError::Http`] when the underlying `reqwest` client cannot be built.
224    pub fn low_level(&self) -> Result<LoopsOpenApiSpecClient> {
225        let mut headers = HeaderMap::new();
226        headers.insert(http::header::AUTHORIZATION, self.authorization.clone());
227        let http = reqwest::Client::builder()
228            .user_agent(USER_AGENT)
229            .default_headers(headers)
230            .build()?;
231        Ok(LoopsOpenApiSpecClient {
232            client: http,
233            base_url: self.base_url.clone(),
234        })
235    }
236
237    /// Validate the API key.
238    ///
239    /// # Errors
240    ///
241    /// [`LoopsError::Api`] with status 401 when the key is invalid.
242    pub async fn health(&self) -> Result<bool> {
243        const ACTION: &str = "validate API key";
244        let raw = self.send(Route::Health, &[], |request| request).await?;
245        if raw.status == StatusCode::UNAUTHORIZED {
246            return Err(LoopsError::Api {
247                message: "Invalid API key".to_owned(),
248                status: Some(401),
249                body: raw.json(),
250            });
251        }
252        match raw.parse(ACTION, TestApiKeyRequest::parse_response).await? {
253            TestApiKeyResponse::Ok(_) => Ok(true),
254            _ => Err(raw.unexpected(ACTION)),
255        }
256    }
257
258    /// Fail when safe mode is on and `email` is outside the allowed domains.
259    fn validate_email(&self, email: Option<&str>) -> Result<()> {
260        let Some(email) = email.filter(|email| !email.is_empty()) else {
261            return Ok(());
262        };
263        if !self.safe_mode {
264            return Ok(());
265        }
266        if self.safe_mode_allowed_domains.is_empty() {
267            return Err(LoopsError::Configuration(
268                "safe_mode is enabled but no safe_mode_allowed_domains configured. Set allowed \
269                 domains via configure(ConfigureOptions::new().safe_mode_allowed_domains([\"@test.com\"])) \
270                 or on LoopsClient::builder()."
271                    .to_owned(),
272            ));
273        }
274        let email_lower = email.to_lowercase();
275        if self
276            .safe_mode_allowed_domains
277            .iter()
278            .any(|domain| email_lower.ends_with(&domain.to_lowercase()))
279        {
280            Ok(())
281        } else {
282            Err(LoopsError::UnsafeEmail {
283                email: email.to_owned(),
284                allowed_domains: self.safe_mode_allowed_domains.clone(),
285            })
286        }
287    }
288
289    fn url(&self, route: Route, params: &[&str]) -> Url {
290        let mut url = self.base_url.clone();
291        {
292            let mut segments = url
293                .path_segments_mut()
294                .expect("base URL was checked to be a base when the client was built");
295            segments.pop_if_empty();
296            let mut params = params.iter();
297            for segment in route
298                .path()
299                .split('/')
300                .filter(|segment| !segment.is_empty())
301            {
302                if segment.starts_with('{') {
303                    let value = params
304                        .next()
305                        .expect("every path placeholder has a parameter");
306                    segments.push(value);
307                } else {
308                    segments.push(segment);
309                }
310            }
311            debug_assert!(
312                params.next().is_none(),
313                "more parameters than placeholders for {route:?}"
314            );
315        }
316        url
317    }
318
319    /// Send a request to `route`, buffer the response, and turn HTTP 429 into
320    /// [`LoopsError::RateLimit`].
321    async fn send(
322        &self,
323        route: Route,
324        params: &[&str],
325        build: impl FnOnce(reqwest::RequestBuilder) -> reqwest::RequestBuilder,
326    ) -> Result<RawResponse> {
327        // An empty, `.` or `..` segment would silently address a different
328        // endpoint: `url` drops dot segments, so `update_campaign_group(".")`
329        // would POST to the collection and create a group.
330        if let Some(param) = params
331            .iter()
332            .find(|param| matches!(**param, "" | "." | ".."))
333        {
334            return Err(LoopsError::InvalidInput(format!(
335                "{} cannot take {param:?} as a path parameter",
336                route.name()
337            )));
338        }
339        let request = self
340            .http
341            .request(route.method().to_http(), self.url(route, params))
342            .header(http::header::AUTHORIZATION, self.authorization.clone());
343        let response = build(request).send().await?;
344        let status = response.status();
345        let headers = response.headers().clone();
346        let body = response.bytes().await?;
347        if status == StatusCode::TOO_MANY_REQUESTS {
348            return Err(LoopsError::RateLimit {
349                limit: header_number(&headers, "x-ratelimit-limit"),
350                remaining: header_number(&headers, "x-ratelimit-remaining"),
351            });
352        }
353        Ok(RawResponse {
354            status,
355            headers,
356            body,
357        })
358    }
359}
360
361fn header_number(headers: &HeaderMap, name: &str) -> u64 {
362    headers
363        .get(name)
364        .and_then(|value| value.to_str().ok())
365        .and_then(|value| value.trim().parse().ok())
366        .unwrap_or(0)
367}
368
369/// Merge caller-supplied properties into a JSON body as top-level keys,
370/// refusing keys the method sets itself. Overwriting `email` would otherwise
371/// redirect the request past the safe-mode check.
372fn merge_properties(
373    body: &mut serde_json::Map<String, Value>,
374    properties: serde_json::Map<String, Value>,
375    reserved: &[&str],
376    action: &str,
377) -> Result<()> {
378    if let Some(key) = properties
379        .keys()
380        .find(|key| reserved.contains(&key.as_str()) || body.contains_key(*key))
381    {
382        return Err(LoopsError::InvalidInput(format!(
383            "{action}: property `{key}` is a field the request sets itself; use its dedicated option"
384        )));
385    }
386    body.extend(properties);
387    Ok(())
388}
389
390/// Endpoints that look a contact up by exactly one identifier.
391fn single_identifier(contact: &ContactId, action: &str) -> Result<()> {
392    if matches!(contact, ContactId::Both { .. }) {
393        return Err(LoopsError::InvalidInput(format!(
394            "{action}: provide either email or user_id, not both"
395        )));
396    }
397    Ok(())
398}
399
400/// Turn a generated request's `validator` failure into [`LoopsError::InvalidInput`].
401fn check(value: &impl validator::Validate) -> Result<()> {
402    value
403        .validate()
404        .map_err(|err| LoopsError::InvalidInput(err.to_string()))
405}
406
407/// Mailing list subscriptions as the JSON object Loops expects, or `None`
408/// when there are none.
409pub(super) fn mailing_lists_value(
410    lists: &std::collections::BTreeMap<String, bool>,
411) -> Option<Value> {
412    (!lists.is_empty()).then(|| {
413        Value::Object(
414            lists
415                .iter()
416                .map(|(id, subscribed)| (id.clone(), Value::Bool(*subscribed)))
417                .collect(),
418        )
419    })
420}
421
422/// A fully buffered response.
423struct RawResponse {
424    status: StatusCode,
425    headers: HeaderMap,
426    body: Bytes,
427}
428
429impl RawResponse {
430    fn is_success(&self) -> bool {
431        self.status.is_success()
432    }
433
434    fn json(&self) -> Option<Value> {
435        serde_json::from_slice(&self.body).ok()
436    }
437
438    /// The `message` field of a JSON failure body.
439    fn message(&self) -> Option<String> {
440        self.json()?.get("message")?.as_str().map(str::to_owned)
441    }
442
443    fn to_reqwest(&self) -> reqwest::Response {
444        let mut response = http::Response::new(self.body.clone());
445        *response.status_mut() = self.status;
446        *response.headers_mut() = self.headers.clone();
447        reqwest::Response::from(response)
448    }
449
450    /// `"Failed to {action}: {message}"`, carrying the status and body.
451    fn failure(&self, action: &str) -> LoopsError {
452        self.failure_with(&format!("Failed to {action}"))
453    }
454
455    /// `"{prefix}: {message}"`, or just `prefix` when the body has no message.
456    fn failure_with(&self, prefix: &str) -> LoopsError {
457        let message = match self.message() {
458            Some(message) => format!("{prefix}: {message}"),
459            None => prefix.to_owned(),
460        };
461        LoopsError::Api {
462            message,
463            status: Some(self.status.as_u16()),
464            body: self.json(),
465        }
466    }
467
468    /// A success status whose variant the method does not handle.
469    fn unexpected(&self, action: &str) -> LoopsError {
470        LoopsError::Api {
471            message: format!("Failed to {action}"),
472            status: Some(self.status.as_u16()),
473            body: self.json(),
474        }
475    }
476
477    /// Decode a successful response with a generated `parse_response`, or
478    /// fail with the response's message when the status is not 2xx.
479    async fn parse<T, F, Fut>(&self, action: &'static str, parse_response: F) -> Result<T>
480    where
481        F: FnOnce(reqwest::Response) -> Fut,
482        Fut: Future<Output = anyhow::Result<T>>,
483    {
484        if !self.is_success() {
485            return Err(self.failure(action));
486        }
487        parse_response(self.to_reqwest())
488            .await
489            .map_err(|err| self.decode_error(action, err.into()))
490    }
491
492    /// Decode the body as untyped JSON, for endpoints whose success payload is
493    /// polymorphic.
494    fn parse_json(&self, action: &'static str) -> Result<Value> {
495        if !self.is_success() {
496            return Err(self.failure(action));
497        }
498        serde_json::from_slice(&self.body).map_err(|err| self.decode_error(action, Box::new(err)))
499    }
500
501    /// Decode the body into a hand-written response type.
502    fn parse_as<T: serde::de::DeserializeOwned>(&self, action: &'static str) -> Result<T> {
503        if !self.is_success() {
504            return Err(self.failure(action));
505        }
506        serde_json::from_slice(&self.body).map_err(|err| self.decode_error(action, Box::new(err)))
507    }
508
509    fn decode_error(
510        &self,
511        action: &'static str,
512        source: Box<dyn std::error::Error + Send + Sync>,
513    ) -> LoopsError {
514        LoopsError::Decode {
515            action,
516            status: self.status.as_u16(),
517            source,
518        }
519    }
520}
521
522static SINGLETON: RwLock<Option<Arc<LoopsClient>>> = RwLock::new(None);
523
524/// The process-wide client, created from the [`configure`](crate::configure)
525/// defaults on first use.
526///
527/// # Errors
528///
529/// [`LoopsError::Configuration`] when no API key is configured.
530pub fn get_client() -> Result<Arc<LoopsClient>> {
531    if let Some(client) = SINGLETON
532        .read()
533        .unwrap_or_else(PoisonError::into_inner)
534        .as_ref()
535    {
536        return Ok(Arc::clone(client));
537    }
538    let mut slot = SINGLETON.write().unwrap_or_else(PoisonError::into_inner);
539    if let Some(client) = slot.as_ref() {
540        return Ok(Arc::clone(client));
541    }
542    let client = Arc::new(LoopsClient::new()?);
543    *slot = Some(Arc::clone(&client));
544    Ok(client)
545}
546
547/// Drop the process-wide client so the next [`get_client`] builds a fresh
548/// one. Call it after [`configure`](crate::configure), or in test teardown.
549pub fn reset_client() {
550    SINGLETON
551        .write()
552        .unwrap_or_else(PoisonError::into_inner)
553        .take();
554}
555
556/// Whether [`get_client`] currently holds a client.
557#[cfg(feature = "testing")]
558pub(crate) fn has_client() -> bool {
559    SINGLETON
560        .read()
561        .unwrap_or_else(PoisonError::into_inner)
562        .is_some()
563}
564
565#[cfg(test)]
566mod tests {
567    use super::normalize_base_url;
568
569    #[test]
570    fn normalize_base_url_strips_trailing_slash_and_v1() {
571        for (given, expected) in [
572            ("https://app.loops.so/api", "https://app.loops.so/api"),
573            ("https://app.loops.so/api/", "https://app.loops.so/api"),
574            ("https://app.loops.so/api/v1", "https://app.loops.so/api"),
575            ("https://app.loops.so/api/v1/", "https://app.loops.so/api"),
576            (
577                "https://proxy.internal/loops/v1",
578                "https://proxy.internal/loops",
579            ),
580        ] {
581            assert_eq!(normalize_base_url(given), expected, "{given}");
582        }
583    }
584}