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