Debian Codegraph @

third_party/rust/glean-core/src/metrics/text.rs

raw
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
5 use std::sync::Arc;
6
7 use crate::common_metric_data::CommonMetricDataInternal;
8 use crate::error_recording::{test_get_num_recorded_errors, ErrorType};
9 use crate::metrics::Metric;
10 use crate::metrics::MetricType;
11 use crate::storage::StorageManager;
12 use crate::util::truncate_string_at_boundary_with_error;
13 use crate::CommonMetricData;
14 use crate::Glean;
15
16 // The maximum number of characters for text.
17 const MAX_LENGTH_VALUE: usize = 200 * 1024;
18
19 /// A text metric.
20 ///
21 /// Records a single long Unicode text,
22 /// used when the limits on `String` are too low.
23 /// Text is length-limited to `MAX_LENGTH_VALUE` bytes.
24 #[derive(Clone, Debug)]
25 pub struct TextMetric {
26 meta: Arc<CommonMetricDataInternal>,
27 }
28
29 impl MetricType for TextMetric {
30 fn meta(&self) -> &CommonMetricDataInternal {
31 &self.meta
32 }
33
34 fn with_name(&self, name: String) -> Self {
35 let mut meta = (*self.meta).clone();
36 meta.inner.name = name;
37 Self {
38 meta: Arc::new(meta),
39 }
40 }
41
42 fn with_dynamic_label(&self, label: String) -> Self {
43 let mut meta = (*self.meta).clone();
44 meta.inner.dynamic_label = Some(label);
45 Self {
46 meta: Arc::new(meta),
47 }
48 }
49 }
50
51 // IMPORTANT:
52 //
53 // When changing this implementation, make sure all the operations are
54 // also declared in the related trait in `../traits/`.
55 impl TextMetric {
56 /// Creates a new text metric.
57 pub fn new(meta: CommonMetricData) -> Self {
58 Self {
59 meta: Arc::new(meta.into()),
60 }
61 }
62
63 /// Sets to the specified value.
64 ///
65 /// # Arguments
66 ///
67 /// * `value` - The text to set the metric to.
68 ///
69 /// ## Notes
70 ///
71 /// Truncates the value (at codepoint boundaries) if it is longer than `MAX_LENGTH_VALUE` bytes
72 /// and logs an error.
73 pub fn set(&self, value: String) {
74 let metric = self.clone();
75 crate::launch_with_glean(move |glean| metric.set_sync(glean, &value))
76 }
77
78 /// Sets to the specified value synchronously,
79 /// truncating and recording an error if longer than `MAX_LENGTH_VALUE`.
80 #[doc(hidden)]
81 pub fn set_sync<S: Into<String>>(&self, glean: &Glean, value: S) {
82 if !self.should_record(glean) {
83 return;
84 }
85
86 let s = truncate_string_at_boundary_with_error(glean, &self.meta, value, MAX_LENGTH_VALUE);
87
88 let value = Metric::Text(s);
89 glean.storage().record(glean, &self.meta, &value)
90 }
91
92 /// Gets the currently-stored value as a string, or None if there is no value.
93 #[doc(hidden)]
94 pub fn get_value<'a, S: Into<Option<&'a str>>>(
95 &self,
96 glean: &Glean,
97 ping_name: S,
98 ) -> Option<String> {
99 let queried_ping_name = ping_name
100 .into()
101 .unwrap_or_else(|| &self.meta().inner.send_in_pings[0]);
102
103 match StorageManager.snapshot_metric_for_test(
104 glean.storage(),
105 queried_ping_name,
106 &self.meta.identifier(glean),
107 self.meta.inner.lifetime,
108 ) {
109 Some(Metric::Text(s)) => Some(s),
110 _ => None,
111 }
112 }
113
114 /// **Test-only API (exported for FFI purposes).**
115 ///
116 /// Gets the currently stored value as a string.
117 ///
118 /// This doesn't clear the stored value.
119 ///
120 /// # Arguments
121 ///
122 /// * `ping_name` - the optional name of the ping to retrieve the metric
123 /// for. Defaults to the first value in `send_in_pings`.
124 ///
125 /// # Returns
126 ///
127 /// The stored value or `None` if nothing stored.
128 pub fn test_get_value(&self, ping_name: Option<String>) -> Option<String> {
129 crate::block_on_dispatcher();
130 crate::core::with_glean(|glean| self.get_value(glean, ping_name.as_deref()))
131 }
132
133 /// **Exported for test purposes.**
134 ///
135 /// Gets the number of recorded errors for the given metric and error type.
136 ///
137 /// # Arguments
138 ///
139 /// * `error` - The type of error
140 ///
141 /// # Returns
142 ///
143 /// The number of errors reported.
144 pub fn test_get_num_recorded_errors(&self, error: ErrorType) -> i32 {
145 crate::block_on_dispatcher();
146
147 crate::core::with_glean(|glean| {
148 test_get_num_recorded_errors(glean, self.meta(), error).unwrap_or(0)
149 })
150 }
151 }
152
153 #[cfg(test)]
154 mod test {
155 use super::*;
156 use crate::tests::new_glean;
157 use crate::util::truncate_string_at_boundary;
158 use crate::Lifetime;
159
160 #[test]
161 fn setting_a_long_string_records_an_error() {
162 let (glean, _t) = new_glean(None);
163
164 let metric = TextMetric::new(CommonMetricData {
165 name: "text_metric".into(),
166 category: "test".into(),
167 send_in_pings: vec!["store1".into()],
168 lifetime: Lifetime::Application,
169 disabled: false,
170 dynamic_label: None,
171 });
172
173 let sample_string = "0123456789".repeat(200 * 1024);
174 metric.set_sync(&glean, sample_string.clone());
175
176 let truncated = truncate_string_at_boundary(sample_string, MAX_LENGTH_VALUE);
177 assert_eq!(truncated, metric.get_value(&glean, "store1").unwrap());
178
179 assert_eq!(
180 1,
181 test_get_num_recorded_errors(&glean, metric.meta(), ErrorType::InvalidOverflow)
182 .unwrap()
183 );
184 }
185 }