Skip to main content

loops_so/
config.rs

1use std::sync::{PoisonError, RwLock};
2
3/// The base URL of the Loops API. The `/v1` version segment is part of each
4/// endpoint path, not of the base URL.
5pub const DEFAULT_BASE_URL: &str = "https://app.loops.so/api";
6
7/// The environment variable read when no API key was configured.
8pub const API_KEY_ENV_VAR: &str = "LOOPS_API_KEY";
9
10/// The process-wide defaults [`LoopsClient`](crate::LoopsClient) falls back to.
11#[derive(Debug, Clone, PartialEq, Eq)]
12#[non_exhaustive]
13pub struct LoopsConfig {
14    /// API key from [`configure`], else the `LOOPS_API_KEY` environment variable.
15    pub api_key: Option<String>,
16    /// Base URL of the Loops API.
17    pub base_url: String,
18    /// When `true`, only addresses ending in one of
19    /// [`safe_mode_allowed_domains`](Self::safe_mode_allowed_domains) are accepted.
20    pub safe_mode: bool,
21    /// Domains allowed in safe mode, each starting with `@` (e.g. `"@test.com"`).
22    pub safe_mode_allowed_domains: Vec<String>,
23}
24
25/// The settings to change in a [`configure`] call. Unset fields keep their
26/// current value.
27#[derive(Debug, Clone, Default, PartialEq, Eq)]
28#[non_exhaustive]
29pub struct ConfigureOptions {
30    /// Loops API key.
31    pub api_key: Option<String>,
32    /// Base URL of the Loops API (default [`DEFAULT_BASE_URL`]).
33    pub base_url: Option<String>,
34    /// Turn safe mode on or off.
35    pub safe_mode: Option<bool>,
36    /// Domains allowed in safe mode, each starting with `@`.
37    pub safe_mode_allowed_domains: Option<Vec<String>>,
38}
39
40impl ConfigureOptions {
41    /// An empty set of changes.
42    pub fn new() -> Self {
43        Self::default()
44    }
45
46    /// Set the API key.
47    #[must_use]
48    pub fn api_key(mut self, api_key: impl Into<String>) -> Self {
49        self.api_key = Some(api_key.into());
50        self
51    }
52
53    /// Set the base URL. Do not include the `/v1` version segment; a trailing
54    /// `/v1` is stripped.
55    #[must_use]
56    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
57        self.base_url = Some(base_url.into());
58        self
59    }
60
61    /// Turn safe mode on or off. Useful in local development to avoid
62    /// emailing real users by accident.
63    #[must_use]
64    pub fn safe_mode(mut self, safe_mode: bool) -> Self {
65        self.safe_mode = Some(safe_mode);
66        self
67    }
68
69    /// Set the domains allowed in safe mode, each starting with `@`.
70    #[must_use]
71    pub fn safe_mode_allowed_domains<I, S>(mut self, domains: I) -> Self
72    where
73        I: IntoIterator<Item = S>,
74        S: Into<String>,
75    {
76        self.safe_mode_allowed_domains = Some(domains.into_iter().map(Into::into).collect());
77        self
78    }
79}
80
81#[derive(Debug, Clone)]
82struct Stored {
83    api_key: Option<String>,
84    base_url: String,
85    safe_mode: bool,
86    safe_mode_allowed_domains: Vec<String>,
87}
88
89static STORED: RwLock<Stored> = RwLock::new(Stored {
90    api_key: None,
91    base_url: String::new(),
92    safe_mode: false,
93    safe_mode_allowed_domains: Vec::new(),
94});
95
96/// Change the process-wide defaults. Only the fields set on `options` change.
97///
98/// Call [`reset_client`](crate::reset_client) afterwards if a client was
99/// already created through [`get_client`](crate::get_client).
100pub fn configure(options: ConfigureOptions) {
101    let mut stored = STORED.write().unwrap_or_else(PoisonError::into_inner);
102    if let Some(api_key) = options.api_key {
103        stored.api_key = Some(api_key);
104    }
105    if let Some(base_url) = options.base_url {
106        stored.base_url = base_url;
107    }
108    if let Some(safe_mode) = options.safe_mode {
109        stored.safe_mode = safe_mode;
110    }
111    if let Some(domains) = options.safe_mode_allowed_domains {
112        stored.safe_mode_allowed_domains = domains;
113    }
114}
115
116/// The current process-wide defaults, with the API key falling back to the
117/// `LOOPS_API_KEY` environment variable.
118pub fn get_config() -> LoopsConfig {
119    let stored = STORED
120        .read()
121        .unwrap_or_else(PoisonError::into_inner)
122        .clone();
123    LoopsConfig {
124        api_key: stored.api_key.filter(|key| !key.is_empty()).or_else(|| {
125            std::env::var(API_KEY_ENV_VAR)
126                .ok()
127                .filter(|key| !key.is_empty())
128        }),
129        base_url: if stored.base_url.is_empty() {
130            DEFAULT_BASE_URL.to_owned()
131        } else {
132            stored.base_url
133        },
134        safe_mode: stored.safe_mode,
135        safe_mode_allowed_domains: stored.safe_mode_allowed_domains,
136    }
137}
138
139/// Snapshot and restore the stored defaults, so the `testing` mock can put
140/// back what the test found.
141#[cfg(feature = "testing")]
142pub(crate) fn snapshot() -> impl FnOnce() + Send + 'static {
143    let saved = STORED
144        .read()
145        .unwrap_or_else(PoisonError::into_inner)
146        .clone();
147    move || *STORED.write().unwrap_or_else(PoisonError::into_inner) = saved
148}