Skip to main content

rust_umami/
context.rs

1use serde::Serialize;
2use std::net::IpAddr;
3use std::time::{SystemTime, UNIX_EPOCH};
4
5/// Visitor and page information attached to an analytics event.
6///
7/// Every field is optional. Umami can infer the user agent and IP address from
8/// the HTTP request, but server-side applications should normally forward the
9/// original visitor values with [`Context::user_agent`] and [`Context::ip`].
10#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
11#[serde(rename_all = "camelCase")]
12pub struct Context {
13    /// Page hostname, for example `example.com`.
14    #[serde(skip_serializing_if = "Option::is_none")]
15    pub hostname: Option<String>,
16    /// Screen size formatted as `WIDTHxHEIGHT`.
17    #[serde(skip_serializing_if = "Option::is_none")]
18    pub screen: Option<String>,
19    /// Browser or application language, for example `en-US`.
20    #[serde(skip_serializing_if = "Option::is_none")]
21    pub language: Option<String>,
22    /// Page URL or path.
23    #[serde(skip_serializing_if = "Option::is_none")]
24    pub url: Option<String>,
25    /// Referring URL or path.
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub referrer: Option<String>,
28    /// Page title.
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub title: Option<String>,
31    /// An additional Umami tag.
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub tag: Option<String>,
34    /// Stable distinct ID used to associate events with a visitor.
35    #[serde(rename = "id", skip_serializing_if = "Option::is_none")]
36    pub distinct_id: Option<String>,
37    /// Original visitor IP address for server-side tracking.
38    #[serde(skip_serializing_if = "Option::is_none")]
39    pub ip: Option<IpAddr>,
40    /// Original visitor user agent for server-side tracking.
41    #[serde(skip_serializing_if = "Option::is_none")]
42    pub user_agent: Option<String>,
43    /// Explicit browser override.
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub browser: Option<String>,
46    /// Explicit operating-system override.
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub os: Option<String>,
49    /// Explicit device override.
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub device: Option<String>,
52    /// Event time as Unix seconds.
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub timestamp: Option<i64>,
55}
56
57impl Context {
58    /// Creates an empty context.
59    #[must_use]
60    pub fn new() -> Self {
61        Self::default()
62    }
63
64    /// Sets the page hostname.
65    #[must_use]
66    pub fn hostname(mut self, hostname: impl Into<String>) -> Self {
67        self.hostname = Some(hostname.into());
68        self
69    }
70
71    /// Sets the screen dimensions.
72    #[must_use]
73    pub fn screen(mut self, width: u32, height: u32) -> Self {
74        self.screen = Some(format!("{width}x{height}"));
75        self
76    }
77
78    /// Sets a preformatted screen value such as `1920x1080`.
79    #[must_use]
80    pub fn screen_value(mut self, screen: impl Into<String>) -> Self {
81        self.screen = Some(screen.into());
82        self
83    }
84
85    /// Sets the visitor language.
86    #[must_use]
87    pub fn language(mut self, language: impl Into<String>) -> Self {
88        self.language = Some(language.into());
89        self
90    }
91
92    /// Sets the page URL or path.
93    #[must_use]
94    pub fn url(mut self, url: impl Into<String>) -> Self {
95        self.url = Some(url.into());
96        self
97    }
98
99    /// Sets the referring URL or path.
100    #[must_use]
101    pub fn referrer(mut self, referrer: impl Into<String>) -> Self {
102        self.referrer = Some(referrer.into());
103        self
104    }
105
106    /// Sets the page title.
107    #[must_use]
108    pub fn title(mut self, title: impl Into<String>) -> Self {
109        self.title = Some(title.into());
110        self
111    }
112
113    /// Sets an Umami tag.
114    #[must_use]
115    pub fn tag(mut self, tag: impl Into<String>) -> Self {
116        self.tag = Some(tag.into());
117        self
118    }
119
120    /// Sets a stable distinct ID.
121    #[must_use]
122    pub fn distinct_id(mut self, distinct_id: impl Into<String>) -> Self {
123        self.distinct_id = Some(distinct_id.into());
124        self
125    }
126
127    /// Sets the original visitor IP address.
128    #[must_use]
129    pub fn ip(mut self, ip: IpAddr) -> Self {
130        self.ip = Some(ip);
131        self
132    }
133
134    /// Sets the original visitor user agent.
135    #[must_use]
136    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
137        self.user_agent = Some(user_agent.into());
138        self
139    }
140
141    /// Overrides Umami's browser detection.
142    #[must_use]
143    pub fn browser(mut self, browser: impl Into<String>) -> Self {
144        self.browser = Some(browser.into());
145        self
146    }
147
148    /// Overrides Umami's operating-system detection.
149    #[must_use]
150    pub fn os(mut self, os: impl Into<String>) -> Self {
151        self.os = Some(os.into());
152        self
153    }
154
155    /// Overrides Umami's device detection.
156    #[must_use]
157    pub fn device(mut self, device: impl Into<String>) -> Self {
158        self.device = Some(device.into());
159        self
160    }
161
162    /// Sets the event time as Unix seconds.
163    ///
164    /// Umami's ingestion endpoint expects seconds here, unlike reporting API
165    /// date ranges, which use milliseconds.
166    #[must_use]
167    pub fn timestamp(mut self, unix_seconds: i64) -> Self {
168        self.timestamp = Some(unix_seconds);
169        self
170    }
171
172    /// Sets the event time from a [`SystemTime`].
173    #[must_use]
174    pub fn at(mut self, time: SystemTime) -> Self {
175        self.timestamp = Some(unix_seconds(time));
176        self
177    }
178}
179
180fn unix_seconds(time: SystemTime) -> i64 {
181    match time.duration_since(UNIX_EPOCH) {
182        Ok(duration) => i64::try_from(duration.as_secs()).unwrap_or(i64::MAX),
183        Err(error) => {
184            let seconds = i64::try_from(error.duration().as_secs()).unwrap_or(i64::MAX);
185            -seconds
186        }
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193    use std::time::Duration;
194
195    #[test]
196    fn converts_system_time_on_both_sides_of_epoch() {
197        assert_eq!(
198            Context::new()
199                .at(UNIX_EPOCH + Duration::from_secs(42))
200                .timestamp,
201            Some(42)
202        );
203        assert_eq!(
204            Context::new()
205                .at(UNIX_EPOCH - Duration::from_secs(42))
206                .timestamp,
207            Some(-42)
208        );
209    }
210}