Skip to main content

glean_sym/
types.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5use std::{collections::HashMap, marker::PhantomData};
6
7/// Types defined in `glean.udl` and used in the public API.
8///
9/// For now these are a copy of the same types in `glean-core`.
10/// We can probably generate (most of) them from the UDL definition as well
11/// (or share the glean-core implementation otherwise),
12/// but for the experimentation phase of `glean-sym` we stick with a manual copy to get it going.
13
14#[derive(uniffi::Enum, Default)]
15pub enum Lifetime {
16    #[default]
17    Ping,
18    Application,
19    User,
20}
21
22#[derive(uniffi::Enum)]
23pub enum MetricLabel {
24    Static(String),
25    Label(String),
26    KeyOnly(String, String),
27    CategoryOnly(String, String),
28    KeyAndCategory(String, String),
29}
30
31#[derive(uniffi::Record, Default)]
32pub struct CommonMetricData {
33    pub category: String,
34    pub name: String,
35    pub send_in_pings: Vec<String>,
36    pub lifetime: Lifetime,
37    pub disabled: bool,
38    pub label: Option<MetricLabel>,
39    pub in_session: bool,
40}
41
42#[derive(uniffi::Record)]
43pub struct Rate {
44    numerator: i32,
45    denominator: i32,
46}
47
48pub type JsonValue = String;
49
50#[derive(uniffi::Record, Debug)]
51pub struct RecordedEvent {
52    timestamp: u64,
53    category: String,
54    name: String,
55    extra: Option<::std::collections::HashMap<String, String>>,
56    session_metadata: Option<SessionMetadata>,
57}
58
59#[derive(uniffi::Record, Debug)]
60pub struct SessionMetadata {
61    pub session_id: String,
62    pub session_seq: u64,
63    pub event_seq: u64,
64    pub session_sample_rate: f64,
65    pub session_start_time: Option<String>,
66}
67
68#[derive(uniffi::Record)]
69pub struct Datetime {
70    year: i32,
71    month: u32,
72    day: u32,
73    hour: u32,
74    minute: u32,
75    second: u32,
76    nanosecond: u32,
77    offset_seconds: i32,
78}
79
80#[derive(uniffi::Record)]
81pub struct DistributionData {
82    values: ::std::collections::HashMap<i64, i64>,
83    sum: i64,
84    count: i64,
85}
86
87#[derive(uniffi::Record)]
88#[cfg_attr(not(feature = "active"), derive(Default))]
89pub struct TimerId {
90    id: u64,
91}
92
93#[derive(uniffi::Enum)]
94pub enum ErrorType {
95    InvalidValue,
96    InvalidLabel,
97    InvalidState,
98    InvalidOverflow,
99}
100
101#[derive(uniffi::Enum)]
102#[repr(i32)]
103pub enum TimeUnit {
104    /// Truncate to nanosecond precision.
105    Nanosecond,
106    /// Truncate to microsecond precision.
107    Microsecond,
108    /// Truncate to millisecond precision.
109    Millisecond,
110    /// Truncate to second precision.
111    Second,
112    /// Truncate to minute precision.
113    Minute,
114    /// Truncate to hour precision.
115    Hour,
116    /// Truncate to day precision.
117    Day,
118}
119
120#[derive(uniffi::Enum)]
121#[repr(i32)] // use i32 to be compatible with our JNA definition
122pub enum MemoryUnit {
123    /// 1 byte
124    Byte,
125    /// 2^10 bytes
126    Kilobyte,
127    /// 2^20 bytes
128    Megabyte,
129    /// 2^30 bytes
130    Gigabyte,
131}
132
133#[derive(uniffi::Enum)]
134pub enum HistogramType {
135    /// A histogram with linear distributed buckets.
136    Linear,
137    /// A histogram with exponential distributed buckets.
138    Exponential,
139}
140
141pub type CowString = std::borrow::Cow<'static, str>;
142
143pub trait ExtraKeys {
144    /// List of allowed extra keys as strings.
145    const ALLOWED_KEYS: &'static [&'static str];
146
147    /// Convert the event extras into a hashmap of extra key to extra value.
148    fn into_ffi_extra(self) -> HashMap<String, String>;
149}
150
151pub enum NoExtraKeys {}
152
153impl ExtraKeys for NoExtraKeys {
154    const ALLOWED_KEYS: &'static [&'static str] = &[];
155
156    fn into_ffi_extra(self) -> HashMap<String, String> {
157        unimplemented!("non-existing extra keys can't be turned into a list")
158    }
159}
160
161/// Developer-facing API for recording event metrics.
162///
163/// Instances of this class type are automatically generated by the parsers
164/// at build time, allowing developers to record values that were previously
165/// registered in the metrics.yaml file.
166pub struct EventMetric<K> {
167    pub(crate) inner: crate::metrics::EventMetric,
168    extra_keys: PhantomData<K>,
169}
170
171impl<K: ExtraKeys> EventMetric<K> {
172    /// The public constructor used by automatically generated metrics.
173    pub fn new(meta: CommonMetricData) -> Self {
174        let allowed_extra_keys = K::ALLOWED_KEYS.iter().map(|s| s.to_string()).collect();
175        let inner = crate::metrics::EventMetric::new(meta, allowed_extra_keys);
176        Self {
177            inner,
178            extra_keys: PhantomData,
179        }
180    }
181
182    /// Records an event.
183    ///
184    /// # Arguments
185    ///
186    /// * `extra` - (optional) An object for the extra keys.
187    pub fn record<M: Into<Option<K>>>(&self, extra: M) {
188        let extra = extra
189            .into()
190            .map(|e| e.into_ffi_extra())
191            .unwrap_or_else(HashMap::new);
192        self.inner.record(extra);
193    }
194
195    /// **Exported for test purposes.**
196    ///
197    /// Gets the number of recorded errors for the given metric and error type.
198    ///
199    /// # Arguments
200    ///
201    /// * `error` - The type of error
202    ///
203    /// # Returns
204    ///
205    /// The number of errors reported.
206    pub fn test_get_num_recorded_errors(&self, error: ErrorType) -> i32 {
207        self.inner.test_get_num_recorded_errors(error)
208    }
209}
210
211#[cfg(not(feature = "active"))]
212pub struct PingType;
213
214#[cfg(feature = "active")]
215pub struct PingType {
216    inner: crate::metrics::PingType,
217}
218
219#[cfg(feature = "active")]
220impl PingType {
221    /// Creates a new ping type.
222    ///
223    /// # Arguments
224    ///
225    /// * `name` - The name of the ping.
226    /// * `include_client_id` - Whether to include the client ID in the assembled ping when.
227    /// * `send_if_empty` - Whether the ping should be sent empty or not.
228    /// * `precise_timestamps` - Whether the ping should use precise timestamps for the start and end time.
229    /// * `include_info_sections` - Whether the ping should include the client/ping_info sections.
230    /// * `enabled` - Whether or not this ping is enabled. Note: Data that would be sent on a disabled
231    ///   ping will still be collected and is discarded instead of being submitted.
232    /// * `schedules_pings` - A list of pings which are triggered for submission when this ping is
233    ///   submitted.
234    /// * `reason_codes` - The valid reason codes for this ping.
235    /// * `uploader_capabilities` - The capabilities required during this ping's upload.
236    #[allow(clippy::too_many_arguments)]
237    pub fn new<A: Into<String>>(
238        name: A,
239        include_client_id: bool,
240        send_if_empty: bool,
241        precise_timestamps: bool,
242        include_info_sections: bool,
243        enabled: bool,
244        schedules_pings: Vec<String>,
245        reason_codes: Vec<String>,
246        follows_collection_enabled: bool,
247        uploader_capabilities: Vec<String>,
248    ) -> Self {
249        let inner = crate::metrics::PingType::new(
250            name.into(),
251            include_client_id,
252            send_if_empty,
253            precise_timestamps,
254            include_info_sections,
255            enabled,
256            schedules_pings,
257            reason_codes,
258            follows_collection_enabled,
259            uploader_capabilities,
260        );
261
262        Self { inner }
263    }
264
265    pub fn submit(&self, reason: Option<&str>) {
266        self.inner.submit(reason.map(|s| s.to_string()))
267    }
268
269    pub fn set_enabled(&self, enabled: bool) {
270        self.inner.set_enabled(enabled)
271    }
272}
273
274#[cfg(not(feature = "active"))]
275impl PingType {
276    /// Creates a new ping type.
277    ///
278    /// # Arguments
279    ///
280    /// * `name` - The name of the ping.
281    /// * `include_client_id` - Whether to include the client ID in the assembled ping when.
282    /// * `send_if_empty` - Whether the ping should be sent empty or not.
283    /// * `precise_timestamps` - Whether the ping should use precise timestamps for the start and end time.
284    /// * `include_info_sections` - Whether the ping should include the client/ping_info sections.
285    /// * `enabled` - Whether or not this ping is enabled. Note: Data that would be sent on a disabled
286    ///   ping will still be collected and is discarded instead of being submitted.
287    /// * `schedules_pings` - A list of pings which are triggered for submission when this ping is
288    ///   submitted.
289    /// * `reason_codes` - The valid reason codes for this ping.
290    /// * `uploader_capabilities` - The capabilities required during this ping's upload.
291    #[allow(clippy::too_many_arguments)]
292    pub fn new<A: Into<String>>(
293        _name: A,
294        _include_client_id: bool,
295        _send_if_empty: bool,
296        _precise_timestamps: bool,
297        _include_info_sections: bool,
298        _enabled: bool,
299        _schedules_pings: Vec<String>,
300        _reason_codes: Vec<String>,
301        _follows_collection_enabled: bool,
302        _uploader_capabilities: Vec<String>,
303    ) -> Self {
304        Self
305    }
306
307    pub fn submit(&self, _reason: Option<&str>) {}
308
309    pub fn set_enabled(&self, _enabled: bool) {}
310}