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