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_CDN_HOST: &str = "https://js.sentry-cdn.com";
17
18#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct AnalyticsConfig {
31 script_id: Option<String>,
32}
33
34impl AnalyticsConfig {
35 #[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 #[must_use]
45 pub const fn disabled() -> Self {
46 Self { script_id: None }
47 }
48
49 #[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 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 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 #[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 #[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 #[must_use]
114 pub const fn is_enabled(&self) -> bool {
115 self.script_id.is_some()
116 }
117
118 #[must_use]
121 pub fn script_id(&self) -> &str {
122 self.script_id.as_deref().unwrap_or_default()
123 }
124
125 #[must_use]
127 pub fn script_id_if_enabled(&self) -> Option<&str> {
128 self.script_id.as_deref()
129 }
130
131 #[must_use]
134 pub fn upstream_script_url(&self) -> String {
135 self.upstream_script_url_if_enabled().unwrap_or_default()
136 }
137
138 #[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 #[must_use]
148 pub fn upstream_event_url() -> String {
149 format!("{PLAUSIBLE_HOST}/api/event")
150 }
151}
152
153#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct SentryDsn {
161 public_key: String,
162 host: String,
163 project_id: String,
164}
165
166#[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 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 #[must_use]
202 pub fn upstream_script_url(&self) -> String {
203 format!("{SENTRY_CDN_HOST}/{}.min.js", self.public_key)
204 }
205
206 #[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}