tauri-plugin-telemetry 0.1.3

Backend-agnostic analytics/telemetry plugin for Tauri v2 apps, with a reference Hono + Supabase backend.
Documentation
mod builder;
mod client;
mod commands;
mod config;
mod dispatcher;
mod session;
mod sys;

use std::sync::Arc;
use std::time::Duration;

pub use builder::{Builder, PanicHook};
use client::TelemetryClient;
use serde_json::Value;
use tauri::{App, AppHandle, Manager, Runtime, Window};

/// Shorthand for `Builder::new(app_key).build()`.
///
/// For full control over `InitOptions` or a custom panic hook, use
/// [`Builder`] directly.
pub fn init<R: Runtime>(app_key: &str) -> tauri::plugin::TauriPlugin<R> {
    Builder::new(app_key).build()
}

/// Options for customizing the analytics backend the plugin talks to.
///
/// The plugin is backend-agnostic: there is no implicit host resolution. Set
/// `host` (and optionally `api_path`, `app_key_header` and `sdk_name`) to point
/// the plugin at your analytics backend. When `host` is unset, tracking is
/// disabled.
#[derive(Default, Debug, Clone)]
pub struct InitOptions {
    /// Base URL of the analytics backend (e.g. `https://analytics.myapp.com`).
    ///
    /// Required to enable tracking. The plugin sends events to
    /// `{host}{api_path}`.
    pub host: Option<String>,
    /// How often to flush queued events to the backend. Defaults to 60s in
    /// release builds and 2s in debug builds.
    pub flush_interval: Option<Duration>,
    /// Path appended to `host` to form the ingest URL. Defaults to
    /// `/v1/events`.
    pub api_path: Option<String>,
    /// Name of the HTTP header that carries the App Key. Defaults to
    /// `App-Key`.
    pub app_key_header: Option<String>,
    /// Value reported in `systemProps.sdkVersion` on each event. Defaults to
    /// `<crate-name>@<crate-version>`.
    pub sdk_name: Option<String>,
}

/// Trait implemented by Tauri handlers.
pub trait EventTracker {
    /// Enqueues an event to be sent to the backend.
    fn track_event(&self, name: &str, props: Option<Value>) -> Result<(), String>;

    /// Flushes the event queue, blocking the current thread.
    fn flush_events_blocking(&self);
}

macro_rules! impl_event_tracker {
    ($($t:ty),*) => {
        $(
            impl EventTracker for $t {
                fn track_event(&self, name: &str, props: Option<Value>) -> Result<(), String> {
                    let client = self.state::<Arc<TelemetryClient>>();
                    client.track_event(name, props)
                }

                fn flush_events_blocking(&self) {
                    let client = self.state::<Arc<TelemetryClient>>();
                    client.flush_blocking()
                }
            }
        )*
    };
}

impl_event_tracker!(App, AppHandle, Window);