Skip to main content

ic_analytics_sdk/
lib.rs

1use candid::{CandidType, Principal};
2use serde::{Deserialize, Serialize};
3
4/// The value carried by an incoming metric record.
5/// Determines how the metric is stored and aggregated.
6#[derive(Clone, Debug, CandidType, Deserialize, Serialize)]
7pub enum MetricValue {
8    /// Delta to apply: positive increments, negative decrements.
9    Counter(i64),
10    /// Absolute value to set.
11    Gauge(f64),
12    /// An (x, y) data point. For time-series use, pass the timestamp as `x`.
13    Histogram { x: f64, y: f64 },
14    /// A text entry; the canister appends it with a timestamp.
15    Log(String),
16}
17
18/// An incoming metric record.
19#[derive(Clone, Debug, CandidType, Deserialize, Serialize)]
20pub struct Metric {
21    pub name: String,
22    pub key: String,
23    pub value: MetricValue,
24}
25
26/// The aggregated metric as stored in the canister, keyed by `key`.
27#[derive(Clone, Debug, CandidType, Deserialize, Serialize)]
28pub enum StoredMetric {
29    Counter { name: String, value: i64 },
30    Gauge { name: String, value: f64 },
31    Histogram { name: String, total: u64 },
32    Log { name: String, total: u64 },
33}
34
35/// A page of log entries returned by `get_log_page`.
36#[derive(Clone, Debug, CandidType, Deserialize, Serialize)]
37pub struct LogPage {
38    pub name: String,
39    pub entries: Vec<(u64, String)>,
40    pub total: u64,
41    pub offset: u64,
42}
43
44/// A page of histogram data points returned by `get_histogram_page`.
45#[derive(Clone, Debug, CandidType, Deserialize, Serialize)]
46pub struct HistogramPage {
47    pub name: String,
48    pub points: Vec<(f64, f64)>,
49    pub total: u64,
50}
51
52/// The result produced by running a transformer script.
53#[derive(Clone, Debug, CandidType, Deserialize, Serialize)]
54pub enum TransformerOutput {
55    /// A single computed number (e.g. integral, average, max).
56    Scalar(f64),
57    /// A derived time series of (x, y) pairs (e.g. derivative, smoothed data).
58    Series(Vec<(f64, f64)>),
59    /// A textual result (e.g. statistical summary).
60    Text(String),
61}
62
63/// Metadata returned when listing or fetching a transformer definition.
64#[derive(Clone, Debug, CandidType, Deserialize, Serialize)]
65pub struct TransformerInfo {
66    pub name: String,
67    pub key: String,
68    pub script: String,
69    pub created_at: u64,
70}
71
72#[derive(Clone, Debug)]
73pub struct AnalyticsClient {
74    pub backend_canister_id: Principal,
75}
76
77impl AnalyticsClient {
78    pub fn new(backend_canister_id: Principal) -> Self {
79        Self {
80            backend_canister_id,
81        }
82    }
83
84    /// Fire-and-forget metric recording
85    pub fn record_metric(&self, metric: Metric) -> Result<(), String> {
86        ic_cdk::call::Call::unbounded_wait(self.backend_canister_id, "record_metric").with_args(&(metric,)).oneway().map_err(|e| e.to_string())?;
87        Ok(())
88    }
89}