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