use crate::client::Sender;
use crate::{Context, Error, Result, TrackResponse};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::net::IpAddr;
use std::time::SystemTime;
use uuid::Uuid;
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum TrackKind {
Event,
Identify,
Performance,
}
#[derive(Debug, Default)]
enum Properties {
#[default]
None,
Ready(Map<String, Value>),
Invalid(String),
}
#[derive(Clone, Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
struct Metrics {
#[serde(skip_serializing_if = "Option::is_none")]
lcp: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
inp: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
cls: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
fcp: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
ttfb: Option<f64>,
}
impl Metrics {
fn is_empty(&self) -> bool {
self.lcp.is_none()
&& self.inp.is_none()
&& self.cls.is_none()
&& self.fcp.is_none()
&& self.ttfb.is_none()
}
fn validate(&self) -> Result<()> {
validate_metric("lcp", self.lcp, 60_000.0, "a finite number from 0 to 60000")?;
validate_metric("inp", self.inp, 60_000.0, "a finite number from 0 to 60000")?;
validate_metric("cls", self.cls, 100.0, "a finite number from 0 to 100")?;
validate_metric("fcp", self.fcp, 60_000.0, "a finite number from 0 to 60000")?;
validate_metric(
"ttfb",
self.ttfb,
60_000.0,
"a finite number from 0 to 60000",
)?;
Ok(())
}
}
fn validate_metric(
name: &'static str,
value: Option<f64>,
maximum: f64,
expected: &'static str,
) -> Result<()> {
if let Some(value) = value
&& (!value.is_finite() || !(0.0..=maximum).contains(&value))
{
return Err(Error::InvalidMetric {
name,
expected,
value,
});
}
Ok(())
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct Payload {
website: Uuid,
#[serde(flatten)]
context: Context,
#[serde(skip_serializing_if = "Option::is_none")]
name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
data: Option<Map<String, Value>>,
#[serde(flatten)]
metrics: Metrics,
}
#[derive(Debug, Serialize)]
pub(crate) struct TrackRequest {
#[serde(rename = "type")]
kind: TrackKind,
payload: Payload,
}
impl TrackRequest {
pub(crate) fn kind(&self) -> TrackKind {
self.kind
}
pub(crate) fn hostname(&self) -> Option<&str> {
self.payload.context.hostname.as_deref()
}
}
#[derive(Debug)]
pub struct Track {
pub(crate) sender: Sender,
kind: TrackKind,
context: Context,
name: Option<String>,
data: Properties,
metrics: Metrics,
cache: Option<String>,
}
impl Track {
pub(crate) fn pageview(sender: Sender, context: Context, url: String) -> Self {
Self {
sender,
kind: TrackKind::Event,
context: context.url(url),
name: None,
data: Properties::None,
metrics: Metrics::default(),
cache: None,
}
}
pub(crate) fn event(sender: Sender, context: Context, name: String) -> Self {
Self {
sender,
kind: TrackKind::Event,
context,
name: Some(name),
data: Properties::None,
metrics: Metrics::default(),
cache: None,
}
}
pub(crate) fn identify(sender: Sender, context: Context, id: Option<String>) -> Self {
let context = match id {
Some(id) => context.distinct_id(id),
None => context,
};
Self {
sender,
kind: TrackKind::Identify,
context,
name: None,
data: Properties::None,
metrics: Metrics::default(),
cache: None,
}
}
pub(crate) fn performance(sender: Sender, context: Context, url: String) -> Self {
Self {
sender,
kind: TrackKind::Performance,
context: context.url(url),
name: None,
data: Properties::None,
metrics: Metrics::default(),
cache: None,
}
}
#[must_use]
pub fn kind(&self) -> TrackKind {
self.kind
}
#[must_use]
pub fn context(mut self, context: Context) -> Self {
self.context = context;
self
}
#[must_use]
pub fn hostname(mut self, hostname: impl Into<String>) -> Self {
self.context.hostname = Some(hostname.into());
self
}
#[must_use]
pub fn screen(mut self, width: u32, height: u32) -> Self {
self.context.screen = Some(format!("{width}x{height}"));
self
}
#[must_use]
pub fn language(mut self, language: impl Into<String>) -> Self {
self.context.language = Some(language.into());
self
}
#[must_use]
pub fn url(mut self, url: impl Into<String>) -> Self {
self.context.url = Some(url.into());
self
}
#[must_use]
pub fn referrer(mut self, referrer: impl Into<String>) -> Self {
self.context.referrer = Some(referrer.into());
self
}
#[must_use]
pub fn title(mut self, title: impl Into<String>) -> Self {
self.context.title = Some(title.into());
self
}
#[must_use]
pub fn tag(mut self, tag: impl Into<String>) -> Self {
self.context.tag = Some(tag.into());
self
}
#[must_use]
pub fn distinct_id(mut self, distinct_id: impl Into<String>) -> Self {
self.context.distinct_id = Some(distinct_id.into());
self
}
#[must_use]
pub fn ip(mut self, ip: IpAddr) -> Self {
self.context.ip = Some(ip);
self
}
#[must_use]
pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
self.context.user_agent = Some(user_agent.into());
self
}
#[must_use]
pub fn browser(mut self, browser: impl Into<String>) -> Self {
self.context.browser = Some(browser.into());
self
}
#[must_use]
pub fn os(mut self, os: impl Into<String>) -> Self {
self.context.os = Some(os.into());
self
}
#[must_use]
pub fn device(mut self, device: impl Into<String>) -> Self {
self.context.device = Some(device.into());
self
}
#[must_use]
pub fn timestamp(mut self, unix_seconds: i64) -> Self {
self.context.timestamp = Some(unix_seconds);
self
}
#[must_use]
pub fn at(mut self, time: SystemTime) -> Self {
self.context = self.context.at(time);
self
}
#[must_use]
pub fn data(mut self, data: impl Serialize) -> Self {
self.data = match serde_json::to_value(data) {
Ok(Value::Object(properties)) => Properties::Ready(properties),
Ok(value) => {
Properties::Invalid(format!("expected a JSON object, got {}", json_kind(&value)))
}
Err(error) => Properties::Invalid(error.to_string()),
};
self
}
#[must_use]
pub fn clear_data(mut self) -> Self {
self.data = Properties::None;
self
}
#[must_use]
pub fn lcp(mut self, milliseconds: f64) -> Self {
self.metrics.lcp = Some(milliseconds);
self
}
#[must_use]
pub fn inp(mut self, milliseconds: f64) -> Self {
self.metrics.inp = Some(milliseconds);
self
}
#[must_use]
pub fn cls(mut self, score: f64) -> Self {
self.metrics.cls = Some(score);
self
}
#[must_use]
pub fn fcp(mut self, milliseconds: f64) -> Self {
self.metrics.fcp = Some(milliseconds);
self
}
#[must_use]
pub fn ttfb(mut self, milliseconds: f64) -> Self {
self.metrics.ttfb = Some(milliseconds);
self
}
#[must_use]
pub fn continue_from(mut self, response: &TrackResponse) -> Self {
self.cache.clone_from(&response.cache);
self
}
pub async fn send(self) -> Result<TrackResponse> {
let (sender, request, cache) = self.into_parts()?;
sender.send(request, cache).await
}
pub(crate) fn into_parts(self) -> Result<(Sender, TrackRequest, Option<String>)> {
let data = match self.data {
Properties::None => None,
Properties::Ready(data) => Some(data),
Properties::Invalid(message) => return Err(Error::InvalidProperties(message)),
};
if let Some(name) = &self.name {
validate_event_name(name)?;
}
self.metrics.validate()?;
if self.kind != TrackKind::Performance && !self.metrics.is_empty() {
return Err(Error::InvalidTrack(
"performance metrics can only be attached to a performance track".into(),
));
}
if self.kind == TrackKind::Performance && data.is_some() {
return Err(Error::InvalidTrack(
"event properties cannot be attached to a performance track".into(),
));
}
let request = TrackRequest {
kind: self.kind,
payload: Payload {
website: self.sender.website_id(),
context: self.context,
name: self.name,
data,
metrics: self.metrics,
},
};
Ok((self.sender, request, self.cache))
}
}
fn validate_event_name(name: &str) -> Result<()> {
if name.is_empty() {
return Err(Error::InvalidEventName(
"custom event names cannot be empty".into(),
));
}
if matches!(
name.as_bytes()[0],
b'=' | b'+' | b'-' | b'@' | b'\t' | b'\r'
) {
return Err(Error::InvalidEventName(
"names cannot begin with =, +, -, @, tab, or carriage return".into(),
));
}
Ok(())
}
fn json_kind(value: &Value) -> &'static str {
match value {
Value::Null => "null",
Value::Bool(_) => "a boolean",
Value::Number(_) => "a number",
Value::String(_) => "a string",
Value::Array(_) => "an array",
Value::Object(_) => "an object",
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_formula_event_names() {
assert!(validate_event_name("=SUM(A1)").is_err());
assert!(validate_event_name("signup").is_ok());
}
#[test]
fn validates_metric_ranges() {
let invalid = Metrics {
cls: Some(f64::NAN),
..Metrics::default()
};
assert!(invalid.validate().is_err());
}
}