rust-umami 0.1.1

An ergonomic Rust client for Umami Analytics event ingestion
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
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;

/// The collection type understood by Umami's ingestion endpoint.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum TrackKind {
    /// A pageview or named custom event.
    Event,
    /// Visitor identity and session properties.
    Identify,
    /// Core Web Vitals performance data.
    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()
    }
}

/// A fluent analytics track ready to send.
///
/// Create tracks through [`crate::Client`] or [`crate::Session`]. Calling
/// [`Track::data`] serializes eagerly but, like `reqwest::RequestBuilder`, any
/// serialization error is reported when [`Track::send`] is awaited. This keeps
/// fluent call sites free of an extra intermediate `Result`.
#[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,
        }
    }

    /// Returns this track's collection kind.
    #[must_use]
    pub fn kind(&self) -> TrackKind {
        self.kind
    }

    /// Replaces the inherited visitor/page context.
    #[must_use]
    pub fn context(mut self, context: Context) -> Self {
        self.context = context;
        self
    }

    /// Sets the page hostname.
    #[must_use]
    pub fn hostname(mut self, hostname: impl Into<String>) -> Self {
        self.context.hostname = Some(hostname.into());
        self
    }

    /// Sets the screen dimensions.
    #[must_use]
    pub fn screen(mut self, width: u32, height: u32) -> Self {
        self.context.screen = Some(format!("{width}x{height}"));
        self
    }

    /// Sets the visitor language.
    #[must_use]
    pub fn language(mut self, language: impl Into<String>) -> Self {
        self.context.language = Some(language.into());
        self
    }

    /// Sets or overrides the page URL/path.
    #[must_use]
    pub fn url(mut self, url: impl Into<String>) -> Self {
        self.context.url = Some(url.into());
        self
    }

    /// Sets the referring URL/path.
    #[must_use]
    pub fn referrer(mut self, referrer: impl Into<String>) -> Self {
        self.context.referrer = Some(referrer.into());
        self
    }

    /// Sets the page title.
    #[must_use]
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.context.title = Some(title.into());
        self
    }

    /// Sets an Umami tag.
    #[must_use]
    pub fn tag(mut self, tag: impl Into<String>) -> Self {
        self.context.tag = Some(tag.into());
        self
    }

    /// Sets a stable distinct ID.
    #[must_use]
    pub fn distinct_id(mut self, distinct_id: impl Into<String>) -> Self {
        self.context.distinct_id = Some(distinct_id.into());
        self
    }

    /// Sets the original visitor IP address.
    #[must_use]
    pub fn ip(mut self, ip: IpAddr) -> Self {
        self.context.ip = Some(ip);
        self
    }

    /// Sets the original visitor user agent.
    #[must_use]
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.context.user_agent = Some(user_agent.into());
        self
    }

    /// Overrides Umami's browser detection.
    #[must_use]
    pub fn browser(mut self, browser: impl Into<String>) -> Self {
        self.context.browser = Some(browser.into());
        self
    }

    /// Overrides Umami's operating-system detection.
    #[must_use]
    pub fn os(mut self, os: impl Into<String>) -> Self {
        self.context.os = Some(os.into());
        self
    }

    /// Overrides Umami's device detection.
    #[must_use]
    pub fn device(mut self, device: impl Into<String>) -> Self {
        self.context.device = Some(device.into());
        self
    }

    /// Sets the event time as Unix seconds.
    #[must_use]
    pub fn timestamp(mut self, unix_seconds: i64) -> Self {
        self.context.timestamp = Some(unix_seconds);
        self
    }

    /// Sets the event time from a [`SystemTime`].
    #[must_use]
    pub fn at(mut self, time: SystemTime) -> Self {
        self.context = self.context.at(time);
        self
    }

    /// Attaches event or session properties from any serializable JSON object.
    ///
    /// Umami requires an object at the top level. Nested values, arrays,
    /// booleans, numbers, strings, and date strings are supported.
    #[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
    }

    /// Removes previously attached properties.
    #[must_use]
    pub fn clear_data(mut self) -> Self {
        self.data = Properties::None;
        self
    }

    /// Sets Largest Contentful Paint in milliseconds.
    #[must_use]
    pub fn lcp(mut self, milliseconds: f64) -> Self {
        self.metrics.lcp = Some(milliseconds);
        self
    }

    /// Sets Interaction to Next Paint in milliseconds.
    #[must_use]
    pub fn inp(mut self, milliseconds: f64) -> Self {
        self.metrics.inp = Some(milliseconds);
        self
    }

    /// Sets Cumulative Layout Shift.
    #[must_use]
    pub fn cls(mut self, score: f64) -> Self {
        self.metrics.cls = Some(score);
        self
    }

    /// Sets First Contentful Paint in milliseconds.
    #[must_use]
    pub fn fcp(mut self, milliseconds: f64) -> Self {
        self.metrics.fcp = Some(milliseconds);
        self
    }

    /// Sets Time to First Byte in milliseconds.
    #[must_use]
    pub fn ttfb(mut self, milliseconds: f64) -> Self {
        self.metrics.ttfb = Some(milliseconds);
        self
    }

    /// Reuses the cache value from a previous response.
    ///
    /// [`crate::Session`] handles this automatically. This method is useful for
    /// stateless clients that persist the response themselves.
    #[must_use]
    pub fn continue_from(mut self, response: &TrackResponse) -> Self {
        self.cache.clone_from(&response.cache);
        self
    }

    /// Sends this track to Umami.
    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());
    }
}