tauri-plugin-telemetry 0.1.1

Backend-agnostic analytics/telemetry plugin for Tauri v2 apps, with a reference Hono + Supabase backend.
Documentation
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use rand::RngExt;
use time::OffsetDateTime;

static SESSION_TIMEOUT: Duration = Duration::from_secs(4 * 60 * 60);

fn new_session_id() -> String {
    let epoch_in_seconds = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("time went backwards")
        .as_secs();

    let mut rng = rand::rng();
    let random: u64 = rng.random_range(0..=99999999);

    let id = epoch_in_seconds * 100_000_000 + random;

    id.to_string()
}

/// A tracking session.
#[derive(Debug, Clone)]
pub struct TrackingSession {
    pub id: String,
    pub last_touch_ts: OffsetDateTime,
}

impl TrackingSession {
    pub fn new() -> Self {
        Self {
            id: new_session_id(),
            last_touch_ts: OffsetDateTime::now_utc(),
        }
    }

    /// Returns the current session ID, creating a new one if the session has
    /// timed out.
    pub fn eval_id(&mut self) -> String {
        let now = OffsetDateTime::now_utc();
        if (now - self.last_touch_ts) > SESSION_TIMEOUT {
            *self = TrackingSession::new();
        } else {
            self.last_touch_ts = now;
        }

        self.id.clone()
    }
}