Debian Codegraph @

third_party/rust/glean-core/src/util.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 chrono::{DateTime, FixedOffset, Local};
6
7 use crate::common_metric_data::CommonMetricDataInternal;
8 use crate::error_recording::{record_error, ErrorType};
9 use crate::metrics::TimeUnit;
10 use crate::Glean;
11
12 /// Generates a pipeline-friendly string
13 /// that replaces non alphanumeric characters with dashes.
14 pub fn sanitize_application_id(application_id: &str) -> String {
15 let mut last_dash = false;
16 application_id
17 .chars()
18 .filter_map(|x| match x {
19 'A'..='Z' | 'a'..='z' | '0'..='9' => {
20 last_dash = false;
21 Some(x.to_ascii_lowercase())
22 }
23 _ => {
24 let result = if last_dash { None } else { Some('-') };
25 last_dash = true;
26 result
27 }
28 })
29 .collect()
30 }
31
32 /// Generates an ISO8601 compliant date/time string for the given time,
33 /// truncating it to the provided [`TimeUnit`].
34 ///
35 /// # Arguments
36 ///
37 /// * `datetime` - the [`DateTime`] object that holds the date, time and timezone information.
38 /// * `truncate_to` - the desired resolution to use for the output string.
39 ///
40 /// # Returns
41 ///
42 /// A string representing the provided date/time truncated to the requested time unit.
43 pub fn get_iso_time_string(datetime: DateTime<FixedOffset>, truncate_to: TimeUnit) -> String {
44 datetime.format(truncate_to.format_pattern()).to_string()
45 }
46
47 /// Get the current date & time with a fixed-offset timezone.
48 ///
49 /// This converts from the `Local` timezone into its fixed-offset equivalent.
50 /// If a timezone outside of [-24h, +24h] is detected it corrects the timezone offset to UTC (+0).
51 pub(crate) fn local_now_with_offset() -> DateTime<FixedOffset> {
52 #[cfg(target_os = "windows")]
53 {
54 // `Local::now` takes the user's timezone offset
55 // and panics if it's not within a range of [-24, +24] hours.
56 // This causes crashes in a small number of clients on Windows.
57 //
58 // We can't determine the faulty clients
59 // or the circumstancens under which this happens,
60 // so the best we can do is have a workaround:
61 //
62 // We try getting the time and timezone first,
63 // then manually check that it is a valid timezone offset.
64 // If it is, we proceed and use that time and offset.
65 // If it isn't we fallback to UTC.
66 //
67 // This has the small downside that it will use 2 calls to get the time,
68 // but only on Windows.
69 //
70 // See https://bugzilla.mozilla.org/show_bug.cgi?id=1611770.
71
72 use chrono::Utc;
73
74 // Get timespec, including the user's timezone.
75 let tm = time::now();
76 // Same as chrono:
77 // https://docs.rs/chrono/0.4.10/src/chrono/offset/local.rs.html#37
78 let offset = tm.tm_utcoff;
79 if let None = FixedOffset::east_opt(offset) {
80 log::warn!(
81 "Detected invalid timezone offset: {}. Using UTC fallback.",
82 offset
83 );
84 let now: DateTime<Utc> = Utc::now();
85 let utc_offset = FixedOffset::east(0);
86 return now.with_timezone(&utc_offset);
87 }
88 }
89
90 let now: DateTime<Local> = Local::now();
91 now.with_timezone(now.offset())
92 }
93
94 /// Truncates a string, ensuring that it doesn't end in the middle of a codepoint.
95 ///
96 /// # Arguments
97 ///
98 /// * `value` - The string to truncate.
99 /// * `length` - The length, in bytes, to truncate to. The resulting string will
100 /// be at most this many bytes, but may be shorter to prevent ending in the middle
101 /// of a codepoint.
102 ///
103 /// # Returns
104 ///
105 /// A string, with at most `length` bytes.
106 pub(crate) fn truncate_string_at_boundary<S: Into<String>>(value: S, length: usize) -> String {
107 let s = value.into();
108 if s.len() > length {
109 for i in (0..=length).rev() {
110 if s.is_char_boundary(i) {
111 return s[0..i].to_string();
112 }
113 }
114 // If we never saw a character boundary, the safest thing we can do is
115 // return the empty string, though this should never happen in practice.
116 return "".to_string();
117 }
118 s
119 }
120
121 /// Truncates a string, ensuring that it doesn't end in the middle of a codepoint.
122 /// If the string required truncation, records an error through the error
123 /// reporting mechanism.
124 ///
125 /// # Arguments
126 ///
127 /// * `glean` - The Glean instance the metric doing the truncation belongs to.
128 /// * `meta` - The metadata for the metric. Used for recording the error.
129 /// * `value` - The String to truncate.
130 /// * `length` - The length, in bytes, to truncate to. The resulting string will
131 /// be at most this many bytes, but may be shorter to prevent ending in the middle
132 /// of a codepoint.
133 ///
134 /// # Returns
135 ///
136 /// A string, with at most `length` bytes.
137 pub(crate) fn truncate_string_at_boundary_with_error<S: Into<String>>(
138 glean: &Glean,
139 meta: &CommonMetricDataInternal,
140 value: S,
141 length: usize,
142 ) -> String {
143 let s = value.into();
144 if s.len() > length {
145 let msg = format!("Value length {} exceeds maximum of {}", s.len(), length);
146 record_error(glean, meta, ErrorType::InvalidOverflow, msg, None);
147 truncate_string_at_boundary(s, length)
148 } else {
149 s
150 }
151 }
152
153 // On i686 on Windows, the CPython interpreter sets the FPU precision control
154 // flag to 53 bits of precision, rather than the 64 bit default. On x86_64 on
155 // Windows, the CPython interpreter changes the rounding control settings. This
156 // causes different floating point results than on other architectures. This
157 // context manager makes it easy to set the correct precision and rounding control
158 // to match our other targets and platforms.
159 //
160 // See https://bugzilla.mozilla.org/show_bug.cgi?id=1623335 for additional context.
161 #[cfg(all(target_os = "windows", target_env = "gnu"))]
162 pub mod floating_point_context {
163 // `size_t` is "pointer size", which is equivalent to Rust's `usize`.
164 // It's defined as such in libc:
165 // * https://github.com/rust-lang/libc/blob/bcbfeb5516cd5bb055198dbfbddf8d626fa2be07/src/unix/mod.rs#L19
166 // * https://github.com/rust-lang/libc/blob/bcbfeb5516cd5bb055198dbfbddf8d626fa2be07/src/windows/mod.rs#L16
167 #[allow(non_camel_case_types)]
168 type size_t = usize;
169
170 #[link(name = "m")]
171 extern "C" {
172 // Gets and sets the floating point control word.
173 // See documentation here:
174 // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/controlfp-s
175 fn _controlfp_s(current: *mut size_t, new: size_t, mask: size_t) -> size_t;
176 }
177
178 // Rounding control mask
179 const MCW_RC: size_t = 0x00000300;
180 // Round by truncation
181 const RC_CHOP: size_t = 0x00000300;
182 // Precision control mask
183 const MCW_PC: size_t = 0x00030000;
184 // Values for 64-bit precision
185 const PC_64: size_t = 0x00000000;
186
187 pub struct FloatingPointContext {
188 original_value: size_t,
189 }
190
191 impl FloatingPointContext {
192 pub fn new() -> Self {
193 let mut current: size_t = 0;
194 let _err = unsafe { _controlfp_s(&mut current, PC_64 | RC_CHOP, MCW_PC | MCW_RC) };
195
196 FloatingPointContext {
197 original_value: current,
198 }
199 }
200 }
201
202 impl Drop for FloatingPointContext {
203 fn drop(&mut self) {
204 let mut current: size_t = 0;
205 let _err = unsafe { _controlfp_s(&mut current, self.original_value, MCW_PC | MCW_RC) };
206 }
207 }
208 }
209
210 #[cfg(not(all(target_os = "windows", target_env = "gnu")))]
211 pub mod floating_point_context {
212 pub struct FloatingPointContext {}
213
214 impl FloatingPointContext {
215 pub fn new() -> Self {
216 FloatingPointContext {}
217 }
218 }
219 }
220
221 #[cfg(test)]
222 mod test {
223 use super::*;
224 use chrono::offset::TimeZone;
225
226 #[test]
227 fn test_sanitize_application_id() {
228 assert_eq!(
229 "org-mozilla-test-app",
230 sanitize_application_id("org.mozilla.test-app")
231 );
232 assert_eq!(
233 "org-mozilla-test-app",
234 sanitize_application_id("org.mozilla..test---app")
235 );
236 assert_eq!(
237 "org-mozilla-test-app",
238 sanitize_application_id("org-mozilla-test-app")
239 );
240 assert_eq!(
241 "org-mozilla-test-app",
242 sanitize_application_id("org.mozilla.Test.App")
243 );
244 }
245
246 #[test]
247 fn test_get_iso_time_string() {
248 // `1985-07-03T12:09:14.000560274+01:00`
249 let dt = FixedOffset::east(3600)
250 .ymd(1985, 7, 3)
251 .and_hms_nano(12, 9, 14, 1_560_274);
252 assert_eq!(
253 "1985-07-03T12:09:14.001560274+01:00",
254 get_iso_time_string(dt, TimeUnit::Nanosecond)
255 );
256 assert_eq!(
257 "1985-07-03T12:09:14.001560+01:00",
258 get_iso_time_string(dt, TimeUnit::Microsecond)
259 );
260 assert_eq!(
261 "1985-07-03T12:09:14.001+01:00",
262 get_iso_time_string(dt, TimeUnit::Millisecond)
263 );
264 assert_eq!(
265 "1985-07-03T12:09:14+01:00",
266 get_iso_time_string(dt, TimeUnit::Second)
267 );
268 assert_eq!(
269 "1985-07-03T12:09+01:00",
270 get_iso_time_string(dt, TimeUnit::Minute)
271 );
272 assert_eq!(
273 "1985-07-03T12+01:00",
274 get_iso_time_string(dt, TimeUnit::Hour)
275 );
276 assert_eq!("1985-07-03+01:00", get_iso_time_string(dt, TimeUnit::Day));
277 }
278
279 #[test]
280 fn local_now_gets_the_time() {
281 let now = Local::now();
282 let fixed_now = local_now_with_offset();
283
284 // We can't compare across differing timezones, so we just compare the UTC timestamps.
285 // The second timestamp should be just a few nanoseconds later.
286 assert!(
287 fixed_now.naive_utc() >= now.naive_utc(),
288 "Time mismatch. Local now: {:?}, Fixed now: {:?}",
289 now,
290 fixed_now
291 );
292 }
293
294 #[test]
295 fn truncate_safely_test() {
296 let value = "电脑坏了".to_string();
297 let truncated = truncate_string_at_boundary(value, 10);
298 assert_eq!("电脑坏", truncated);
299
300 let value = "0123456789abcdef".to_string();
301 let truncated = truncate_string_at_boundary(value, 10);
302 assert_eq!("0123456789", truncated);
303 }
304
305 #[test]
306 #[should_panic]
307 fn truncate_naive() {
308 // Ensure that truncating the naïve way on this string would panic
309 let value = "电脑坏了".to_string();
310 value[0..10].to_string();
311 }
312 }