Debian Codegraph @

third_party/rust/glean/tests/upload_timing.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 //! This integration test should model how the RLB is used when embedded in another Rust application
6 //! (e.g. FOG/Firefox Desktop).
7 //!
8 //! We write a single test scenario per file to avoid any state keeping across runs
9 //! (different files run as different processes).
10
11 mod common;
12
13 use std::io::Read;
14 use std::sync::atomic::{AtomicUsize, Ordering};
15 use std::thread;
16 use std::time;
17
18 use crossbeam_channel::{bounded, Sender};
19 use flate2::read::GzDecoder;
20 use serde_json::Value as JsonValue;
21
22 use glean::net;
23 use glean::ConfigurationBuilder;
24
25 pub mod metrics {
26 #![allow(non_upper_case_globals)]
27
28 use glean::{
29 private::BooleanMetric, private::TimingDistributionMetric, CommonMetricData, Lifetime,
30 TimeUnit,
31 };
32
33 pub static sample_boolean: once_cell::sync::Lazy<BooleanMetric> =
34 once_cell::sync::Lazy::new(|| {
35 BooleanMetric::new(CommonMetricData {
36 name: "sample_boolean".into(),
37 category: "test.metrics".into(),
38 send_in_pings: vec!["validation".into()],
39 disabled: false,
40 lifetime: Lifetime::Ping,
41 ..Default::default()
42 })
43 });
44
45 // The following are duplicated from `glean-core/src/internal_metrics.rs`
46 // so we can use the test APIs to query them.
47
48 pub static send_success: once_cell::sync::Lazy<TimingDistributionMetric> =
49 once_cell::sync::Lazy::new(|| {
50 TimingDistributionMetric::new(
51 CommonMetricData {
52 name: "send_success".into(),
53 category: "glean.upload".into(),
54 send_in_pings: vec!["metrics".into()],
55 lifetime: Lifetime::Ping,
56 disabled: false,
57 dynamic_label: None,
58 },
59 TimeUnit::Millisecond,
60 )
61 });
62
63 pub static send_failure: once_cell::sync::Lazy<TimingDistributionMetric> =
64 once_cell::sync::Lazy::new(|| {
65 TimingDistributionMetric::new(
66 CommonMetricData {
67 name: "send_failure".into(),
68 category: "glean.upload".into(),
69 send_in_pings: vec!["metrics".into()],
70 lifetime: Lifetime::Ping,
71 disabled: false,
72 dynamic_label: None,
73 },
74 TimeUnit::Millisecond,
75 )
76 });
77
78 pub static shutdown_wait: once_cell::sync::Lazy<TimingDistributionMetric> =
79 once_cell::sync::Lazy::new(|| {
80 TimingDistributionMetric::new(
81 CommonMetricData {
82 name: "shutdown_wait".into(),
83 category: "glean.validation".into(),
84 send_in_pings: vec!["metrics".into()],
85 lifetime: Lifetime::Ping,
86 disabled: false,
87 dynamic_label: None,
88 },
89 TimeUnit::Millisecond,
90 )
91 });
92 }
93
94 mod pings {
95 use super::*;
96 use glean::private::PingType;
97 use once_cell::sync::Lazy;
98
99 #[allow(non_upper_case_globals)]
100 pub static validation: Lazy<PingType> = Lazy::new(|| {
101 common::PingBuilder::new("validation")
102 .with_send_if_empty(true)
103 .build()
104 });
105 }
106
107 // Define a fake uploader that sleeps.
108 #[derive(Debug)]
109 struct FakeUploader {
110 calls: AtomicUsize,
111 sender: Sender<JsonValue>,
112 }
113
114 impl net::PingUploader for FakeUploader {
115 fn upload(&self, upload_request: net::CapablePingUploadRequest) -> net::UploadResult {
116 let upload_request = upload_request.capable(|_| true).unwrap();
117 let calls = self.calls.fetch_add(1, Ordering::SeqCst);
118 let body = upload_request.body;
119 let decode = |body: Vec<u8>| {
120 let mut gzip_decoder = GzDecoder::new(&body[..]);
121 let mut s = String::with_capacity(body.len());
122
123 gzip_decoder
124 .read_to_string(&mut s)
125 .ok()
126 .map(|_| &s[..])
127 .or_else(|| std::str::from_utf8(&body).ok())
128 .and_then(|payload| serde_json::from_str(payload).ok())
129 .unwrap()
130 };
131
132 match calls {
133 // First goes through as is.
134 0 => net::UploadResult::http_status(200),
135 // Second briefly sleeps
136 1 => {
137 thread::sleep(time::Duration::from_millis(100));
138 net::UploadResult::http_status(200)
139 }
140 // Third one fails
141 2 => net::UploadResult::http_status(404),
142 // Fourth one fast again
143 3 => {
144 self.sender.send(decode(body)).unwrap();
145 net::UploadResult::http_status(200)
146 }
147 // Last one is the metrics ping, a-ok.
148 _ => {
149 self.sender.send(decode(body)).unwrap();
150 net::UploadResult::http_status(200)
151 }
152 }
153 }
154 }
155
156 /// Test scenario: Different timings for upload on success and failure.
157 ///
158 /// The app is initialized, in turn Glean gets initialized without problems.
159 /// A custom ping is submitted multiple times to trigger upload.
160 /// A metrics ping is submitted to get the upload timing data.
161 ///
162 /// And later the whole process is shutdown.
163 #[test]
164 fn upload_timings() {
165 common::enable_test_logging();
166
167 // Create a custom configuration to use a validating uploader.
168 let dir = tempfile::tempdir().unwrap();
169 let tmpname = dir.path().to_path_buf();
170 let (tx, rx) = bounded(1);
171
172 let cfg = ConfigurationBuilder::new(true, tmpname.clone(), "glean-upload-timing")
173 .with_server_endpoint("invalid-test-host")
174 .with_use_core_mps(false)
175 .with_uploader(FakeUploader {
176 calls: AtomicUsize::new(0),
177 sender: tx,
178 })
179 .build();
180 common::initialize(cfg);
181
182 // Wait for init to finish,
183 // otherwise we might be to quick with calling `shutdown`.
184 let _ = metrics::sample_boolean.test_get_value(None);
185
186 // fast
187 pings::validation.submit(None);
188 // slow
189 pings::validation.submit(None);
190 // failed
191 pings::validation.submit(None);
192 // fast
193 pings::validation.submit(None);
194
195 // wait for the last ping
196 let _body = rx.recv().unwrap();
197
198 assert_eq!(
199 3,
200 metrics::send_success.test_get_value(None).unwrap().count,
201 "Successful pings: two fast, one slow"
202 );
203 assert_eq!(
204 1,
205 metrics::send_failure.test_get_value(None).unwrap().count,
206 "One failed ping"
207 );
208
209 // This is awkward, but it's what gets us very close to just starting a new process with a
210 // fresh Glean.
211 // This also calls `glean::shutdown();` internally, waiting on the uploader.
212 let data_path = Some(tmpname.display().to_string());
213 glean_core::glean_test_destroy_glean(false, data_path);
214
215 let cfg = ConfigurationBuilder::new(true, tmpname, "glean-upload-timing")
216 .with_server_endpoint("invalid-test-host")
217 .with_use_core_mps(false)
218 .build();
219 common::initialize(cfg);
220
221 assert_eq!(
222 1,
223 metrics::shutdown_wait.test_get_value(None).unwrap().count,
224 "Measured time waiting for shutdown exactly once"
225 );
226 }