glean_core/core/mod.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
5use std::collections::HashMap;
6use std::fs::{self, File};
7use std::io::{self, Write};
8use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicU8, Ordering};
10use std::sync::{Arc, Mutex};
11use std::time::Duration;
12
13use chrono::{DateTime, FixedOffset, SecondsFormat, Utc};
14use malloc_size_of_derive::MallocSizeOf;
15use once_cell::sync::OnceCell;
16use uuid::Uuid;
17
18#[cfg(feature = "sqlite")]
19use crate::database::sqlite::MigrationResult;
20use crate::database::Database;
21use crate::debug::DebugOptions;
22use crate::error::ClientIdFileError;
23use crate::event_database::EventDatabase;
24use crate::flows::{self, FlowRegistry, FlowState};
25use crate::internal_metrics::{
26 AdditionalMetrics, CoreMetrics, DatabaseMetrics, ExceptionState, HealthMetrics,
27};
28use crate::internal_pings::InternalPings;
29use crate::metrics::{
30 self, ExperimentMetric, Metric, MetricType, PingType, RecordedExperiment, RemoteSettingsConfig,
31};
32use crate::ping::PingMaker;
33use crate::session::{self, EventSessionContext, SessionManager, SessionMode, SessionState};
34use crate::storage::{StorageManager, INTERNAL_STORAGE};
35use crate::upload::{PingUploadManager, PingUploadTask, UploadResult, UploadTaskAction};
36#[cfg(feature = "sqlite")]
37use crate::util::truncate_string_at_boundary;
38use crate::util::{local_now_with_offset, sanitize_application_id};
39use crate::{
40 scheduler, system, AttributionMetrics, CommonMetricData, DistributionMetrics, ErrorKind,
41 ExternalBackup, InternalConfiguration, Lifetime, PingRateLimit, Result, DEFAULT_MAX_EVENTS,
42 GLEAN_SCHEMA_VERSION, GLEAN_VERSION, KNOWN_CLIENT_ID,
43};
44
45const CLIENT_ID_PLAIN_FILENAME: &str = "client_id.txt";
46static GLEAN: OnceCell<Mutex<Glean>> = OnceCell::new();
47
48/// Rate limiting defaults
49/// 15 pings every 60 seconds.
50pub const DEFAULT_SECONDS_PER_INTERVAL: u64 = 60;
51pub const DEFAULT_PINGS_PER_INTERVAL: u32 = 15;
52
53pub fn global_glean() -> Option<&'static Mutex<Glean>> {
54 GLEAN.get()
55}
56
57/// Sets or replaces the global Glean object.
58pub fn setup_glean(glean: Glean) -> Result<()> {
59 // The `OnceCell` type wrapping our Glean is thread-safe and can only be set once.
60 // Therefore even if our check for it being empty succeeds, setting it could fail if a
61 // concurrent thread is quicker in setting it.
62 // However this will not cause a bigger problem, as the second `set` operation will just fail.
63 // We can log it and move on.
64 //
65 // For all wrappers this is not a problem, as the Glean object is intialized exactly once on
66 // calling `initialize` on the global singleton and further operations check that it has been
67 // initialized.
68 if GLEAN.get().is_none() {
69 if GLEAN.set(Mutex::new(glean)).is_err() {
70 log::warn!(
71 "Global Glean object is initialized already. This probably happened concurrently."
72 )
73 }
74 } else {
75 // We allow overriding the global Glean object to support test mode.
76 // In test mode the Glean object is fully destroyed and recreated.
77 // This all happens behind a mutex and is therefore also thread-safe..
78 let mut lock = GLEAN.get().unwrap().lock().unwrap();
79 *lock = glean;
80 }
81 Ok(())
82}
83
84/// Execute `f` passing the global Glean object.
85///
86/// Panics if the global Glean object has not been set.
87pub fn with_glean<F, R>(f: F) -> R
88where
89 F: FnOnce(&Glean) -> R,
90{
91 let glean = global_glean().expect("Global Glean object not initialized");
92 let lock = glean.lock().unwrap();
93 f(&lock)
94}
95
96/// Execute `f` passing the global Glean object mutable.
97///
98/// Panics if the global Glean object has not been set.
99pub fn with_glean_mut<F, R>(f: F) -> R
100where
101 F: FnOnce(&mut Glean) -> R,
102{
103 let glean = global_glean().expect("Global Glean object not initialized");
104 let mut lock = glean.lock().unwrap();
105 f(&mut lock)
106}
107
108/// Execute `f` passing the global Glean object if it has been set.
109///
110/// Returns `None` if the global Glean object has not been set.
111/// Returns `Some(T)` otherwise.
112pub fn with_opt_glean<F, R>(f: F) -> Option<R>
113where
114 F: FnOnce(&Glean) -> R,
115{
116 let glean = global_glean()?;
117 let lock = glean.lock().unwrap();
118 Some(f(&lock))
119}
120
121/// The object holding meta information about a Glean instance.
122///
123/// ## Example
124///
125/// Create a new Glean instance, register a ping, record a simple counter and then send the final
126/// ping.
127///
128/// ```rust,no_run
129/// # use glean_core::{Glean, InternalConfiguration, CommonMetricData, metrics::*};
130/// let cfg = InternalConfiguration {
131/// data_path: "/tmp/glean".into(),
132/// application_id: "glean.sample.app".into(),
133/// language_binding_name: "Rust".into(),
134/// upload_enabled: true,
135/// max_events: None,
136/// delay_ping_lifetime_io: false,
137/// app_build: "".into(),
138/// use_core_mps: false,
139/// trim_data_to_registered_pings: false,
140/// log_level: None,
141/// rate_limit: None,
142/// enable_event_timestamps: true,
143/// experimentation_id: None,
144/// enable_internal_pings: true,
145/// ping_schedule: Default::default(),
146/// ping_lifetime_threshold: 1000,
147/// ping_lifetime_max_time: 2000,
148/// max_pending_pings_count: None,
149/// max_pending_pings_directory_size: None,
150/// session_mode: glean_core::SessionMode::Auto,
151/// session_sample_rate: 1.0,
152/// session_inactivity_timeout_ms: 1_800_000,
153/// events_ping_acceleration_factor: None,
154/// enable_store_submitted_pings: false,
155/// flows: vec![],
156/// };
157/// let mut glean = Glean::new(cfg, None).unwrap();
158/// let ping = PingType::new("sample", true, false, true, true, true, vec![], vec![], true, vec![]);
159/// glean.register_ping_type(&ping);
160///
161/// let call_counter: CounterMetric = CounterMetric::new(CommonMetricData {
162/// name: "calls".into(),
163/// category: "local".into(),
164/// send_in_pings: vec!["sample".into()],
165/// ..Default::default()
166/// });
167///
168/// call_counter.add_sync(&glean, 1);
169///
170/// ping.submit_sync(&glean, None);
171/// ```
172///
173/// ## Note
174///
175/// In specific language bindings, this is usually wrapped in a singleton and all metric recording goes to a single instance of this object.
176/// In the Rust core, it is possible to create multiple instances, which is used in testing.
177#[derive(Debug, MallocSizeOf)]
178pub struct Glean {
179 upload_enabled: bool,
180 pub(crate) data_store: Option<Database>,
181 event_data_store: EventDatabase,
182 pub(crate) core_metrics: CoreMetrics,
183 pub(crate) additional_metrics: AdditionalMetrics,
184 pub(crate) database_metrics: DatabaseMetrics,
185 pub(crate) health_metrics: HealthMetrics,
186 pub(crate) internal_pings: InternalPings,
187 data_path: PathBuf,
188 application_id: String,
189 ping_registry: HashMap<String, PingType>,
190 #[ignore_malloc_size_of = "external non-allocating type"]
191 start_time: DateTime<FixedOffset>,
192 max_events: u32,
193 is_first_run: bool,
194 pub(crate) upload_manager: PingUploadManager,
195 debug: DebugOptions,
196 pub(crate) app_build: String,
197 pub(crate) schedule_metrics_pings: bool,
198 pub(crate) remote_settings_epoch: AtomicU8,
199 #[ignore_malloc_size_of = "TODO: Expose Glean's inner memory allocations (bug 1960592)"]
200 pub(crate) remote_settings_config: Arc<Mutex<RemoteSettingsConfig>>,
201 pub(crate) with_timestamps: bool,
202 pub(crate) ping_schedule: HashMap<String, Vec<String>>,
203 pub(crate) flow_registry: FlowRegistry,
204 #[ignore_malloc_size_of = "TODO: Expose flow state memory allocations (bug 1960592)"]
205 pub(crate) flow_state: Mutex<FlowState>,
206 #[ignore_malloc_size_of = "TODO: Expose session memory allocations (bug 2043355)"]
207 pub(crate) session_manager: SessionManager,
208 events_ping_acceleration_factor: Option<usize>,
209 pub(crate) store_submitted_pings_enabled: bool,
210 backup: Option<Box<dyn ExternalBackup>>,
211}
212
213impl Glean {
214 /// Creates and initializes a new Glean object for use in a subprocess.
215 ///
216 /// Importantly, this will not send any pings at startup, since that
217 /// sort of management should only happen in the main process.
218 pub fn new_for_subprocess(cfg: &InternalConfiguration, scan_directories: bool) -> Result<Self> {
219 log::info!("Creating new Glean v{}", GLEAN_VERSION);
220
221 let application_id = sanitize_application_id(&cfg.application_id);
222 if application_id.is_empty() {
223 return Err(ErrorKind::InvalidConfig.into());
224 }
225
226 let data_path = Path::new(&cfg.data_path);
227 let event_data_store = EventDatabase::new(data_path)?;
228
229 // Create an upload manager with rate limiting of 15 pings every 60 seconds.
230 let mut upload_manager = PingUploadManager::new(&cfg.data_path, &cfg.language_binding_name);
231 let rate_limit = cfg.rate_limit.as_ref().unwrap_or(&PingRateLimit {
232 seconds_per_interval: DEFAULT_SECONDS_PER_INTERVAL,
233 pings_per_interval: DEFAULT_PINGS_PER_INTERVAL,
234 });
235 upload_manager.set_rate_limiter(
236 rate_limit.seconds_per_interval,
237 rate_limit.pings_per_interval,
238 );
239 if let Some(n) = cfg.max_pending_pings_count {
240 upload_manager.set_max_pending_pings_count(n);
241 }
242 if let Some(n) = cfg.max_pending_pings_directory_size {
243 upload_manager.set_max_pending_pings_directory_size(n);
244 }
245 if let Some(n) = cfg.max_recoverable_failures {
246 upload_manager.set_max_recoverable_failures(n);
247 }
248 if let Some(n) = cfg.max_wait_attempts {
249 upload_manager.set_max_wait_attempts(n);
250 }
251 if let Some(n) = cfg.max_ping_body_size {
252 upload_manager.set_max_ping_body_size(n);
253 }
254
255 // We only scan the pending ping directories when calling this from a subprocess,
256 // when calling this from ::new we need to scan the directories after dealing with the upload state.
257 if scan_directories {
258 let _scanning_thread = upload_manager.scan_pending_pings_directories(false);
259 }
260
261 let start_time = local_now_with_offset();
262 let mut this = Self {
263 upload_enabled: cfg.upload_enabled,
264 // In the subprocess, we want to avoid accessing the database entirely.
265 // The easiest way to ensure that is to just not initialize it.
266 data_store: None,
267 event_data_store,
268 core_metrics: CoreMetrics::new(),
269 additional_metrics: AdditionalMetrics::new(),
270 database_metrics: DatabaseMetrics::new(),
271 health_metrics: HealthMetrics::new(),
272 internal_pings: InternalPings::new(cfg.enable_internal_pings),
273 upload_manager,
274 data_path: PathBuf::from(&cfg.data_path),
275 application_id,
276 ping_registry: HashMap::new(),
277 start_time,
278 max_events: cfg.max_events.unwrap_or(DEFAULT_MAX_EVENTS),
279 is_first_run: false,
280 debug: DebugOptions::new(),
281 app_build: cfg.app_build.to_string(),
282 // Subprocess doesn't use "metrics" pings so has no need for a scheduler.
283 schedule_metrics_pings: false,
284 remote_settings_epoch: AtomicU8::new(0),
285 remote_settings_config: Arc::new(Mutex::new(RemoteSettingsConfig::new())),
286 with_timestamps: cfg.enable_event_timestamps,
287 ping_schedule: cfg.ping_schedule.clone(),
288 // Built here, rather than applied after init like pre-init ping
289 // registration, because `Glean::new()` restores persisted session
290 // state (and with it, flow instances) before it returns.
291 flow_registry: FlowRegistry::new(&cfg.flows),
292 flow_state: Mutex::new(FlowState::default()),
293 // The SessionManager is deliberately left in its default (hollow)
294 // state for subprocesses. `restore_session_state_from_storage()`
295 // is only called in `Glean::new()`, not here, so the subprocess
296 // never loads or mutates the main process's persisted session
297 // state. This prevents subprocesses from interfering with the
298 // main process's session lifecycle (seq counters, dirty flags,
299 // boundary events, etc.).
300 session_manager: SessionManager::new(
301 cfg.session_mode,
302 cfg.session_sample_rate,
303 std::time::Duration::from_millis(cfg.session_inactivity_timeout_ms),
304 ),
305 events_ping_acceleration_factor: cfg
306 .events_ping_acceleration_factor
307 .map(|x| x as usize),
308 store_submitted_pings_enabled: cfg.enable_store_submitted_pings,
309 backup: None,
310 };
311
312 // Ensuring these pings are registered.
313 let pings = this.internal_pings.clone();
314 this.register_ping_type(&pings.baseline);
315 this.register_ping_type(&pings.metrics);
316 this.register_ping_type(&pings.events);
317 this.register_ping_type(&pings.health);
318 this.register_ping_type(&pings.deletion_request);
319
320 Ok(this)
321 }
322
323 /// Creates and initializes a new Glean object.
324 ///
325 /// This will create the necessary directories and files in
326 /// [`cfg.data_path`](InternalConfiguration::data_path). This will also initialize
327 /// the core metrics.
328 pub fn new(
329 cfg: InternalConfiguration,
330 backup: Option<Box<dyn ExternalBackup>>,
331 ) -> Result<Self> {
332 let mut glean = Self::new_for_subprocess(&cfg, false)?;
333 glean.backup = backup;
334
335 // Creating the data store creates the necessary path as well.
336 // If that fails we bail out and don't initialize further.
337 let data_path = Path::new(&cfg.data_path);
338 let ping_lifetime_threshold = cfg.ping_lifetime_threshold as usize;
339 let ping_lifetime_max_time = Duration::from_millis(cfg.ping_lifetime_max_time);
340 glean.data_store = Some(Database::new(
341 data_path,
342 cfg.delay_ping_lifetime_io,
343 ping_lifetime_threshold,
344 ping_lifetime_max_time,
345 )?);
346
347 #[cfg(feature = "sqlite")]
348 if let Some(state) = glean.data_store.as_mut().unwrap().migration_state.take() {
349 glean
350 .database_metrics
351 .migrated_metrics
352 .add_sync(&glean, state.migrated_metrics);
353 glean
354 .database_metrics
355 .metrics_in_sqlite
356 .add_sync(&glean, state.metrics_in_sql);
357 glean
358 .database_metrics
359 .failed_metrics
360 .add_sync(&glean, state.failed_metrics);
361
362 let duration_ns = state.duration.as_nanos().try_into().unwrap_or(u64::MAX);
363 glean
364 .database_metrics
365 .migration_duration
366 .accumulate_raw_samples_nanos_sync(&glean, &[duration_ns]);
367 }
368
369 #[cfg(feature = "sqlite")]
370 if glean.data_store.as_mut().unwrap().migration_error == MigrationResult::Error {
371 glean.database_metrics.migration_error.add_sync(&glean, 1);
372 }
373
374 glean.restore_session_state_from_storage();
375
376 // This code references different states from the "Client ID recovery" flowchart.
377 // See https://mozilla.github.io/glean/dev/core/internal/client_id_recovery.html for details.
378
379 // We don't have the database yet when we first encounter the error,
380 // so we store it and apply it later.
381 // state (a)
382 let stored_client_id = match glean.client_id_from_file() {
383 Ok(id) if id == *KNOWN_CLIENT_ID => {
384 glean
385 .health_metrics
386 .file_read_error
387 .get("c0ffee-in-file")
388 .add_sync(&glean, 1);
389 None
390 }
391 Ok(id) => Some(id),
392 Err(ClientIdFileError::NotFound) => {
393 // That's ok, the file might just not exist yet.
394 glean
395 .health_metrics
396 .file_read_error
397 .get("file-not-found")
398 .add_sync(&glean, 1);
399 None
400 }
401 Err(ClientIdFileError::PermissionDenied) => {
402 // state (b)
403 // Uhm ... who removed our permission?
404 glean
405 .health_metrics
406 .file_read_error
407 .get("permission-denied")
408 .add_sync(&glean, 1);
409 None
410 }
411 Err(ClientIdFileError::ParseError(e)) => {
412 // state (b)
413 log::trace!("reading cliend_id.txt. Could not parse into UUID: {e}");
414 glean
415 .health_metrics
416 .file_read_error
417 .get("parse")
418 .add_sync(&glean, 1);
419 None
420 }
421 Err(ClientIdFileError::IoError(e)) => {
422 // state (b)
423 // We can't handle other IO errors (most couldn't occur on this operation anyway)
424 log::trace!("reading client_id.txt. Unexpected io error: {e}");
425 glean
426 .health_metrics
427 .file_read_error
428 .get("io")
429 .add_sync(&glean, 1);
430 None
431 }
432 };
433
434 {
435 let data_store = glean.data_store.as_ref().unwrap();
436 let file_size = data_store.file_size().map(|n| n.get()).unwrap_or(0);
437
438 // If we have a client ID on disk, we check the database
439 if let Some(stored_client_id) = stored_client_id {
440 // state (c)
441 if file_size == 0 {
442 log::trace!("no database. database size={file_size}. stored_client_id={stored_client_id}");
443 // state (d)
444 glean
445 .health_metrics
446 .recovered_client_id
447 .set_from_uuid_sync(&glean, stored_client_id);
448 glean
449 .health_metrics
450 .exception_state
451 .set_sync(&glean, ExceptionState::EmptyDb);
452
453 // state (e) -- mitigation: store recovered client ID in DB
454 glean
455 .core_metrics
456 .client_id
457 .set_from_uuid_sync(&glean, stored_client_id);
458 } else {
459 let db_client_id = glean
460 .core_metrics
461 .client_id
462 .get_value(&glean, Some("glean_client_info"));
463
464 match db_client_id {
465 None => {
466 // state (f)
467 log::trace!("no client_id in DB. stored_client_id={stored_client_id}");
468 glean
469 .health_metrics
470 .exception_state
471 .set_sync(&glean, ExceptionState::RegenDb);
472
473 // state (e) -- mitigation: store recovered client ID in DB
474 glean
475 .core_metrics
476 .client_id
477 .set_from_uuid_sync(&glean, stored_client_id);
478 }
479 Some(db_client_id) if db_client_id == *KNOWN_CLIENT_ID => {
480 // state (i)
481 log::trace!(
482 "c0ffee client_id in DB, stored_client_id={stored_client_id}"
483 );
484 glean
485 .health_metrics
486 .recovered_client_id
487 .set_from_uuid_sync(&glean, stored_client_id);
488 glean
489 .health_metrics
490 .exception_state
491 .set_sync(&glean, ExceptionState::C0ffeeInDb);
492
493 // If we have a recovered client ID we also overwrite the database.
494 // state (e)
495 glean
496 .core_metrics
497 .client_id
498 .set_from_uuid_sync(&glean, stored_client_id);
499 }
500 Some(db_client_id) if db_client_id == stored_client_id => {
501 // all valid. nothing to do
502 log::trace!("database consistent. db_client_id == stored_client_id: {db_client_id}");
503 }
504 Some(db_client_id) => {
505 // state (g)
506 log::trace!(
507 "client_id mismatch. db_client_id{db_client_id}, stored_client_id={stored_client_id}. Overwriting file with db's client_id."
508 );
509 glean
510 .health_metrics
511 .recovered_client_id
512 .set_from_uuid_sync(&glean, stored_client_id);
513 glean
514 .health_metrics
515 .exception_state
516 .set_sync(&glean, ExceptionState::ClientIdMismatch);
517
518 // state (h)
519 glean.store_client_id_with_reporting(
520 db_client_id,
521 "client_id mismatch will re-occur.",
522 );
523 }
524 }
525 }
526 } else {
527 log::trace!("No stored client ID. Database might have it.");
528
529 let db_client_id = glean
530 .core_metrics
531 .client_id
532 .get_value(&glean, Some("glean_client_info"));
533 if let Some(db_client_id) = db_client_id {
534 // state (h)
535 glean.store_client_id_with_reporting(
536 db_client_id,
537 "Might happen on next init then.",
538 );
539 } else {
540 log::trace!("Database has no client ID either. We might be fresh!");
541 }
542 }
543 }
544
545 {
546 // state (j): Load the backup ID.
547 let backup_client_id = glean
548 .backup
549 .as_ref()
550 .and_then(|b| b.load("client_id".into()));
551 if let Some(backup_client_id) = backup_client_id {
552 let backup_client_id = Uuid::try_parse(&backup_client_id);
553 let client_id = glean
554 .core_metrics
555 .client_id
556 .get_value(&glean, Some("glean_client_info"));
557 match backup_client_id {
558 Err(_) => {
559 log::trace!("Backup client_id not a parseable UUID");
560 glean
561 .health_metrics
562 .backup_client_id_status
563 .get("parse")
564 .add_sync(&glean, 1);
565 }
566 Ok(backup_client_id) if backup_client_id == *KNOWN_CLIENT_ID => {
567 log::trace!("c0ffee in backup client_id. But how?");
568 glean
569 .health_metrics
570 .backup_client_id_status
571 .get("c0ffee")
572 .add_sync(&glean, 1);
573 }
574 Ok(backup_client_id) => {
575 if let Some(client_id) = client_id {
576 if backup_client_id == client_id {
577 log::trace!("Backup client_id matches chosen client_id");
578 glean
579 .health_metrics
580 .backup_client_id_status
581 .get("match")
582 .add_sync(&glean, 1);
583 } else {
584 log::trace!("Backup client_id mismatch with chosen client_id");
585 glean
586 .health_metrics
587 .backup_client_id_status
588 .get("mismatch")
589 .add_sync(&glean, 1);
590 glean.backup_client_id(client_id);
591 }
592 } else {
593 // state (k): Here we go, the one case where the backup is used.
594 log::trace!("No current client_id, but a valid backup client_id.");
595 glean
596 .health_metrics
597 .backup_client_id_status
598 .get("backup_only")
599 .add_sync(&glean, 1);
600 if glean
601 .backup
602 .as_ref()
603 .is_some_and(|b| b.should_apply_stored_client_id())
604 {
605 log::trace!("Applying backup client_id.");
606 glean
607 .health_metrics
608 .recovered_client_id
609 .set_from_uuid_sync(&glean, backup_client_id);
610 glean.store_client_id_with_reporting(
611 backup_client_id,
612 "will have to hope backup keeps working.",
613 );
614 glean
615 .core_metrics
616 .client_id
617 .set_from_uuid_sync(&glean, backup_client_id);
618 }
619 }
620 }
621 }
622 } else {
623 log::trace!("No backup or no backup-stored client_id.");
624 glean
625 .health_metrics
626 .backup_client_id_status
627 .get("none")
628 .add_sync(&glean, 1);
629 if let Some(client_id) = glean
630 .core_metrics
631 .client_id
632 .get_value(&glean, Some("glean_client_info"))
633 {
634 glean.backup_client_id(client_id);
635 }
636 }
637 }
638
639 // Set experimentation identifier (if any)
640 if let Some(experimentation_id) = &cfg.experimentation_id {
641 glean
642 .additional_metrics
643 .experimentation_id
644 .set_sync(&glean, experimentation_id.to_string());
645 }
646
647 glean.set_early_metrics();
648
649 // The upload enabled flag may have changed since the last run, for
650 // example by the changing of a config file.
651 if cfg.upload_enabled {
652 // If upload is enabled, just follow the normal code path to
653 // instantiate the core metrics.
654 glean.on_upload_enabled();
655 } else {
656 // If upload is disabled, then clear the metrics
657 // but do not send a deletion request ping.
658 // If we have run before, and we have an old client_id,
659 // do the full upload disabled operations to clear metrics
660 // and send a deletion request ping.
661 match glean
662 .core_metrics
663 .client_id
664 .get_value(&glean, Some("glean_client_info"))
665 {
666 None => glean.clear_metrics(),
667 Some(uuid) => {
668 if let Err(e) = glean.remove_stored_client_id() {
669 log::error!("Couldn't remove client ID on disk. This might lead to a resurrection of this client ID later. Error: {e}");
670 }
671 if let Some(backup) = glean.backup.as_ref() {
672 backup.clear("client_id".into());
673 }
674 if uuid == *KNOWN_CLIENT_ID {
675 // Previously Glean kept the KNOWN_CLIENT_ID stored.
676 // Let's ensure we erase it now.
677 if let Some(data) = glean.data_store.as_ref() {
678 _ = data.remove_single_metric(
679 Lifetime::User,
680 "glean_client_info",
681 "client_id",
682 );
683 }
684 } else {
685 // Temporarily enable uploading so we can submit a
686 // deletion request ping.
687 glean.upload_enabled = true;
688 glean.on_upload_disabled(true);
689 }
690 }
691 }
692 }
693
694 // We set this only for non-subprocess situations.
695 // If internal pings are disabled, we don't set up the MPS either,
696 // it wouldn't send any data anyway.
697 glean.schedule_metrics_pings = cfg.enable_internal_pings && cfg.use_core_mps;
698
699 // We only scan the pendings pings directories **after** dealing with the upload state.
700 // If upload is disabled, we delete all pending pings files
701 // and we need to do that **before** scanning the pending pings folder
702 // to ensure we don't enqueue pings before their files are deleted.
703 let _scanning_thread = glean.upload_manager.scan_pending_pings_directories(true);
704
705 Ok(glean)
706 }
707
708 /// For tests make it easy to create a Glean object using only the required configuration.
709 #[cfg(test)]
710 pub(crate) fn with_options(
711 data_path: &str,
712 application_id: &str,
713 upload_enabled: bool,
714 enable_internal_pings: bool,
715 ) -> Self {
716 let cfg = InternalConfiguration {
717 data_path: data_path.into(),
718 application_id: application_id.into(),
719 language_binding_name: "Rust".into(),
720 upload_enabled,
721 max_events: None,
722 delay_ping_lifetime_io: false,
723 app_build: "Unknown".into(),
724 use_core_mps: false,
725 trim_data_to_registered_pings: false,
726 log_level: None,
727 rate_limit: None,
728 enable_event_timestamps: true,
729 experimentation_id: None,
730 enable_internal_pings,
731 ping_schedule: Default::default(),
732 ping_lifetime_threshold: 0,
733 ping_lifetime_max_time: 0,
734 max_pending_pings_count: None,
735 max_pending_pings_directory_size: None,
736 max_recoverable_failures: None,
737 max_wait_attempts: None,
738 max_ping_body_size: None,
739 session_mode: SessionMode::Auto,
740 session_sample_rate: 1.0,
741 session_inactivity_timeout_ms: 1_800_000,
742 events_ping_acceleration_factor: None,
743 enable_store_submitted_pings: false,
744 flows: vec![],
745 };
746
747 let mut glean = Self::new(cfg, None).unwrap();
748
749 // Disable all upload manager policies for testing
750 glean.upload_manager = PingUploadManager::no_policy(data_path);
751
752 glean
753 }
754
755 /// Close the database connection.
756 ///
757 /// After this Glean needs to be reinitialized.
758 pub fn close_db(&mut self) {
759 self.data_store = None;
760 }
761
762 fn client_id_file_path(&self) -> PathBuf {
763 self.data_path.join(CLIENT_ID_PLAIN_FILENAME)
764 }
765
766 /// Write the client ID to a separate plain file on disk
767 ///
768 /// Use `store_client_id_with_reporting` to handle the error cases.
769 fn store_client_id(&self, client_id: Uuid) -> Result<(), ClientIdFileError> {
770 let mut fp = File::create(self.client_id_file_path())?;
771
772 let mut buffer = Uuid::encode_buffer();
773 let uuid_str = client_id.hyphenated().encode_lower(&mut buffer);
774 fp.write_all(uuid_str.as_bytes())?;
775 fp.sync_all()?;
776
777 Ok(())
778 }
779
780 /// Write the client ID to a separate plain file on disk
781 ///
782 /// When an error occurs an error message is logged and the error is counted in a metric.
783 fn store_client_id_with_reporting(&self, client_id: Uuid, msg: &str) {
784 if let Err(err) = self.store_client_id(client_id) {
785 log::error!(
786 "Could not write {client_id} to state file. {} Error: {err}",
787 msg
788 );
789 match err {
790 ClientIdFileError::NotFound => {
791 self.health_metrics
792 .file_write_error
793 .get("not-found")
794 .add_sync(self, 1);
795 }
796 ClientIdFileError::PermissionDenied => {
797 self.health_metrics
798 .file_write_error
799 .get("permission-denied")
800 .add_sync(self, 1);
801 }
802 ClientIdFileError::IoError(..) => {
803 self.health_metrics
804 .file_write_error
805 .get("io")
806 .add_sync(self, 1);
807 }
808 ClientIdFileError::ParseError(..) => {
809 log::error!("Parse error encountered on file write. This is impossible.");
810 }
811 }
812 }
813 }
814
815 /// Try to load a client ID from the plain file on disk.
816 fn client_id_from_file(&self) -> Result<Uuid, ClientIdFileError> {
817 let uuid_str = fs::read_to_string(self.client_id_file_path())?;
818 // We don't write a newline, but we still trim it. Who knows who else touches that file by accident.
819 // We're also a bit more lenient in what we accept here:
820 // uppercase, lowercase, with or without dashes, urn, braced (and whatever else `Uuid`
821 // parses by default).
822 let uuid = Uuid::try_parse(uuid_str.trim_end())?;
823 Ok(uuid)
824 }
825
826 /// Remove the stored client ID from disk.
827 /// Should only be called when the client ID is also removed from the database.
828 fn remove_stored_client_id(&self) -> Result<(), ClientIdFileError> {
829 match fs::remove_file(self.client_id_file_path()) {
830 Ok(()) => Ok(()),
831 Err(e) if e.kind() == io::ErrorKind::NotFound => {
832 // File was already missing. No need to report that.
833 Ok(())
834 }
835 Err(e) => Err(e.into()),
836 }
837 }
838
839 /// Backup the client ID to ExternalBackup (if available).
840 fn backup_client_id(&self, client_id: Uuid) {
841 if let Some(backup) = self.backup.as_ref() {
842 backup.store(
843 "client_id".into(),
844 client_id
845 .hyphenated()
846 .encode_lower(&mut Uuid::encode_buffer())
847 .into(),
848 )
849 }
850 }
851
852 /// Initializes the core metrics managed by Glean's Rust core.
853 fn initialize_core_metrics(&mut self) {
854 let need_new_client_id = match self
855 .core_metrics
856 .client_id
857 .get_value(self, Some("glean_client_info"))
858 {
859 None => true,
860 Some(uuid) => uuid == *KNOWN_CLIENT_ID,
861 };
862 if need_new_client_id {
863 log::trace!("Generating new client_id");
864 let new_clientid = self.core_metrics.client_id.generate_and_set_sync(self);
865 self.store_client_id_with_reporting(new_clientid, "New client in database only.");
866 self.backup_client_id(new_clientid);
867 }
868 }
869
870 /// Initializes the database metrics managed by Glean's Rust core.
871 fn initialize_database_metrics(&mut self) {
872 log::trace!("Initializing database metrics");
873
874 if let Some(size) = self
875 .data_store
876 .as_ref()
877 .and_then(|database| database.file_size())
878 {
879 log::trace!("Database file size: {}", size.get());
880 self.database_metrics
881 .size
882 .accumulate_sync(self, size.get() as i64)
883 }
884
885 #[cfg(feature = "sqlite")]
886 if let Some(load_state) = self
887 .data_store
888 .as_ref()
889 .and_then(|database| database.load_state())
890 {
891 use crate::metrics::string::MAX_LENGTH_VALUE;
892 let load_state = truncate_string_at_boundary(load_state, MAX_LENGTH_VALUE);
893 self.database_metrics.load_error.set_sync(self, load_state)
894 }
895
896 #[cfg(not(feature = "sqlite"))]
897 if let Some(rkv_load_state) = self
898 .data_store
899 .as_ref()
900 .and_then(|database| database.rkv_load_state())
901 {
902 self.database_metrics
903 .rkv_load_error
904 .set_sync(self, rkv_load_state);
905 }
906 }
907
908 /// Signals that the environment is ready to submit pings.
909 ///
910 /// Should be called when Glean is initialized to the point where it can correctly assemble pings.
911 /// Usually called from the language binding after all of the core metrics have been set
912 /// and the ping types have been registered.
913 ///
914 /// # Arguments
915 ///
916 /// * `trim_data_to_registered_pings` - Whether we should limit to storing data only for
917 /// data belonging to pings previously registered via `register_ping_type`.
918 ///
919 /// # Returns
920 ///
921 /// Whether the "events" ping was submitted.
922 pub fn on_ready_to_submit_pings(&mut self, trim_data_to_registered_pings: bool) -> bool {
923 // When upload is disabled on init we already clear out metrics.
924 // However at that point not all pings are registered and so we keep that data around.
925 // By the time we would be ready to submit we try again cleaning out metrics from
926 // now-known pings.
927 if !self.upload_enabled {
928 log::debug!("on_ready_to_submit_pings. let's clear pings once again.");
929 self.clear_metrics();
930 }
931
932 self.event_data_store
933 .flush_pending_events_on_startup(self, trim_data_to_registered_pings)
934 }
935
936 /// Sets whether upload is enabled or not.
937 ///
938 /// When uploading is disabled, metrics aren't recorded at all and no
939 /// data is uploaded.
940 ///
941 /// When disabling, all pending metrics, events and queued pings are cleared.
942 ///
943 /// When enabling, the core Glean metrics are recreated.
944 ///
945 /// If the value of this flag is not actually changed, this is a no-op.
946 ///
947 /// # Arguments
948 ///
949 /// * `flag` - When true, enable metric collection.
950 ///
951 /// # Returns
952 ///
953 /// Whether the flag was different from the current value,
954 /// and actual work was done to clear or reinstate metrics.
955 pub fn set_upload_enabled(&mut self, flag: bool) -> bool {
956 log::info!("Upload enabled: {:?}", flag);
957
958 if self.upload_enabled != flag {
959 if flag {
960 self.on_upload_enabled();
961 } else {
962 self.on_upload_disabled(false);
963 }
964 true
965 } else {
966 false
967 }
968 }
969
970 /// Sets whether storing submitted pings is enabled or not.
971 ///
972 /// # Arguments
973 ///
974 /// * `enabled` - When true, enables storing submitted pings.
975 ///
976 pub fn set_store_submitted_pings_enabled(&mut self, enabled: bool) {
977 self.store_submitted_pings_enabled = enabled;
978 }
979
980 /// Enable or disable a ping.
981 ///
982 /// Disabling a ping causes all data for that ping to be removed from storage
983 /// and all pending pings of that type to be deleted.
984 ///
985 /// **Note**: Do not use directly. Call `PingType::set_enabled` instead.
986 #[doc(hidden)]
987 pub fn set_ping_enabled(&mut self, ping: &PingType, enabled: bool) {
988 ping.store_enabled(enabled);
989 if !enabled {
990 if let Some(data) = self.data_store.as_ref() {
991 _ = data.clear_ping_lifetime_storage(ping.name());
992 _ = data.clear_lifetime_storage(Lifetime::User, ping.name());
993 _ = data.clear_lifetime_storage(Lifetime::Application, ping.name());
994 }
995 if let Err(err) = self.event_storage().clear_for_ping(ping.name()) {
996 log::warn!("Error clearing event storage for ping: {}", err);
997 }
998
999 let ping_maker = PingMaker::new();
1000 let disabled_pings = &[ping.name()][..];
1001 if let Err(err) = ping_maker.clear_pending_pings(self.get_data_path(), disabled_pings) {
1002 log::warn!("Error clearing pending pings: {}", err);
1003 }
1004 }
1005 }
1006
1007 /// Determines whether upload is enabled.
1008 ///
1009 /// When upload is disabled, no data will be recorded.
1010 pub fn is_upload_enabled(&self) -> bool {
1011 self.upload_enabled
1012 }
1013
1014 /// Check if a ping is enabled.
1015 ///
1016 /// Note that some internal "ping" names are considered to be always enabled.
1017 ///
1018 /// If a ping is not known to Glean ("unregistered") it is always considered disabled.
1019 /// If a ping is known, it can be enabled/disabled at any point.
1020 /// Only data for enabled pings is recorded.
1021 /// Disabled pings are never submitted.
1022 pub fn is_ping_enabled(&self, ping: &str) -> bool {
1023 // We "abuse" pings/storage names for internal data.
1024 const DEFAULT_ENABLED: &[&str] = &[
1025 "glean_client_info",
1026 "glean_internal_info",
1027 // for `experimentation_id`.
1028 // That should probably have gone into `glean_internal_info` instead.
1029 "all-pings",
1030 ];
1031
1032 // `client_info`-like stuff is always enabled.
1033 if DEFAULT_ENABLED.contains(&ping) {
1034 return true;
1035 }
1036
1037 let Some(ping) = self.ping_registry.get(ping) else {
1038 log::trace!("Unknown ping {ping}. Assuming disabled.");
1039 return false;
1040 };
1041
1042 ping.enabled(self)
1043 }
1044
1045 /// Handles the changing of state from upload disabled to enabled.
1046 ///
1047 /// Should only be called when the state actually changes.
1048 ///
1049 /// The `upload_enabled` flag is set to true and the core Glean metrics are
1050 /// recreated.
1051 fn on_upload_enabled(&mut self) {
1052 self.upload_enabled = true;
1053 self.initialize_core_metrics();
1054 self.initialize_database_metrics();
1055 }
1056
1057 /// Handles the changing of state from upload enabled to disabled.
1058 ///
1059 /// Should only be called when the state actually changes.
1060 ///
1061 /// A deletion_request ping is sent, all pending metrics, events and queued
1062 /// pings are cleared, and the client_id is set to KNOWN_CLIENT_ID.
1063 /// Afterward, the upload_enabled flag is set to false.
1064 fn on_upload_disabled(&mut self, during_init: bool) {
1065 // The upload_enabled flag should be true here, or the deletion ping
1066 // won't be submitted.
1067 let reason = if during_init {
1068 Some("at_init")
1069 } else {
1070 Some("set_upload_enabled")
1071 };
1072 if !self
1073 .internal_pings
1074 .deletion_request
1075 .submit_sync(self, reason)
1076 {
1077 log::error!("Failed to submit deletion-request ping on optout.");
1078 }
1079 self.clear_metrics();
1080 self.upload_enabled = false;
1081 }
1082
1083 /// Clear any pending metrics when telemetry is disabled.
1084 fn clear_metrics(&mut self) {
1085 // Clear the pending pings queue and acquire the lock
1086 // so that it can't be accessed until this function is done.
1087 let _lock = self.upload_manager.clear_ping_queue();
1088
1089 // Clear any pending pings that follow `collection_enabled`.
1090 let ping_maker = PingMaker::new();
1091 let disabled_pings = self
1092 .ping_registry
1093 .iter()
1094 .filter(|&(_ping_name, ping)| ping.follows_collection_enabled())
1095 .map(|(ping_name, _ping)| &ping_name[..])
1096 .collect::<Vec<_>>();
1097 if let Err(err) = ping_maker.clear_pending_pings(self.get_data_path(), &disabled_pings) {
1098 log::warn!("Error clearing pending pings: {}", err);
1099 }
1100
1101 if let Err(e) = self.remove_stored_client_id() {
1102 log::error!("Couldn't remove client ID on disk. This might lead to a resurrection of this client ID later. Error: {e}");
1103 }
1104 if let Some(backup) = self.backup.as_ref() {
1105 backup.clear_all();
1106 }
1107
1108 // Delete all stored metrics.
1109 // Note that this also includes the ping sequence numbers, so it has
1110 // the effect of resetting those to their initial values.
1111 if let Some(data) = self.data_store.as_ref() {
1112 let warn_on_error = |result, msg| {
1113 if let Err(e) = result {
1114 log::warn!("{msg}: {e}");
1115 }
1116 };
1117
1118 warn_on_error(
1119 data.clear_lifetime_storage(Lifetime::User, INTERNAL_STORAGE),
1120 "failed to clear internal storage",
1121 );
1122 warn_on_error(
1123 data.remove_single_metric(Lifetime::User, "glean_client_info", "client_id"),
1124 "failed to clear internal client info storage",
1125 );
1126 for (ping_name, ping) in &self.ping_registry {
1127 if ping.follows_collection_enabled() {
1128 warn_on_error(
1129 data.clear_ping_lifetime_storage(ping_name),
1130 "failed to clear ping lifetime storage",
1131 );
1132 warn_on_error(
1133 data.clear_lifetime_storage(Lifetime::User, ping_name),
1134 "failed to clear user lifetime storage",
1135 );
1136 warn_on_error(
1137 data.clear_lifetime_storage(Lifetime::Application, ping_name),
1138 "failed to clear application lifetime storage",
1139 );
1140 }
1141 }
1142 }
1143 if let Err(err) = self.event_data_store.clear_all() {
1144 log::warn!("Error clearing pending events: {}", err);
1145 }
1146
1147 // The persisted `session#*` keys were cleared with internal storage above.
1148 // Reset the in-memory session state to match, so a later opt-in can't
1149 // continue the pre-opt-out session. No `session_end` is recorded, since
1150 // upload is being disabled.
1151 self.session_manager = SessionManager::new(
1152 self.session_manager.mode,
1153 self.session_manager.configured_sample_rate,
1154 self.session_manager.inactivity_timeout,
1155 );
1156
1157 // Persisted flow state was cleared with internal storage above. Reset the
1158 // in-memory state to match, recording no `flow_end`.
1159 *self.flow_state.lock().unwrap() = FlowState::default();
1160
1161 // This does not clear the experiments store (which isn't managed by the
1162 // StorageEngineManager), since doing so would mean we would have to have the
1163 // application tell us again which experiments are active if telemetry is
1164 // re-enabled.
1165 }
1166
1167 /// Gets the application ID as specified on instantiation.
1168 pub fn get_application_id(&self) -> &str {
1169 &self.application_id
1170 }
1171
1172 /// Gets the data path of this instance.
1173 pub fn get_data_path(&self) -> &Path {
1174 &self.data_path
1175 }
1176
1177 /// Gets a handle to the database.
1178 #[track_caller] // If this fails we're interested in the caller.
1179 pub fn storage(&self) -> &Database {
1180 self.data_store.as_ref().expect("No database found")
1181 }
1182
1183 /// Gets an optional handle to the database.
1184 pub fn storage_opt(&self) -> Option<&Database> {
1185 self.data_store.as_ref()
1186 }
1187
1188 /// Gets a handle to the event database.
1189 pub fn event_storage(&self) -> &EventDatabase {
1190 &self.event_data_store
1191 }
1192
1193 /// Gets a reference to the session manager.
1194 pub fn session_manager(&self) -> &SessionManager {
1195 &self.session_manager
1196 }
1197
1198 pub(crate) fn with_timestamps(&self) -> bool {
1199 self.with_timestamps
1200 }
1201
1202 /// Gets the maximum number of events to store before sending a ping.
1203 pub fn get_max_events(&self) -> usize {
1204 let remote_settings_config = self.remote_settings_config.lock().unwrap();
1205
1206 if let Some(max_events) = remote_settings_config.event_threshold {
1207 max_events as usize
1208 } else {
1209 self.max_events as usize
1210 }
1211 }
1212
1213 /// Gets the number of "events" pings to accelerate each session, plus one.
1214 pub fn get_events_ping_acceleration_factor(&self) -> usize {
1215 let remote_settings_config = self.remote_settings_config.lock().unwrap();
1216
1217 if let Some(factor) = remote_settings_config.events_ping_acceleration_factor {
1218 factor
1219 } else {
1220 self.events_ping_acceleration_factor.unwrap_or(1)
1221 }
1222 }
1223
1224 /// Gets the next task for an uploader.
1225 ///
1226 /// This can be one of:
1227 ///
1228 /// * [`Wait`](PingUploadTask::Wait) - which means the requester should ask
1229 /// again later;
1230 /// * [`Upload(PingRequest)`](PingUploadTask::Upload) - which means there is
1231 /// a ping to upload. This wraps the actual request object;
1232 /// * [`Done`](PingUploadTask::Done) - which means requester should stop
1233 /// asking for now.
1234 ///
1235 /// # Returns
1236 ///
1237 /// A [`PingUploadTask`] representing the next task.
1238 pub fn get_upload_task(&self) -> PingUploadTask {
1239 self.upload_manager.get_upload_task(self, self.log_pings())
1240 }
1241
1242 /// Processes the response from an attempt to upload a ping.
1243 ///
1244 /// # Arguments
1245 ///
1246 /// * `uuid` - The UUID of the ping in question.
1247 /// * `status` - The upload result.
1248 pub fn process_ping_upload_response(
1249 &self,
1250 uuid: &str,
1251 status: UploadResult,
1252 ) -> UploadTaskAction {
1253 self.upload_manager
1254 .process_ping_upload_response(self, uuid, status)
1255 }
1256
1257 /// Takes a snapshot for the given store and optionally clear it.
1258 ///
1259 /// # Arguments
1260 ///
1261 /// * `store_name` - The store to snapshot.
1262 /// * `clear_store` - Whether to clear the store after snapshotting.
1263 ///
1264 /// # Returns
1265 ///
1266 /// The snapshot in a string encoded as JSON. If the snapshot is empty, returns an empty string.
1267 pub fn snapshot(&mut self, store_name: &str, clear_store: bool) -> String {
1268 StorageManager
1269 .snapshot(self.storage(), store_name, clear_store)
1270 .unwrap_or_else(|| String::from(""))
1271 }
1272
1273 pub(crate) fn make_path(&self, ping_name: &str, doc_id: &str) -> String {
1274 format!(
1275 "/submit/{}/{}/{}/{}",
1276 self.get_application_id(),
1277 ping_name,
1278 GLEAN_SCHEMA_VERSION,
1279 doc_id
1280 )
1281 }
1282
1283 /// Collects and submits a ping by name for eventual uploading.
1284 ///
1285 /// The ping content is assembled as soon as possible, but upload is not
1286 /// guaranteed to happen immediately, as that depends on the upload policies.
1287 ///
1288 /// If the ping currently contains no content, it will not be sent,
1289 /// unless it is configured to be sent if empty.
1290 ///
1291 /// # Arguments
1292 ///
1293 /// * `ping_name` - The name of the ping to submit
1294 /// * `reason` - A reason code to include in the ping
1295 ///
1296 /// # Returns
1297 ///
1298 /// Whether the ping was succesfully assembled and queued.
1299 ///
1300 /// # Errors
1301 ///
1302 /// If collecting or writing the ping to disk failed.
1303 pub fn submit_ping_by_name(&self, ping_name: &str, reason: Option<&str>) -> bool {
1304 match self.get_ping_by_name(ping_name) {
1305 None => {
1306 log::error!("Attempted to submit unknown ping '{}'", ping_name);
1307 false
1308 }
1309 Some(ping) => ping.submit_sync(self, reason),
1310 }
1311 }
1312
1313 /// Gets a [`PingType`] by name.
1314 ///
1315 /// # Returns
1316 ///
1317 /// The [`PingType`] of a ping if the given name was registered before, [`None`]
1318 /// otherwise.
1319 pub fn get_ping_by_name(&self, ping_name: &str) -> Option<&PingType> {
1320 self.ping_registry.get(ping_name)
1321 }
1322
1323 /// Register a new [`PingType`](metrics/struct.PingType.html).
1324 pub fn register_ping_type(&mut self, ping: &PingType) {
1325 if self.ping_registry.contains_key(ping.name()) {
1326 log::debug!("Duplicate ping named '{}'", ping.name())
1327 }
1328
1329 self.ping_registry
1330 .insert(ping.name().to_string(), ping.clone());
1331 }
1332
1333 /// Gets a list of currently registered ping names.
1334 ///
1335 /// # Returns
1336 ///
1337 /// The list of ping names that are currently registered.
1338 pub fn get_registered_ping_names(&self) -> Vec<&str> {
1339 self.ping_registry.keys().map(String::as_str).collect()
1340 }
1341
1342 /// Get create time of the Glean object.
1343 pub(crate) fn start_time(&self) -> DateTime<FixedOffset> {
1344 self.start_time
1345 }
1346
1347 /// Indicates that an experiment is running.
1348 ///
1349 /// Glean will then add an experiment annotation to the environment
1350 /// which is sent with pings. This information is not persisted between runs.
1351 ///
1352 /// # Arguments
1353 ///
1354 /// * `experiment_id` - The id of the active experiment (maximum 30 bytes).
1355 /// * `branch` - The experiment branch (maximum 30 bytes).
1356 /// * `extra` - Optional metadata to output with the ping.
1357 pub fn set_experiment_active(
1358 &self,
1359 experiment_id: String,
1360 branch: String,
1361 extra: HashMap<String, String>,
1362 ) {
1363 let metric = ExperimentMetric::new(self, experiment_id);
1364 metric.set_active_sync(self, branch, extra);
1365 }
1366
1367 /// Indicates that an experiment is no longer running.
1368 ///
1369 /// # Arguments
1370 ///
1371 /// * `experiment_id` - The id of the active experiment to deactivate (maximum 30 bytes).
1372 pub fn set_experiment_inactive(&self, experiment_id: String) {
1373 let metric = ExperimentMetric::new(self, experiment_id);
1374 metric.set_inactive_sync(self);
1375 }
1376
1377 /// **Test-only API (exported for FFI purposes).**
1378 ///
1379 /// Gets stored data for the requested experiment.
1380 ///
1381 /// # Arguments
1382 ///
1383 /// * `experiment_id` - The id of the active experiment (maximum 30 bytes).
1384 pub fn test_get_experiment_data(&self, experiment_id: String) -> Option<RecordedExperiment> {
1385 let metric = ExperimentMetric::new(self, experiment_id);
1386 metric.test_get_value(self)
1387 }
1388
1389 /// **Test-only API (exported for FFI purposes).**
1390 ///
1391 /// Gets stored experimentation id annotation.
1392 pub fn test_get_experimentation_id(&self) -> Option<String> {
1393 self.additional_metrics
1394 .experimentation_id
1395 .get_value(self, None)
1396 }
1397
1398 /// Set configuration to override the default state, typically initiated from a
1399 /// remote_settings experiment or rollout
1400 ///
1401 /// # Arguments
1402 ///
1403 /// * `cfg` - The stringified JSON representation of a `RemoteSettingsConfig` object
1404 pub fn apply_server_knobs_config(&self, cfg: RemoteSettingsConfig) {
1405 let config_value = {
1406 // Hold the lock while merging config and serializing, then release
1407 // before performing IO in set_sync.
1408 let mut remote_settings_config = self.remote_settings_config.lock().unwrap();
1409
1410 // Merge the exising metrics configuration with the supplied one
1411 remote_settings_config
1412 .metrics_enabled
1413 .extend(cfg.metrics_enabled);
1414
1415 // Merge the exising ping configuration with the supplied one
1416 remote_settings_config
1417 .pings_enabled
1418 .extend(cfg.pings_enabled);
1419
1420 remote_settings_config.event_threshold = cfg.event_threshold;
1421
1422 // Clamp to [0.0, 1.0] so callers can't accidentally set an invalid rate.
1423 //
1424 // NOTE: `session_sample_rate` is intentionally NOT applied to any
1425 // currently-active session. The override is picked up at the next
1426 // `session_start()` call. This "sticky per session" design means:
1427 // - A mid-session RS rollout does not change sampling mid-flight,
1428 // which would otherwise cause partial session data.
1429 // - To clear the override and revert to the configured rate, set
1430 // `session_sample_rate` to `null` in the RS payload. The next
1431 // session will use `configured_sample_rate` as the fallback.
1432 //
1433 // This override is intentionally NOT persisted to storage. Remote
1434 // Settings configuration is refreshed on every app startup, so the
1435 // override will be re-applied before the next session begins.
1436 // Persisting it would risk making a stale value sticky if the RS
1437 // payload changes or is removed between restarts.
1438 remote_settings_config.session_sample_rate = cfg.session_sample_rate.map(|r| {
1439 let clamped = r.clamp(0.0, 1.0);
1440 if clamped != r {
1441 log::warn!(
1442 "session_sample_rate {} out of range, clamped to {}",
1443 r,
1444 clamped
1445 );
1446 }
1447 clamped
1448 });
1449
1450 remote_settings_config.events_ping_acceleration_factor =
1451 cfg.events_ping_acceleration_factor;
1452
1453 // Store the Server Knobs configuration as an ObjectMetric
1454 // Since RemoteSettingsConfig only contains maps with string keys and primitives,
1455 // serialization via the derived Serialize impl cannot fail so it is safe to unwrap.
1456 serde_json::to_value(&*remote_settings_config).unwrap()
1457 };
1458
1459 self.additional_metrics
1460 .server_knobs_config
1461 .set_sync(self, config_value);
1462
1463 // Update remote_settings epoch
1464 self.remote_settings_epoch.fetch_add(1, Ordering::SeqCst);
1465 }
1466
1467 /// Persists [`Lifetime::Ping`] data that might be in memory in case
1468 /// [`delay_ping_lifetime_io`](InternalConfiguration::delay_ping_lifetime_io) is set
1469 /// or was set at a previous time.
1470 ///
1471 /// If there is no data to persist, this function does nothing.
1472 pub fn persist_ping_lifetime_data(&self) -> Result<()> {
1473 if let Some(data) = self.data_store.as_ref() {
1474 return data.persist_ping_lifetime_data();
1475 }
1476
1477 Ok(())
1478 }
1479
1480 /// Set early metrics unconditionally.
1481 ///
1482 /// This covers e.g. the `first_run_date` and application lifetime metrics known at build time.
1483 fn set_early_metrics(&mut self) {
1484 // We set the first_run_date unconditionally nowadays
1485 if self
1486 .core_metrics
1487 .first_run_date
1488 .get_value(self, "glean_client_info")
1489 .is_none()
1490 {
1491 self.core_metrics.first_run_date.set_sync(self, None);
1492 // The `first_run_date` field is generated on the very first run
1493 // and persisted across upload toggling. We can assume that, the only
1494 // time it is set, that's indeed our "first run".
1495 self.is_first_run = true;
1496 }
1497 self.set_application_lifetime_core_metrics();
1498 }
1499
1500 /// Sets internally-handled application lifetime metrics.
1501 fn set_application_lifetime_core_metrics(&self) {
1502 self.core_metrics.os.set_sync(self, system::OS);
1503 }
1504
1505 /// **This is not meant to be used directly.**
1506 ///
1507 /// Clears all the metrics that have [`Lifetime::Application`].
1508 pub fn clear_application_lifetime_metrics(&self) {
1509 log::trace!("Clearing Lifetime::Application metrics");
1510 if let Some(data) = self.data_store.as_ref() {
1511 data.clear_lifetime(Lifetime::Application);
1512 }
1513
1514 // Set internally handled app lifetime metrics again.
1515 self.set_application_lifetime_core_metrics();
1516 }
1517
1518 /// Whether or not this is the first run on this profile.
1519 pub fn is_first_run(&self) -> bool {
1520 self.is_first_run
1521 }
1522
1523 /// Sets a debug view tag.
1524 ///
1525 /// This will return `false` in case `value` is not a valid tag.
1526 ///
1527 /// When the debug view tag is set, pings are sent with a `X-Debug-ID` header with the value of the tag
1528 /// and are sent to the ["Ping Debug Viewer"](https://mozilla.github.io/glean/book/dev/core/internal/debug-pings.html).
1529 ///
1530 /// # Arguments
1531 ///
1532 /// * `value` - A valid HTTP header value. Must match the regex: "[a-zA-Z0-9-]{1,20}".
1533 pub fn set_debug_view_tag(&mut self, value: &str) -> bool {
1534 self.debug.debug_view_tag.set(value.into())
1535 }
1536
1537 /// Return the value for the debug view tag or [`None`] if it hasn't been set.
1538 ///
1539 /// The `debug_view_tag` may be set from an environment variable
1540 /// (`GLEAN_DEBUG_VIEW_TAG`) or through the [`set_debug_view_tag`](Glean::set_debug_view_tag) function.
1541 pub fn debug_view_tag(&self) -> Option<&String> {
1542 self.debug.debug_view_tag.get()
1543 }
1544
1545 /// Sets source tags.
1546 ///
1547 /// This will return `false` in case `value` contains invalid tags.
1548 ///
1549 /// Ping tags will show in the destination datasets, after ingestion.
1550 ///
1551 /// **Note** If one or more tags are invalid, all tags are ignored.
1552 ///
1553 /// # Arguments
1554 ///
1555 /// * `value` - A vector of at most 5 valid HTTP header values. Individual tags must match the regex: "[a-zA-Z0-9-]{1,20}".
1556 pub fn set_source_tags(&mut self, value: Vec<String>) -> bool {
1557 self.debug.source_tags.set(value)
1558 }
1559
1560 /// Return the value for the source tags or [`None`] if it hasn't been set.
1561 ///
1562 /// The `source_tags` may be set from an environment variable (`GLEAN_SOURCE_TAGS`)
1563 /// or through the [`set_source_tags`](Glean::set_source_tags) function.
1564 pub(crate) fn source_tags(&self) -> Option<&Vec<String>> {
1565 self.debug.source_tags.get()
1566 }
1567
1568 /// Sets the log pings debug option.
1569 ///
1570 /// This will return `false` in case we are unable to set the option.
1571 ///
1572 /// When the log pings debug option is `true`,
1573 /// we log the payload of all succesfully assembled pings.
1574 ///
1575 /// # Arguments
1576 ///
1577 /// * `value` - The value of the log pings option
1578 pub fn set_log_pings(&mut self, value: bool) -> bool {
1579 self.debug.log_pings.set(value)
1580 }
1581
1582 /// Return the value for the log pings debug option or `false` if it hasn't been set.
1583 ///
1584 /// The `log_pings` option may be set from an environment variable (`GLEAN_LOG_PINGS`)
1585 /// or through the `set_log_pings` function.
1586 pub fn log_pings(&self) -> bool {
1587 self.debug.log_pings.get().copied().unwrap_or(false)
1588 }
1589
1590 fn get_dirty_bit_metric(&self) -> metrics::BooleanMetric {
1591 metrics::BooleanMetric::new(CommonMetricData {
1592 name: "dirtybit".into(),
1593 // We don't need a category, the name is already unique
1594 category: "".into(),
1595 send_in_pings: vec![INTERNAL_STORAGE.into()],
1596 lifetime: Lifetime::User,
1597 ..Default::default()
1598 })
1599 }
1600
1601 /// **This is not meant to be used directly.**
1602 ///
1603 /// Sets the value of a "dirty flag" in the permanent storage.
1604 ///
1605 /// The "dirty flag" is meant to have the following behaviour, implemented
1606 /// by the consumers of the FFI layer:
1607 ///
1608 /// - on mobile: set to `false` when going to background or shutting down,
1609 /// set to `true` at startup and when going to foreground.
1610 /// - on non-mobile platforms: set to `true` at startup and `false` at
1611 /// shutdown.
1612 ///
1613 /// At startup, before setting its new value, if the "dirty flag" value is
1614 /// `true`, then Glean knows it did not exit cleanly and can implement
1615 /// coping mechanisms (e.g. sending a `baseline` ping).
1616 pub fn set_dirty_flag(&self, new_value: bool) {
1617 self.get_dirty_bit_metric().set_sync(self, new_value);
1618 }
1619
1620 /// **This is not meant to be used directly.**
1621 ///
1622 /// Checks the stored value of the "dirty flag".
1623 pub fn is_dirty_flag_set(&self) -> bool {
1624 let dirty_bit_metric = self.get_dirty_bit_metric();
1625 match self.storage().get_metric(
1626 #[cfg(not(feature = "sqlite"))]
1627 self,
1628 dirty_bit_metric.meta(),
1629 INTERNAL_STORAGE,
1630 ) {
1631 Some(Metric::Boolean(b)) => b,
1632 _ => false,
1633 }
1634 }
1635
1636 // -----------------------------------------------------------------------
1637 // Session lifecycle methods
1638 // -----------------------------------------------------------------------
1639
1640 /// Restores session state from persistent storage at startup.
1641 ///
1642 /// Must be called after `data_store` is initialized (i.e. after
1643 /// `Database::new` succeeds) so that the storage reads are valid.
1644 ///
1645 /// **Sequence counter**: `session_seq` is always restored so it is
1646 /// monotonically increasing across restarts. Note that if a crash occurs
1647 /// between `store_session_seq` and `persist_session_id` inside
1648 /// `session_start`, the sequence number will have been incremented but no
1649 /// session ID will be persisted. On the next restart this method will
1650 /// restore the incremented seq and the next session will be assigned
1651 /// seq+1, leaving a one-element gap. This is acceptable — downstream
1652 /// analysts should treat sequence numbers as monotonically non-decreasing,
1653 /// not strictly contiguous.
1654 ///
1655 /// **AUTO mode resumption**: requires both a persisted `session_id` **and**
1656 /// an `inactive_since` timestamp. If either is absent the previous session
1657 /// is considered abandoned and the next `handle_client_active` call will
1658 /// start a fresh session via `session_start()`. On a crash restart,
1659 /// `recover_session_on_dirty_flag()` overwrites whatever this method
1660 /// restores, so the dirty-flag path is always authoritative.
1661 fn restore_session_state_from_storage(&mut self) {
1662 // Always restore seq so new sessions increment from the last known value.
1663 self.session_manager.session_seq = session::read_session_seq(self);
1664
1665 // Check for an orphaned session from a previous build that used a
1666 // different SessionMode. If the current mode would not restore the
1667 // persisted session, emit a synthetic session_end("abandoned") and
1668 // clear all persisted session state so it doesn't leak across builds.
1669 if self.session_manager.mode != SessionMode::Auto {
1670 // The abandoned session's flow instances end with it, before its
1671 // `session_end`, as on a crash.
1672 flows::recover_abnormal(self);
1673 if let Some(id_str) = session::read_session_id(self) {
1674 log::info!(
1675 "Orphaned session {} found from a previous Auto-mode build; \
1676 emitting session_end(\"abandoned\") and clearing storage",
1677 id_str
1678 );
1679 let seq = self.session_manager.session_seq;
1680 self.record_session_end_event(&id_str, seq, Some("abandoned"));
1681 session::clear(self);
1682 }
1683 return;
1684 }
1685
1686 // AUTO mode: restore inactive session state so inactivity timeout
1687 // evaluation can happen lazily on the next handle_client_active call.
1688 if let Some(inactive_since) = session::read_inactive_since(self) {
1689 if let Some(id_str) = session::read_session_id(self) {
1690 if let Ok(id) = Uuid::parse_str(&id_str) {
1691 // Recompute sampled_in deterministically from the UUID so
1692 // the sampling decision is consistent across the resumed session.
1693 let sampled_in = session::uuid_to_sample_value(&id)
1694 < self.session_manager.configured_sample_rate;
1695 self.session_manager.session_id = Some(id);
1696 self.session_manager.inactive_since = Some(inactive_since);
1697 self.session_manager.sampled_in = sampled_in;
1698 self.session_manager.session_start_time =
1699 session::read_session_start_time(self);
1700 if self.session_manager.session_start_time.is_none() {
1701 log::warn!(
1702 "Resumed session {} has no persisted session_start_time; \
1703 events in this session will carry session_start_time: null",
1704 id
1705 );
1706 }
1707 // Restore event_seq so the resumed session issues
1708 // monotonically increasing sequence numbers even across
1709 // a clean restart.
1710 self.session_manager
1711 .event_seq
1712 .store(session::read_session_event_seq(self), Ordering::Relaxed);
1713 self.session_manager.state = SessionState::Inactive;
1714 self.restore_flow_state(&id_str);
1715 return;
1716 }
1717 }
1718 }
1719
1720 // No session was resumed, so no persisted flow instance can be either.
1721 // After a crash, `recover_session_on_dirty_flag()` still needs them.
1722 if !self.is_dirty_flag_set() {
1723 flows::discard_persisted(self);
1724 }
1725 }
1726
1727 /// Restores the resumed session's flow instances, closing any that expired
1728 /// while the app was not running.
1729 ///
1730 /// Skipped after a crash, where `recover_session_on_dirty_flag()` closes
1731 /// them with `reason: abnormal` instead.
1732 fn restore_flow_state(&mut self, session_id: &str) {
1733 if self.is_dirty_flag_set() {
1734 return;
1735 }
1736 flows::restore(self, session_id);
1737
1738 // Close expired instances now, in the session that owns them. As in the
1739 // timeout path of `session_transition_to_active()`, the session is marked
1740 // active just long enough to record in it.
1741 let event_seq_before = self.session_manager.event_seq.load(Ordering::Relaxed);
1742 self.session_manager.state = SessionState::Active;
1743 flows::close_all_expired(self);
1744 self.session_manager.state = SessionState::Inactive;
1745
1746 // Persist any `event_seq` consumed by a `flow_end`, so a crash before the
1747 // next inactive transition doesn't reuse it.
1748 let event_seq = self.session_manager.event_seq.load(Ordering::Relaxed);
1749 if event_seq != event_seq_before {
1750 session::store_session_event_seq(self, event_seq);
1751 }
1752 }
1753
1754 /// Injects a `glean_timestamp` key into `extra` when event timestamps are enabled.
1755 ///
1756 /// Uses the wall clock, matching `EventMetric::record`. The event's main
1757 /// `timestamp` stays on the monotonic clock.
1758 pub(crate) fn maybe_inject_glean_timestamp(
1759 &self,
1760 extra: &mut std::collections::HashMap<String, String>,
1761 ) {
1762 if self.with_timestamps {
1763 let precise_timestamp = Utc::now().timestamp_millis() as u64;
1764 extra.insert("glean_timestamp".to_string(), precise_timestamp.to_string());
1765 }
1766 }
1767
1768 /// Records a `glean.session_start` boundary event (always, regardless of sampling).
1769 fn record_session_start_event(
1770 &self,
1771 session_id: &str,
1772 seq: u64,
1773 start_time: DateTime<FixedOffset>,
1774 sampled_in: bool,
1775 ) {
1776 let meta = CommonMetricData {
1777 name: "session_start".into(),
1778 category: "glean".into(),
1779 send_in_pings: vec!["events".into()],
1780 lifetime: Lifetime::Ping,
1781 ..Default::default()
1782 };
1783 let timestamp = crate::get_timestamp_ms();
1784 let mut extra = std::collections::HashMap::new();
1785 extra.insert("session_id".to_string(), session_id.to_string());
1786 extra.insert("session_seq".to_string(), seq.to_string());
1787 extra.insert(
1788 "session_start_time".to_string(),
1789 start_time.to_rfc3339_opts(SecondsFormat::Millis, true),
1790 );
1791 extra.insert("sampled_in".to_string(), sampled_in.to_string());
1792 self.maybe_inject_glean_timestamp(&mut extra);
1793 self.event_data_store.record(
1794 self,
1795 &meta.into(),
1796 timestamp,
1797 Some(extra),
1798 EventSessionContext::OutOfSession,
1799 Vec::new(),
1800 );
1801 }
1802
1803 /// Records a `glean.session_end` boundary event (always, regardless of sampling).
1804 fn record_session_end_event(&self, session_id: &str, seq: u64, reason: Option<&str>) {
1805 let meta = CommonMetricData {
1806 name: "session_end".into(),
1807 category: "glean".into(),
1808 send_in_pings: vec!["events".into()],
1809 lifetime: Lifetime::Ping,
1810 ..Default::default()
1811 };
1812 let timestamp = crate::get_timestamp_ms();
1813 let mut extra = std::collections::HashMap::new();
1814 extra.insert("session_id".to_string(), session_id.to_string());
1815 extra.insert("session_seq".to_string(), seq.to_string());
1816 if let Some(r) = reason {
1817 extra.insert("reason".to_string(), r.to_string());
1818 }
1819 self.maybe_inject_glean_timestamp(&mut extra);
1820 self.event_data_store.record(
1821 self,
1822 &meta.into(),
1823 timestamp,
1824 Some(extra),
1825 EventSessionContext::OutOfSession,
1826 Vec::new(),
1827 );
1828 }
1829
1830 /// Starts a new session, persists state, and records a boundary event.
1831 ///
1832 /// If a session is already active it is ended cleanly before the new one
1833 /// starts, preventing orphaned sessions with no corresponding `session_end`.
1834 pub fn session_start(&mut self) {
1835 // End any already-active session so we never orphan a session_end event.
1836 if self.session_manager.is_active() {
1837 self.session_end(Some("replaced"));
1838 }
1839
1840 // 1. Compute new seq from in-memory value (authoritative after init).
1841 let new_seq = self.session_manager.session_seq + 1;
1842
1843 // 2. Generate new session_id and compute sampling.
1844 // Prefer a remote-settings override if one has been set, falling back
1845 // to the immutable configured_sample_rate (never the last effective
1846 // rate) so RS overrides can be fully cleared without residual effects.
1847 // The rate is sampled once here and is sticky for the entire session;
1848 // any RS update received mid-session takes effect at the next session_start.
1849 let session_id = uuid::Uuid::new_v4();
1850 let sample_rate = {
1851 let remote = self.remote_settings_config.lock().unwrap();
1852 remote
1853 .session_sample_rate
1854 .unwrap_or(self.session_manager.configured_sample_rate)
1855 };
1856 let sampled_in = session::uuid_to_sample_value(&session_id) < sample_rate;
1857
1858 // 3. Update in-memory state.
1859 self.session_manager.sample_rate = sample_rate;
1860 // Truncate to millisecond precision so that in-memory and persisted
1861 // (RFC 3339 millis) representations are identical after a round-trip.
1862 let start_time = {
1863 let now = local_now_with_offset();
1864 let millis = now.timestamp_millis();
1865 DateTime::from_timestamp_millis(millis)
1866 .expect("valid timestamp")
1867 .with_timezone(now.offset())
1868 };
1869 self.session_manager.session_start_time = Some(start_time);
1870 self.session_manager.session_id = Some(session_id);
1871 self.session_manager.session_seq = new_seq;
1872 self.session_manager.event_seq.store(0, Ordering::Relaxed);
1873 self.session_manager.sampled_in = sampled_in;
1874 self.session_manager.state = SessionState::Active;
1875 self.session_manager.inactive_since = None;
1876 flows::reset_for_new_session(self);
1877
1878 // 4. Persist to storage.
1879 session::store_session_seq(self, new_seq);
1880 session::persist_session_id(self, &session_id.to_string());
1881 session::persist_session_start_time(self, start_time);
1882 session::clear_inactive_since(self);
1883
1884 // 5. Increment diagnostic counter.
1885 self.additional_metrics.sessions_seen.add_sync(self, 1);
1886
1887 // 6. Record boundary event.
1888 self.record_session_start_event(&session_id.to_string(), new_seq, start_time, sampled_in);
1889 }
1890
1891 /// Ends the current session, persists state, and records a boundary event.
1892 ///
1893 /// Returns the ended session's metadata, or `None` if no session was active.
1894 pub fn session_end(&mut self, reason: Option<&str>) -> Option<crate::session::SessionMetadata> {
1895 if self.session_manager.state != SessionState::Active {
1896 return None;
1897 }
1898
1899 let session_id = self.session_manager.session_id?;
1900
1901 // Close every active flow instance first, while this session is still
1902 // current, so each `glean.flow_end` is recorded in-session and takes a
1903 // `session.event_seq` from the session that owns the instance.
1904 flows::close_all_at_session_end(self);
1905
1906 let seq = self.session_manager.session_seq;
1907 let event_seq = self.session_manager.event_seq.load(Ordering::Relaxed);
1908 let sample_rate = self.session_manager.sample_rate;
1909 let start_time = self.session_manager.session_start_time;
1910
1911 // Clear persistence.
1912 session::clear(self);
1913
1914 // Reset in-memory state so the next session_start gets a clean slate.
1915 self.session_manager.reset_state();
1916
1917 // Record boundary event.
1918 self.record_session_end_event(&session_id.to_string(), seq, reason);
1919
1920 Some(crate::session::SessionMetadata {
1921 session_id: session_id.to_string(),
1922 session_seq: seq,
1923 event_seq,
1924 session_sample_rate: sample_rate,
1925 session_start_time: start_time.map(|t| t.to_rfc3339_opts(SecondsFormat::Millis, true)),
1926 })
1927 }
1928
1929 /// Transitions the current session to inactive (AUTO mode).
1930 ///
1931 /// Records the `inactive_since` timestamp for timeout evaluation on next activation.
1932 /// Does NOT end the session — that happens lazily on next `handle_client_active`.
1933 pub(crate) fn session_transition_to_inactive(&mut self) {
1934 if self.session_manager.state != SessionState::Active {
1935 return;
1936 }
1937
1938 let now = local_now_with_offset();
1939 // Snapshot event_seq before changing state so the value is stable.
1940 let event_seq = self.session_manager.event_seq.load(Ordering::Relaxed);
1941 self.session_manager.state = SessionState::Inactive;
1942 self.session_manager.inactive_since = Some(now);
1943
1944 // Persist for crash recovery and clean-restart resumption.
1945 // event_seq is persisted here (rather than on every increment) because
1946 // this is the only point where events stop being recorded mid-session;
1947 // if the app crashes before the next activation, the recovered session
1948 // will at least have the correct seq baseline from the last inactive
1949 // transition.
1950 session::persist_inactive_since(self, now);
1951 session::store_session_event_seq(self, event_seq);
1952 }
1953
1954 /// Handles transitioning from inactive to active (AUTO mode).
1955 ///
1956 /// Evaluates the inactivity timeout:
1957 /// - If the timeout has NOT expired: resume the existing session.
1958 /// - If the timeout HAS expired: end the old session and start a new one.
1959 ///
1960 /// Returns `true` if a new session was started.
1961 pub(crate) fn session_transition_to_active(&mut self) -> bool {
1962 match self.session_manager.inactive_since {
1963 None => {
1964 // No inactive_since recorded: treat as a cold activation and start
1965 // a fresh session. The call site in handle_client_active guards
1966 // with `inactive_since.is_some()` so this is normally unreachable,
1967 // but we handle it safely rather than leaving state inconsistent.
1968 self.session_start();
1969 true
1970 }
1971 Some(inactive_since) => {
1972 let now = local_now_with_offset();
1973 let elapsed = (now - inactive_since).to_std().unwrap_or_default();
1974
1975 // A timeout of zero means "never time out" (session always resumes).
1976 if !self.session_manager.inactivity_timeout.is_zero()
1977 && elapsed >= self.session_manager.inactivity_timeout
1978 {
1979 // Timeout expired → end old session (emits boundary event), start new one.
1980 // The session state was set to Inactive by session_transition_to_inactive(),
1981 // but session_id is still set. Restore Active so session_end() can proceed.
1982 self.session_manager.state = SessionState::Active;
1983 self.session_end(Some("timeout"));
1984 self.session_start();
1985 true
1986 } else {
1987 // Timeout has NOT expired → resume existing session.
1988 self.session_manager.state = SessionState::Active;
1989 self.session_manager.inactive_since = None;
1990 session::clear_inactive_since(self);
1991 false
1992 }
1993 }
1994 }
1995 }
1996
1997 /// Called during initialization to recover an abnormally terminated session.
1998 ///
1999 /// If the dirty flag was set and a session ID is persisted, emits a synthetic
2000 /// `session_end` event with reason "abnormal" and clears session state.
2001 pub(crate) fn recover_session_on_dirty_flag(&mut self) {
2002 // Close the crashed session's flow instances first, so their
2003 // `flow_end`s precede its synthetic `session_end`.
2004 flows::recover_abnormal(self);
2005
2006 let persisted_id = match session::read_session_id(self) {
2007 Some(id) => id,
2008 None => return, // No previous session to recover.
2009 };
2010
2011 let persisted_seq = self.session_manager.session_seq;
2012 let inactive_since = session::read_inactive_since(self);
2013
2014 // Determine if the session ended while inactive (timeout may have expired).
2015 let reason = if inactive_since.is_some() {
2016 "abnormal_inactive"
2017 } else {
2018 "abnormal"
2019 };
2020
2021 log::info!(
2022 "Recovering abnormally terminated session: {} (seq={})",
2023 persisted_id,
2024 persisted_seq
2025 );
2026
2027 // Emit synthetic session_end.
2028 self.record_session_end_event(&persisted_id, persisted_seq, Some(reason));
2029
2030 // Clear persisted session state so the recovered session won't be replayed.
2031 session::clear(self);
2032
2033 // Reset in-memory state so the next session_start gets a clean slate.
2034 self.session_manager.reset_state();
2035 }
2036
2037 // -----------------------------------------------------------------------
2038 // Client lifecycle methods
2039 // -----------------------------------------------------------------------
2040
2041 /// Performs the collection/cleanup operations required by becoming active.
2042 ///
2043 /// This functions generates a baseline ping with reason `active`
2044 /// and then sets the dirty bit.
2045 pub fn handle_client_active(&mut self) {
2046 match self.session_manager.mode {
2047 SessionMode::Auto => {
2048 if !self.session_manager.is_active() {
2049 if self.session_manager.inactive_since.is_some() {
2050 // Was inactive — evaluate timeout.
2051 self.session_transition_to_active();
2052 } else {
2053 // First activation — start initial session.
2054 self.session_start();
2055 }
2056 }
2057 }
2058 SessionMode::Lifecycle => {
2059 // Only start a session on the first activation following an inactive
2060 // transition. Guard against duplicate handle_client_active calls which
2061 // are not a real lifecycle transition.
2062 if !self.session_manager.is_active() {
2063 self.session_start();
2064 }
2065 }
2066 SessionMode::Manual => {
2067 // No automatic session management.
2068 }
2069 }
2070
2071 // Check flow timeouts now that any resumed session is active again. A
2072 // session that timed out has already closed its instances.
2073 flows::close_all_expired(self);
2074
2075 if !self
2076 .internal_pings
2077 .baseline
2078 .submit_sync(self, Some("active"))
2079 {
2080 log::info!("baseline ping not submitted on active");
2081 }
2082
2083 self.set_dirty_flag(true);
2084 }
2085
2086 /// Performs the collection/cleanup operations required by becoming inactive.
2087 ///
2088 /// This functions generates a baseline and an events ping with reason
2089 /// `inactive` and then clears the dirty bit.
2090 pub fn handle_client_inactive(&mut self) {
2091 // Check flow timeouts while the session is still active, so any
2092 // `flow_end` is recorded in-session and sent in this events ping.
2093 flows::close_all_expired(self);
2094
2095 match self.session_manager.mode {
2096 SessionMode::Auto => {
2097 // In AUTO mode, don't end the session immediately. Instead record
2098 // inactive_since for lazy timeout evaluation on next activation.
2099 self.session_transition_to_inactive();
2100 }
2101 SessionMode::Lifecycle => {
2102 // End session immediately on going inactive.
2103 self.session_end(Some("inactive"));
2104 }
2105 SessionMode::Manual => {
2106 // No automatic session management.
2107 }
2108 }
2109
2110 if !self
2111 .internal_pings
2112 .baseline
2113 .submit_sync(self, Some("inactive"))
2114 {
2115 log::info!("baseline ping not submitted on inactive");
2116 }
2117
2118 if !self
2119 .internal_pings
2120 .events
2121 .submit_sync(self, Some("inactive"))
2122 {
2123 log::info!("events ping not submitted on inactive");
2124 }
2125
2126 self.set_dirty_flag(false);
2127 }
2128
2129 /// **Test-only API (exported for FFI purposes).**
2130 ///
2131 /// Deletes all stored metrics.
2132 ///
2133 /// Note that this also includes the ping sequence numbers, so it has
2134 /// the effect of resetting those to their initial values.
2135 pub fn test_clear_all_stores(&self) {
2136 if let Some(data) = self.data_store.as_ref() {
2137 data.clear_all()
2138 }
2139 // We don't care about this failing, maybe the data does just not exist.
2140 let _ = self.event_data_store.clear_all();
2141 }
2142
2143 /// Instructs the Metrics Ping Scheduler's thread to exit cleanly.
2144 /// If Glean was configured with `use_core_mps: false`, this has no effect.
2145 pub fn cancel_metrics_ping_scheduler(&self) {
2146 if self.schedule_metrics_pings {
2147 scheduler::cancel();
2148 }
2149 }
2150
2151 /// Instructs the Metrics Ping Scheduler to being scheduling metrics pings.
2152 /// If Glean wsa configured with `use_core_mps: false`, this has no effect.
2153 pub fn start_metrics_ping_scheduler(&self) {
2154 if self.schedule_metrics_pings {
2155 scheduler::schedule(self);
2156 }
2157 }
2158
2159 /// Clears the core attribution data.
2160 /// Does not clear glean.attribution.ext.
2161 pub fn clear_attribution(&self) {
2162 if let Some(data) = self.data_store.as_ref() {
2163 [
2164 &self.core_metrics.attribution_source,
2165 &self.core_metrics.attribution_medium,
2166 &self.core_metrics.attribution_campaign,
2167 &self.core_metrics.attribution_term,
2168 &self.core_metrics.attribution_content,
2169 ]
2170 .iter()
2171 .for_each(|metric| {
2172 let meta = metric.meta();
2173 _ = data.remove_single_metric(
2174 meta.inner.lifetime,
2175 &meta.storage_names()[0],
2176 &meta.base_identifier(),
2177 );
2178 });
2179 }
2180 }
2181
2182 /// Updates attribution fields with new values.
2183 /// AttributionMetrics fields with `None` values will not overwrite older values.
2184 pub fn update_attribution(&self, attribution: AttributionMetrics) {
2185 const MAX_ATTRIBUTION_LENGTH: usize = 512;
2186
2187 if let Some(source) = attribution.source {
2188 self.core_metrics
2189 .attribution_source
2190 .set_sync_with_max_length(self, source, MAX_ATTRIBUTION_LENGTH);
2191 }
2192 if let Some(medium) = attribution.medium {
2193 self.core_metrics
2194 .attribution_medium
2195 .set_sync_with_max_length(self, medium, MAX_ATTRIBUTION_LENGTH);
2196 }
2197 if let Some(campaign) = attribution.campaign {
2198 self.core_metrics
2199 .attribution_campaign
2200 .set_sync_with_max_length(self, campaign, MAX_ATTRIBUTION_LENGTH);
2201 }
2202 if let Some(term) = attribution.term {
2203 self.core_metrics.attribution_term.set_sync_with_max_length(
2204 self,
2205 term,
2206 MAX_ATTRIBUTION_LENGTH,
2207 );
2208 }
2209 if let Some(content) = attribution.content {
2210 self.core_metrics
2211 .attribution_content
2212 .set_sync_with_max_length(self, content, MAX_ATTRIBUTION_LENGTH);
2213 }
2214 }
2215
2216 /// **TEST-ONLY Method**
2217 ///
2218 /// Returns the current attribution metrics.
2219 pub fn test_get_attribution(&self) -> AttributionMetrics {
2220 AttributionMetrics {
2221 source: self
2222 .core_metrics
2223 .attribution_source
2224 .get_value(self, Some("glean_client_info")),
2225 medium: self
2226 .core_metrics
2227 .attribution_medium
2228 .get_value(self, Some("glean_client_info")),
2229 campaign: self
2230 .core_metrics
2231 .attribution_campaign
2232 .get_value(self, Some("glean_client_info")),
2233 term: self
2234 .core_metrics
2235 .attribution_term
2236 .get_value(self, Some("glean_client_info")),
2237 content: self
2238 .core_metrics
2239 .attribution_content
2240 .get_value(self, Some("glean_client_info")),
2241 }
2242 }
2243
2244 /// Clears the core distribution data.
2245 /// Does not clear glean.distribution.ext.
2246 pub fn clear_distribution(&self) {
2247 if let Some(data) = self.data_store.as_ref() {
2248 let meta = self.core_metrics.distribution_name.meta();
2249 _ = data.remove_single_metric(
2250 meta.inner.lifetime,
2251 &meta.storage_names()[0],
2252 &meta.base_identifier(),
2253 );
2254 }
2255 }
2256
2257 /// Updates distribution fields with new values.
2258 /// DistributionMetrics fields with `None` values will not overwrite older values.
2259 pub fn update_distribution(&self, distribution: DistributionMetrics) {
2260 if let Some(name) = distribution.name {
2261 self.core_metrics.distribution_name.set_sync(self, name);
2262 }
2263 }
2264
2265 /// **TEST-ONLY Method**
2266 ///
2267 /// Returns the current distribution metrics.
2268 pub fn test_get_distribution(&self) -> DistributionMetrics {
2269 DistributionMetrics {
2270 name: self
2271 .core_metrics
2272 .distribution_name
2273 .get_value(self, Some("glean_client_info")),
2274 }
2275 }
2276}