| 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 |
mod common; |
| 6 |
use crate::common::*; |
| 7 |
|
| 8 |
use std::collections::HashMap; |
| 9 |
use std::io::Read; |
| 10 |
|
| 11 |
use flate2::read::GzDecoder; |
| 12 |
use jsonschema_valid::schemas::Draft; |
| 13 |
use serde_json::Value; |
| 14 |
|
| 15 |
use glean::net::{CapablePingUploadRequest, UploadResult}; |
| 16 |
use glean::private::*; |
| 17 |
use glean::{ |
| 18 |
traits, ClientInfoMetrics, CommonMetricData, ConfigurationBuilder, HistogramType, MemoryUnit, |
| 19 |
TimeUnit, |
| 20 |
}; |
| 21 |
|
| 22 |
const SCHEMA_JSON: &str = include_str!("../../../glean.1.schema.json"); |
| 23 |
|
| 24 |
fn load_schema() -> Value { |
| 25 |
serde_json::from_str(SCHEMA_JSON).unwrap() |
| 26 |
} |
| 27 |
|
| 28 |
const GLOBAL_APPLICATION_ID: &str = "org.mozilla.glean.test.app"; |
| 29 |
|
| 30 |
struct SomeExtras { |
| 31 |
extra1: Option<String>, |
| 32 |
extra2: Option<bool>, |
| 33 |
} |
| 34 |
|
| 35 |
impl traits::ExtraKeys for SomeExtras { |
| 36 |
const ALLOWED_KEYS: &'static [&'static str] = &["extra1", "extra2"]; |
| 37 |
|
| 38 |
fn into_ffi_extra(self) -> HashMap<String, String> { |
| 39 |
let mut map = HashMap::new(); |
| 40 |
|
| 41 |
self.extra1 |
| 42 |
.and_then(|val| map.insert("extra1".to_string(), val)); |
| 43 |
self.extra2 |
| 44 |
.and_then(|val| map.insert("extra2".to_string(), val.to_string())); |
| 45 |
|
| 46 |
map |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
#[test] |
| 51 |
fn validate_against_schema() { |
| 52 |
let _ = env_logger::builder().try_init(); |
| 53 |
|
| 54 |
let schema = load_schema(); |
| 55 |
|
| 56 |
let (s, r) = crossbeam_channel::bounded::<Vec<u8>>(1); |
| 57 |
|
| 58 |
// Define a fake uploader that reports back the submitted payload |
| 59 |
// using a crossbeam channel. |
| 60 |
#[derive(Debug)] |
| 61 |
pub struct ValidatingUploader { |
| 62 |
sender: crossbeam_channel::Sender<Vec<u8>>, |
| 63 |
} |
| 64 |
impl glean::net::PingUploader for ValidatingUploader { |
| 65 |
fn upload(&self, ping_request: CapablePingUploadRequest) -> UploadResult { |
| 66 |
let ping_request = ping_request.capable(|_| true).unwrap(); |
| 67 |
self.sender.send(ping_request.body).unwrap(); |
| 68 |
UploadResult::http_status(200) |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
// Create a custom configuration to use a validating uploader. |
| 73 |
let dir = tempfile::tempdir().unwrap(); |
| 74 |
let tmpname = dir.path().to_path_buf(); |
| 75 |
|
| 76 |
let cfg = ConfigurationBuilder::new(true, tmpname, GLOBAL_APPLICATION_ID) |
| 77 |
.with_server_endpoint("invalid-test-host") |
| 78 |
.with_uploader(ValidatingUploader { sender: s }) |
| 79 |
.build(); |
| 80 |
|
| 81 |
let client_info = ClientInfoMetrics { |
| 82 |
app_build: env!("CARGO_PKG_VERSION").to_string(), |
| 83 |
app_display_version: env!("CARGO_PKG_VERSION").to_string(), |
| 84 |
channel: Some("testing".to_string()), |
| 85 |
locale: Some("xx-XX".to_string()), |
| 86 |
}; |
| 87 |
|
| 88 |
glean::initialize(cfg, client_info); |
| 89 |
|
| 90 |
const PING_NAME: &str = "test-ping"; |
| 91 |
|
| 92 |
let common = |name: &str| CommonMetricData { |
| 93 |
category: "test".into(), |
| 94 |
name: name.into(), |
| 95 |
send_in_pings: vec![PING_NAME.into()], |
| 96 |
..Default::default() |
| 97 |
}; |
| 98 |
|
| 99 |
// Test each of the metric types, just for basic smoke testing against the |
| 100 |
// schema |
| 101 |
|
| 102 |
// TODO: 1695762 Test all of the metric types against the schema from Rust |
| 103 |
|
| 104 |
let counter_metric = CounterMetric::new(common("counter")); |
| 105 |
counter_metric.add(42); |
| 106 |
|
| 107 |
let bool_metric = BooleanMetric::new(common("bool")); |
| 108 |
bool_metric.set(true); |
| 109 |
|
| 110 |
let string_metric = StringMetric::new(common("string")); |
| 111 |
string_metric.set("test".into()); |
| 112 |
|
| 113 |
let stringlist_metric = StringListMetric::new(common("stringlist")); |
| 114 |
stringlist_metric.add("one".into()); |
| 115 |
stringlist_metric.add("two".into()); |
| 116 |
|
| 117 |
// Let's make sure an empty array is accepted. |
| 118 |
let stringlist_metric2 = StringListMetric::new(common("stringlist2")); |
| 119 |
stringlist_metric2.set(vec![]); |
| 120 |
|
| 121 |
let timespan_metric = TimespanMetric::new(common("timespan"), TimeUnit::Nanosecond); |
| 122 |
timespan_metric.start(); |
| 123 |
timespan_metric.stop(); |
| 124 |
|
| 125 |
let timing_dist = TimingDistributionMetric::new(common("timing_dist"), TimeUnit::Nanosecond); |
| 126 |
let id = timing_dist.start(); |
| 127 |
timing_dist.stop_and_accumulate(id); |
| 128 |
|
| 129 |
let memory_dist = MemoryDistributionMetric::new(common("memory_dist"), MemoryUnit::Byte); |
| 130 |
memory_dist.accumulate(100); |
| 131 |
|
| 132 |
let uuid_metric = UuidMetric::new(common("uuid")); |
| 133 |
// chosen by fair dic roll (`uuidgen`) |
| 134 |
uuid_metric.set("3ee4db5f-ee26-4557-9a66-bc7425d7893f".into()); |
| 135 |
|
| 136 |
// We can't test the URL metric, |
| 137 |
// because the regex used in the schema uses a negative lookahead, |
| 138 |
// which the regex crate doesn't handle. |
| 139 |
// |
| 140 |
//let url_metric = UrlMetric::new(common("url")); |
| 141 |
//url_metric.set("https://mozilla.github.io/glean/"); |
| 142 |
|
| 143 |
let datetime_metric = DatetimeMetric::new(common("datetime"), TimeUnit::Day); |
| 144 |
datetime_metric.set(None); |
| 145 |
|
| 146 |
let event_metric = EventMetric::<SomeExtras>::new(common("event")); |
| 147 |
event_metric.record(None); |
| 148 |
event_metric.record(SomeExtras { |
| 149 |
extra1: Some("test".into()), |
| 150 |
extra2: Some(false), |
| 151 |
}); |
| 152 |
|
| 153 |
let custom_dist = |
| 154 |
CustomDistributionMetric::new(common("custom_dist"), 1, 100, 100, HistogramType::Linear); |
| 155 |
custom_dist.accumulate_samples(vec![50, 51]); |
| 156 |
|
| 157 |
let quantity_metric = QuantityMetric::new(common("quantity")); |
| 158 |
quantity_metric.set(0); |
| 159 |
|
| 160 |
let rate_metric = RateMetric::new(common("rate")); |
| 161 |
rate_metric.add_to_numerator(1); |
| 162 |
rate_metric.add_to_denominator(1); |
| 163 |
|
| 164 |
let numerator_metric1 = NumeratorMetric::new(common("num1")); |
| 165 |
let numerator_metric2 = NumeratorMetric::new(common("num2")); |
| 166 |
let denominator_metric = |
| 167 |
DenominatorMetric::new(common("den"), vec![common("num1"), common("num2")]); |
| 168 |
|
| 169 |
numerator_metric1.add_to_numerator(1); |
| 170 |
numerator_metric2.add_to_numerator(2); |
| 171 |
denominator_metric.add(3); |
| 172 |
|
| 173 |
let text_metric = TextMetric::new(common("text")); |
| 174 |
text_metric.set("loooooong text".repeat(100)); |
| 175 |
|
| 176 |
// Define a new ping and submit it. |
| 177 |
let custom_ping = PingBuilder::new(PING_NAME).with_send_if_empty(true).build(); |
| 178 |
custom_ping.submit(None); |
| 179 |
|
| 180 |
// Wait for the ping to arrive. |
| 181 |
let raw_body = r.recv().unwrap(); |
| 182 |
|
| 183 |
// Decode the gzipped body. |
| 184 |
let mut gzip_decoder = GzDecoder::new(&raw_body[..]); |
| 185 |
let mut s = String::with_capacity(raw_body.len()); |
| 186 |
|
| 187 |
let data = gzip_decoder |
| 188 |
.read_to_string(&mut s) |
| 189 |
.ok() |
| 190 |
.map(|_| &s[..]) |
| 191 |
.or_else(|| std::str::from_utf8(&raw_body).ok()) |
| 192 |
.and_then(|payload| serde_json::from_str(payload).ok()) |
| 193 |
.unwrap(); |
| 194 |
|
| 195 |
// Now validate against the vendored schema |
| 196 |
let cfg = jsonschema_valid::Config::from_schema(&schema, Some(Draft::Draft6)).unwrap(); |
| 197 |
let validation = cfg.validate(&data); |
| 198 |
match validation { |
| 199 |
Ok(()) => {} |
| 200 |
Err(errors) => { |
| 201 |
let mut msg = format!("Data: {data:#?}\n Errors:\n"); |
| 202 |
for (idx, error) in errors.enumerate() { |
| 203 |
msg.push_str(&format!("Error {}: ", idx + 1)); |
| 204 |
msg.push_str(&error.to_string()); |
| 205 |
msg.push('\n'); |
| 206 |
} |
| 207 |
panic!("{}", msg); |
| 208 |
} |
| 209 |
} |
| 210 |
} |