ic-analytics-sdk 0.2.1

IC Analytics SDK
Documentation
use candid::{CandidType, Principal};
use serde::{Deserialize, Serialize};

/// The value carried by an incoming metric record.
/// Determines how the metric is stored and aggregated.
#[derive(Clone, Debug, CandidType, Deserialize, Serialize)]
pub enum MetricValue {
    /// Delta to apply: positive increments, negative decrements.
    Counter(i64),
    /// Absolute value to set.
    Gauge(f64),
    /// An (x, y) data point. For time-series use, pass the timestamp as `x`.
    Histogram { x: f64, y: f64 },
    /// A text entry; the canister appends it with a timestamp.
    Log(String),
}

/// An incoming metric record.
#[derive(Clone, Debug, CandidType, Deserialize, Serialize)]
pub struct Metric {
    pub name: String,
    pub key: String,
    pub value: MetricValue,
}

/// The aggregated metric as stored in the canister, keyed by `key`.
#[derive(Clone, Debug, CandidType, Deserialize, Serialize)]
pub enum StoredMetric {
    Counter { name: String, value: i64 },
    Gauge { name: String, value: f64 },
    Histogram { name: String, total: u64 },
    Log { name: String, total: u64 },
}

/// A page of log entries returned by `get_log_page`.
#[derive(Clone, Debug, CandidType, Deserialize, Serialize)]
pub struct LogPage {
    pub name: String,
    pub entries: Vec<(u64, String)>,
    pub total: u64,
    pub offset: u64,
}

/// A page of histogram data points returned by `get_histogram_page`.
#[derive(Clone, Debug, CandidType, Deserialize, Serialize)]
pub struct HistogramPage {
    pub name: String,
    pub points: Vec<(f64, f64)>,
    pub total: u64,
}

/// The result produced by running a transformer script.
#[derive(Clone, Debug, CandidType, Deserialize, Serialize)]
pub enum TransformerOutput {
    /// A single computed number (e.g. integral, average, max).
    Scalar(f64),
    /// A derived time series of (x, y) pairs (e.g. derivative, smoothed data).
    Series(Vec<(f64, f64)>),
    /// A textual result (e.g. statistical summary).
    Text(String),
}

/// Metadata returned when listing or fetching a transformer definition.
#[derive(Clone, Debug, CandidType, Deserialize, Serialize)]
pub struct TransformerInfo {
    pub name: String,
    pub key: String,
    pub script: String,
    pub created_at: u64,
}

#[derive(Clone, Debug)]
pub struct AnalyticsClient {
    pub backend_canister_id: Principal,
}

impl AnalyticsClient {
    pub fn new(backend_canister_id: Principal) -> Self {
        Self {
            backend_canister_id,
        }
    }

    /// Fire-and-forget metric recording
    pub fn record_metric(&self, metric: Metric) -> Result<(), String> {
        ic_cdk::call::Call::unbounded_wait(self.backend_canister_id, "record_metric").with_args(&(metric,)).oneway().map_err(|e| e.to_string())?;
        Ok(())
    }
}