xref: /aosp_15_r20/external/cronet/components/metrics/metrics_service.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2014 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // This file defines a service that collects information about the user
6 // experience in order to help improve future versions of the app.
7 
8 #ifndef COMPONENTS_METRICS_METRICS_SERVICE_H_
9 #define COMPONENTS_METRICS_METRICS_SERVICE_H_
10 
11 #include <stdint.h>
12 
13 #include <map>
14 #include <memory>
15 #include <string>
16 
17 #include "base/callback_list.h"
18 #include "base/functional/bind.h"
19 #include "base/functional/callback_forward.h"
20 #include "base/gtest_prod_util.h"
21 #include "base/memory/raw_ptr.h"
22 #include "base/memory/weak_ptr.h"
23 #include "base/metrics/field_trial.h"
24 #include "base/metrics/histogram_flattener.h"
25 #include "base/metrics/histogram_snapshot_manager.h"
26 #include "base/metrics/statistics_recorder.h"
27 #include "base/metrics/user_metrics.h"
28 #include "base/observer_list.h"
29 #include "base/scoped_observation.h"
30 #include "base/sequence_checker.h"
31 #include "base/time/time.h"
32 #include "build/build_config.h"
33 #include "build/chromeos_buildflags.h"
34 #include "components/metrics/delegating_provider.h"
35 #include "components/metrics/metrics_log.h"
36 #include "components/metrics/metrics_log_store.h"
37 #include "components/metrics/metrics_logs_event_manager.h"
38 #include "components/metrics/metrics_provider.h"
39 #include "components/metrics/metrics_reporting_service.h"
40 
41 class PrefService;
42 class PrefRegistrySimple;
43 FORWARD_DECLARE_TEST(ChromeMetricsServiceClientTest,
44                      TestRegisterMetricsServiceProviders);
45 FORWARD_DECLARE_TEST(IOSChromeMetricsServiceClientTest,
46                      TestRegisterMetricsServiceProviders);
47 
48 namespace variations {
49 class SyntheticTrialRegistry;
50 }
51 
52 namespace metrics {
53 
54 class MetricsRotationScheduler;
55 class MetricsServiceClient;
56 class MetricsServiceObserver;
57 class MetricsStateManager;
58 
59 // See metrics_service.cc for a detailed description.
60 class MetricsService {
61  public:
62   // Creates the MetricsService with the given |state_manager|, |client|, and
63   // |local_state|.  Does not take ownership of the paramaters; instead stores
64   // a weak pointer to each. Caller should ensure that the parameters are valid
65   // for the lifetime of this class.
66   MetricsService(MetricsStateManager* state_manager,
67                  MetricsServiceClient* client,
68                  PrefService* local_state);
69 
70   MetricsService(const MetricsService&) = delete;
71   MetricsService& operator=(const MetricsService&) = delete;
72 
73   virtual ~MetricsService();
74 
75   // Initializes metrics recording state. Updates various bookkeeping values in
76   // prefs and sets up the scheduler. This is a separate function rather than
77   // being done by the constructor so that field trials could be created before
78   // this is run.
79   void InitializeMetricsRecordingState();
80 
81   // Starts the metrics system, turning on recording and uploading of metrics.
82   // Should be called when starting up with metrics enabled, or when metrics
83   // are turned on.
84   void Start();
85 
86   // Starts the metrics system in a special test-only mode. Metrics won't ever
87   // be uploaded or persisted in this mode, but metrics will be recorded in
88   // memory.
89   void StartRecordingForTests();
90 
91   // Starts updating the "last live" browser timestamp.
92   void StartUpdatingLastLiveTimestamp();
93 
94   // Shuts down the metrics system. Should be called at shutdown, or if metrics
95   // are turned off.
96   void Stop();
97 
98   // Enable/disable transmission of accumulated logs and crash reports (dumps).
99   // Calling Start() automatically enables reporting, but sending is
100   // asyncronous so this can be called immediately after Start() to prevent
101   // any uploading.
102   void EnableReporting();
103   void DisableReporting();
104 
105   // Returns the client ID for this client, or the empty string if metrics
106   // recording is not currently running.
107   std::string GetClientId() const;
108 
109   // Get the low entropy source values.
110   int GetLowEntropySource();
111   int GetOldLowEntropySource();
112   int GetPseudoLowEntropySource();
113 
114   // Get the limited entropy randomization source.
115   std::string_view GetLimitedEntropyRandomizationSource();
116 
117   // Set an external provided id for the metrics service. This method can be
118   // set by a caller which wants to explicitly control the *next* id used by the
119   // metrics service. Note that setting the external client id will *not* change
120   // the current metrics client id. In order to change the current client id,
121   // callers should call ResetClientId to change the current client id to the
122   // provided id.
123   void SetExternalClientId(const std::string& id);
124 
125   // Returns the date at which the current metrics client ID was created as
126   // an int64_t containing seconds since the epoch.
127   int64_t GetMetricsReportingEnabledDate();
128 
129   // Returns true if the last session exited cleanly.
130   bool WasLastShutdownClean() const;
131 
132   // Registers local state prefs used by this class.
133   static void RegisterPrefs(PrefRegistrySimple* registry);
134 
135   // This should be called when the application is not idle, i.e. the user seems
136   // to be interacting with the application.
137   void OnApplicationNotIdle();
138 
139 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
140   // Called when the application is going into background mode.
141   // If |keep_recording_in_background| is true, UMA is still recorded and
142   // reported while in the background.
143   void OnAppEnterBackground(bool keep_recording_in_background = false);
144 
145   // Called when the application is coming out of background mode.
146   void OnAppEnterForeground(bool force_open_new_log = false);
147 #endif  // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
148 
149   // Called when a document first starts loading.
150   void OnPageLoadStarted();
151 
152   // Signals that the browser is shutting down cleanly. Intended to be called
153   // during shutdown after critical shutdown tasks have completed.
154   void LogCleanShutdown();
155 
156   bool recording_active() const;
157   bool reporting_active() const;
158   bool has_unsent_logs() const;
159 
160   bool IsMetricsReportingEnabled() const;
161 
162   // Register the specified |provider| to provide additional metrics into the
163   // UMA log. Should be called during MetricsService initialization only.
164   void RegisterMetricsProvider(std::unique_ptr<MetricsProvider> provider);
165 
166   // Check if this install was cloned or imaged from another machine. If a
167   // clone is detected, reset the client id and low entropy source. This
168   // should not be called more than once.
169   void CheckForClonedInstall();
170 
171   // Checks if the cloned install detector says that client ids should be reset.
172   bool ShouldResetClientIdsOnClonedInstall();
173 
174   // Clears the stability metrics that are saved in local state.
175   void ClearSavedStabilityMetrics();
176 
177   // Marks current histograms as reported by snapshotting them, without
178   // actually saving the deltas. At a higher level, this is used to throw
179   // away new histogram samples (since the last log) so that they will not
180   // be included in the next log.
181   void MarkCurrentHistogramsAsReported();
182 
183 #if BUILDFLAG(IS_CHROMEOS_ASH)
184   // Binds a user log store to store unsent logs. This log store will be
185   // fully managed by MetricsLogStore. This will no-op if another log store has
186   // already been set.
187   //
188   // If this is called before initial logs are recorded, then histograms
189   // recorded before user log store is set will be included with user histograms
190   // when initial logs are recorded.
191   //
192   // If this is called after initial logs are recorded, then this will flush all
193   // logs recorded before swapping to |user_log_store|.
194   void SetUserLogStore(std::unique_ptr<UnsentLogStore> user_log_store);
195 
196   // Unbinds the user log store. If there was no user log store, then this does
197   // nothing.
198   //
199   // If this is called before initial logs are recorded, then histograms and the
200   // current log will be discarded.
201   //
202   // If called after initial logs are recorded, then this will flush all logs
203   // before the user log store is unset.
204   void UnsetUserLogStore();
205 
206   // Returns true if a user log store has been bound.
207   bool HasUserLogStore();
208 
209   // Initializes per-user metrics collection. Logs recorded during a user
210   // session will be stored within each user's directory and consent to send
211   // these logs will be controlled by each user. Logs recorded before any user
212   // logs in or during guest sessions (given device owner has consented) will be
213   // stored in local_state.
214   //
215   // This is in its own function because the MetricsService is created very
216   // early on and a user metrics service may have dependencies on services that
217   // are created happen after MetricsService is initialized.
218   void InitPerUserMetrics();
219 
220   // Returns the current user metrics consent if it should be applied to
221   // determine metrics reporting state.
222   //
223   // See comments at MetricsServiceClient::GetCurrentUserMetricsConsent() for
224   // more details.
225   std::optional<bool> GetCurrentUserMetricsConsent() const;
226 
227   // Returns the current logged in user id. See comments at
228   // MetricsServiceClient::GetCurrentUserId() for more details.
229   std::optional<std::string> GetCurrentUserId() const;
230 
231   // Updates the current user metrics consent. No-ops if no user has logged in.
232   void UpdateCurrentUserMetricsConsent(bool user_metrics_consent);
233 #endif  // BUILDFLAG(IS_CHROMEOS_ASH)
234 
235 #if BUILDFLAG(IS_CHROMEOS)
236   // Forces the client ID to be reset and generates a new client ID. This will
237   // be called when a user re-consents to metrics collection and the user had
238   // consented in the past.
239   //
240   // This is to preserve the pseudo-anonymous identifier <client_id, user_id>.
241   void ResetClientId();
242 #endif  // BUILDFLAG(IS_CHROMEOS)
243 
244   variations::SyntheticTrialRegistry* GetSyntheticTrialRegistry();
245 
246   // Returns the delay before the init tasks (to asynchronously initialize
247   // metrics providers) run.
248   base::TimeDelta GetInitializationDelay();
249 
250   // Returns the delay before the task to update the "last alive timestamp" is
251   // run.
252   base::TimeDelta GetUpdateLastAliveTimestampDelay();
253 
LogStoreForTest()254   MetricsLogStore* LogStoreForTest() {
255     return reporting_service_.metrics_log_store();
256   }
257 
258   // Test hook to safely stage the current log in the log store.
259   bool StageCurrentLogForTest();
260 
GetCurrentLogForTest()261   MetricsLog* GetCurrentLogForTest() { return current_log_.get(); }
262 
GetDelegatingProviderForTesting()263   DelegatingProvider* GetDelegatingProviderForTesting() {
264     return &delegating_provider_;
265   }
266 
267   // Adds/Removes a logs observer. Observers are notified when a log is newly
268   // created and is now known by the metrics service. This may occur when
269   // closing a log, or when loading a log from persistent storage. Observers are
270   // also notified when an event occurs on the log (e.g., log is staged,
271   // uploaded, etc.). See MetricsLogsEventManager::LogEvent for more details.
272   void AddLogsObserver(MetricsLogsEventManager::Observer* observer);
273   void RemoveLogsObserver(MetricsLogsEventManager::Observer* observer);
274 
logs_event_observer()275   MetricsServiceObserver* logs_event_observer() {
276     return logs_event_observer_.get();
277   }
278 
279   // Observers will be notified when the enablement state changes. The callback
280   // should accept one boolean argument, which will signal whether or not the
281   // metrics collection has been enabled.
282   base::CallbackListSubscription AddEnablementObserver(
283       const base::RepeatingCallback<void(bool)>& observer);
284 
285 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
IsInForegroundForTesting()286   bool IsInForegroundForTesting() const { return is_in_foreground_; }
287 #endif
288 
289   // Creates a new MetricsLog instance with the given |log_type|.
CreateLogForTesting(MetricsLog::LogType log_type)290   std::unique_ptr<MetricsLog> CreateLogForTesting(
291       MetricsLog::LogType log_type) {
292     return CreateLog(log_type);
293   }
294 
295  protected:
296   // Sets the persistent system profile. Virtual for tests.
297   virtual void SetPersistentSystemProfile(const std::string& serialized_proto,
298                                           bool complete);
299 
300   // Records the current environment (system profile) in |log|, and persists
301   // the results in prefs.
302   // Exposed for testing.
303   static std::string RecordCurrentEnvironmentHelper(
304       MetricsLog* log,
305       PrefService* local_state,
306       DelegatingProvider* delegating_provider);
307 
308   // The MetricsService has a lifecycle that is stored as a state.
309   // See metrics_service.cc for description of this lifecycle.
310   enum State {
311     CONSTRUCTED,          // Constructor was called.
312     INITIALIZED,          // InitializeMetricsRecordingState() was called.
313     INIT_TASK_SCHEDULED,  // Waiting for deferred init tasks to finish.
314     INIT_TASK_DONE,       // Waiting for timer to send initial log.
315     SENDING_LOGS,         // Sending logs and creating new ones when we run out.
316   };
317 
state()318   State state() const { return state_; }
319 
320  private:
321   // The current state of recording for the MetricsService. The state is UNSET
322   // until set to something else, at which point it remains INACTIVE or ACTIVE
323   // for the lifetime of the object.
324   enum RecordingState {
325     INACTIVE,
326     ACTIVE,
327     UNSET,
328   };
329 
330   // The result of a call to FinalizeLog().
331   struct FinalizedLog {
332     FinalizedLog();
333     ~FinalizedLog();
334 
335     // This type is move only.
336     FinalizedLog(FinalizedLog&& other);
337     FinalizedLog& operator=(FinalizedLog&& other);
338 
339     // The size of the uncompressed log data. This is only used for calculating
340     // some metrics.
341     size_t uncompressed_log_size;
342 
343     // A LogInfo object representing the log, which contains its compressed
344     // data, hash, signature, timestamp, and some metadata.
345     std::unique_ptr<UnsentLogStore::LogInfo> log_info;
346   };
347 
348   // Writes snapshots of histograms owned by the StatisticsRecorder to a log.
349   // Does not take ownership of the log.
350   // TODO(crbug.com/40897621): Although this class takes in |required_flags| in
351   // its constructor to filter the StatisticsRecorder histograms being put into
352   // the log, the |histogram_snapshot_manager_| is not aware of this. So if
353   // the |histogram_snapshot_manager_| is passed to some other caller, this
354   // caller will need to manually filter the histograms. Re-factor the code so
355   // that this is not needed.
356   class MetricsLogHistogramWriter {
357    public:
358     explicit MetricsLogHistogramWriter(MetricsLog* log);
359 
360     MetricsLogHistogramWriter(MetricsLog* log,
361                               base::HistogramBase::Flags required_flags);
362 
363     MetricsLogHistogramWriter(const MetricsLogHistogramWriter&) = delete;
364     MetricsLogHistogramWriter& operator=(const MetricsLogHistogramWriter&) =
365         delete;
366 
367     ~MetricsLogHistogramWriter();
368 
369     // Snapshots the deltas of histograms known by the StatisticsRecorder and
370     // writes them to the log passed in the constructor. This also marks the
371     // samples (the deltas) as logged.
372     void SnapshotStatisticsRecorderDeltas();
373 
374     // Snapshots the unlogged samples of histograms known by the
375     // StatisticsRecorder and writes them to the log passed in the constructor.
376     // Note that unlike SnapshotStatisticsRecorderDeltas(), this does not mark
377     // the samples as logged. To do so, a call to MarkUnloggedSamplesAsLogged()
378     // (in |histogram_snapshot_manager_|) should be made.
379     void SnapshotStatisticsRecorderUnloggedSamples();
380 
histogram_snapshot_manager()381     base::HistogramSnapshotManager* histogram_snapshot_manager() {
382       return histogram_snapshot_manager_.get();
383     }
384 
snapshot_transaction_id()385     base::StatisticsRecorder::SnapshotTransactionId snapshot_transaction_id() {
386       return snapshot_transaction_id_;
387     }
388 
389    private:
390     // Used to select which histograms to record when calling
391     // SnapshotStatisticsRecorderHistograms() or
392     // SnapshotStatisticsRecorderUnloggedSamples().
393     const base::HistogramBase::Flags required_flags_;
394 
395     // Used to write histograms to the log passed in the constructor.
396     std::unique_ptr<base::HistogramFlattener> flattener_;
397 
398     // Used to snapshot histograms.
399     std::unique_ptr<base::HistogramSnapshotManager> histogram_snapshot_manager_;
400 
401     // The snapshot transaction ID of a call to either
402     // SnapshotStatisticsRecorderDeltas() or
403     // SnapshotStatisticsRecorderUnloggedSamples().
404     base::StatisticsRecorder::SnapshotTransactionId snapshot_transaction_id_;
405   };
406 
407   // Loads "independent" metrics from a metrics provider and executes a
408   // callback when complete, which could be immediate or after some
409   // execution on a background thread.
410   class IndependentMetricsLoader {
411    public:
412     explicit IndependentMetricsLoader(std::unique_ptr<MetricsLog> log,
413                                       std::string app_version,
414                                       std::string signing_key);
415 
416     IndependentMetricsLoader(const IndependentMetricsLoader&) = delete;
417     IndependentMetricsLoader& operator=(const IndependentMetricsLoader&) =
418         delete;
419 
420     ~IndependentMetricsLoader();
421 
422     // Call ProvideIndependentMetrics (which may execute on a background thread)
423     // for the |metrics_provider| and execute the |done_callback| when complete
424     // with the result (true if successful). |done_callback| must own |this|.
425     void Run(base::OnceCallback<void(bool)> done_callback,
426              MetricsProvider* metrics_provider);
427 
428     // Finalizes/serializes |log_|, and stores the result in |finalized_log_|.
429     // Should only be called once, after |log_| has been filled.
430     void FinalizeLog();
431 
432     // Returns whether FinalizeLog() was called.
433     bool HasFinalizedLog();
434 
435     // Extracts |finalized_log_|. Should be only called once, after
436     // FinalizeLog() has been called. No more operations should be done after
437     // this.
438     FinalizedLog ReleaseFinalizedLog();
439 
440    private:
441     std::unique_ptr<MetricsLog> log_;
442     std::unique_ptr<base::HistogramFlattener> flattener_;
443     std::unique_ptr<base::HistogramSnapshotManager> snapshot_manager_;
444     bool run_called_ = false;
445 
446     // Used for finalizing |log_| in FinalizeLog().
447     const std::string app_version_;
448     const std::string signing_key_;
449 
450     // Stores the result of FinalizeLog().
451     FinalizedLog finalized_log_;
452     bool finalize_log_called_ = false;
453     bool release_finalized_log_called_ = false;
454   };
455 
456   // Gets the LogStore for UMA logs.
log_store()457   MetricsLogStore* log_store() {
458     return reporting_service_.metrics_log_store();
459   }
460 
461   // Calls into the client to initialize some system profile metrics.
462   void StartInitTask();
463 
464   // Callback that moves the state to INIT_TASK_DONE. When this is called, the
465   // state should be INIT_TASK_SCHEDULED.
466   void FinishedInitTask();
467 
468   void OnUserAction(const std::string& action, base::TimeTicks action_time);
469 
470   // Get the amount of uptime since this process started and since the last
471   // call to this function.  Also updates the cumulative uptime metric (stored
472   // as a pref) for uninstall.  Uptimes are measured using TimeTicks, which
473   // guarantees that it is monotonic and does not jump if the user changes
474   // their clock.  The TimeTicks implementation also makes the clock not
475   // count time the computer is suspended.
476   void GetUptimes(PrefService* pref,
477                   base::TimeDelta* incremental_uptime,
478                   base::TimeDelta* uptime);
479 
480   // Turns recording on or off.
481   // DisableRecording() also forces a persistent save of logging state (if
482   // anything has been recorded, or transmitted).
483   void EnableRecording();
484   void DisableRecording();
485 
486   // If in_idle is true, sets idle_since_last_transmission to true.
487   // If in_idle is false and idle_since_last_transmission_ is true, sets
488   // idle_since_last_transmission to false and starts the timer (provided
489   // starting the timer is permitted).
490   void HandleIdleSinceLastTransmission(bool in_idle);
491 
492   // Set up client ID, session ID, etc.
493   void InitializeMetricsState();
494 
495   // Opens a new log for recording user experience metrics. If |call_providers|
496   // is true, OnDidCreateMetricsLog() of providers will be called right after
497   // opening the new log.
498   void OpenNewLog(bool call_providers = true);
499 
500   // Closes out the current log after adding any last information. |async|
501   // determines whether finalizing the log will be done in a background thread.
502   // |log_stored_callback| will be run (on the main thread) after the finalized
503   // log is stored. Note that when |async| is true, the closed log could end up
504   // not being stored (see MaybeCleanUpAndStoreFinalizedLog()). Regardless,
505   // |log_stored_callback| is still run. Note that currently, there is only
506   // support to close one log asynchronously at a time (this should be enforced
507   // by the caller).
508   void CloseCurrentLog(
509       bool async,
510       MetricsLogsEventManager::CreateReason reason,
511       base::OnceClosure log_stored_callback = base::DoNothing());
512 
513   // Stores the |finalized_log| in |log_store()|.
514   void StoreFinalizedLog(MetricsLog::LogType log_type,
515                          MetricsLogsEventManager::CreateReason reason,
516                          base::OnceClosure done_callback,
517                          FinalizedLog finalized_log);
518 
519   // Calls MarkUnloggedSamplesAsLogged() on |log_histogram_writer| and stores
520   // the |finalized_log| (see StoreFinalizedLog()), but only if the
521   // StatisticRecorder's last transaction ID is the same as the one from
522   // |log_histogram_writer| at the time of calling. See comments in the
523   // implementation for more details.
524   void MaybeCleanUpAndStoreFinalizedLog(
525       std::unique_ptr<MetricsLogHistogramWriter> log_histogram_writer,
526       MetricsLog::LogType log_type,
527       MetricsLogsEventManager::CreateReason reason,
528       base::OnceClosure done_callback,
529       FinalizedLog finalized_log);
530 
531   // Pushes the text of the current and staged logs into persistent storage.
532   void PushPendingLogsToPersistentStorage(
533       MetricsLogsEventManager::CreateReason reason);
534 
535   // Ensures that scheduler is running, assuming the current settings are such
536   // that metrics should be reported. If not, this is a no-op.
537   void StartSchedulerIfNecessary();
538 
539   // Starts the process of uploading metrics data.
540   void StartScheduledUpload();
541 
542   // Called by the client via a callback when final log info collection is
543   // complete.
544   void OnFinalLogInfoCollectionDone();
545 
546   // Called via a callback after a periodic ongoing log (created through the
547   // MetricsRotationScheduler) was stored in |log_store()|.
548   void OnAsyncPeriodicOngoingLogStored();
549 
550   // Prepares the initial stability log, which is only logged when the previous
551   // run of Chrome crashed.  This log contains any stability metrics left over
552   // from that previous run, and only these stability metrics.  It uses the
553   // system profile from the previous session.  |prefs_previous_version| is used
554   // to validate the version number recovered from the system profile.  Returns
555   // true if a log was created.
556   bool PrepareInitialStabilityLog(const std::string& prefs_previous_version);
557 
558   // Creates a new MetricsLog instance with the given |log_type|.
559   std::unique_ptr<MetricsLog> CreateLog(MetricsLog::LogType log_type);
560 
561   // Records the current environment (system profile) in |log|, and persists
562   // the results in prefs and GlobalPersistentSystemProfile.
563   void RecordCurrentEnvironment(MetricsLog* log, bool complete);
564 
565   // Handle completion of PrepareProviderMetricsLog which is run as a
566   // background task.
567   void PrepareProviderMetricsLogDone(
568       std::unique_ptr<IndependentMetricsLoader> loader,
569       bool success);
570 
571   // Record a single independent profile and associated histogram from
572   // metrics providers. If this returns true, one was found and there may
573   // be more.
574   bool PrepareProviderMetricsLog();
575 
576   // Records one independent histogram log and then reschedules itself to
577   // check for others. The interval is so as to not adversely impact the UI.
578   void PrepareProviderMetricsTask();
579 
580   // Updates the "last live" browser timestamp and schedules the next update.
581   void UpdateLastLiveTimestampTask();
582 
583   // Returns whether it is too early to close a log.
584   bool IsTooEarlyToCloseLog();
585 
586   // Called if this install is detected as cloned.
587   void OnClonedInstallDetected();
588 
589   // Snapshots histogram deltas using the passed |log_histogram_writer| and then
590   // finalizes |log| by calling FinalizeLog(). |log|, |current_app_version| and
591   // |signing_key| are used to finalize the log (see FinalizeLog()).
592   // Semantically, this is equivalent to SnapshotUnloggedSamplesAndFinalizeLog()
593   // followed by MarkUnloggedSamplesAsLogged().
594   static FinalizedLog SnapshotDeltasAndFinalizeLog(
595       std::unique_ptr<MetricsLogHistogramWriter> log_histogram_writer,
596       std::unique_ptr<MetricsLog> log,
597       bool truncate_events,
598       std::optional<ChromeUserMetricsExtension::RealLocalTime> close_time,
599       std::string&& current_app_version,
600       std::string&& signing_key);
601 
602   // Snapshots unlogged histogram samples using the passed
603   // |log_histogram_writer| and then finalizes |log| by calling FinalizeLog().
604   // |log|, |current_app_version| and |signing_key| are used to finalize the log
605   // (see FinalizeLog()). Note that unlike SnapshotDeltasAndFinalizeLog(), this
606   // does not own the passed |log_histogram_writer|, because it should be
607   // available to eventually mark the unlogged samples as logged.
608   static FinalizedLog SnapshotUnloggedSamplesAndFinalizeLog(
609       MetricsLogHistogramWriter* log_histogram_writer,
610       std::unique_ptr<MetricsLog> log,
611       bool truncate_events,
612       std::optional<ChromeUserMetricsExtension::RealLocalTime> close_time,
613       std::string&& current_app_version,
614       std::string&& signing_key);
615 
616   // Finalizes |log| (see MetricsLog::FinalizeLog()). The |signing_key| is used
617   // to compute a signature for the log.
618   static FinalizedLog FinalizeLog(
619       std::unique_ptr<MetricsLog> log,
620       bool truncate_events,
621       std::optional<ChromeUserMetricsExtension::RealLocalTime> close_time,
622       const std::string& current_app_version,
623       const std::string& signing_key);
624 
625   // Sub-service for uploading logs.
626   MetricsReportingService reporting_service_;
627 
628   // The log that we are still appending to.
629   std::unique_ptr<MetricsLog> current_log_;
630 
631   // Used to manage various metrics reporting state prefs, such as client id,
632   // low entropy source and whether metrics reporting is enabled. Weak pointer.
633   const raw_ptr<MetricsStateManager> state_manager_;
634 
635   // Used to interact with the embedder. Weak pointer; must outlive |this|
636   // instance.
637   const raw_ptr<MetricsServiceClient> client_;
638 
639   // Registered metrics providers.
640   DelegatingProvider delegating_provider_;
641 
642   raw_ptr<PrefService> local_state_;
643 
644   base::ActionCallback action_callback_;
645 
646   // Indicate whether recording and reporting are currently happening.
647   // These should not be set directly, but by calling SetRecording and
648   // SetReporting.
649   RecordingState recording_state_;
650 
651   // Indicate whether test mode is enabled, where the initial log should never
652   // be cut, and logs are neither persisted nor uploaded.
653   bool test_mode_active_;
654 
655   // The progression of states made by the browser are recorded in the following
656   // state.
657   State state_;
658 
659   // Whether the MetricsService object has received any notifications since
660   // the last time a transmission was sent.
661   bool idle_since_last_transmission_;
662 
663   // A number that identifies the how many times the app has been launched.
664   int session_id_;
665 
666   // The scheduler for determining when log rotations should happen.
667   std::unique_ptr<MetricsRotationScheduler> rotation_scheduler_;
668 
669   // Stores the time of the first call to |GetUptimes()|.
670   base::TimeTicks first_updated_time_;
671 
672   // Stores the time of the last call to |GetUptimes()|.
673   base::TimeTicks last_updated_time_;
674 
675   // Indicates if loading of independent metrics is currently active.
676   bool independent_loader_active_ = false;
677 
678   // Indicates whether or not there is currently a periodic ongoing log being
679   // finalized (or is scheduled to be finalized).
680   bool pending_ongoing_log_ = false;
681 
682   // Stores the time when we last posted a task to finalize a periodic ongoing
683   // log asynchronously.
684   base::TimeTicks async_ongoing_log_posted_time_;
685 
686   // Logs event manager to keep track of the various logs that the metrics
687   // service interacts with. An unowned pointer of this instance is passed down
688   // to various objects that are owned by this class.
689   MetricsLogsEventManager logs_event_manager_;
690 
691   // An observer that observes all events notified through |logs_event_manager_|
692   // since the creation of this MetricsService instance. This is only created
693   // if this is a debug build, or the |kExportUmaLogsToFile| command line flag
694   // is passed. This is primarily used by the chrome://metrics-internals debug
695   // page.
696   std::unique_ptr<MetricsServiceObserver> logs_event_observer_;
697 
698   // A set of observers that keeps track of the metrics reporting state.
699   base::RepeatingCallbackList<void(bool)> enablement_observers_;
700 
701   // Subscription for a callback that runs if this install is detected as
702   // cloned.
703   base::CallbackListSubscription cloned_install_subscription_;
704 
705 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
706   // Indicates whether OnAppEnterForeground() (true) or OnAppEnterBackground
707   // (false) was called.
708   bool is_in_foreground_ = false;
709 #endif
710 
711   FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, ActiveFieldTrialsReported);
712   FRIEND_TEST_ALL_PREFIXES(MetricsServiceTest, IsPluginProcess);
713   FRIEND_TEST_ALL_PREFIXES(::ChromeMetricsServiceClientTest,
714                            TestRegisterMetricsServiceProviders);
715   FRIEND_TEST_ALL_PREFIXES(::IOSChromeMetricsServiceClientTest,
716                            TestRegisterMetricsServiceProviders);
717   SEQUENCE_CHECKER(sequence_checker_);
718 
719   // Weak pointers factory used to post task on different threads. All weak
720   // pointers managed by this factory have the same lifetime as MetricsService.
721   base::WeakPtrFactory<MetricsService> self_ptr_factory_{this};
722 };
723 
724 }  // namespace metrics
725 
726 #endif  // COMPONENTS_METRICS_METRICS_SERVICE_H_
727