Skip to main content

webserver_base/analytics/
config.rs

1//! What the proxies need to know about their upstreams.
2
3use crate::env::{self, EnvError};
4use crate::environment::Environment;
5
6/// The environment variable holding the Plausible script id.
7pub const ENV_ANALYTICS_ID: &str = "WSB_ANALYTICS_ID";
8
9/// The environment variable holding the browser Sentry DSN.
10pub const ENV_SENTRY_BROWSER_DSN: &str = "WSB_SENTRY_BROWSER_DSN";
11
12/// Plausible's script host.
13pub const PLAUSIBLE_HOST: &str = "https://plausible.io";
14
15/// Sentry's loader-script CDN.
16pub const SENTRY_CDN_HOST: &str = "https://js.sentry-cdn.com";
17
18/// Which Plausible site events belong to, or that none do.
19///
20/// Modern Plausible identifies a site by the id embedded in its script URL
21/// rather than a `data-domain` attribute, so this is the whole configuration.
22/// Deriving it from the request's hostname instead would split `www.` and
23/// apex traffic into two sites Plausible does not both know about, and would
24/// let a staging deploy pour into production's numbers.
25///
26/// A config can also be *disabled*: no script tag, no proxy routes, no
27/// upstream fetch, no event forwarding. That is what a local run gets, and
28/// what a blank or missing id gets.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct AnalyticsConfig {
31    script_id: Option<String>,
32}
33
34impl AnalyticsConfig {
35    /// Events for the site this script id belongs to. A blank id disables
36    /// analytics, as [`AnalyticsConfig::disabled`] does.
37    #[must_use]
38    pub fn new(script_id: impl Into<String>) -> Self {
39        let script_id: String = script_id.into();
40        Self::from_optional_id(Some(&script_id))
41    }
42
43    /// Analytics off: nothing is rendered, mounted, fetched or forwarded.
44    #[must_use]
45    pub const fn disabled() -> Self {
46        Self { script_id: None }
47    }
48
49    /// Enabled only for a non-blank id.
50    #[must_use]
51    pub fn from_optional_id(script_id: Option<&str>) -> Self {
52        Self {
53            script_id: script_id
54                .map(str::trim)
55                .filter(|id| !id.is_empty())
56                .map(String::from),
57        }
58    }
59
60    /// Reads [`ENV_ANALYTICS_ID`] and `WSB_ENVIRONMENT`.
61    ///
62    /// Disabled when the environment is `local`, or when the id is unset or
63    /// blank. Only a production run with an id is enabled.
64    ///
65    /// # Errors
66    ///
67    /// [`EnvError`] if `WSB_ENVIRONMENT` is unset, blank or invalid.
68    pub fn from_env() -> Result<Self, EnvError> {
69        Self::from_values(
70            std::env::var("WSB_ENVIRONMENT").ok().as_deref(),
71            env::optional(ENV_ANALYTICS_ID).as_deref(),
72        )
73    }
74
75    /// [`AnalyticsConfig::from_env`]'s logic over already-read values.
76    ///
77    /// # Errors
78    ///
79    /// [`EnvError`] if the environment is `None`, blank or invalid.
80    pub fn from_values(
81        environment: Option<&str>,
82        script_id: Option<&str>,
83    ) -> Result<Self, EnvError> {
84        Ok(Self::resolve(
85            Environment::from_value(environment)?,
86            script_id,
87        ))
88    }
89
90    /// The config for `environment` and an optional id: disabled when local or
91    /// when the id is missing or blank.
92    #[must_use]
93    pub fn resolve(environment: Environment, script_id: Option<&str>) -> Self {
94        if environment.is_local() {
95            Self::disabled()
96        } else {
97            Self::from_optional_id(script_id)
98        }
99    }
100
101    /// This config as it applies in `environment`: always disabled when local,
102    /// whatever id was passed in.
103    #[must_use]
104    pub fn for_environment(self, environment: Environment) -> Self {
105        if environment.is_local() {
106            Self::disabled()
107        } else {
108            self
109        }
110    }
111
112    /// Whether analytics is on.
113    #[must_use]
114    pub const fn is_enabled(&self) -> bool {
115        self.script_id.is_some()
116    }
117
118    /// The configured script id, or `""` when analytics is disabled. Prefer
119    /// [`AnalyticsConfig::script_id_if_enabled`].
120    #[must_use]
121    pub fn script_id(&self) -> &str {
122        self.script_id.as_deref().unwrap_or_default()
123    }
124
125    /// The configured script id, if enabled.
126    #[must_use]
127    pub fn script_id_if_enabled(&self) -> Option<&str> {
128        self.script_id.as_deref()
129    }
130
131    /// The upstream script URL this proxy fetches, or `""` when analytics is
132    /// disabled. Prefer [`AnalyticsConfig::upstream_script_url_if_enabled`].
133    #[must_use]
134    pub fn upstream_script_url(&self) -> String {
135        self.upstream_script_url_if_enabled().unwrap_or_default()
136    }
137
138    /// The upstream script URL this proxy fetches, if enabled.
139    #[must_use]
140    pub fn upstream_script_url_if_enabled(&self) -> Option<String> {
141        self.script_id
142            .as_ref()
143            .map(|id| format!("{PLAUSIBLE_HOST}/js/{id}.js"))
144    }
145
146    /// The upstream event endpoint this proxy forwards to.
147    #[must_use]
148    pub fn upstream_event_url() -> String {
149        format!("{PLAUSIBLE_HOST}/api/event")
150    }
151}
152
153/// A parsed Sentry DSN.
154///
155/// Only the pieces the tunnel needs: which host to relay to, and which project.
156/// Because a frontend declares exactly one browser DSN, the tunnel never has to
157/// parse an envelope to discover where an event belongs — which keeps it a dumb
158/// byte relay and stops it being usable as an open relay to arbitrary projects.
159#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct SentryDsn {
161    public_key: String,
162    host: String,
163    project_id: String,
164}
165
166/// Why a DSN could not be understood.
167#[derive(Debug, thiserror::Error)]
168#[error("`{dsn}` is not a Sentry DSN; expected `https://<key>@<host>/<project id>`")]
169pub struct SentryDsnParseError {
170    dsn: String,
171}
172
173impl SentryDsn {
174    /// Parses `https://<public key>@<host>/<project id>`.
175    ///
176    /// # Errors
177    ///
178    /// [`SentryDsnParseError`] if the DSN is not in that shape.
179    pub fn parse(dsn: &str) -> Result<Self, SentryDsnParseError> {
180        let malformed = || SentryDsnParseError {
181            dsn: dsn.to_string(),
182        };
183
184        let scheme_end: usize = dsn.find("://").ok_or_else(malformed)? + 3;
185        let rest: &str = &dsn[scheme_end..];
186        let (public_key, remainder) = rest.split_once('@').ok_or_else(malformed)?;
187        let (host, project_id) = remainder.rsplit_once('/').ok_or_else(malformed)?;
188
189        if public_key.is_empty() || host.is_empty() || project_id.is_empty() {
190            return Err(malformed());
191        }
192
193        Ok(Self {
194            public_key: public_key.to_string(),
195            host: host.to_string(),
196            project_id: project_id.to_string(),
197        })
198    }
199
200    /// The upstream loader script for this DSN's public key.
201    #[must_use]
202    pub fn upstream_script_url(&self) -> String {
203        format!("{SENTRY_CDN_HOST}/{}.min.js", self.public_key)
204    }
205
206    /// Where envelopes are relayed, verbatim.
207    #[must_use]
208    pub fn upstream_envelope_url(&self) -> String {
209        format!("https://{}/api/{}/envelope/", self.host, self.project_id)
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    use super::{AnalyticsConfig, SentryDsn};
216    use crate::environment::Environment;
217
218    #[test]
219    fn local_mode_disables_analytics_even_with_an_id() {
220        let config: AnalyticsConfig = AnalyticsConfig::resolve(Environment::Local, Some("pa-x"));
221        assert!(!config.is_enabled());
222        assert_eq!(None, config.upstream_script_url_if_enabled());
223
224        let config: AnalyticsConfig =
225            AnalyticsConfig::new("pa-x").for_environment(Environment::Local);
226        assert!(!config.is_enabled());
227    }
228
229    #[test]
230    fn an_unset_or_blank_id_disables_analytics_in_production() {
231        assert!(!AnalyticsConfig::resolve(Environment::Production, None).is_enabled());
232        assert!(!AnalyticsConfig::resolve(Environment::Production, Some("")).is_enabled());
233        assert!(!AnalyticsConfig::resolve(Environment::Production, Some("  ")).is_enabled());
234        assert!(!AnalyticsConfig::new("").is_enabled());
235    }
236
237    #[test]
238    fn from_values_covers_local_production_and_an_unset_environment() {
239        let local = AnalyticsConfig::from_values(Some("local"), Some("pa-x")).expect("valid");
240        assert!(!local.is_enabled());
241
242        let prod = AnalyticsConfig::from_values(Some("production"), Some("pa-x")).expect("valid");
243        assert!(prod.is_enabled());
244
245        let no_id = AnalyticsConfig::from_values(Some("production"), None).expect("valid");
246        assert!(!no_id.is_enabled());
247
248        assert!(AnalyticsConfig::from_values(None, Some("pa-x")).is_err());
249        assert!(AnalyticsConfig::from_values(Some(""), Some("pa-x")).is_err());
250        assert!(AnalyticsConfig::from_values(Some("staging"), Some("pa-x")).is_err());
251    }
252
253    #[test]
254    fn the_plain_accessors_keep_their_types_and_are_empty_when_disabled() {
255        let off: AnalyticsConfig = AnalyticsConfig::disabled();
256        assert_eq!("", off.script_id());
257        assert_eq!(String::new(), off.upstream_script_url());
258
259        let on: AnalyticsConfig = AnalyticsConfig::new("pa-x");
260        assert_eq!("pa-x", on.script_id());
261        assert_eq!("https://plausible.io/js/pa-x.js", on.upstream_script_url());
262    }
263
264    #[test]
265    fn production_with_an_id_is_unchanged() {
266        let config: AnalyticsConfig =
267            AnalyticsConfig::resolve(Environment::Production, Some("pa-x"));
268        assert!(config.is_enabled());
269        assert_eq!(Some("pa-x"), config.script_id_if_enabled());
270        assert_eq!(config, AnalyticsConfig::new("pa-x"));
271        assert_eq!(
272            config,
273            AnalyticsConfig::new("pa-x").for_environment(Environment::Production)
274        );
275    }
276
277    #[test]
278    fn the_plausible_script_url_embeds_the_site_id() {
279        let config: AnalyticsConfig = AnalyticsConfig::new("pa-1qi0TQEvpewNxVHboeeOC");
280
281        let expected: Option<String> = Some(String::from(
282            "https://plausible.io/js/pa-1qi0TQEvpewNxVHboeeOC.js",
283        ));
284        let actual: Option<String> = config.upstream_script_url_if_enabled();
285        assert_eq!(expected, actual);
286    }
287
288    #[test]
289    fn a_dsn_yields_its_loader_script_and_envelope_endpoint() {
290        let dsn: SentryDsn =
291            SentryDsn::parse("https://abc123@o4504844394627072.ingest.sentry.io/4504862450515968")
292                .expect("a well-formed DSN");
293
294        let expected: String = String::from("https://js.sentry-cdn.com/abc123.min.js");
295        let actual: String = dsn.upstream_script_url();
296        assert_eq!(expected, actual);
297
298        let expected: String = String::from(
299            "https://o4504844394627072.ingest.sentry.io/api/4504862450515968/envelope/",
300        );
301        let actual: String = dsn.upstream_envelope_url();
302        assert_eq!(expected, actual);
303    }
304
305    #[test]
306    fn a_malformed_dsn_is_rejected_at_boot_rather_than_at_the_first_error() {
307        assert!(SentryDsn::parse("not-a-dsn").is_err());
308        assert!(SentryDsn::parse("https://o123.ingest.sentry.io/456").is_err());
309        assert!(SentryDsn::parse("https://key@host/").is_err());
310        assert!(SentryDsn::parse("https://@host/456").is_err());
311    }
312}