1mod 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#[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#[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 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 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 pub fn safe_mode(mut self, safe_mode: bool) -> Self {
112 self.safe_mode = Some(safe_mode);
113 self
114 }
115
116 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 pub fn http_client(mut self, client: reqwest::Client) -> Self {
131 self.http_client = Some(client);
132 self
133 }
134
135 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
183pub(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 pub fn new() -> Result<Self> {
198 Self::builder().build()
199 }
200
201 pub fn builder() -> LoopsClientBuilder {
203 LoopsClientBuilder::default()
204 }
205
206 pub fn base_url(&self) -> &str {
208 self.base_url.as_str()
209 }
210
211 pub fn safe_mode(&self) -> bool {
213 self.safe_mode
214 }
215
216 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 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 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 async fn send(
322 &self,
323 route: Route,
324 params: &[&str],
325 build: impl FnOnce(reqwest::RequestBuilder) -> reqwest::RequestBuilder,
326 ) -> Result<RawResponse> {
327 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
369fn 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
390fn 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
400fn check(value: &impl validator::Validate) -> Result<()> {
402 value
403 .validate()
404 .map_err(|err| LoopsError::InvalidInput(err.to_string()))
405}
406
407pub(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
422struct 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 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 fn failure(&self, action: &str) -> LoopsError {
452 self.failure_with(&format!("Failed to {action}"))
453 }
454
455 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 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 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 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 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
524pub 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
547pub fn reset_client() {
550 SINGLETON
551 .write()
552 .unwrap_or_else(PoisonError::into_inner)
553 .take();
554}
555
556#[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}