File: ping_maker.rs

package info (click to toggle)
thunderbird 1%3A140.4.0esr-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,609,432 kB
  • sloc: cpp: 7,672,442; javascript: 5,901,613; ansic: 3,898,954; python: 1,413,343; xml: 653,997; asm: 462,286; java: 180,927; sh: 113,489; makefile: 20,460; perl: 14,288; objc: 13,059; yacc: 4,583; pascal: 3,352; lex: 1,720; ruby: 1,222; exp: 762; sql: 715; awk: 580; php: 436; lisp: 430; sed: 70; csh: 10
file content (375 lines) | stat: -rw-r--r-- 12,390 bytes parent folder | download | duplicates (15)
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
// 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 https://mozilla.org/MPL/2.0/.

mod common;
use crate::common::*;
use glean_core::{AttributionMetrics, DistributionMetrics};
use serde_json::json;

use glean_core::metrics::*;
use glean_core::ping::PingMaker;
use glean_core::{CommonMetricData, Glean, Lifetime};

fn set_up_basic_ping() -> (Glean, PingMaker, PingType, tempfile::TempDir) {
    let (tempdir, _) = tempdir();
    let (mut glean, t) = new_glean(Some(tempdir));
    let ping_maker = PingMaker::new();
    let ping_type = new_test_ping(&mut glean, "store1");

    // Record something, so the ping will have data
    let metric = BooleanMetric::new(CommonMetricData {
        name: "boolean_metric".into(),
        category: "telemetry".into(),
        send_in_pings: vec!["store1".into()],
        disabled: false,
        lifetime: Lifetime::User,
        ..Default::default()
    });
    metric.set_sync(&glean, true);

    (glean, ping_maker, ping_type, t)
}

#[test]
fn ping_info_must_contain_a_nonempty_start_and_end_time() {
    let (glean, ping_maker, ping_type, _t) = set_up_basic_ping();

    let ping = ping_maker
        .collect(&glean, &ping_type, None, "", "")
        .unwrap();
    let ping_info = ping.content["ping_info"].as_object().unwrap();

    let start_time_str = ping_info["start_time"].as_str().unwrap();
    let start_time_date = iso8601_to_chrono(&iso8601::datetime(start_time_str).unwrap());

    let end_time_str = ping_info["end_time"].as_str().unwrap();
    let end_time_date = iso8601_to_chrono(&iso8601::datetime(end_time_str).unwrap());

    assert!(start_time_date <= end_time_date);
}

#[test]
fn get_ping_info_must_report_all_the_required_fields() {
    let (glean, ping_maker, ping_type, _t) = set_up_basic_ping();

    let ping = ping_maker
        .collect(&glean, &ping_type, None, "", "")
        .unwrap();
    let ping_info = ping.content["ping_info"].as_object().unwrap();

    assert!(ping_info.get("start_time").is_some());
    assert!(ping_info.get("end_time").is_some());
    assert!(ping_info.get("seq").is_some());
}

#[test]
fn get_client_info_must_report_all_the_available_data() {
    let (glean, ping_maker, ping_type, _t) = set_up_basic_ping();

    let ping = ping_maker
        .collect(&glean, &ping_type, None, "", "")
        .unwrap();
    let client_info = ping.content["client_info"].as_object().unwrap();

    client_info["telemetry_sdk_build"].as_str().unwrap();
}

#[test]
fn test_metrics_must_report_experimentation_id() {
    let (tempdir, _) = tempdir();
    let mut glean = Glean::new(glean_core::InternalConfiguration {
        data_path: tempdir.path().display().to_string(),
        application_id: GLOBAL_APPLICATION_ID.into(),
        language_binding_name: "Rust".into(),
        upload_enabled: true,
        max_events: None,
        delay_ping_lifetime_io: false,
        app_build: "Unknown".into(),
        use_core_mps: false,
        trim_data_to_registered_pings: false,
        log_level: None,
        rate_limit: None,
        enable_event_timestamps: true,
        experimentation_id: Some("test-experimentation-id".to_string()),
        enable_internal_pings: true,
        ping_schedule: Default::default(),
        ping_lifetime_threshold: 0,
        ping_lifetime_max_time: 0,
    })
    .unwrap();
    let ping_maker = PingMaker::new();
    let ping_type = PingBuilder::new("store1").build();
    glean.register_ping_type(&ping_type);

    // Record something, so the ping will have data
    let metric = BooleanMetric::new(CommonMetricData {
        name: "boolean_metric".into(),
        category: "telemetry".into(),
        send_in_pings: vec!["store1".into()],
        disabled: false,
        lifetime: Lifetime::User,
        ..Default::default()
    });
    metric.set_sync(&glean, true);

    let ping = ping_maker
        .collect(&glean, &ping_type, None, "", "")
        .unwrap();
    let metrics = ping.content["metrics"].as_object().unwrap();

    let strings = metrics["string"].as_object().unwrap();
    assert_eq!(
        strings["glean.client.annotation.experimentation_id"]
            .as_str()
            .unwrap(),
        "test-experimentation-id",
        "experimentation ids must match"
    );
}

#[test]
fn experimentation_id_is_removed_if_send_if_empty_is_false() {
    // Initialize Glean with an experimentation id, it should be removed if the ping is empty
    // and send_if_empty is false.
    let (tempdir, _) = tempdir();
    let mut glean = Glean::new(glean_core::InternalConfiguration {
        data_path: tempdir.path().display().to_string(),
        application_id: GLOBAL_APPLICATION_ID.into(),
        language_binding_name: "Rust".into(),
        upload_enabled: true,
        max_events: None,
        delay_ping_lifetime_io: false,
        app_build: "Unknown".into(),
        use_core_mps: false,
        trim_data_to_registered_pings: false,
        log_level: None,
        rate_limit: None,
        enable_event_timestamps: true,
        experimentation_id: Some("test-experimentation-id".to_string()),
        enable_internal_pings: true,
        ping_schedule: Default::default(),
        ping_lifetime_threshold: 0,
        ping_lifetime_max_time: 0,
    })
    .unwrap();
    let ping_maker = PingMaker::new();

    let unknown_ping_type = PingBuilder::new("unknown").build();
    glean.register_ping_type(&unknown_ping_type);

    assert!(ping_maker
        .collect(&glean, &unknown_ping_type, None, "", "")
        .is_none());
}

#[test]
fn collect_must_report_none_when_no_data_is_stored() {
    // NOTE: This is a behavior change from glean-ac which returned an empty
    // string in this case. As this is an implementation detail and not part of
    // the public API, it's safe to change this.

    let (mut glean, ping_maker, ping_type, _t) = set_up_basic_ping();

    let unknown_ping_type = PingBuilder::new("unknown").build();
    glean.register_ping_type(&ping_type);

    assert!(ping_maker
        .collect(&glean, &unknown_ping_type, None, "", "")
        .is_none());
}

#[test]
fn seq_number_must_be_sequential() {
    let (mut glean, ping_maker, _ping_type, _t) = set_up_basic_ping();

    let metric = BooleanMetric::new(CommonMetricData {
        name: "boolean_metric".into(),
        category: "telemetry".into(),
        send_in_pings: vec!["store2".into()],
        disabled: false,
        lifetime: Lifetime::User,
        ..Default::default()
    });
    metric.set_sync(&glean, true);

    for i in 0..=1 {
        for ping_name in ["store1", "store2"].iter() {
            let ping_type = PingBuilder::new(ping_name).build();
            let ping = ping_maker
                .collect(&glean, &ping_type, None, "", "")
                .unwrap();
            let seq_num = ping.content["ping_info"]["seq"].as_i64().unwrap();
            // Ensure sequence numbers in different stores are independent of
            // each other
            assert_eq!(i, seq_num);
        }
    }

    // Test that ping sequence numbers increase independently.
    {
        let ping_type = new_test_ping(&mut glean, "store1");

        // 3rd ping of store1
        let ping = ping_maker
            .collect(&glean, &ping_type, None, "", "")
            .unwrap();
        let seq_num = ping.content["ping_info"]["seq"].as_i64().unwrap();
        assert_eq!(2, seq_num);

        // 4th ping of store1
        let ping = ping_maker
            .collect(&glean, &ping_type, None, "", "")
            .unwrap();
        let seq_num = ping.content["ping_info"]["seq"].as_i64().unwrap();
        assert_eq!(3, seq_num);
    }

    {
        let ping_type = new_test_ping(&mut glean, "store2");

        // 3rd ping of store2
        let ping = ping_maker
            .collect(&glean, &ping_type, None, "", "")
            .unwrap();
        let seq_num = ping.content["ping_info"]["seq"].as_i64().unwrap();
        assert_eq!(2, seq_num);
    }

    {
        let ping_type = new_test_ping(&mut glean, "store1");

        // 5th ping of store1
        let ping = ping_maker
            .collect(&glean, &ping_type, None, "", "")
            .unwrap();
        let seq_num = ping.content["ping_info"]["seq"].as_i64().unwrap();
        assert_eq!(4, seq_num);
    }
}

#[test]
fn clear_pending_pings() {
    let (mut glean, _t) = new_glean(None);
    let ping_maker = PingMaker::new();
    let ping_type = new_test_ping(&mut glean, "store1");

    // Record something, so the ping will have data
    let metric = BooleanMetric::new(CommonMetricData {
        name: "boolean_metric".into(),
        category: "telemetry".into(),
        send_in_pings: vec!["store1".into()],
        disabled: false,
        lifetime: Lifetime::User,
        ..Default::default()
    });
    metric.set_sync(&glean, true);

    assert!(ping_type.submit_sync(&glean, None));
    assert_eq!(1, get_queued_pings(glean.get_data_path()).unwrap().len());

    let disabled_pings = &["store1"][..];
    assert!(ping_maker
        .clear_pending_pings(glean.get_data_path(), disabled_pings)
        .is_ok());
    assert_eq!(0, get_queued_pings(glean.get_data_path()).unwrap().len());
}

#[test]
fn no_pings_submitted_if_upload_disabled() {
    // Regression test, bug 1603571

    let (mut glean, _t) = new_glean(None);
    let ping_type = PingBuilder::new("store1").with_send_if_empty(true).build();
    glean.register_ping_type(&ping_type);

    assert!(ping_type.submit_sync(&glean, None));
    assert_eq!(1, get_queued_pings(glean.get_data_path()).unwrap().len());

    // Disable upload, then try to sumbit
    glean.set_upload_enabled(false);

    // Test again through the direct call
    assert!(!ping_type.submit_sync(&glean, None));
    assert_eq!(0, get_queued_pings(glean.get_data_path()).unwrap().len());
}

#[test]
fn metadata_is_correctly_added_when_necessary() {
    let (mut glean, _t) = new_glean(None);
    glean.set_debug_view_tag("valid-tag");
    let ping_type = PingBuilder::new("store1").with_send_if_empty(true).build();
    glean.register_ping_type(&ping_type);

    assert!(ping_type.submit_sync(&glean, None));

    let (_, _, metadata) = &get_queued_pings(glean.get_data_path()).unwrap()[0];
    let headers = metadata.as_ref().unwrap().get("headers").unwrap();
    assert_eq!(headers.get("X-Debug-ID").unwrap(), "valid-tag");
}

#[test]
fn attribution_and_distribution_appear_in_client_info() {
    let (glean, ping_maker, ping_type, _t) = set_up_basic_ping();

    let attribution = AttributionMetrics {
        source: Some("source".into()),
        medium: Some("medium".into()),
        campaign: Some("campaign".into()),
        term: Some("term".into()),
        content: Some("content".into()),
    };
    let distribution = DistributionMetrics {
        name: Some("name".into()),
    };
    glean.update_attribution(attribution);
    glean.update_distribution(distribution);

    let ping = ping_maker
        .collect(&glean, &ping_type, None, "", "")
        .unwrap();
    let client_info = ping.content["client_info"].as_object().unwrap();

    assert_eq!(json!({"name": "name"}), client_info["distribution"]);
    assert_eq!(
        json!({
            "source": "source",
            "medium": "medium",
            "campaign": "campaign",
            "term": "term",
            "content": "content",
        }),
        client_info["attribution"]
    );

    // Now let's test updated values.
    let attribution_update = AttributionMetrics {
        content: Some("what a boring word".into()),
        ..Default::default()
    };
    let distribution_update = DistributionMetrics {
        name: Some("what's in a name".into()),
    };
    glean.update_attribution(attribution_update);
    glean.update_distribution(distribution_update);

    let ping = ping_maker
        .collect(&glean, &ping_type, None, "", "")
        .unwrap();
    let client_info = ping.content["client_info"].as_object().unwrap();

    assert_eq!(
        json!({"name": "what's in a name"}),
        client_info["distribution"]
    );
    assert_eq!(
        json!({
            "source": "source",
            "medium": "medium",
            "campaign": "campaign",
            "term": "term",
            "content": "what a boring word",
        }),
        client_info["attribution"]
    );
}