summaryrefslogtreecommitdiffstats
path: root/toolkit/components/glean/api/src/private/object.rs
blob: 5199cfad31de5fbf9c6d80a9e9dc1f6857e7d87b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use super::{CommonMetricData, MetricId};

use crate::ipc::need_ipc;

use glean::traits::ObjectSerialize;

/// An object metric.
pub enum ObjectMetric<K> {
    Parent {
        id: MetricId,
        inner: glean::private::ObjectMetric<K>,
    },
    Child,
}

impl<K: ObjectSerialize> ObjectMetric<K> {
    /// Create a new object metric.
    pub fn new(id: MetricId, meta: CommonMetricData) -> Self {
        if need_ipc() {
            ObjectMetric::Child
        } else {
            let inner = glean::private::ObjectMetric::new(meta);
            ObjectMetric::Parent { id, inner }
        }
    }

    pub fn set(&self, value: K) {
        match self {
            ObjectMetric::Parent { inner, .. } => {
                inner.set(value);
            }
            ObjectMetric::Child => {
                log::error!("Unable to set object metric in non-main process. This operation will be ignored.");
                // TODO: Record an error.
            }
        };
    }

    pub fn set_string(&self, value: String) {
        match self {
            ObjectMetric::Parent { inner, .. } => {
                inner.set_string(value);
            }
            ObjectMetric::Child => {
                log::error!("Unable to set object metric in non-main process. This operation will be ignored.");
                // TODO: Record an error.
            }
        };
    }

    pub fn test_get_value<'a, S: Into<Option<&'a str>>>(
        &self,
        ping_name: S,
    ) -> Option<serde_json::Value> {
        match self {
            ObjectMetric::Parent { inner, .. } => inner.test_get_value(ping_name),
            ObjectMetric::Child => {
                panic!("Cannot get test value for object metric in non-parent process!",)
            }
        }
    }

    pub fn test_get_value_as_str<'a, S: Into<Option<&'a str>>>(
        &self,
        ping_name: S,
    ) -> Option<String> {
        self.test_get_value(ping_name)
            .map(|val| serde_json::to_string(&val).unwrap())
    }

    pub fn test_get_num_recorded_errors(&self, error: glean::ErrorType) -> i32 {
        match self {
            ObjectMetric::Parent { inner, .. } => inner.test_get_num_recorded_errors(error),
            ObjectMetric::Child => {
                panic!("Cannot get the number of recorded errors in non-parent process!")
            }
        }
    }
}