Skip to main content

rust_umami/
event.rs

1use crate::client::Sender;
2use crate::{Context, Error, Result, TrackResponse};
3use serde::{Deserialize, Serialize};
4use serde_json::{Map, Value};
5use std::net::IpAddr;
6use std::time::SystemTime;
7use uuid::Uuid;
8
9/// The collection type understood by Umami's ingestion endpoint.
10#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
11#[serde(rename_all = "lowercase")]
12pub enum TrackKind {
13    /// A pageview or named custom event.
14    Event,
15    /// Visitor identity and session properties.
16    Identify,
17    /// Core Web Vitals performance data.
18    Performance,
19}
20
21#[derive(Debug, Default)]
22enum Properties {
23    #[default]
24    None,
25    Ready(Map<String, Value>),
26    Invalid(String),
27}
28
29#[derive(Clone, Debug, Default, Serialize)]
30#[serde(rename_all = "camelCase")]
31struct Metrics {
32    #[serde(skip_serializing_if = "Option::is_none")]
33    lcp: Option<f64>,
34    #[serde(skip_serializing_if = "Option::is_none")]
35    inp: Option<f64>,
36    #[serde(skip_serializing_if = "Option::is_none")]
37    cls: Option<f64>,
38    #[serde(skip_serializing_if = "Option::is_none")]
39    fcp: Option<f64>,
40    #[serde(skip_serializing_if = "Option::is_none")]
41    ttfb: Option<f64>,
42}
43
44impl Metrics {
45    fn is_empty(&self) -> bool {
46        self.lcp.is_none()
47            && self.inp.is_none()
48            && self.cls.is_none()
49            && self.fcp.is_none()
50            && self.ttfb.is_none()
51    }
52
53    fn validate(&self) -> Result<()> {
54        validate_metric("lcp", self.lcp, 60_000.0, "a finite number from 0 to 60000")?;
55        validate_metric("inp", self.inp, 60_000.0, "a finite number from 0 to 60000")?;
56        validate_metric("cls", self.cls, 100.0, "a finite number from 0 to 100")?;
57        validate_metric("fcp", self.fcp, 60_000.0, "a finite number from 0 to 60000")?;
58        validate_metric(
59            "ttfb",
60            self.ttfb,
61            60_000.0,
62            "a finite number from 0 to 60000",
63        )?;
64        Ok(())
65    }
66}
67
68fn validate_metric(
69    name: &'static str,
70    value: Option<f64>,
71    maximum: f64,
72    expected: &'static str,
73) -> Result<()> {
74    if let Some(value) = value
75        && (!value.is_finite() || !(0.0..=maximum).contains(&value))
76    {
77        return Err(Error::InvalidMetric {
78            name,
79            expected,
80            value,
81        });
82    }
83    Ok(())
84}
85
86#[derive(Debug, Serialize)]
87#[serde(rename_all = "camelCase")]
88struct Payload {
89    website: Uuid,
90    #[serde(flatten)]
91    context: Context,
92    #[serde(skip_serializing_if = "Option::is_none")]
93    name: Option<String>,
94    #[serde(skip_serializing_if = "Option::is_none")]
95    data: Option<Map<String, Value>>,
96    #[serde(flatten)]
97    metrics: Metrics,
98}
99
100#[derive(Debug, Serialize)]
101pub(crate) struct TrackRequest {
102    #[serde(rename = "type")]
103    kind: TrackKind,
104    payload: Payload,
105}
106
107impl TrackRequest {
108    pub(crate) fn kind(&self) -> TrackKind {
109        self.kind
110    }
111
112    pub(crate) fn hostname(&self) -> Option<&str> {
113        self.payload.context.hostname.as_deref()
114    }
115}
116
117/// A fluent analytics track ready to send.
118///
119/// Create tracks through [`crate::Client`] or [`crate::Session`]. Calling
120/// [`Track::data`] serializes eagerly but, like `reqwest::RequestBuilder`, any
121/// serialization error is reported when [`Track::send`] is awaited. This keeps
122/// fluent call sites free of an extra intermediate `Result`.
123#[derive(Debug)]
124pub struct Track {
125    pub(crate) sender: Sender,
126    kind: TrackKind,
127    context: Context,
128    name: Option<String>,
129    data: Properties,
130    metrics: Metrics,
131    cache: Option<String>,
132}
133
134impl Track {
135    pub(crate) fn pageview(sender: Sender, context: Context, url: String) -> Self {
136        Self {
137            sender,
138            kind: TrackKind::Event,
139            context: context.url(url),
140            name: None,
141            data: Properties::None,
142            metrics: Metrics::default(),
143            cache: None,
144        }
145    }
146
147    pub(crate) fn event(sender: Sender, context: Context, name: String) -> Self {
148        Self {
149            sender,
150            kind: TrackKind::Event,
151            context,
152            name: Some(name),
153            data: Properties::None,
154            metrics: Metrics::default(),
155            cache: None,
156        }
157    }
158
159    pub(crate) fn identify(sender: Sender, context: Context, id: Option<String>) -> Self {
160        let context = match id {
161            Some(id) => context.distinct_id(id),
162            None => context,
163        };
164        Self {
165            sender,
166            kind: TrackKind::Identify,
167            context,
168            name: None,
169            data: Properties::None,
170            metrics: Metrics::default(),
171            cache: None,
172        }
173    }
174
175    pub(crate) fn performance(sender: Sender, context: Context, url: String) -> Self {
176        Self {
177            sender,
178            kind: TrackKind::Performance,
179            context: context.url(url),
180            name: None,
181            data: Properties::None,
182            metrics: Metrics::default(),
183            cache: None,
184        }
185    }
186
187    /// Returns this track's collection kind.
188    #[must_use]
189    pub fn kind(&self) -> TrackKind {
190        self.kind
191    }
192
193    /// Replaces the inherited visitor/page context.
194    #[must_use]
195    pub fn context(mut self, context: Context) -> Self {
196        self.context = context;
197        self
198    }
199
200    /// Sets the page hostname.
201    #[must_use]
202    pub fn hostname(mut self, hostname: impl Into<String>) -> Self {
203        self.context.hostname = Some(hostname.into());
204        self
205    }
206
207    /// Sets the screen dimensions.
208    #[must_use]
209    pub fn screen(mut self, width: u32, height: u32) -> Self {
210        self.context.screen = Some(format!("{width}x{height}"));
211        self
212    }
213
214    /// Sets the visitor language.
215    #[must_use]
216    pub fn language(mut self, language: impl Into<String>) -> Self {
217        self.context.language = Some(language.into());
218        self
219    }
220
221    /// Sets or overrides the page URL/path.
222    #[must_use]
223    pub fn url(mut self, url: impl Into<String>) -> Self {
224        self.context.url = Some(url.into());
225        self
226    }
227
228    /// Sets the referring URL/path.
229    #[must_use]
230    pub fn referrer(mut self, referrer: impl Into<String>) -> Self {
231        self.context.referrer = Some(referrer.into());
232        self
233    }
234
235    /// Sets the page title.
236    #[must_use]
237    pub fn title(mut self, title: impl Into<String>) -> Self {
238        self.context.title = Some(title.into());
239        self
240    }
241
242    /// Sets an Umami tag.
243    #[must_use]
244    pub fn tag(mut self, tag: impl Into<String>) -> Self {
245        self.context.tag = Some(tag.into());
246        self
247    }
248
249    /// Sets a stable distinct ID.
250    #[must_use]
251    pub fn distinct_id(mut self, distinct_id: impl Into<String>) -> Self {
252        self.context.distinct_id = Some(distinct_id.into());
253        self
254    }
255
256    /// Sets the original visitor IP address.
257    #[must_use]
258    pub fn ip(mut self, ip: IpAddr) -> Self {
259        self.context.ip = Some(ip);
260        self
261    }
262
263    /// Sets the original visitor user agent.
264    #[must_use]
265    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
266        self.context.user_agent = Some(user_agent.into());
267        self
268    }
269
270    /// Overrides Umami's browser detection.
271    #[must_use]
272    pub fn browser(mut self, browser: impl Into<String>) -> Self {
273        self.context.browser = Some(browser.into());
274        self
275    }
276
277    /// Overrides Umami's operating-system detection.
278    #[must_use]
279    pub fn os(mut self, os: impl Into<String>) -> Self {
280        self.context.os = Some(os.into());
281        self
282    }
283
284    /// Overrides Umami's device detection.
285    #[must_use]
286    pub fn device(mut self, device: impl Into<String>) -> Self {
287        self.context.device = Some(device.into());
288        self
289    }
290
291    /// Sets the event time as Unix seconds.
292    #[must_use]
293    pub fn timestamp(mut self, unix_seconds: i64) -> Self {
294        self.context.timestamp = Some(unix_seconds);
295        self
296    }
297
298    /// Sets the event time from a [`SystemTime`].
299    #[must_use]
300    pub fn at(mut self, time: SystemTime) -> Self {
301        self.context = self.context.at(time);
302        self
303    }
304
305    /// Attaches event or session properties from any serializable JSON object.
306    ///
307    /// Umami requires an object at the top level. Nested values, arrays,
308    /// booleans, numbers, strings, and date strings are supported.
309    #[must_use]
310    pub fn data(mut self, data: impl Serialize) -> Self {
311        self.data = match serde_json::to_value(data) {
312            Ok(Value::Object(properties)) => Properties::Ready(properties),
313            Ok(value) => {
314                Properties::Invalid(format!("expected a JSON object, got {}", json_kind(&value)))
315            }
316            Err(error) => Properties::Invalid(error.to_string()),
317        };
318        self
319    }
320
321    /// Removes previously attached properties.
322    #[must_use]
323    pub fn clear_data(mut self) -> Self {
324        self.data = Properties::None;
325        self
326    }
327
328    /// Sets Largest Contentful Paint in milliseconds.
329    #[must_use]
330    pub fn lcp(mut self, milliseconds: f64) -> Self {
331        self.metrics.lcp = Some(milliseconds);
332        self
333    }
334
335    /// Sets Interaction to Next Paint in milliseconds.
336    #[must_use]
337    pub fn inp(mut self, milliseconds: f64) -> Self {
338        self.metrics.inp = Some(milliseconds);
339        self
340    }
341
342    /// Sets Cumulative Layout Shift.
343    #[must_use]
344    pub fn cls(mut self, score: f64) -> Self {
345        self.metrics.cls = Some(score);
346        self
347    }
348
349    /// Sets First Contentful Paint in milliseconds.
350    #[must_use]
351    pub fn fcp(mut self, milliseconds: f64) -> Self {
352        self.metrics.fcp = Some(milliseconds);
353        self
354    }
355
356    /// Sets Time to First Byte in milliseconds.
357    #[must_use]
358    pub fn ttfb(mut self, milliseconds: f64) -> Self {
359        self.metrics.ttfb = Some(milliseconds);
360        self
361    }
362
363    /// Reuses the cache value from a previous response.
364    ///
365    /// [`crate::Session`] handles this automatically. This method is useful for
366    /// stateless clients that persist the response themselves.
367    #[must_use]
368    pub fn continue_from(mut self, response: &TrackResponse) -> Self {
369        self.cache.clone_from(&response.cache);
370        self
371    }
372
373    /// Sends this track to Umami.
374    pub async fn send(self) -> Result<TrackResponse> {
375        let (sender, request, cache) = self.into_parts()?;
376        sender.send(request, cache).await
377    }
378
379    pub(crate) fn into_parts(self) -> Result<(Sender, TrackRequest, Option<String>)> {
380        let data = match self.data {
381            Properties::None => None,
382            Properties::Ready(data) => Some(data),
383            Properties::Invalid(message) => return Err(Error::InvalidProperties(message)),
384        };
385
386        if let Some(name) = &self.name {
387            validate_event_name(name)?;
388        }
389
390        self.metrics.validate()?;
391        if self.kind != TrackKind::Performance && !self.metrics.is_empty() {
392            return Err(Error::InvalidTrack(
393                "performance metrics can only be attached to a performance track".into(),
394            ));
395        }
396        if self.kind == TrackKind::Performance && data.is_some() {
397            return Err(Error::InvalidTrack(
398                "event properties cannot be attached to a performance track".into(),
399            ));
400        }
401
402        let request = TrackRequest {
403            kind: self.kind,
404            payload: Payload {
405                website: self.sender.website_id(),
406                context: self.context,
407                name: self.name,
408                data,
409                metrics: self.metrics,
410            },
411        };
412
413        Ok((self.sender, request, self.cache))
414    }
415}
416
417fn validate_event_name(name: &str) -> Result<()> {
418    if name.is_empty() {
419        return Err(Error::InvalidEventName(
420            "custom event names cannot be empty".into(),
421        ));
422    }
423    if matches!(
424        name.as_bytes()[0],
425        b'=' | b'+' | b'-' | b'@' | b'\t' | b'\r'
426    ) {
427        return Err(Error::InvalidEventName(
428            "names cannot begin with =, +, -, @, tab, or carriage return".into(),
429        ));
430    }
431    Ok(())
432}
433
434fn json_kind(value: &Value) -> &'static str {
435    match value {
436        Value::Null => "null",
437        Value::Bool(_) => "a boolean",
438        Value::Number(_) => "a number",
439        Value::String(_) => "a string",
440        Value::Array(_) => "an array",
441        Value::Object(_) => "an object",
442    }
443}
444
445#[cfg(test)]
446mod tests {
447    use super::*;
448
449    #[test]
450    fn rejects_formula_event_names() {
451        assert!(validate_event_name("=SUM(A1)").is_err());
452        assert!(validate_event_name("signup").is_ok());
453    }
454
455    #[test]
456    fn validates_metric_ranges() {
457        let invalid = Metrics {
458            cls: Some(f64::NAN),
459            ..Metrics::default()
460        };
461        assert!(invalid.validate().is_err());
462    }
463}