glean_core/
lib.rs

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#![allow(clippy::doc_overindented_list_items)]
6#![allow(clippy::significant_drop_in_scrutinee)]
7#![allow(clippy::uninlined_format_args)]
8#![deny(rustdoc::broken_intra_doc_links)]
9#![deny(missing_docs)]
10
11//! Glean is a modern approach for recording and sending Telemetry data.
12//!
13//! It's in use at Mozilla.
14//!
15//! All documentation can be found online:
16//!
17//! ## [The Glean SDK Book](https://mozilla.github.io/glean)
18
19use std::borrow::Cow;
20use std::collections::HashMap;
21use std::path::Path;
22use std::sync::atomic::{AtomicBool, Ordering};
23use std::sync::{Arc, Mutex};
24use std::time::{Duration, UNIX_EPOCH};
25use std::{fmt, fs};
26
27use crossbeam_channel::unbounded;
28use log::LevelFilter;
29use malloc_size_of_derive::MallocSizeOf;
30use once_cell::sync::{Lazy, OnceCell};
31use uuid::Uuid;
32
33use metrics::RemoteSettingsConfig;
34
35mod common_metric_data;
36mod core;
37mod core_metrics;
38mod coverage;
39mod database;
40mod debug;
41mod dispatcher;
42mod error;
43mod error_recording;
44mod event_database;
45mod glean_metrics;
46mod histogram;
47mod internal_metrics;
48mod internal_pings;
49pub mod metrics;
50pub mod ping;
51mod scheduler;
52pub mod storage;
53mod system;
54#[doc(hidden)]
55pub mod thread;
56pub mod traits;
57pub mod upload;
58mod util;
59
60#[cfg(all(not(target_os = "android"), not(target_os = "ios")))]
61mod fd_logger;
62
63pub use crate::common_metric_data::{CommonMetricData, DynamicLabelType, Lifetime};
64pub use crate::core::Glean;
65pub use crate::core_metrics::{AttributionMetrics, ClientInfoMetrics, DistributionMetrics};
66use crate::dispatcher::is_test_mode;
67pub use crate::error::{Error, ErrorKind, Result};
68pub use crate::error_recording::{test_get_num_recorded_errors, ErrorType};
69pub use crate::histogram::HistogramType;
70use crate::internal_metrics::DataDirectoryInfoObject;
71pub use crate::metrics::labeled::{
72    AllowLabeled, LabeledBoolean, LabeledCounter, LabeledCustomDistribution,
73    LabeledMemoryDistribution, LabeledMetric, LabeledMetricData, LabeledQuantity, LabeledString,
74    LabeledTimingDistribution,
75};
76pub use crate::metrics::{
77    BooleanMetric, CounterMetric, CustomDistributionMetric, Datetime, DatetimeMetric,
78    DenominatorMetric, DistributionData, DualLabeledCounterMetric, EventMetric,
79    LocalCustomDistribution, LocalMemoryDistribution, LocalTimingDistribution,
80    MemoryDistributionMetric, MemoryUnit, NumeratorMetric, ObjectMetric, PingType, QuantityMetric,
81    Rate, RateMetric, RecordedEvent, RecordedExperiment, StringListMetric, StringMetric,
82    TestGetValue, TextMetric, TimeUnit, TimerId, TimespanMetric, TimingDistributionMetric,
83    UrlMetric, UuidMetric,
84};
85pub use crate::upload::{PingRequest, PingUploadTask, UploadResult, UploadTaskAction};
86
87const GLEAN_VERSION: &str = env!("CARGO_PKG_VERSION");
88const GLEAN_SCHEMA_VERSION: u32 = 1;
89const DEFAULT_MAX_EVENTS: u32 = 500;
90static KNOWN_CLIENT_ID: Lazy<Uuid> =
91    Lazy::new(|| Uuid::parse_str("c0ffeec0-ffee-c0ff-eec0-ffeec0ffeec0").unwrap());
92
93// The names of the pings directories.
94pub(crate) const PENDING_PINGS_DIRECTORY: &str = "pending_pings";
95pub(crate) const DELETION_REQUEST_PINGS_DIRECTORY: &str = "deletion_request";
96
97/// Set when `glean::initialize()` returns.
98/// This allows to detect calls that happen before `glean::initialize()` was called.
99/// Note: The initialization might still be in progress, as it runs in a separate thread.
100static INITIALIZE_CALLED: AtomicBool = AtomicBool::new(false);
101
102/// Keep track of the debug features before Glean is initialized.
103static PRE_INIT_DEBUG_VIEW_TAG: Mutex<String> = Mutex::new(String::new());
104static PRE_INIT_LOG_PINGS: AtomicBool = AtomicBool::new(false);
105static PRE_INIT_SOURCE_TAGS: Mutex<Vec<String>> = Mutex::new(Vec::new());
106
107/// Keep track of pings registered before Glean is initialized.
108static PRE_INIT_PING_REGISTRATION: Mutex<Vec<metrics::PingType>> = Mutex::new(Vec::new());
109static PRE_INIT_PING_ENABLED: Mutex<Vec<(metrics::PingType, bool)>> = Mutex::new(Vec::new());
110
111/// Keep track of attribution and distribution supplied before Glean is initialized.
112static PRE_INIT_ATTRIBUTION: Mutex<Option<AttributionMetrics>> = Mutex::new(None);
113static PRE_INIT_DISTRIBUTION: Mutex<Option<DistributionMetrics>> = Mutex::new(None);
114
115/// Global singleton of the handles of the glean.init threads.
116/// For joining. For tests.
117/// (Why a Vec? There might be more than one concurrent call to initialize.)
118static INIT_HANDLES: Lazy<Arc<Mutex<Vec<std::thread::JoinHandle<()>>>>> =
119    Lazy::new(|| Arc::new(Mutex::new(Vec::new())));
120
121/// Configuration for Glean
122#[derive(Debug, Clone, MallocSizeOf)]
123pub struct InternalConfiguration {
124    /// Whether upload should be enabled.
125    pub upload_enabled: bool,
126    /// Path to a directory to store all data in.
127    pub data_path: String,
128    /// The application ID (will be sanitized during initialization).
129    pub application_id: String,
130    /// The name of the programming language used by the binding creating this instance of Glean.
131    pub language_binding_name: String,
132    /// The maximum number of events to store before sending a ping containing events.
133    pub max_events: Option<u32>,
134    /// Whether Glean should delay persistence of data from metrics with ping lifetime.
135    pub delay_ping_lifetime_io: bool,
136    /// The application's build identifier. If this is different from the one provided for a previous init,
137    /// and use_core_mps is `true`, we will trigger a "metrics" ping.
138    pub app_build: String,
139    /// Whether Glean should schedule "metrics" pings.
140    pub use_core_mps: bool,
141    /// Whether Glean should, on init, trim its event storage to only the registered pings.
142    pub trim_data_to_registered_pings: bool,
143    /// The internal logging level.
144    /// ignore
145    #[ignore_malloc_size_of = "external non-allocating type"]
146    pub log_level: Option<LevelFilter>,
147    /// The rate at which pings may be uploaded before they are throttled.
148    pub rate_limit: Option<PingRateLimit>,
149    /// Whether to add a wallclock timestamp to all events.
150    pub enable_event_timestamps: bool,
151    /// An experimentation identifier derived by the application to be sent with all pings, it should
152    /// be noted that this has an underlying StringMetric and so should conform to the limitations that
153    /// StringMetric places on length, etc.
154    pub experimentation_id: Option<String>,
155    /// Whether to enable internal pings. Default: true
156    pub enable_internal_pings: bool,
157    /// A ping schedule map.
158    /// Maps a ping name to a list of pings to schedule along with it.
159    /// Only used if the ping's own ping schedule list is empty.
160    pub ping_schedule: HashMap<String, Vec<String>>,
161
162    /// Write count threshold when to auto-flush. `0` disables it.
163    pub ping_lifetime_threshold: u64,
164    /// After what time to auto-flush. 0 disables it.
165    pub ping_lifetime_max_time: u64,
166}
167
168/// How to specify the rate at which pings may be uploaded before they are throttled.
169#[derive(Debug, Clone, MallocSizeOf)]
170pub struct PingRateLimit {
171    /// Length of time in seconds of a ping uploading interval.
172    pub seconds_per_interval: u64,
173    /// Number of pings that may be uploaded in a ping uploading interval.
174    pub pings_per_interval: u32,
175}
176
177/// Launches a new task on the global dispatch queue with a reference to the Glean singleton.
178fn launch_with_glean(callback: impl FnOnce(&Glean) + Send + 'static) {
179    dispatcher::launch(|| core::with_glean(callback));
180}
181
182/// Launches a new task on the global dispatch queue with a mutable reference to the
183/// Glean singleton.
184fn launch_with_glean_mut(callback: impl FnOnce(&mut Glean) + Send + 'static) {
185    dispatcher::launch(|| core::with_glean_mut(callback));
186}
187
188/// Block on the dispatcher emptying.
189///
190/// This will panic if called before Glean is initialized.
191fn block_on_dispatcher() {
192    dispatcher::block_on_queue()
193}
194
195/// Returns a timestamp corresponding to "now" with millisecond precision, awake time only.
196pub fn get_awake_timestamp_ms() -> u64 {
197    const NANOS_PER_MILLI: u64 = 1_000_000;
198    zeitstempel::now_awake() / NANOS_PER_MILLI
199}
200
201/// Returns a timestamp corresponding to "now" with millisecond precision.
202pub fn get_timestamp_ms() -> u64 {
203    const NANOS_PER_MILLI: u64 = 1_000_000;
204    zeitstempel::now() / NANOS_PER_MILLI
205}
206
207/// State to keep track for the Rust Language bindings.
208///
209/// This is useful for setting Glean SDK-owned metrics when
210/// the state of the upload is toggled.
211struct State {
212    /// Client info metrics set by the application.
213    client_info: ClientInfoMetrics,
214
215    callbacks: Box<dyn OnGleanEvents>,
216}
217
218/// A global singleton storing additional state for Glean.
219///
220/// Requires a Mutex, because in tests we can actual reset this.
221static STATE: OnceCell<Mutex<State>> = OnceCell::new();
222
223/// Get a reference to the global state object.
224///
225/// Panics if no global state object was set.
226#[track_caller] // If this fails we're interested in the caller.
227fn global_state() -> &'static Mutex<State> {
228    STATE.get().unwrap()
229}
230
231/// Attempt to get a reference to the global state object.
232///
233/// If it hasn't been set yet, we return None.
234#[track_caller] // If this fails we're interested in the caller.
235fn maybe_global_state() -> Option<&'static Mutex<State>> {
236    STATE.get()
237}
238
239/// Set or replace the global bindings State object.
240fn setup_state(state: State) {
241    // The `OnceCell` type wrapping our state is thread-safe and can only be set once.
242    // Therefore even if our check for it being empty succeeds, setting it could fail if a
243    // concurrent thread is quicker in setting it.
244    // However this will not cause a bigger problem, as the second `set` operation will just fail.
245    // We can log it and move on.
246    //
247    // For all wrappers this is not a problem, as the State object is intialized exactly once on
248    // calling `initialize` on the global singleton and further operations check that it has been
249    // initialized.
250    if STATE.get().is_none() {
251        if STATE.set(Mutex::new(state)).is_err() {
252            log::error!(
253                "Global Glean state object is initialized already. This probably happened concurrently."
254            );
255        }
256    } else {
257        // We allow overriding the global State object to support test mode.
258        // In test mode the State object is fully destroyed and recreated.
259        // This all happens behind a mutex and is therefore also thread-safe.
260        let mut lock = STATE.get().unwrap().lock().unwrap();
261        *lock = state;
262    }
263}
264
265/// A global singleton that stores listener callbacks registered with Glean
266/// to receive event recording notifications.
267static EVENT_LISTENERS: OnceCell<Mutex<HashMap<String, Box<dyn GleanEventListener>>>> =
268    OnceCell::new();
269
270fn event_listeners() -> &'static Mutex<HashMap<String, Box<dyn GleanEventListener>>> {
271    EVENT_LISTENERS.get_or_init(|| Mutex::new(HashMap::new()))
272}
273
274fn register_event_listener(tag: String, listener: Box<dyn GleanEventListener>) {
275    let mut lock = event_listeners().lock().unwrap();
276    lock.insert(tag, listener);
277}
278
279fn unregister_event_listener(tag: String) {
280    let mut lock = event_listeners().lock().unwrap();
281    lock.remove(&tag);
282}
283
284/// An error returned from callbacks.
285#[derive(Debug)]
286pub enum CallbackError {
287    /// An unexpected error occured.
288    UnexpectedError,
289}
290
291impl fmt::Display for CallbackError {
292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293        write!(f, "Unexpected error")
294    }
295}
296
297impl std::error::Error for CallbackError {}
298
299impl From<uniffi::UnexpectedUniFFICallbackError> for CallbackError {
300    fn from(_: uniffi::UnexpectedUniFFICallbackError) -> CallbackError {
301        CallbackError::UnexpectedError
302    }
303}
304
305/// A callback object used to trigger actions on the foreign-language side.
306///
307/// A callback object is stored in glean-core for the entire lifetime of the application.
308pub trait OnGleanEvents: Send {
309    /// Initialization finished.
310    ///
311    /// The language SDK can do additional things from within the same initializer thread,
312    /// e.g. starting to observe application events for foreground/background behavior.
313    /// The observer then needs to call the respective client activity API.
314    fn initialize_finished(&self);
315
316    /// Trigger the uploader whenever a ping was submitted.
317    ///
318    /// This should not block.
319    /// The uploader needs to asynchronously poll Glean for new pings to upload.
320    fn trigger_upload(&self) -> Result<(), CallbackError>;
321
322    /// Start the Metrics Ping Scheduler.
323    fn start_metrics_ping_scheduler(&self) -> bool;
324
325    /// Called when upload is disabled and uploads should be stopped
326    fn cancel_uploads(&self) -> Result<(), CallbackError>;
327
328    /// Called on shutdown, before glean-core is fully shutdown.
329    ///
330    /// * This MUST NOT put any new tasks on the dispatcher.
331    ///   * New tasks will be ignored.
332    /// * This SHOULD NOT block arbitrarily long.
333    ///   * Shutdown waits for a maximum of 30 seconds.
334    fn shutdown(&self) -> Result<(), CallbackError> {
335        // empty by default
336        Ok(())
337    }
338}
339
340/// A callback handler that receives the base identifier of recorded events
341/// The identifier is in the format: `<category>.<name>`
342pub trait GleanEventListener: Send {
343    /// Called when an event is recorded, indicating the id of the event
344    fn on_event_recorded(&self, id: String);
345}
346
347/// Initializes Glean.
348///
349/// # Arguments
350///
351/// * `cfg` - the [`InternalConfiguration`] options to initialize with.
352/// * `client_info` - the [`ClientInfoMetrics`] values used to set Glean
353///   core metrics.
354/// * `callbacks` - A callback object, stored for the entire application lifetime.
355pub fn glean_initialize(
356    cfg: InternalConfiguration,
357    client_info: ClientInfoMetrics,
358    callbacks: Box<dyn OnGleanEvents>,
359) {
360    initialize_inner(cfg, client_info, callbacks);
361}
362
363/// Shuts down Glean in an orderly fashion.
364pub fn glean_shutdown() {
365    shutdown();
366}
367
368/// Creates and initializes a new Glean object for use in a subprocess.
369///
370/// Importantly, this will not send any pings at startup, since that
371/// sort of management should only happen in the main process.
372pub fn glean_initialize_for_subprocess(cfg: InternalConfiguration) -> bool {
373    let glean = match Glean::new_for_subprocess(&cfg, true) {
374        Ok(glean) => glean,
375        Err(err) => {
376            log::error!("Failed to initialize Glean: {}", err);
377            return false;
378        }
379    };
380    if core::setup_glean(glean).is_err() {
381        return false;
382    }
383    log::info!("Glean initialized for subprocess");
384    true
385}
386
387fn initialize_inner(
388    cfg: InternalConfiguration,
389    client_info: ClientInfoMetrics,
390    callbacks: Box<dyn OnGleanEvents>,
391) {
392    if was_initialize_called() {
393        log::error!("Glean should not be initialized multiple times");
394        return;
395    }
396
397    let init_handle = thread::spawn("glean.init", move || {
398        let upload_enabled = cfg.upload_enabled;
399        let trim_data_to_registered_pings = cfg.trim_data_to_registered_pings;
400
401        // Set the internal logging level.
402        if let Some(level) = cfg.log_level {
403            log::set_max_level(level)
404        }
405
406        let data_path_str = cfg.data_path.clone();
407        let data_path = Path::new(&data_path_str);
408        let internal_pings_enabled = cfg.enable_internal_pings;
409        let dir_info = if !is_test_mode() && internal_pings_enabled {
410            collect_directory_info(Path::new(&data_path))
411        } else {
412            None
413        };
414
415        let glean = match Glean::new(cfg) {
416            Ok(glean) => glean,
417            Err(err) => {
418                log::error!("Failed to initialize Glean: {}", err);
419                return;
420            }
421        };
422        if core::setup_glean(glean).is_err() {
423            return;
424        }
425
426        log::info!("Glean initialized");
427
428        core::with_glean(|glean| {
429            glean.health_metrics.init_count.add_sync(glean, 1);
430        });
431
432        setup_state(State {
433            client_info,
434            callbacks,
435        });
436
437        let mut is_first_run = false;
438        let mut dirty_flag = false;
439        let mut pings_submitted = false;
440        core::with_glean_mut(|glean| {
441            // The debug view tag might have been set before initialize,
442            // get the cached value and set it.
443            let debug_tag = PRE_INIT_DEBUG_VIEW_TAG.lock().unwrap();
444            if !debug_tag.is_empty() {
445                glean.set_debug_view_tag(&debug_tag);
446            }
447
448            // The log pings debug option might have been set before initialize,
449            // get the cached value and set it.
450            let log_pigs = PRE_INIT_LOG_PINGS.load(Ordering::SeqCst);
451            if log_pigs {
452                glean.set_log_pings(log_pigs);
453            }
454
455            // The source tags might have been set before initialize,
456            // get the cached value and set them.
457            let source_tags = PRE_INIT_SOURCE_TAGS.lock().unwrap();
458            if !source_tags.is_empty() {
459                glean.set_source_tags(source_tags.to_vec());
460            }
461
462            // Get the current value of the dirty flag so we know whether to
463            // send a dirty startup baseline ping below.  Immediately set it to
464            // `false` so that dirty startup pings won't be sent if Glean
465            // initialization does not complete successfully.
466            dirty_flag = glean.is_dirty_flag_set();
467            glean.set_dirty_flag(false);
468
469            // Perform registration of pings that were attempted to be
470            // registered before init.
471            let pings = PRE_INIT_PING_REGISTRATION.lock().unwrap();
472            for ping in pings.iter() {
473                glean.register_ping_type(ping);
474            }
475            let pings = PRE_INIT_PING_ENABLED.lock().unwrap();
476            for (ping, enabled) in pings.iter() {
477                glean.set_ping_enabled(ping, *enabled);
478            }
479
480            // The attribution and distribution might have been set before initialize,
481            // take the cached values and set them.
482            if let Some(attribution) = PRE_INIT_ATTRIBUTION.lock().unwrap().take() {
483                glean.update_attribution(attribution);
484            }
485            if let Some(distribution) = PRE_INIT_DISTRIBUTION.lock().unwrap().take() {
486                glean.update_distribution(distribution);
487            }
488
489            // If this is the first time ever the Glean SDK runs, make sure to set
490            // some initial core metrics in case we need to generate early pings.
491            // The next times we start, we would have them around already.
492            is_first_run = glean.is_first_run();
493            if is_first_run {
494                let state = global_state().lock().unwrap();
495                initialize_core_metrics(glean, &state.client_info);
496            }
497
498            // Deal with any pending events so we can start recording new ones
499            pings_submitted = glean.on_ready_to_submit_pings(trim_data_to_registered_pings);
500        });
501
502        {
503            let state = global_state().lock().unwrap();
504            // We need to kick off upload in these cases:
505            // 1. Pings were submitted through Glean and it is ready to upload those pings;
506            // 2. Upload is disabled, to upload a possible deletion-request ping.
507            if pings_submitted || !upload_enabled {
508                if let Err(e) = state.callbacks.trigger_upload() {
509                    log::error!("Triggering upload failed. Error: {}", e);
510                }
511            }
512        }
513
514        core::with_glean(|glean| {
515            // Start the MPS if its handled within Rust.
516            glean.start_metrics_ping_scheduler();
517        });
518
519        // The metrics ping scheduler might _synchronously_ submit a ping
520        // so that it runs before we clear application-lifetime metrics further below.
521        // For that it needs access to the `Glean` object.
522        // Thus we need to unlock that by leaving the context above,
523        // then re-lock it afterwards.
524        // That's safe because user-visible functions will be queued and thus not execute until
525        // we unblock later anyway.
526        {
527            let state = global_state().lock().unwrap();
528
529            // Set up information and scheduling for Glean owned pings. Ideally, the "metrics"
530            // ping startup check should be performed before any other ping, since it relies
531            // on being dispatched to the API context before any other metric.
532            if state.callbacks.start_metrics_ping_scheduler() {
533                if let Err(e) = state.callbacks.trigger_upload() {
534                    log::error!("Triggering upload failed. Error: {}", e);
535                }
536            }
537        }
538
539        core::with_glean_mut(|glean| {
540            let state = global_state().lock().unwrap();
541
542            // Check if the "dirty flag" is set. That means the product was probably
543            // force-closed. If that's the case, submit a 'baseline' ping with the
544            // reason "dirty_startup". We only do that from the second run.
545            if !is_first_run && dirty_flag {
546                // The `submit_ping_by_name_sync` function cannot be used, otherwise
547                // startup will cause a dead-lock, since that function requests a
548                // write lock on the `glean` object.
549                // Note that unwrapping below is safe: the function will return an
550                // `Ok` value for a known ping.
551                if glean.submit_ping_by_name("baseline", Some("dirty_startup")) {
552                    if let Err(e) = state.callbacks.trigger_upload() {
553                        log::error!("Triggering upload failed. Error: {}", e);
554                    }
555                }
556            }
557
558            // From the second time we run, after all startup pings are generated,
559            // make sure to clear `lifetime: application` metrics and set them again.
560            // Any new value will be sent in newly generated pings after startup.
561            if !is_first_run {
562                glean.clear_application_lifetime_metrics();
563                initialize_core_metrics(glean, &state.client_info);
564            }
565        });
566
567        // Signal Dispatcher that init is complete
568        // bug 1839433: It is important that this happens after any init tasks
569        // that shutdown() depends on. At time of writing that's only setting up
570        // the global Glean, but it is probably best to flush the preinit queue
571        // as late as possible in the glean.init thread.
572        match dispatcher::flush_init() {
573            Ok(task_count) if task_count > 0 => {
574                core::with_glean(|glean| {
575                    glean_metrics::error::preinit_tasks_overflow.add_sync(glean, task_count as i32);
576                });
577            }
578            Ok(_) => {}
579            Err(err) => log::error!("Unable to flush the preinit queue: {}", err),
580        }
581
582        if !is_test_mode() && internal_pings_enabled {
583            // Now that Glean is initialized, we can capture the directory info from the pre_init phase and send it in
584            // a health ping with reason "pre_init".
585            record_dir_info_and_submit_health_ping(dir_info, "pre_init");
586
587            // Now capture a post_init snapshot of the state of Glean's data directories after initialization to send
588            // in a health ping with reason "post_init".
589            record_dir_info_and_submit_health_ping(collect_directory_info(data_path), "post_init");
590        }
591        let state = global_state().lock().unwrap();
592        state.callbacks.initialize_finished();
593    })
594    .expect("Failed to spawn Glean's init thread");
595
596    // For test purposes, store the glean init thread's JoinHandle.
597    INIT_HANDLES.lock().unwrap().push(init_handle);
598
599    // Mark the initialization as called: this needs to happen outside of the
600    // dispatched block!
601    INITIALIZE_CALLED.store(true, Ordering::SeqCst);
602
603    // In test mode we wait for initialization to finish.
604    // This needs to run after we set `INITIALIZE_CALLED`, so it's similar to normal behavior.
605    if dispatcher::global::is_test_mode() {
606        join_init();
607    }
608}
609
610/// Return the heap usage of the `Glean` object and all descendant heap-allocated structures.
611///
612/// Value is in bytes.
613pub fn alloc_size(ops: &mut malloc_size_of::MallocSizeOfOps) -> usize {
614    use malloc_size_of::MallocSizeOf;
615    core::with_glean(|glean| glean.size_of(ops))
616}
617
618/// TEST ONLY FUNCTION
619/// Waits on all the glean.init threads' join handles.
620pub fn join_init() {
621    let mut handles = INIT_HANDLES.lock().unwrap();
622    for handle in handles.drain(..) {
623        handle.join().unwrap();
624    }
625}
626
627/// Call the `shutdown` callback.
628///
629/// This calls the shutdown in a separate thread and waits up to 30s for it to finish.
630/// If not finished in that time frame it continues.
631///
632/// Under normal operation that is fine, as the main process will end
633/// and thus the thread will get killed.
634fn uploader_shutdown() {
635    let timer_id = core::with_glean(|glean| glean.additional_metrics.shutdown_wait.start_sync());
636    let (tx, rx) = unbounded();
637
638    let handle = thread::spawn("glean.shutdown", move || {
639        let state = global_state().lock().unwrap();
640        if let Err(e) = state.callbacks.shutdown() {
641            log::error!("Shutdown callback failed: {e:?}");
642        }
643
644        // Best-effort sending. The other side might have timed out already.
645        let _ = tx.send(()).ok();
646    })
647    .expect("Unable to spawn thread to wait on shutdown");
648
649    // TODO: 30 seconds? What's a good default here? Should this be configurable?
650    // Reasoning:
651    //   * If we shut down early we might still be processing pending pings.
652    //     In this case we wait at most 3 times for 1s = 3s before we upload.
653    //   * If we're rate-limited the uploader sleeps for up to 60s.
654    //     Thus waiting 30s will rarely allow another upload.
655    //   * We don't know how long uploads take until we get data from bug 1814592.
656    let result = rx.recv_timeout(Duration::from_secs(30));
657
658    let stop_time = zeitstempel::now_awake();
659    core::with_glean(|glean| {
660        glean
661            .additional_metrics
662            .shutdown_wait
663            .set_stop_and_accumulate(glean, timer_id, stop_time);
664    });
665
666    if result.is_err() {
667        log::warn!("Waiting for upload failed. We're shutting down.");
668    } else {
669        let _ = handle.join().ok();
670    }
671}
672
673/// Shuts down Glean in an orderly fashion.
674pub fn shutdown() {
675    // Shutdown might have been called
676    // 1) Before init was called
677    //    * (data loss, oh well. Not enough time to do squat)
678    // 2) After init was called, but before it completed
679    //    * (we're willing to wait a little bit for init to complete)
680    // 3) After init completed
681    //    * (we can shut down immediately)
682
683    // Case 1: "Before init was called"
684    if !was_initialize_called() {
685        log::warn!("Shutdown called before Glean is initialized");
686        if let Err(e) = dispatcher::kill() {
687            log::error!("Can't kill dispatcher thread: {:?}", e);
688        }
689        return;
690    }
691
692    // Case 2: "After init was called, but before it completed"
693    if core::global_glean().is_none() {
694        log::warn!("Shutdown called before Glean is initialized. Waiting.");
695        // We can't join on the `glean.init` thread because there's no (easy) way
696        // to do that with a timeout. Instead, we wait for the preinit queue to
697        // empty, which is the last meaningful thing we do on that thread.
698
699        // TODO: Make the timeout configurable?
700        // We don't need the return value, as we're less interested in whether
701        // this times out than we are in whether there's a Global Glean at the end.
702        let _ = dispatcher::block_on_queue_timeout(Duration::from_secs(10));
703    }
704    // We can't shut down Glean if there's no Glean to shut down.
705    if core::global_glean().is_none() {
706        log::warn!("Waiting for Glean initialization timed out. Exiting.");
707        if let Err(e) = dispatcher::kill() {
708            log::error!("Can't kill dispatcher thread: {:?}", e);
709        }
710        return;
711    }
712
713    // Case 3: "After init completed"
714    crate::launch_with_glean_mut(|glean| {
715        glean.cancel_metrics_ping_scheduler();
716        glean.set_dirty_flag(false);
717    });
718
719    // We need to wait for above task to finish,
720    // but we also don't wait around forever.
721    //
722    // TODO: Make the timeout configurable?
723    // The default hang watchdog on Firefox waits 60s,
724    // Glean's `uploader_shutdown` further below waits up to 30s.
725    let timer_id = core::with_glean(|glean| {
726        glean
727            .additional_metrics
728            .shutdown_dispatcher_wait
729            .start_sync()
730    });
731    let blocked = dispatcher::block_on_queue_timeout(Duration::from_secs(10));
732
733    // Always record the dispatcher wait, regardless of the timeout.
734    let stop_time = zeitstempel::now_awake();
735    core::with_glean(|glean| {
736        glean
737            .additional_metrics
738            .shutdown_dispatcher_wait
739            .set_stop_and_accumulate(glean, timer_id, stop_time);
740    });
741    if blocked.is_err() {
742        log::error!(
743            "Timeout while blocking on the dispatcher. No further shutdown cleanup will happen."
744        );
745        return;
746    }
747
748    if let Err(e) = dispatcher::shutdown() {
749        log::error!("Can't shutdown dispatcher thread: {:?}", e);
750    }
751
752    uploader_shutdown();
753
754    // Be sure to call this _after_ draining the dispatcher
755    core::with_glean(|glean| {
756        if let Err(e) = glean.persist_ping_lifetime_data() {
757            log::info!("Can't persist ping lifetime data: {:?}", e);
758        }
759    });
760}
761
762/// Asks the database to persist ping-lifetime data to disk.
763///
764/// Probably expensive to call.
765/// Only has effect when Glean is configured with `delay_ping_lifetime_io: true`.
766/// If Glean hasn't been initialized this will dispatch and return Ok(()),
767/// otherwise it will block until the persist is done and return its Result.
768pub fn glean_persist_ping_lifetime_data() {
769    // This is async, we can't get the Error back to the caller.
770    crate::launch_with_glean(|glean| {
771        let _ = glean.persist_ping_lifetime_data();
772    });
773}
774
775fn initialize_core_metrics(glean: &Glean, client_info: &ClientInfoMetrics) {
776    core_metrics::internal_metrics::app_build.set_sync(glean, &client_info.app_build[..]);
777    core_metrics::internal_metrics::app_display_version
778        .set_sync(glean, &client_info.app_display_version[..]);
779    core_metrics::internal_metrics::app_build_date
780        .set_sync(glean, Some(client_info.app_build_date.clone()));
781    if let Some(app_channel) = client_info.channel.as_ref() {
782        core_metrics::internal_metrics::app_channel.set_sync(glean, app_channel);
783    }
784
785    core_metrics::internal_metrics::os_version.set_sync(glean, &client_info.os_version);
786    core_metrics::internal_metrics::architecture.set_sync(glean, &client_info.architecture);
787
788    if let Some(android_sdk_version) = client_info.android_sdk_version.as_ref() {
789        core_metrics::internal_metrics::android_sdk_version.set_sync(glean, android_sdk_version);
790    }
791    if let Some(windows_build_number) = client_info.windows_build_number.as_ref() {
792        core_metrics::internal_metrics::windows_build_number.set_sync(glean, *windows_build_number);
793    }
794    if let Some(device_manufacturer) = client_info.device_manufacturer.as_ref() {
795        core_metrics::internal_metrics::device_manufacturer.set_sync(glean, device_manufacturer);
796    }
797    if let Some(device_model) = client_info.device_model.as_ref() {
798        core_metrics::internal_metrics::device_model.set_sync(glean, device_model);
799    }
800    if let Some(locale) = client_info.locale.as_ref() {
801        core_metrics::internal_metrics::locale.set_sync(glean, locale);
802    }
803}
804
805/// Checks if [`initialize`] was ever called.
806///
807/// # Returns
808///
809/// `true` if it was, `false` otherwise.
810fn was_initialize_called() -> bool {
811    INITIALIZE_CALLED.load(Ordering::SeqCst)
812}
813
814/// Initialize the logging system based on the target platform. This ensures
815/// that logging is shown when executing the Glean SDK unit tests.
816#[no_mangle]
817pub extern "C" fn glean_enable_logging() {
818    #[cfg(target_os = "android")]
819    {
820        let _ = std::panic::catch_unwind(|| {
821            let filter = android_logger::FilterBuilder::new()
822                .filter_module("glean_ffi", log::LevelFilter::Debug)
823                .filter_module("glean_core", log::LevelFilter::Debug)
824                .filter_module("glean", log::LevelFilter::Debug)
825                .filter_module("glean_core::ffi", log::LevelFilter::Info)
826                .build();
827            android_logger::init_once(
828                android_logger::Config::default()
829                    .with_max_level(log::LevelFilter::Debug)
830                    .with_filter(filter)
831                    .with_tag("libglean_ffi"),
832            );
833            log::trace!("Android logging should be hooked up!")
834        });
835    }
836
837    // On iOS enable logging with a level filter.
838    #[cfg(target_os = "ios")]
839    {
840        // Debug logging in debug mode.
841        // (Note: `debug_assertions` is the next best thing to determine if this is a debug build)
842        #[cfg(debug_assertions)]
843        let level = log::LevelFilter::Debug;
844        #[cfg(not(debug_assertions))]
845        let level = log::LevelFilter::Info;
846
847        let logger = oslog::OsLogger::new("org.mozilla.glean")
848            .level_filter(level)
849            // Filter UniFFI log messages
850            .category_level_filter("glean_core::ffi", log::LevelFilter::Info);
851
852        match logger.init() {
853            Ok(_) => log::trace!("os_log should be hooked up!"),
854            // Please note that this is only expected to fail during unit tests,
855            // where the logger might have already been initialized by a previous
856            // test. So it's fine to print with the "logger".
857            Err(_) => log::warn!("os_log was already initialized"),
858        };
859    }
860
861    // When specifically requested make sure logging does something on non-Android platforms as well.
862    // Use the RUST_LOG environment variable to set the desired log level,
863    // e.g. setting RUST_LOG=debug sets the log level to debug.
864    #[cfg(all(
865        not(target_os = "android"),
866        not(target_os = "ios"),
867        feature = "enable_env_logger"
868    ))]
869    {
870        match env_logger::try_init() {
871            Ok(_) => log::trace!("stdout logging should be hooked up!"),
872            // Please note that this is only expected to fail during unit tests,
873            // where the logger might have already been initialized by a previous
874            // test. So it's fine to print with the "logger".
875            Err(_) => log::warn!("stdout logging was already initialized"),
876        };
877    }
878}
879
880/// **DEPRECATED** Sets whether upload is enabled or not.
881///
882/// **DEPRECATION NOTICE**:
883/// This API is deprecated. Use `set_collection_enabled` instead.
884pub fn glean_set_upload_enabled(enabled: bool) {
885    if !was_initialize_called() {
886        return;
887    }
888
889    crate::launch_with_glean_mut(move |glean| {
890        let state = global_state().lock().unwrap();
891        let original_enabled = glean.is_upload_enabled();
892
893        if !enabled {
894            // Stop the MPS if its handled within Rust.
895            glean.cancel_metrics_ping_scheduler();
896            // Stop wrapper-controlled uploader.
897            if let Err(e) = state.callbacks.cancel_uploads() {
898                log::error!("Canceling upload failed. Error: {}", e);
899            }
900        }
901
902        glean.set_upload_enabled(enabled);
903
904        if !original_enabled && enabled {
905            initialize_core_metrics(glean, &state.client_info);
906        }
907
908        if original_enabled && !enabled {
909            if let Err(e) = state.callbacks.trigger_upload() {
910                log::error!("Triggering upload failed. Error: {}", e);
911            }
912        }
913    })
914}
915
916/// Sets whether collection is enabled or not.
917///
918/// This replaces `set_upload_enabled`.
919pub fn glean_set_collection_enabled(enabled: bool) {
920    glean_set_upload_enabled(enabled)
921}
922
923/// Enable or disable a ping.
924///
925/// Disabling a ping causes all data for that ping to be removed from storage
926/// and all pending pings of that type to be deleted.
927pub fn set_ping_enabled(ping: &PingType, enabled: bool) {
928    let ping = ping.clone();
929    if was_initialize_called() && core::global_glean().is_some() {
930        crate::launch_with_glean_mut(move |glean| glean.set_ping_enabled(&ping, enabled));
931    } else {
932        let m = &PRE_INIT_PING_ENABLED;
933        let mut lock = m.lock().unwrap();
934        lock.push((ping, enabled));
935    }
936}
937
938/// Register a new [`PingType`](PingType).
939pub(crate) fn register_ping_type(ping: &PingType) {
940    // If this happens after Glean.initialize is called (and returns),
941    // we dispatch ping registration on the thread pool.
942    // Registering a ping should not block the application.
943    // Submission itself is also dispatched, so it will always come after the registration.
944    if was_initialize_called() && core::global_glean().is_some() {
945        let ping = ping.clone();
946        crate::launch_with_glean_mut(move |glean| {
947            glean.register_ping_type(&ping);
948        })
949    } else {
950        // We need to keep track of pings, so they get re-registered after a reset or
951        // if ping registration is attempted before Glean initializes.
952        // This state is kept across Glean resets, which should only ever happen in test mode.
953        // It's a set and keeping them around forever should not have much of an impact.
954        let m = &PRE_INIT_PING_REGISTRATION;
955        let mut lock = m.lock().unwrap();
956        lock.push(ping.clone());
957    }
958}
959
960/// Gets a list of currently registered ping names.
961///
962/// # Returns
963///
964/// The list of ping names that are currently registered.
965pub fn glean_get_registered_ping_names() -> Vec<String> {
966    block_on_dispatcher();
967    core::with_glean(|glean| {
968        glean
969            .get_registered_ping_names()
970            .iter()
971            .map(|ping| ping.to_string())
972            .collect()
973    })
974}
975
976/// Indicate that an experiment is running.  Glean will then add an
977/// experiment annotation to the environment which is sent with pings. This
978/// infomration is not persisted between runs.
979///
980/// See [`core::Glean::set_experiment_active`].
981pub fn glean_set_experiment_active(
982    experiment_id: String,
983    branch: String,
984    extra: HashMap<String, String>,
985) {
986    launch_with_glean(|glean| glean.set_experiment_active(experiment_id, branch, extra))
987}
988
989/// Indicate that an experiment is no longer running.
990///
991/// See [`core::Glean::set_experiment_inactive`].
992pub fn glean_set_experiment_inactive(experiment_id: String) {
993    launch_with_glean(|glean| glean.set_experiment_inactive(experiment_id))
994}
995
996/// TEST ONLY FUNCTION.
997/// Returns the [`RecordedExperiment`] for the given `experiment_id`
998/// or `None` if the id isn't found.
999pub fn glean_test_get_experiment_data(experiment_id: String) -> Option<RecordedExperiment> {
1000    block_on_dispatcher();
1001    core::with_glean(|glean| glean.test_get_experiment_data(experiment_id.to_owned()))
1002}
1003
1004/// Set an experimentation identifier dynamically.
1005///
1006/// Note: it's probably a good idea to unenroll from any experiments when identifiers change.
1007pub fn glean_set_experimentation_id(experimentation_id: String) {
1008    launch_with_glean(move |glean| {
1009        glean
1010            .additional_metrics
1011            .experimentation_id
1012            .set(experimentation_id);
1013    });
1014}
1015
1016/// TEST ONLY FUNCTION.
1017/// Gets stored experimentation id annotation.
1018pub fn glean_test_get_experimentation_id() -> Option<String> {
1019    block_on_dispatcher();
1020    core::with_glean(|glean| glean.test_get_experimentation_id())
1021}
1022
1023/// Sets a remote configuration to override metrics' default enabled/disabled
1024/// state
1025///
1026/// See [`core::Glean::apply_server_knobs_config`].
1027pub fn glean_apply_server_knobs_config(json: String) {
1028    // An empty config means it is not set,
1029    // so we avoid logging an error about it.
1030    if json.is_empty() {
1031        return;
1032    }
1033
1034    match RemoteSettingsConfig::try_from(json) {
1035        Ok(cfg) => launch_with_glean(|glean| {
1036            glean.apply_server_knobs_config(cfg);
1037        }),
1038        Err(e) => {
1039            log::error!("Error setting metrics feature config: {:?}", e);
1040        }
1041    }
1042}
1043
1044/// Sets a debug view tag.
1045///
1046/// When the debug view tag is set, pings are sent with a `X-Debug-ID` header with the
1047/// value of the tag and are sent to the ["Ping Debug Viewer"](https://mozilla.github.io/glean/book/dev/core/internal/debug-pings.html).
1048///
1049/// # Arguments
1050///
1051/// * `tag` - A valid HTTP header value. Must match the regex: "[a-zA-Z0-9-]{1,20}".
1052///
1053/// # Returns
1054///
1055/// This will return `false` in case `tag` is not a valid tag and `true` otherwise.
1056/// If called before Glean is initialized it will always return `true`.
1057pub fn glean_set_debug_view_tag(tag: String) -> bool {
1058    if was_initialize_called() && core::global_glean().is_some() {
1059        crate::launch_with_glean_mut(move |glean| {
1060            glean.set_debug_view_tag(&tag);
1061        });
1062        true
1063    } else {
1064        // Glean has not been initialized yet. Cache the provided tag value.
1065        let m = &PRE_INIT_DEBUG_VIEW_TAG;
1066        let mut lock = m.lock().unwrap();
1067        *lock = tag;
1068        // When setting the debug view tag before initialization,
1069        // we don't validate the tag, thus this function always returns true.
1070        true
1071    }
1072}
1073
1074/// Gets the currently set debug view tag.
1075///
1076/// # Returns
1077///
1078/// Return the value for the debug view tag or [`None`] if it hasn't been set.
1079pub fn glean_get_debug_view_tag() -> Option<String> {
1080    block_on_dispatcher();
1081    core::with_glean(|glean| glean.debug_view_tag().map(|tag| tag.to_string()))
1082}
1083
1084/// Sets source tags.
1085///
1086/// Overrides any existing source tags.
1087/// Source tags will show in the destination datasets, after ingestion.
1088///
1089/// **Note** If one or more tags are invalid, all tags are ignored.
1090///
1091/// # Arguments
1092///
1093/// * `tags` - A vector of at most 5 valid HTTP header values. Individual
1094///   tags must match the regex: "[a-zA-Z0-9-]{1,20}".
1095pub fn glean_set_source_tags(tags: Vec<String>) -> bool {
1096    if was_initialize_called() && core::global_glean().is_some() {
1097        crate::launch_with_glean_mut(|glean| {
1098            glean.set_source_tags(tags);
1099        });
1100        true
1101    } else {
1102        // Glean has not been initialized yet. Cache the provided source tags.
1103        let m = &PRE_INIT_SOURCE_TAGS;
1104        let mut lock = m.lock().unwrap();
1105        *lock = tags;
1106        // When setting the source tags before initialization,
1107        // we don't validate the tags, thus this function always returns true.
1108        true
1109    }
1110}
1111
1112/// Sets the log pings debug option.
1113///
1114/// When the log pings debug option is `true`,
1115/// we log the payload of all succesfully assembled pings.
1116///
1117/// # Arguments
1118///
1119/// * `value` - The value of the log pings option
1120pub fn glean_set_log_pings(value: bool) {
1121    if was_initialize_called() && core::global_glean().is_some() {
1122        crate::launch_with_glean_mut(move |glean| {
1123            glean.set_log_pings(value);
1124        });
1125    } else {
1126        PRE_INIT_LOG_PINGS.store(value, Ordering::SeqCst);
1127    }
1128}
1129
1130/// Gets the current log pings value.
1131///
1132/// # Returns
1133///
1134/// Return the value for the log pings debug option.
1135pub fn glean_get_log_pings() -> bool {
1136    block_on_dispatcher();
1137    core::with_glean(|glean| glean.log_pings())
1138}
1139
1140/// Performs the collection/cleanup operations required by becoming active.
1141///
1142/// This functions generates a baseline ping with reason `active`
1143/// and then sets the dirty bit.
1144/// This should be called whenever the consuming product becomes active (e.g.
1145/// getting to foreground).
1146pub fn glean_handle_client_active() {
1147    dispatcher::launch(|| {
1148        core::with_glean_mut(|glean| {
1149            glean.handle_client_active();
1150        });
1151
1152        // The above call may generate pings, so we need to trigger
1153        // the uploader. It's fine to trigger it if no ping was generated:
1154        // it will bail out.
1155        let state = global_state().lock().unwrap();
1156        if let Err(e) = state.callbacks.trigger_upload() {
1157            log::error!("Triggering upload failed. Error: {}", e);
1158        }
1159    });
1160
1161    // The previous block of code may send a ping containing the `duration` metric,
1162    // in `glean.handle_client_active`. We intentionally start recording a new
1163    // `duration` after that happens, so that the measurement gets reported when
1164    // calling `handle_client_inactive`.
1165    core_metrics::internal_metrics::baseline_duration.start();
1166}
1167
1168/// Performs the collection/cleanup operations required by becoming inactive.
1169///
1170/// This functions generates a baseline and an events ping with reason
1171/// `inactive` and then clears the dirty bit.
1172/// This should be called whenever the consuming product becomes inactive (e.g.
1173/// getting to background).
1174pub fn glean_handle_client_inactive() {
1175    // This needs to be called before the `handle_client_inactive` api: it stops
1176    // measuring the duration of the previous activity time, before any ping is sent
1177    // by the next call.
1178    core_metrics::internal_metrics::baseline_duration.stop();
1179
1180    dispatcher::launch(|| {
1181        core::with_glean_mut(|glean| {
1182            glean.handle_client_inactive();
1183        });
1184
1185        // The above call may generate pings, so we need to trigger
1186        // the uploader. It's fine to trigger it if no ping was generated:
1187        // it will bail out.
1188        let state = global_state().lock().unwrap();
1189        if let Err(e) = state.callbacks.trigger_upload() {
1190            log::error!("Triggering upload failed. Error: {}", e);
1191        }
1192    })
1193}
1194
1195/// Collect and submit a ping for eventual upload by name.
1196pub fn glean_submit_ping_by_name(ping_name: String, reason: Option<String>) {
1197    dispatcher::launch(|| {
1198        let sent =
1199            core::with_glean(move |glean| glean.submit_ping_by_name(&ping_name, reason.as_deref()));
1200
1201        if sent {
1202            let state = global_state().lock().unwrap();
1203            if let Err(e) = state.callbacks.trigger_upload() {
1204                log::error!("Triggering upload failed. Error: {}", e);
1205            }
1206        }
1207    })
1208}
1209
1210/// Collect and submit a ping (by its name) for eventual upload, synchronously.
1211///
1212/// Note: This does not trigger the uploader. The caller is responsible to do this.
1213pub fn glean_submit_ping_by_name_sync(ping_name: String, reason: Option<String>) -> bool {
1214    if !was_initialize_called() {
1215        return false;
1216    }
1217
1218    core::with_opt_glean(|glean| glean.submit_ping_by_name(&ping_name, reason.as_deref()))
1219        .unwrap_or(false)
1220}
1221
1222/// EXPERIMENTAL: Register a listener object to recieve notifications of event recordings.
1223///
1224/// # Arguments
1225///
1226/// * `tag` - A string identifier used to later unregister the listener
1227/// * `listener` - Implements the `GleanEventListener` trait
1228pub fn glean_register_event_listener(tag: String, listener: Box<dyn GleanEventListener>) {
1229    register_event_listener(tag, listener);
1230}
1231
1232/// Unregister an event listener from recieving notifications.
1233///
1234/// Does not panic if the listener doesn't exist.
1235///
1236/// # Arguments
1237///
1238/// * `tag` - The tag used when registering the listener to be unregistered
1239pub fn glean_unregister_event_listener(tag: String) {
1240    unregister_event_listener(tag);
1241}
1242
1243/// **TEST-ONLY Method**
1244///
1245/// Set test mode
1246pub fn glean_set_test_mode(enabled: bool) {
1247    dispatcher::global::TESTING_MODE.store(enabled, Ordering::SeqCst);
1248}
1249
1250/// **TEST-ONLY Method**
1251///
1252/// Destroy the underlying database.
1253pub fn glean_test_destroy_glean(clear_stores: bool, data_path: Option<String>) {
1254    if was_initialize_called() {
1255        // Just because initialize was called doesn't mean it's done.
1256        join_init();
1257
1258        dispatcher::reset_dispatcher();
1259
1260        // Only useful if Glean initialization finished successfully
1261        // and set up the storage.
1262        let has_storage = core::with_opt_glean(|glean| {
1263            // We need to flush the ping lifetime data before a full shutdown.
1264            glean
1265                .storage_opt()
1266                .map(|storage| storage.persist_ping_lifetime_data())
1267                .is_some()
1268        })
1269        .unwrap_or(false);
1270        if has_storage {
1271            uploader_shutdown();
1272        }
1273
1274        if core::global_glean().is_some() {
1275            core::with_glean_mut(|glean| {
1276                if clear_stores {
1277                    glean.test_clear_all_stores()
1278                }
1279                glean.destroy_db()
1280            });
1281        }
1282
1283        // Allow us to go through initialization again.
1284        INITIALIZE_CALLED.store(false, Ordering::SeqCst);
1285    } else if clear_stores {
1286        if let Some(data_path) = data_path {
1287            let _ = std::fs::remove_dir_all(data_path).ok();
1288        } else {
1289            log::warn!("Asked to clear stores before initialization, but no data path given.");
1290        }
1291    }
1292}
1293
1294/// Get the next upload task
1295pub fn glean_get_upload_task() -> PingUploadTask {
1296    core::with_opt_glean(|glean| glean.get_upload_task()).unwrap_or_else(PingUploadTask::done)
1297}
1298
1299/// Processes the response from an attempt to upload a ping.
1300pub fn glean_process_ping_upload_response(uuid: String, result: UploadResult) -> UploadTaskAction {
1301    core::with_glean(|glean| glean.process_ping_upload_response(&uuid, result))
1302}
1303
1304/// **TEST-ONLY Method**
1305///
1306/// Set the dirty flag
1307pub fn glean_set_dirty_flag(new_value: bool) {
1308    core::with_glean(|glean| glean.set_dirty_flag(new_value))
1309}
1310
1311/// Updates attribution fields with new values.
1312/// AttributionMetrics fields with `None` values will not overwrite older values.
1313pub fn glean_update_attribution(attribution: AttributionMetrics) {
1314    if was_initialize_called() && core::global_glean().is_some() {
1315        core::with_glean(|glean| glean.update_attribution(attribution));
1316    } else {
1317        PRE_INIT_ATTRIBUTION
1318            .lock()
1319            .unwrap()
1320            .get_or_insert(Default::default())
1321            .update(attribution);
1322    }
1323}
1324
1325/// **TEST-ONLY Method**
1326///
1327/// Returns the current attribution metrics.
1328/// Panics if called before init.
1329pub fn glean_test_get_attribution() -> AttributionMetrics {
1330    join_init();
1331    core::with_glean(|glean| glean.test_get_attribution())
1332}
1333
1334/// Updates distribution fields with new values.
1335/// DistributionMetrics fields with `None` values will not overwrite older values.
1336pub fn glean_update_distribution(distribution: DistributionMetrics) {
1337    if was_initialize_called() && core::global_glean().is_some() {
1338        core::with_glean(|glean| glean.update_distribution(distribution));
1339    } else {
1340        PRE_INIT_DISTRIBUTION
1341            .lock()
1342            .unwrap()
1343            .get_or_insert(Default::default())
1344            .update(distribution);
1345    }
1346}
1347
1348/// **TEST-ONLY Method**
1349///
1350/// Returns the current distribution metrics.
1351/// Panics if called before init.
1352pub fn glean_test_get_distribution() -> DistributionMetrics {
1353    join_init();
1354    core::with_glean(|glean| glean.test_get_distribution())
1355}
1356
1357#[cfg(all(not(target_os = "android"), not(target_os = "ios")))]
1358static FD_LOGGER: OnceCell<fd_logger::FdLogger> = OnceCell::new();
1359
1360/// Initialize the logging system to send JSON messages to a file descriptor
1361/// (Unix) or file handle (Windows).
1362///
1363/// Not available on Android and iOS.
1364///
1365/// `fd` is a writable file descriptor (on Unix) or file handle (on Windows).
1366///
1367/// # Safety
1368///
1369/// `fd` MUST be a valid open file descriptor (Unix) or file handle (Windows).
1370/// This function is marked safe,
1371/// because we can't call unsafe functions from generated UniFFI code.
1372#[cfg(all(not(target_os = "android"), not(target_os = "ios")))]
1373pub fn glean_enable_logging_to_fd(fd: u64) {
1374    // SAFETY:
1375    // This functions is unsafe.
1376    // Due to UniFFI restrictions we cannot mark it as such.
1377    //
1378    // `fd` MUST be a valid open file descriptor (Unix) or file handle (Windows).
1379    unsafe {
1380        // Set up logging to a file descriptor/handle. For this usage, the
1381        // language binding should setup a pipe and pass in the descriptor to
1382        // the writing side of the pipe as the `fd` parameter. Log messages are
1383        // written as JSON to the file descriptor.
1384        let logger = FD_LOGGER.get_or_init(|| fd_logger::FdLogger::new(fd));
1385        // Set the level so everything goes through to the language
1386        // binding side where it will be filtered by the language
1387        // binding's logging system.
1388        if log::set_logger(logger).is_ok() {
1389            log::set_max_level(log::LevelFilter::Debug);
1390        }
1391    }
1392}
1393
1394/// Collects information about the data directories used by FOG.
1395fn collect_directory_info(path: &Path) -> Option<serde_json::Value> {
1396    // List of child directories to check
1397    let subdirs = ["db", "events", "pending_pings"];
1398    let mut directories_info: crate::internal_metrics::DataDirectoryInfoObject =
1399        DataDirectoryInfoObject::with_capacity(subdirs.len());
1400
1401    for subdir in subdirs.iter() {
1402        let dir_path = path.join(subdir);
1403
1404        // Initialize a DataDirectoryInfoObjectItem for each directory
1405        let mut directory_info = crate::internal_metrics::DataDirectoryInfoObjectItem {
1406            dir_name: Some(subdir.to_string()),
1407            dir_exists: None,
1408            dir_created: None,
1409            dir_modified: None,
1410            file_count: None,
1411            files: Vec::new(),
1412            error_message: None,
1413        };
1414
1415        // Check if the directory exists
1416        if dir_path.is_dir() {
1417            directory_info.dir_exists = Some(true);
1418
1419            // Get directory metadata
1420            match fs::metadata(&dir_path) {
1421                Ok(metadata) => {
1422                    if let Ok(created) = metadata.created() {
1423                        directory_info.dir_created = Some(
1424                            created
1425                                .duration_since(UNIX_EPOCH)
1426                                .unwrap_or(Duration::ZERO)
1427                                .as_secs() as i64,
1428                        );
1429                    }
1430                    if let Ok(modified) = metadata.modified() {
1431                        directory_info.dir_modified = Some(
1432                            modified
1433                                .duration_since(UNIX_EPOCH)
1434                                .unwrap_or(Duration::ZERO)
1435                                .as_secs() as i64,
1436                        );
1437                    }
1438                }
1439                Err(error) => {
1440                    let msg = format!("Unable to get metadata: {}", error.kind());
1441                    directory_info.error_message = Some(msg.clone());
1442                    log::warn!("{}", msg);
1443                    continue;
1444                }
1445            }
1446
1447            // Read the directory's contents
1448            let mut file_count = 0;
1449            let entries = match fs::read_dir(&dir_path) {
1450                Ok(entries) => entries,
1451                Err(error) => {
1452                    let msg = format!("Unable to read subdir: {}", error.kind());
1453                    directory_info.error_message = Some(msg.clone());
1454                    log::warn!("{}", msg);
1455                    continue;
1456                }
1457            };
1458            for entry in entries {
1459                directory_info.files.push(
1460                    crate::internal_metrics::DataDirectoryInfoObjectItemItemFilesItem {
1461                        file_name: None,
1462                        file_created: None,
1463                        file_modified: None,
1464                        file_size: None,
1465                        error_message: None,
1466                    },
1467                );
1468                // Safely get and unwrap the file_info we just pushed so we can populate it
1469                let file_info = directory_info.files.last_mut().unwrap();
1470                let entry = match entry {
1471                    Ok(entry) => entry,
1472                    Err(error) => {
1473                        let msg = format!("Unable to read file: {}", error.kind());
1474                        file_info.error_message = Some(msg.clone());
1475                        log::warn!("{}", msg);
1476                        continue;
1477                    }
1478                };
1479                let file_name = match entry.file_name().into_string() {
1480                    Ok(file_name) => file_name,
1481                    _ => {
1482                        let msg = "Unable to convert file name to string".to_string();
1483                        file_info.error_message = Some(msg.clone());
1484                        log::warn!("{}", msg);
1485                        continue;
1486                    }
1487                };
1488                let metadata = match entry.metadata() {
1489                    Ok(metadata) => metadata,
1490                    Err(error) => {
1491                        let msg = format!("Unable to read file metadata: {}", error.kind());
1492                        file_info.file_name = Some(file_name);
1493                        file_info.error_message = Some(msg.clone());
1494                        log::warn!("{}", msg);
1495                        continue;
1496                    }
1497                };
1498
1499                // Check if the entry is a file
1500                if metadata.is_file() {
1501                    file_count += 1;
1502
1503                    // Collect file details
1504                    file_info.file_name = Some(file_name);
1505                    file_info.file_created = Some(
1506                        metadata
1507                            .created()
1508                            .unwrap_or(UNIX_EPOCH)
1509                            .duration_since(UNIX_EPOCH)
1510                            .unwrap_or(Duration::ZERO)
1511                            .as_secs() as i64,
1512                    );
1513                    file_info.file_modified = Some(
1514                        metadata
1515                            .modified()
1516                            .unwrap_or(UNIX_EPOCH)
1517                            .duration_since(UNIX_EPOCH)
1518                            .unwrap_or(Duration::ZERO)
1519                            .as_secs() as i64,
1520                    );
1521                    file_info.file_size = Some(metadata.len() as i64);
1522                } else {
1523                    let msg = format!("Skipping non-file entry: {}", file_name.clone());
1524                    file_info.file_name = Some(file_name);
1525                    file_info.error_message = Some(msg.clone());
1526                    log::warn!("{}", msg);
1527                }
1528            }
1529
1530            directory_info.file_count = Some(file_count as i64);
1531        } else {
1532            directory_info.dir_exists = Some(false);
1533        }
1534
1535        // Add the directory info to the final collection
1536        directories_info.push(directory_info);
1537    }
1538
1539    if let Ok(directories_info_json) = serde_json::to_value(directories_info) {
1540        Some(directories_info_json)
1541    } else {
1542        log::error!("Failed to serialize data directory info");
1543        None
1544    }
1545}
1546
1547fn record_dir_info_and_submit_health_ping(dir_info: Option<serde_json::Value>, reason: &str) {
1548    core::with_glean(|glean| {
1549        glean
1550            .health_metrics
1551            .data_directory_info
1552            .set_sync(glean, dir_info.unwrap_or(serde_json::json!({})));
1553        glean.internal_pings.health.submit_sync(glean, Some(reason));
1554    });
1555}
1556
1557/// Unused function. Not used on Android or iOS.
1558#[cfg(any(target_os = "android", target_os = "ios"))]
1559pub fn glean_enable_logging_to_fd(_fd: u64) {
1560    // intentionally left empty
1561}
1562
1563#[allow(missing_docs)]
1564// uniffi-generated code should not be checked.
1565#[allow(clippy::all)]
1566mod ffi {
1567    use super::*;
1568    uniffi::include_scaffolding!("glean");
1569
1570    type CowString = Cow<'static, str>;
1571
1572    uniffi::custom_type!(CowString, String, {
1573        remote,
1574        lower: |s| s.into_owned(),
1575        try_lift: |s| Ok(Cow::from(s))
1576    });
1577
1578    type JsonValue = serde_json::Value;
1579
1580    uniffi::custom_type!(JsonValue, String, {
1581        remote,
1582        lower: |s| serde_json::to_string(&s).unwrap(),
1583        try_lift: |s| Ok(serde_json::from_str(&s)?)
1584    });
1585}
1586pub use ffi::*;
1587
1588// Split unit tests to a separate file, to reduce the file of this one.
1589#[cfg(test)]
1590#[path = "lib_unit_tests.rs"]
1591mod tests;