rust-umami 0.1.1

An ergonomic Rust client for Umami Analytics event ingestion
Documentation
use serde::Serialize;
use std::net::IpAddr;
use std::time::{SystemTime, UNIX_EPOCH};

/// Visitor and page information attached to an analytics event.
///
/// Every field is optional. Umami can infer the user agent and IP address from
/// the HTTP request, but server-side applications should normally forward the
/// original visitor values with [`Context::user_agent`] and [`Context::ip`].
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Context {
    /// Page hostname, for example `example.com`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hostname: Option<String>,
    /// Screen size formatted as `WIDTHxHEIGHT`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub screen: Option<String>,
    /// Browser or application language, for example `en-US`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
    /// Page URL or path.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// Referring URL or path.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub referrer: Option<String>,
    /// Page title.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// An additional Umami tag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tag: Option<String>,
    /// Stable distinct ID used to associate events with a visitor.
    #[serde(rename = "id", skip_serializing_if = "Option::is_none")]
    pub distinct_id: Option<String>,
    /// Original visitor IP address for server-side tracking.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ip: Option<IpAddr>,
    /// Original visitor user agent for server-side tracking.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_agent: Option<String>,
    /// Explicit browser override.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub browser: Option<String>,
    /// Explicit operating-system override.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub os: Option<String>,
    /// Explicit device override.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub device: Option<String>,
    /// Event time as Unix seconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<i64>,
}

impl Context {
    /// Creates an empty context.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

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

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

    /// Sets a preformatted screen value such as `1920x1080`.
    #[must_use]
    pub fn screen_value(mut self, screen: impl Into<String>) -> Self {
        self.screen = Some(screen.into());
        self
    }

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

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

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

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

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

    /// Sets the original visitor IP address.
    #[must_use]
    pub fn ip(mut self, ip: IpAddr) -> Self {
        self.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.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.browser = Some(browser.into());
        self
    }

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

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

    /// Sets the event time as Unix seconds.
    ///
    /// Umami's ingestion endpoint expects seconds here, unlike reporting API
    /// date ranges, which use milliseconds.
    #[must_use]
    pub fn timestamp(mut self, unix_seconds: i64) -> Self {
        self.timestamp = Some(unix_seconds);
        self
    }

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

fn unix_seconds(time: SystemTime) -> i64 {
    match time.duration_since(UNIX_EPOCH) {
        Ok(duration) => i64::try_from(duration.as_secs()).unwrap_or(i64::MAX),
        Err(error) => {
            let seconds = i64::try_from(error.duration().as_secs()).unwrap_or(i64::MAX);
            -seconds
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn converts_system_time_on_both_sides_of_epoch() {
        assert_eq!(
            Context::new()
                .at(UNIX_EPOCH + Duration::from_secs(42))
                .timestamp,
            Some(42)
        );
        assert_eq!(
            Context::new()
                .at(UNIX_EPOCH - Duration::from_secs(42))
                .timestamp,
            Some(-42)
        );
    }
}