summaryrefslogtreecommitdiffstats
path: root/toolkit/components/glean/build_scripts/glean_parser_ext/templates/rust.jinja2
blob: ac86d2c6deb218b3db79d4f23176d774371123b3 (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
// -*- mode: Rust -*-

// AUTOGENERATED BY glean_parser.  DO NOT EDIT.
{# The rendered source is autogenerated, but this
Jinja2 template is not. Please file bugs! #}

/* 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 http://mozilla.org/MPL/2.0/. */

{% macro generate_extra_keys(obj) %}
{% for name, suffix in obj["_generate_enums"] %}
{% if obj|attr(name)|length %}
    #[derive(Clone, Copy, Hash, Eq, PartialEq)]
    pub enum {{ obj.name|Camelize }}{{ suffix }} {
        {% for key in obj|attr(name) %}
        {{ key | Camelize }},
        {% endfor %}
    }

    impl ExtraKeys for {{ obj.name|Camelize }}{{ suffix }} {
        const ALLOWED_KEYS: &'static [&'static str] = {{ obj.allowed_extra_keys|extra_keys }};

        fn index(self) -> i32 {
            self as i32
        }
    }

    /// Convert from an extra key's index to its variant.
    impl std::convert::TryFrom<i32> for {{ obj.name|Camelize }}{{ suffix }} {
        type Error = EventRecordingError;

        fn try_from(value: i32) -> Result<Self, Self::Error> {
          match value {
              {% for key in obj|attr(name) %}
              {{loop.index-1}} => Ok(Self::{{key | Camelize}}),
              {% endfor %}
              _ => Err(EventRecordingError::InvalidExtraKey),
          }
        }
    }

    /// Convert from an extra key's string representation to its variant.
    impl std::convert::TryFrom<&str> for {{ obj.name|Camelize }}{{ suffix }} {
        type Error = EventRecordingError;

        fn try_from(value: &str) -> Result<Self, Self::Error> {
          match value {
              {% for key in obj|attr(name) %}
              "{{key}}" => Ok(Self::{{key | Camelize}}),
              {% endfor %}
              _ => Err(EventRecordingError::InvalidExtraKey),
          }
        }
    }

{% endif %}
{% endfor %}
{% endmacro %}

{% for category_name, objs in all_objs.items() %}
pub mod {{ category_name|snake_case }} {
    use crate::private::*;
    use glean_core::CommonMetricData;
    use once_cell::sync::Lazy;

    {% for obj in objs.values() %}
    {% if obj|attr("_generate_enums") %}
{{ generate_extra_keys(obj) }}
    {%- endif %}
    #[allow(non_upper_case_globals)]
    /// generated from {{ category_name }}.{{ obj.name }}
    ///
    /// {{ obj.description|wordwrap() | replace('\n', '\n    /// ') }}
    pub static {{ obj.name|snake_case }}: Lazy<{{ obj|type_name }}> = Lazy::new(|| {
        {{ obj|ctor }}({{obj|metric_id}}.into(), CommonMetricData {
            {% for arg_name in common_metric_data_args if obj[arg_name] is defined %}
            {{ arg_name }}: {{ obj[arg_name]|rust }},
            {% endfor %}
            ..Default::default()
        }
        {%- for arg_name in extra_args if obj[arg_name] is defined and arg_name not in common_metric_data_args and arg_name != 'allowed_extra_keys' -%}
            , {{ obj[arg_name]|rust }}
        {%- endfor -%}
        {{ ", " if obj.labeled else ")\n" }}
        {%- if obj.labeled -%}
        {%- if obj.labels -%}
        Some({{ obj.labels|rust }})
        {%- else -%}
        None
        {%- endif -%})
        {% endif %}
    });

    {% endfor %}
}
{% endfor %}

{% if metric_by_type|length > 0 %}
#[allow(dead_code)]
pub(crate) mod __glean_metric_maps {
    use std::collections::HashMap;
    use std::convert::TryInto;

    use crate::private::*;
    use once_cell::sync::Lazy;

{% for typ, metrics in metric_by_type.items() %}
    pub static {{typ.0}}: Lazy<HashMap<MetricId, &Lazy<{{typ.1}}>>> = Lazy::new(|| {
        let mut map = HashMap::with_capacity({{metrics|length}});
        {% for metric in metrics %}
        map.insert({{metric.0}}.into(), &super::{{metric.1}});
        {% endfor %}
        map
    });

{% endfor %}

    /// Helper to get the number of allowed extra keys for a given event metric.
    fn extra_keys_len<K: ExtraKeys>(_event: &EventMetric<K>) -> usize {
        K::ALLOWED_KEYS.len()
    }

    /// Wrapper to record an event based on its metric ID.
    ///
    /// # Arguments
    ///
    /// * `metric_id` - The metric's ID to look up
    /// * `extra`     - An (optional) map of (extra key id, string) pairs.
    ///                 The map will be decoded into the appropriate `ExtraKeys` type.
    /// # Returns
    ///
    /// Returns `Ok(())` if the event was found and `record` was called with the given `extra`,
    /// or an `EventRecordingError::InvalidId` if no event by that ID exists
    /// or an `EventRecordingError::InvalidExtraKey` the `extra` map could not be deserialized.
    pub(crate) fn event_record_wrapper(metric_id: u32, extra: HashMap<i32, String>) -> Result<(), EventRecordingError> {
        match metric_id {
{% for metric_id, event in events_by_id.items() %}
          {{metric_id}} => {
              assert!(
                  extra_keys_len(&super::{{event}}) != 0 || extra.is_empty(),
                  "No extra keys allowed, but some were passed"
              );

              // In case of `NoExtraKeys` the whole iterator is impossible, so rustc complains.
              #[allow(unused_variables)]
              let extra: HashMap<_, _> = extra
                  .into_iter()
                  .map(|(k, v)| k.try_into().map(|k| (k, v)))
                  .collect::<Result<HashMap<_, _>, _>>()?;
              super::{{event}}.record(Some(extra));
              Ok(())
          }
{% endfor %}
           _ => Err(EventRecordingError::InvalidId),
        }
    }

    /// Wrapper to record an event based on its metric ID.
    ///
    /// # Arguments
    ///
    /// * `metric_id` - The metric's ID to look up
    /// * `extra`     - An (optional) map of (string, string) pairs.
    ///                 The map will be decoded into the appropriate `ExtraKeys` types.
    /// # Returns
    ///
    /// Returns `Ok(())` if the event was found and `record` was called with the given `extra`,
    /// or an `EventRecordingError::InvalidId` if no event by that ID exists
    /// or an `EventRecordingError::InvalidExtraKey` the `extra` map could not be deserialized.
    pub(crate) fn event_record_wrapper_str(metric_id: u32, extra: HashMap<String, String>) -> Result<(), EventRecordingError> {
        match metric_id {
{% for metric_id, event in events_by_id.items() %}
          {{metric_id}} => {
              assert!(
                  extra_keys_len(&super::{{event}}) != 0 || extra.is_empty(),
                  "No extra keys allowed, but some were passed"
              );

              // In case of `NoExtraKeys` the whole iterator is impossible, so rustc complains.
              #[allow(unused_variables)]
              let extra = extra
                  .into_iter()
                  .map(|(k, v)| (&*k).try_into().map(|k| (k, v)))
                  .collect::<Result<HashMap<_, _>, _>>()?;
              super::{{event}}.record(Some(extra));
              Ok(())
          }
{% endfor %}
           _ => Err(EventRecordingError::InvalidId),
        }
    }

    /// Wrapper to get the currently stored events for event metric.
    ///
    /// # Arguments
    ///
    /// * `metric_id` - The metric's ID to look up
    /// * `storage_name` - the storage name to look into.
    ///
    /// # Returns
    ///
    /// Returns the recorded events or `None` if nothing stored.
    ///
    /// # Panics
    ///
    /// Panics if no event by the given metric ID could be found.
    pub(crate) fn event_test_get_value_wrapper(metric_id: u32, storage_name: &str) -> Option<Vec<RecordedEvent>> {
        match metric_id {
{% for metric_id, event in events_by_id.items() %}
           {{metric_id}} => super::{{event}}.test_get_value(storage_name),
{% endfor %}
           _ => panic!("No event for metric id {}", metric_id),
        }
    }
}
{% endif %}