use crate::env::{self, EnvError};
use crate::environment::Environment;
pub const ENV_ANALYTICS_ID: &str = "WSB_ANALYTICS_ID";
pub const ENV_SENTRY_BROWSER_DSN: &str = "WSB_SENTRY_BROWSER_DSN";
pub const PLAUSIBLE_HOST: &str = "https://plausible.io";
pub const SENTRY_CDN_HOST: &str = "https://js.sentry-cdn.com";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnalyticsConfig {
script_id: Option<String>,
}
impl AnalyticsConfig {
#[must_use]
pub fn new(script_id: impl Into<String>) -> Self {
let script_id: String = script_id.into();
Self::from_optional_id(Some(&script_id))
}
#[must_use]
pub const fn disabled() -> Self {
Self { script_id: None }
}
#[must_use]
pub fn from_optional_id(script_id: Option<&str>) -> Self {
Self {
script_id: script_id
.map(str::trim)
.filter(|id| !id.is_empty())
.map(String::from),
}
}
pub fn from_env() -> Result<Self, EnvError> {
Self::from_values(
std::env::var("WSB_ENVIRONMENT").ok().as_deref(),
env::optional(ENV_ANALYTICS_ID).as_deref(),
)
}
pub fn from_values(
environment: Option<&str>,
script_id: Option<&str>,
) -> Result<Self, EnvError> {
Ok(Self::resolve(
Environment::from_value(environment)?,
script_id,
))
}
#[must_use]
pub fn resolve(environment: Environment, script_id: Option<&str>) -> Self {
if environment.is_local() {
Self::disabled()
} else {
Self::from_optional_id(script_id)
}
}
#[must_use]
pub fn for_environment(self, environment: Environment) -> Self {
if environment.is_local() {
Self::disabled()
} else {
self
}
}
#[must_use]
pub const fn is_enabled(&self) -> bool {
self.script_id.is_some()
}
#[must_use]
pub fn script_id(&self) -> &str {
self.script_id.as_deref().unwrap_or_default()
}
#[must_use]
pub fn script_id_if_enabled(&self) -> Option<&str> {
self.script_id.as_deref()
}
#[must_use]
pub fn upstream_script_url(&self) -> String {
self.upstream_script_url_if_enabled().unwrap_or_default()
}
#[must_use]
pub fn upstream_script_url_if_enabled(&self) -> Option<String> {
self.script_id
.as_ref()
.map(|id| format!("{PLAUSIBLE_HOST}/js/{id}.js"))
}
#[must_use]
pub fn upstream_event_url() -> String {
format!("{PLAUSIBLE_HOST}/api/event")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SentryDsn {
public_key: String,
host: String,
project_id: String,
}
#[derive(Debug, thiserror::Error)]
#[error("`{dsn}` is not a Sentry DSN; expected `https://<key>@<host>/<project id>`")]
pub struct SentryDsnParseError {
dsn: String,
}
impl SentryDsn {
pub fn parse(dsn: &str) -> Result<Self, SentryDsnParseError> {
let malformed = || SentryDsnParseError {
dsn: dsn.to_string(),
};
let scheme_end: usize = dsn.find("://").ok_or_else(malformed)? + 3;
let rest: &str = &dsn[scheme_end..];
let (public_key, remainder) = rest.split_once('@').ok_or_else(malformed)?;
let (host, project_id) = remainder.rsplit_once('/').ok_or_else(malformed)?;
if public_key.is_empty() || host.is_empty() || project_id.is_empty() {
return Err(malformed());
}
Ok(Self {
public_key: public_key.to_string(),
host: host.to_string(),
project_id: project_id.to_string(),
})
}
#[must_use]
pub fn upstream_script_url(&self) -> String {
format!("{SENTRY_CDN_HOST}/{}.min.js", self.public_key)
}
#[must_use]
pub fn upstream_envelope_url(&self) -> String {
format!("https://{}/api/{}/envelope/", self.host, self.project_id)
}
}
#[cfg(test)]
mod tests {
use super::{AnalyticsConfig, SentryDsn};
use crate::environment::Environment;
#[test]
fn local_mode_disables_analytics_even_with_an_id() {
let config: AnalyticsConfig = AnalyticsConfig::resolve(Environment::Local, Some("pa-x"));
assert!(!config.is_enabled());
assert_eq!(None, config.upstream_script_url_if_enabled());
let config: AnalyticsConfig =
AnalyticsConfig::new("pa-x").for_environment(Environment::Local);
assert!(!config.is_enabled());
}
#[test]
fn an_unset_or_blank_id_disables_analytics_in_production() {
assert!(!AnalyticsConfig::resolve(Environment::Production, None).is_enabled());
assert!(!AnalyticsConfig::resolve(Environment::Production, Some("")).is_enabled());
assert!(!AnalyticsConfig::resolve(Environment::Production, Some(" ")).is_enabled());
assert!(!AnalyticsConfig::new("").is_enabled());
}
#[test]
fn from_values_covers_local_production_and_an_unset_environment() {
let local = AnalyticsConfig::from_values(Some("local"), Some("pa-x")).expect("valid");
assert!(!local.is_enabled());
let prod = AnalyticsConfig::from_values(Some("production"), Some("pa-x")).expect("valid");
assert!(prod.is_enabled());
let no_id = AnalyticsConfig::from_values(Some("production"), None).expect("valid");
assert!(!no_id.is_enabled());
assert!(AnalyticsConfig::from_values(None, Some("pa-x")).is_err());
assert!(AnalyticsConfig::from_values(Some(""), Some("pa-x")).is_err());
assert!(AnalyticsConfig::from_values(Some("staging"), Some("pa-x")).is_err());
}
#[test]
fn the_plain_accessors_keep_their_types_and_are_empty_when_disabled() {
let off: AnalyticsConfig = AnalyticsConfig::disabled();
assert_eq!("", off.script_id());
assert_eq!(String::new(), off.upstream_script_url());
let on: AnalyticsConfig = AnalyticsConfig::new("pa-x");
assert_eq!("pa-x", on.script_id());
assert_eq!("https://plausible.io/js/pa-x.js", on.upstream_script_url());
}
#[test]
fn production_with_an_id_is_unchanged() {
let config: AnalyticsConfig =
AnalyticsConfig::resolve(Environment::Production, Some("pa-x"));
assert!(config.is_enabled());
assert_eq!(Some("pa-x"), config.script_id_if_enabled());
assert_eq!(config, AnalyticsConfig::new("pa-x"));
assert_eq!(
config,
AnalyticsConfig::new("pa-x").for_environment(Environment::Production)
);
}
#[test]
fn the_plausible_script_url_embeds_the_site_id() {
let config: AnalyticsConfig = AnalyticsConfig::new("pa-1qi0TQEvpewNxVHboeeOC");
let expected: Option<String> = Some(String::from(
"https://plausible.io/js/pa-1qi0TQEvpewNxVHboeeOC.js",
));
let actual: Option<String> = config.upstream_script_url_if_enabled();
assert_eq!(expected, actual);
}
#[test]
fn a_dsn_yields_its_loader_script_and_envelope_endpoint() {
let dsn: SentryDsn =
SentryDsn::parse("https://abc123@o4504844394627072.ingest.sentry.io/4504862450515968")
.expect("a well-formed DSN");
let expected: String = String::from("https://js.sentry-cdn.com/abc123.min.js");
let actual: String = dsn.upstream_script_url();
assert_eq!(expected, actual);
let expected: String = String::from(
"https://o4504844394627072.ingest.sentry.io/api/4504862450515968/envelope/",
);
let actual: String = dsn.upstream_envelope_url();
assert_eq!(expected, actual);
}
#[test]
fn a_malformed_dsn_is_rejected_at_boot_rather_than_at_the_first_error() {
assert!(SentryDsn::parse("not-a-dsn").is_err());
assert!(SentryDsn::parse("https://o123.ingest.sentry.io/456").is_err());
assert!(SentryDsn::parse("https://key@host/").is_err());
assert!(SentryDsn::parse("https://@host/456").is_err());
}
}