webserver_base/analytics/
config.rs1use crate::env::{self, EnvError};
4use crate::environment::Environment;
5
6pub const ENV_ANALYTICS_ID: &str = "WSB_ANALYTICS_ID";
8
9pub const ENV_SENTRY_BROWSER_DSN: &str = "WSB_SENTRY_BROWSER_DSN";
11
12pub const PLAUSIBLE_HOST: &str = "https://plausible.io";
14
15pub const SENTRY_BROWSER_CDN_HOST: &str = "https://browser.sentry-cdn.com";
17
18pub const SENTRY_BROWSER_SDK_VERSION: &str = "10.78.0";
26
27#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct AnalyticsConfig {
40 script_id: Option<String>,
41}
42
43impl AnalyticsConfig {
44 #[must_use]
47 pub fn new(script_id: impl Into<String>) -> Self {
48 let script_id: String = script_id.into();
49 Self::from_optional_id(Some(&script_id))
50 }
51
52 #[must_use]
54 pub const fn disabled() -> Self {
55 Self { script_id: None }
56 }
57
58 #[must_use]
60 pub fn from_optional_id(script_id: Option<&str>) -> Self {
61 Self {
62 script_id: script_id
63 .map(str::trim)
64 .filter(|id| !id.is_empty())
65 .map(String::from),
66 }
67 }
68
69 pub fn from_env() -> Result<Self, EnvError> {
78 Self::from_values(
79 std::env::var("WSB_ENVIRONMENT").ok().as_deref(),
80 env::optional(ENV_ANALYTICS_ID).as_deref(),
81 )
82 }
83
84 pub fn from_values(
90 environment: Option<&str>,
91 script_id: Option<&str>,
92 ) -> Result<Self, EnvError> {
93 Ok(Self::resolve(
94 Environment::from_value(environment)?,
95 script_id,
96 ))
97 }
98
99 #[must_use]
102 pub fn resolve(environment: Environment, script_id: Option<&str>) -> Self {
103 if environment.is_local() {
104 Self::disabled()
105 } else {
106 Self::from_optional_id(script_id)
107 }
108 }
109
110 #[must_use]
113 pub fn for_environment(self, environment: Environment) -> Self {
114 if environment.is_local() {
115 Self::disabled()
116 } else {
117 self
118 }
119 }
120
121 #[must_use]
123 pub const fn is_enabled(&self) -> bool {
124 self.script_id.is_some()
125 }
126
127 #[must_use]
130 pub fn script_id(&self) -> &str {
131 self.script_id.as_deref().unwrap_or_default()
132 }
133
134 #[must_use]
136 pub fn script_id_if_enabled(&self) -> Option<&str> {
137 self.script_id.as_deref()
138 }
139
140 #[must_use]
143 pub fn upstream_script_url(&self) -> String {
144 self.upstream_script_url_if_enabled().unwrap_or_default()
145 }
146
147 #[must_use]
149 pub fn upstream_script_url_if_enabled(&self) -> Option<String> {
150 self.script_id
151 .as_ref()
152 .map(|id| format!("{PLAUSIBLE_HOST}/js/{id}.js"))
153 }
154
155 #[must_use]
157 pub fn upstream_event_url() -> String {
158 format!("{PLAUSIBLE_HOST}/api/event")
159 }
160}
161
162#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct SentryDsn {
170 dsn: String,
171 host: String,
172 project_id: String,
173}
174
175#[derive(Debug, thiserror::Error)]
177#[error("`{dsn}` is not a Sentry DSN; expected `https://<key>@<host>/<project id>`")]
178pub struct SentryDsnParseError {
179 dsn: String,
180}
181
182impl SentryDsn {
183 pub fn parse(dsn: &str) -> Result<Self, SentryDsnParseError> {
189 let malformed = || SentryDsnParseError {
190 dsn: dsn.to_string(),
191 };
192
193 let scheme_end: usize = dsn.find("://").ok_or_else(malformed)? + 3;
194 let rest: &str = &dsn[scheme_end..];
195 let (public_key, remainder) = rest.split_once('@').ok_or_else(malformed)?;
196 let (host, project_id) = remainder.rsplit_once('/').ok_or_else(malformed)?;
197
198 if public_key.is_empty() || host.is_empty() || project_id.is_empty() {
199 return Err(malformed());
200 }
201
202 Ok(Self {
203 dsn: dsn.to_string(),
204 host: host.to_string(),
205 project_id: project_id.to_string(),
206 })
207 }
208
209 #[must_use]
212 pub fn as_str(&self) -> &str {
213 &self.dsn
214 }
215
216 #[must_use]
225 pub fn upstream_bundle_url(tracing: bool) -> String {
226 let bundle: &str = if tracing { "bundle.tracing" } else { "bundle" };
227 format!("{SENTRY_BROWSER_CDN_HOST}/{SENTRY_BROWSER_SDK_VERSION}/{bundle}.min.js")
228 }
229
230 #[must_use]
232 pub fn upstream_envelope_url(&self) -> String {
233 format!("https://{}/api/{}/envelope/", self.host, self.project_id)
234 }
235}
236
237#[cfg(test)]
238mod tests {
239 use super::{AnalyticsConfig, SENTRY_BROWSER_SDK_VERSION, SentryDsn};
240 use crate::environment::Environment;
241
242 #[test]
243 fn local_mode_disables_analytics_even_with_an_id() {
244 let config: AnalyticsConfig = AnalyticsConfig::resolve(Environment::Local, Some("pa-x"));
245 assert!(!config.is_enabled());
246 assert_eq!(None, config.upstream_script_url_if_enabled());
247
248 let config: AnalyticsConfig =
249 AnalyticsConfig::new("pa-x").for_environment(Environment::Local);
250 assert!(!config.is_enabled());
251 }
252
253 #[test]
254 fn an_unset_or_blank_id_disables_analytics_in_production() {
255 assert!(!AnalyticsConfig::resolve(Environment::Production, None).is_enabled());
256 assert!(!AnalyticsConfig::resolve(Environment::Production, Some("")).is_enabled());
257 assert!(!AnalyticsConfig::resolve(Environment::Production, Some(" ")).is_enabled());
258 assert!(!AnalyticsConfig::new("").is_enabled());
259 }
260
261 #[test]
262 fn from_values_covers_local_production_and_an_unset_environment() {
263 let local = AnalyticsConfig::from_values(Some("local"), Some("pa-x")).expect("valid");
264 assert!(!local.is_enabled());
265
266 let prod = AnalyticsConfig::from_values(Some("production"), Some("pa-x")).expect("valid");
267 assert!(prod.is_enabled());
268
269 let no_id = AnalyticsConfig::from_values(Some("production"), None).expect("valid");
270 assert!(!no_id.is_enabled());
271
272 assert!(AnalyticsConfig::from_values(None, Some("pa-x")).is_err());
273 assert!(AnalyticsConfig::from_values(Some(""), Some("pa-x")).is_err());
274 assert!(AnalyticsConfig::from_values(Some("staging"), Some("pa-x")).is_err());
275 }
276
277 #[test]
278 fn the_plain_accessors_keep_their_types_and_are_empty_when_disabled() {
279 let off: AnalyticsConfig = AnalyticsConfig::disabled();
280 assert_eq!("", off.script_id());
281 assert_eq!(String::new(), off.upstream_script_url());
282
283 let on: AnalyticsConfig = AnalyticsConfig::new("pa-x");
284 assert_eq!("pa-x", on.script_id());
285 assert_eq!("https://plausible.io/js/pa-x.js", on.upstream_script_url());
286 }
287
288 #[test]
289 fn production_with_an_id_is_unchanged() {
290 let config: AnalyticsConfig =
291 AnalyticsConfig::resolve(Environment::Production, Some("pa-x"));
292 assert!(config.is_enabled());
293 assert_eq!(Some("pa-x"), config.script_id_if_enabled());
294 assert_eq!(config, AnalyticsConfig::new("pa-x"));
295 assert_eq!(
296 config,
297 AnalyticsConfig::new("pa-x").for_environment(Environment::Production)
298 );
299 }
300
301 #[test]
302 fn the_plausible_script_url_embeds_the_site_id() {
303 let config: AnalyticsConfig = AnalyticsConfig::new("pa-1qi0TQEvpewNxVHboeeOC");
304
305 let expected: Option<String> = Some(String::from(
306 "https://plausible.io/js/pa-1qi0TQEvpewNxVHboeeOC.js",
307 ));
308 let actual: Option<String> = config.upstream_script_url_if_enabled();
309 assert_eq!(expected, actual);
310 }
311
312 #[test]
313 fn a_dsn_yields_its_envelope_endpoint_and_is_kept_verbatim() {
314 let dsn: SentryDsn =
315 SentryDsn::parse("https://abc123@o4504844394627072.ingest.sentry.io/4504862450515968")
316 .expect("a well-formed DSN");
317
318 let expected: &str = "https://abc123@o4504844394627072.ingest.sentry.io/4504862450515968";
319 assert_eq!(expected, dsn.as_str());
320
321 let expected: String = String::from(
322 "https://o4504844394627072.ingest.sentry.io/api/4504862450515968/envelope/",
323 );
324 let actual: String = dsn.upstream_envelope_url();
325 assert_eq!(expected, actual);
326 }
327
328 #[test]
329 fn the_bundle_is_pinned_and_the_tracing_one_is_only_named_when_asked_for() {
330 let expected: String =
331 format!("https://browser.sentry-cdn.com/{SENTRY_BROWSER_SDK_VERSION}/bundle.min.js");
332 assert_eq!(expected, SentryDsn::upstream_bundle_url(false));
333
334 let expected: String = format!(
335 "https://browser.sentry-cdn.com/{SENTRY_BROWSER_SDK_VERSION}/bundle.tracing.min.js"
336 );
337 assert_eq!(expected, SentryDsn::upstream_bundle_url(true));
338 }
339
340 #[test]
341 fn a_malformed_dsn_is_rejected_at_boot_rather_than_at_the_first_error() {
342 assert!(SentryDsn::parse("not-a-dsn").is_err());
343 assert!(SentryDsn::parse("https://o123.ingest.sentry.io/456").is_err());
344 assert!(SentryDsn::parse("https://key@host/").is_err());
345 assert!(SentryDsn::parse("https://@host/456").is_err());
346 }
347}