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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
#![allow(clippy::significant_drop_in_scrutinee)]
#![allow(clippy::uninlined_format_args)]
#![deny(rustdoc::broken_intra_doc_links)]
#![deny(missing_docs)]
use std::borrow::Cow;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use crossbeam_channel::unbounded;
use once_cell::sync::{Lazy, OnceCell};
use uuid::Uuid;
use metrics::MetricsDisabledConfig;
mod common_metric_data;
mod core;
mod core_metrics;
mod coverage;
mod database;
mod debug;
mod dispatcher;
mod error;
mod error_recording;
mod event_database;
mod glean_metrics;
mod histogram;
mod internal_metrics;
mod internal_pings;
pub mod metrics;
pub mod ping;
mod scheduler;
pub mod storage;
mod system;
pub mod traits;
pub mod upload;
mod util;
#[cfg(all(not(target_os = "android"), not(target_os = "ios")))]
mod fd_logger;
pub use crate::common_metric_data::{CommonMetricData, Lifetime};
pub use crate::core::Glean;
pub use crate::core_metrics::ClientInfoMetrics;
pub use crate::error::{Error, ErrorKind, Result};
pub use crate::error_recording::{test_get_num_recorded_errors, ErrorType};
pub use crate::histogram::HistogramType;
pub use crate::metrics::labeled::{
AllowLabeled, LabeledBoolean, LabeledCounter, LabeledMetric, LabeledString,
};
pub use crate::metrics::{
BooleanMetric, CounterMetric, CustomDistributionMetric, Datetime, DatetimeMetric,
DenominatorMetric, DistributionData, EventMetric, MemoryDistributionMetric, MemoryUnit,
NumeratorMetric, PingType, QuantityMetric, Rate, RateMetric, RecordedEvent, RecordedExperiment,
StringListMetric, StringMetric, TextMetric, TimeUnit, TimerId, TimespanMetric,
TimingDistributionMetric, UrlMetric, UuidMetric,
};
pub use crate::upload::{PingRequest, PingUploadTask, UploadResult, UploadTaskAction};
const GLEAN_VERSION: &str = env!("CARGO_PKG_VERSION");
const GLEAN_SCHEMA_VERSION: u32 = 1;
const DEFAULT_MAX_EVENTS: u32 = 500;
static KNOWN_CLIENT_ID: Lazy<Uuid> =
Lazy::new(|| Uuid::parse_str("c0ffeec0-ffee-c0ff-eec0-ffeec0ffeec0").unwrap());
pub(crate) const PENDING_PINGS_DIRECTORY: &str = "pending_pings";
pub(crate) const DELETION_REQUEST_PINGS_DIRECTORY: &str = "deletion_request";
static INITIALIZE_CALLED: AtomicBool = AtomicBool::new(false);
static PRE_INIT_DEBUG_VIEW_TAG: OnceCell<Mutex<String>> = OnceCell::new();
static PRE_INIT_LOG_PINGS: AtomicBool = AtomicBool::new(false);
static PRE_INIT_SOURCE_TAGS: OnceCell<Mutex<Vec<String>>> = OnceCell::new();
static PRE_INIT_PING_REGISTRATION: OnceCell<Mutex<Vec<metrics::PingType>>> = OnceCell::new();
static INIT_HANDLES: Lazy<Arc<Mutex<Vec<std::thread::JoinHandle<()>>>>> =
Lazy::new(|| Arc::new(Mutex::new(Vec::new())));
#[derive(Debug, Clone)]
pub struct InternalConfiguration {
pub upload_enabled: bool,
pub data_path: String,
pub application_id: String,
pub language_binding_name: String,
pub max_events: Option<u32>,
pub delay_ping_lifetime_io: bool,
pub app_build: String,
pub use_core_mps: bool,
pub trim_data_to_registered_pings: bool,
}
fn launch_with_glean(callback: impl FnOnce(&Glean) + Send + 'static) {
dispatcher::launch(|| core::with_glean(callback));
}
fn launch_with_glean_mut(callback: impl FnOnce(&mut Glean) + Send + 'static) {
dispatcher::launch(|| core::with_glean_mut(callback));
}
fn block_on_dispatcher() {
dispatcher::block_on_queue()
}
pub fn get_timestamp_ms() -> u64 {
const NANOS_PER_MILLI: u64 = 1_000_000;
zeitstempel::now() / NANOS_PER_MILLI
}
struct State {
client_info: ClientInfoMetrics,
callbacks: Box<dyn OnGleanEvents>,
}
static STATE: OnceCell<Mutex<State>> = OnceCell::new();
fn global_state() -> &'static Mutex<State> {
STATE.get().unwrap()
}
fn setup_state(state: State) {
if STATE.get().is_none() {
if STATE.set(Mutex::new(state)).is_err() {
log::error!(
"Global Glean state object is initialized already. This probably happened concurrently."
);
}
} else {
let mut lock = STATE.get().unwrap().lock().unwrap();
*lock = state;
}
}
#[derive(Debug)]
pub enum CallbackError {
UnexpectedError,
}
impl fmt::Display for CallbackError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Unexpected error")
}
}
impl From<uniffi::UnexpectedUniFFICallbackError> for CallbackError {
fn from(_: uniffi::UnexpectedUniFFICallbackError) -> CallbackError {
CallbackError::UnexpectedError
}
}
pub trait OnGleanEvents: Send {
fn initialize_finished(&self);
fn trigger_upload(&self) -> Result<(), CallbackError>;
fn start_metrics_ping_scheduler(&self) -> bool;
fn cancel_uploads(&self) -> Result<(), CallbackError>;
fn shutdown(&self) -> Result<(), CallbackError> {
Ok(())
}
}
pub fn glean_initialize(
cfg: InternalConfiguration,
client_info: ClientInfoMetrics,
callbacks: Box<dyn OnGleanEvents>,
) {
initialize_inner(cfg, client_info, callbacks);
}
pub fn glean_initialize_for_subprocess(cfg: InternalConfiguration) -> bool {
let glean = match Glean::new_for_subprocess(&cfg, true) {
Ok(glean) => glean,
Err(err) => {
log::error!("Failed to initialize Glean: {}", err);
return false;
}
};
if core::setup_glean(glean).is_err() {
return false;
}
log::info!("Glean initialized for subprocess");
true
}
fn initialize_inner(
cfg: InternalConfiguration,
client_info: ClientInfoMetrics,
callbacks: Box<dyn OnGleanEvents>,
) {
if was_initialize_called() {
log::error!("Glean should not be initialized multiple times");
return;
}
let init_handle = std::thread::Builder::new()
.name("glean.init".into())
.spawn(move || {
let upload_enabled = cfg.upload_enabled;
let trim_data_to_registered_pings = cfg.trim_data_to_registered_pings;
let glean = match Glean::new(cfg) {
Ok(glean) => glean,
Err(err) => {
log::error!("Failed to initialize Glean: {}", err);
return;
}
};
if core::setup_glean(glean).is_err() {
return;
}
log::info!("Glean initialized");
setup_state(State {
client_info,
callbacks,
});
let mut is_first_run = false;
let mut dirty_flag = false;
let mut pings_submitted = false;
core::with_glean_mut(|glean| {
if let Some(tag) = PRE_INIT_DEBUG_VIEW_TAG.get() {
let lock = tag.try_lock();
if let Ok(ref debug_tag) = lock {
glean.set_debug_view_tag(debug_tag);
}
}
let log_pigs = PRE_INIT_LOG_PINGS.load(Ordering::SeqCst);
if log_pigs {
glean.set_log_pings(log_pigs);
}
if let Some(tags) = PRE_INIT_SOURCE_TAGS.get() {
let lock = tags.try_lock();
if let Ok(ref source_tags) = lock {
glean.set_source_tags(source_tags.to_vec());
}
}
dirty_flag = glean.is_dirty_flag_set();
glean.set_dirty_flag(false);
if let Some(tags) = PRE_INIT_PING_REGISTRATION.get() {
let lock = tags.try_lock();
if let Ok(pings) = lock {
for ping in &*pings {
glean.register_ping_type(ping);
}
}
}
is_first_run = glean.is_first_run();
if is_first_run {
let state = global_state().lock().unwrap();
initialize_core_metrics(glean, &state.client_info);
}
pings_submitted = glean.on_ready_to_submit_pings(trim_data_to_registered_pings);
});
{
let state = global_state().lock().unwrap();
if pings_submitted || !upload_enabled {
if let Err(e) = state.callbacks.trigger_upload() {
log::error!("Triggering upload failed. Error: {}", e);
}
}
}
core::with_glean(|glean| {
glean.start_metrics_ping_scheduler();
});
{
let state = global_state().lock().unwrap();
if state.callbacks.start_metrics_ping_scheduler() {
if let Err(e) = state.callbacks.trigger_upload() {
log::error!("Triggering upload failed. Error: {}", e);
}
}
}
core::with_glean_mut(|glean| {
let state = global_state().lock().unwrap();
if !is_first_run && dirty_flag {
if glean.submit_ping_by_name("baseline", Some("dirty_startup")) {
if let Err(e) = state.callbacks.trigger_upload() {
log::error!("Triggering upload failed. Error: {}", e);
}
}
}
if !is_first_run {
glean.clear_application_lifetime_metrics();
initialize_core_metrics(glean, &state.client_info);
}
});
match dispatcher::flush_init() {
Ok(task_count) if task_count > 0 => {
core::with_glean(|glean| {
glean_metrics::error::preinit_tasks_overflow
.add_sync(glean, task_count as i32);
});
}
Ok(_) => {}
Err(err) => log::error!("Unable to flush the preinit queue: {}", err),
}
let state = global_state().lock().unwrap();
state.callbacks.initialize_finished();
})
.expect("Failed to spawn Glean's init thread");
INIT_HANDLES.lock().unwrap().push(init_handle);
INITIALIZE_CALLED.store(true, Ordering::SeqCst);
if dispatcher::global::is_test_mode() {
join_init();
}
}
pub fn join_init() {
let mut handles = INIT_HANDLES.lock().unwrap();
for handle in handles.drain(..) {
handle.join().unwrap();
}
}
fn uploader_shutdown() {
let timer_id = core::with_glean(|glean| glean.additional_metrics.shutdown_wait.start_sync());
let (tx, rx) = unbounded();
let handle = thread::Builder::new()
.name("glean.shutdown".to_string())
.spawn(move || {
let state = global_state().lock().unwrap();
if let Err(e) = state.callbacks.shutdown() {
log::error!("Shutdown callback failed: {e:?}");
}
let _ = tx.send(()).ok();
})
.expect("Unable to spawn thread to wait on shutdown");
let result = rx.recv_timeout(Duration::from_secs(30));
let stop_time = time::precise_time_ns();
core::with_glean(|glean| {
glean
.additional_metrics
.shutdown_wait
.set_stop_and_accumulate(glean, timer_id, stop_time);
});
if result.is_err() {
log::warn!("Waiting for upload failed. We're shutting down.");
} else {
let _ = handle.join().ok();
}
}
pub fn shutdown() {
if !was_initialize_called() || core::global_glean().is_none() {
log::warn!("Shutdown called before Glean is initialized");
if let Err(e) = dispatcher::kill() {
log::error!("Can't kill dispatcher thread: {:?}", e);
}
return;
}
crate::launch_with_glean_mut(|glean| {
glean.cancel_metrics_ping_scheduler();
glean.set_dirty_flag(false);
});
dispatcher::block_on_queue();
if let Err(e) = dispatcher::shutdown() {
log::error!("Can't shutdown dispatcher thread: {:?}", e);
}
uploader_shutdown();
core::with_glean(|glean| {
if let Err(e) = glean.persist_ping_lifetime_data() {
log::error!("Can't persist ping lifetime data: {:?}", e);
}
});
}
pub fn persist_ping_lifetime_data() {
crate::launch_with_glean(|glean| {
let _ = glean.persist_ping_lifetime_data();
});
}
fn initialize_core_metrics(glean: &Glean, client_info: &ClientInfoMetrics) {
core_metrics::internal_metrics::app_build.set_sync(glean, &client_info.app_build[..]);
core_metrics::internal_metrics::app_display_version
.set_sync(glean, &client_info.app_display_version[..]);
core_metrics::internal_metrics::app_build_date
.set_sync(glean, Some(client_info.app_build_date.clone()));
if let Some(app_channel) = client_info.channel.as_ref() {
core_metrics::internal_metrics::app_channel.set_sync(glean, app_channel);
}
core_metrics::internal_metrics::os_version.set_sync(glean, &client_info.os_version);
core_metrics::internal_metrics::architecture.set_sync(glean, &client_info.architecture);
if let Some(android_sdk_version) = client_info.android_sdk_version.as_ref() {
core_metrics::internal_metrics::android_sdk_version.set_sync(glean, android_sdk_version);
}
if let Some(windows_build_number) = client_info.windows_build_number.as_ref() {
core_metrics::internal_metrics::windows_build_number.set_sync(glean, *windows_build_number);
}
if let Some(device_manufacturer) = client_info.device_manufacturer.as_ref() {
core_metrics::internal_metrics::device_manufacturer.set_sync(glean, device_manufacturer);
}
if let Some(device_model) = client_info.device_model.as_ref() {
core_metrics::internal_metrics::device_model.set_sync(glean, device_model);
}
if let Some(locale) = client_info.locale.as_ref() {
core_metrics::internal_metrics::locale.set_sync(glean, locale);
}
}
fn was_initialize_called() -> bool {
INITIALIZE_CALLED.load(Ordering::SeqCst)
}
#[no_mangle]
pub extern "C" fn glean_enable_logging() {
#[cfg(target_os = "android")]
{
let _ = std::panic::catch_unwind(|| {
let filter = android_logger::FilterBuilder::new()
.filter_module("glean_ffi", log::LevelFilter::Debug)
.filter_module("glean_core", log::LevelFilter::Debug)
.filter_module("glean", log::LevelFilter::Debug)
.filter_module("glean_core::ffi", log::LevelFilter::Info)
.build();
android_logger::init_once(
android_logger::Config::default()
.with_max_level(log::LevelFilter::Debug)
.with_filter(filter)
.with_tag("libglean_ffi"),
);
log::trace!("Android logging should be hooked up!")
});
}
#[cfg(target_os = "ios")]
{
#[cfg(debug_assertions)]
let level = log::LevelFilter::Debug;
#[cfg(not(debug_assertions))]
let level = log::LevelFilter::Info;
let logger = oslog::OsLogger::new("org.mozilla.glean")
.level_filter(level)
.category_level_filter("glean_core::ffi", log::LevelFilter::Info);
match logger.init() {
Ok(_) => log::trace!("os_log should be hooked up!"),
Err(_) => log::warn!("os_log was already initialized"),
};
}
#[cfg(all(
not(target_os = "android"),
not(target_os = "ios"),
feature = "enable_env_logger"
))]
{
match env_logger::try_init() {
Ok(_) => log::trace!("stdout logging should be hooked up!"),
Err(_) => log::warn!("stdout logging was already initialized"),
};
}
}
pub fn glean_set_upload_enabled(enabled: bool) {
if !was_initialize_called() {
return;
}
crate::launch_with_glean_mut(move |glean| {
let state = global_state().lock().unwrap();
let original_enabled = glean.is_upload_enabled();
if !enabled {
glean.cancel_metrics_ping_scheduler();
if let Err(e) = state.callbacks.cancel_uploads() {
log::error!("Canceling upload failed. Error: {}", e);
}
}
glean.set_upload_enabled(enabled);
if !original_enabled && enabled {
initialize_core_metrics(glean, &state.client_info);
}
if original_enabled && !enabled {
if let Err(e) = state.callbacks.trigger_upload() {
log::error!("Triggering upload failed. Error: {}", e);
}
}
})
}
pub(crate) fn register_ping_type(ping: &PingType) {
if was_initialize_called() {
let ping = ping.clone();
crate::launch_with_glean_mut(move |glean| {
glean.register_ping_type(&ping);
})
} else {
let m = PRE_INIT_PING_REGISTRATION.get_or_init(Default::default);
let mut lock = m.lock().unwrap();
lock.push(ping.clone());
}
}
pub fn glean_set_experiment_active(
experiment_id: String,
branch: String,
extra: HashMap<String, String>,
) {
launch_with_glean(|glean| glean.set_experiment_active(experiment_id, branch, extra))
}
pub fn glean_set_experiment_inactive(experiment_id: String) {
launch_with_glean(|glean| glean.set_experiment_inactive(experiment_id))
}
pub fn glean_test_get_experiment_data(experiment_id: String) -> Option<RecordedExperiment> {
block_on_dispatcher();
core::with_glean(|glean| glean.test_get_experiment_data(experiment_id.to_owned()))
}
pub fn glean_set_metrics_disabled_config(json: String) {
match MetricsDisabledConfig::try_from(json) {
Ok(cfg) => launch_with_glean(|glean| {
glean.set_metrics_disabled_config(cfg);
}),
Err(e) => {
log::error!("Error setting metrics feature config: {:?}", e);
}
}
}
pub fn glean_set_debug_view_tag(tag: String) -> bool {
if was_initialize_called() {
crate::launch_with_glean_mut(move |glean| {
glean.set_debug_view_tag(&tag);
});
true
} else {
let m = PRE_INIT_DEBUG_VIEW_TAG.get_or_init(Default::default);
let mut lock = m.lock().unwrap();
*lock = tag;
true
}
}
pub fn glean_set_source_tags(tags: Vec<String>) -> bool {
if was_initialize_called() {
crate::launch_with_glean_mut(|glean| {
glean.set_source_tags(tags);
});
true
} else {
let m = PRE_INIT_SOURCE_TAGS.get_or_init(Default::default);
let mut lock = m.lock().unwrap();
*lock = tags;
true
}
}
pub fn glean_set_log_pings(value: bool) {
if was_initialize_called() {
crate::launch_with_glean_mut(move |glean| {
glean.set_log_pings(value);
});
} else {
PRE_INIT_LOG_PINGS.store(value, Ordering::SeqCst);
}
}
pub fn glean_handle_client_active() {
dispatcher::launch(|| {
core::with_glean_mut(|glean| {
glean.handle_client_active();
});
let state = global_state().lock().unwrap();
if let Err(e) = state.callbacks.trigger_upload() {
log::error!("Triggering upload failed. Error: {}", e);
}
});
core_metrics::internal_metrics::baseline_duration.start();
}
pub fn glean_handle_client_inactive() {
core_metrics::internal_metrics::baseline_duration.stop();
dispatcher::launch(|| {
core::with_glean_mut(|glean| {
glean.handle_client_inactive();
});
let state = global_state().lock().unwrap();
if let Err(e) = state.callbacks.trigger_upload() {
log::error!("Triggering upload failed. Error: {}", e);
}
})
}
pub fn glean_submit_ping_by_name(ping_name: String, reason: Option<String>) {
dispatcher::launch(|| {
let sent =
core::with_glean(move |glean| glean.submit_ping_by_name(&ping_name, reason.as_deref()));
if sent {
let state = global_state().lock().unwrap();
if let Err(e) = state.callbacks.trigger_upload() {
log::error!("Triggering upload failed. Error: {}", e);
}
}
})
}
pub fn glean_submit_ping_by_name_sync(ping_name: String, reason: Option<String>) -> bool {
if !was_initialize_called() {
return false;
}
core::with_glean(|glean| glean.submit_ping_by_name(&ping_name, reason.as_deref()))
}
pub fn glean_set_test_mode(enabled: bool) {
dispatcher::global::TESTING_MODE.store(enabled, Ordering::SeqCst);
}
pub fn glean_test_destroy_glean(clear_stores: bool, data_path: Option<String>) {
if was_initialize_called() {
join_init();
dispatcher::reset_dispatcher();
let has_storage =
core::with_opt_glean(|glean| glean.storage_opt().is_some()).unwrap_or(false);
if has_storage {
uploader_shutdown();
}
if core::global_glean().is_some() {
core::with_glean_mut(|glean| {
if clear_stores {
glean.test_clear_all_stores()
}
glean.destroy_db()
});
}
INITIALIZE_CALLED.store(false, Ordering::SeqCst);
} else if clear_stores {
if let Some(data_path) = data_path {
let _ = remove_dir_all::remove_dir_all(data_path).ok();
} else {
log::warn!("Asked to clear stores before initialization, but no data path given.");
}
}
}
pub fn glean_get_upload_task() -> PingUploadTask {
core::with_opt_glean(|glean| glean.get_upload_task()).unwrap_or_else(PingUploadTask::done)
}
pub fn glean_process_ping_upload_response(uuid: String, result: UploadResult) -> UploadTaskAction {
core::with_glean(|glean| glean.process_ping_upload_response(&uuid, result))
}
pub fn glean_set_dirty_flag(new_value: bool) {
core::with_glean(|glean| glean.set_dirty_flag(new_value))
}
#[cfg(all(not(target_os = "android"), not(target_os = "ios")))]
static FD_LOGGER: OnceCell<fd_logger::FdLogger> = OnceCell::new();
#[cfg(all(not(target_os = "android"), not(target_os = "ios")))]
pub fn glean_enable_logging_to_fd(fd: u64) {
unsafe {
let logger = FD_LOGGER.get_or_init(|| fd_logger::FdLogger::new(fd));
if log::set_logger(logger).is_ok() {
log::set_max_level(log::LevelFilter::Debug);
}
}
}
#[cfg(any(target_os = "android", target_os = "ios"))]
pub fn glean_enable_logging_to_fd(_fd: u64) {
}
#[allow(missing_docs)]
mod ffi {
use super::*;
uniffi::include_scaffolding!("glean");
type CowString = Cow<'static, str>;
impl UniffiCustomTypeConverter for CowString {
type Builtin = String;
fn into_custom(val: Self::Builtin) -> uniffi::Result<Self> {
Ok(Cow::from(val))
}
fn from_custom(obj: Self) -> Self::Builtin {
obj.into_owned()
}
}
}
pub use ffi::*;
#[cfg(test)]
#[path = "lib_unit_tests.rs"]
mod tests;