ukm_service.h 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. // Copyright 2017 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef COMPONENTS_UKM_UKM_SERVICE_H_
  5. #define COMPONENTS_UKM_UKM_SERVICE_H_
  6. #include <stddef.h>
  7. #include <memory>
  8. #include "base/feature_list.h"
  9. #include "base/gtest_prod_util.h"
  10. #include "base/memory/raw_ptr.h"
  11. #include "base/memory/weak_ptr.h"
  12. #include "base/sequence_checker.h"
  13. #include "base/time/time.h"
  14. #include "build/build_config.h"
  15. #include "components/metrics/delegating_provider.h"
  16. #include "components/metrics/metrics_provider.h"
  17. #include "components/metrics/metrics_rotation_scheduler.h"
  18. #include "components/metrics/ukm_demographic_metrics_provider.h"
  19. #include "components/ukm/ukm_entry_filter.h"
  20. #include "components/ukm/ukm_recorder_impl.h"
  21. #include "components/ukm/ukm_reporting_service.h"
  22. class PrefRegistrySimple;
  23. class PrefService;
  24. FORWARD_DECLARE_TEST(ChromeMetricsServiceClientTest, TestRegisterUKMProviders);
  25. FORWARD_DECLARE_TEST(IOSChromeMetricsServiceClientTest,
  26. TestRegisterUkmProvidersWhenUKMFeatureEnabled);
  27. namespace metrics {
  28. class MetricsServiceClient;
  29. class UkmBrowserTestBase;
  30. }
  31. namespace ukm {
  32. class Report;
  33. class UkmTestHelper;
  34. namespace debug {
  35. class UkmDebugDataExtractor;
  36. }
  37. // These values are persisted to logs. Entries should not be renumbered and
  38. // numeric values should never be reused. This maps to the enum UkmResetReason.
  39. enum class ResetReason {
  40. kOnUkmAllowedStateChanged = 0,
  41. kUpdatePermissions = 1,
  42. kClonedInstall = 2,
  43. kMaxValue = kClonedInstall,
  44. };
  45. // The URL-Keyed Metrics (UKM) service is responsible for gathering and
  46. // uploading reports that contain fine grained performance metrics including
  47. // URLs for top-level navigations.
  48. class UkmService : public UkmRecorderImpl {
  49. public:
  50. // Constructs a UkmService.
  51. // Calling code is responsible for ensuring that the lifetime of
  52. // |pref_service| is longer than the lifetime of UkmService. The parameters
  53. // |pref_service|, |client| must not be null. |demographics_provider| may be
  54. // null.
  55. UkmService(PrefService* pref_service,
  56. metrics::MetricsServiceClient* client,
  57. std::unique_ptr<metrics::UkmDemographicMetricsProvider>
  58. demographics_provider,
  59. uint64_t external_client_id = 0);
  60. UkmService(const UkmService&) = delete;
  61. UkmService& operator=(const UkmService&) = delete;
  62. ~UkmService() override;
  63. // Initializes the UKM service.
  64. void Initialize();
  65. // Enables/disables transmission of accumulated logs. Logs that have already
  66. // been created will remain persisted to disk.
  67. void EnableReporting();
  68. void DisableReporting();
  69. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
  70. void OnAppEnterBackground();
  71. void OnAppEnterForeground();
  72. #endif
  73. // Records all collected data into logs, and writes to disk.
  74. void Flush();
  75. // Deletes all unsent local data (Sources, Events, aggregate info for
  76. // collected event metrics, etc.).
  77. void Purge();
  78. // Deletes all unsent local data related to Chrome extensions.
  79. void PurgeExtensionsData();
  80. // Deletes all unsent local data related to Apps.
  81. void PurgeAppsData();
  82. // Resets the client prefs (client_id/session_id). |reason| should be passed
  83. // to provide the reason of the reset - this is only used for UMA logging.
  84. void ResetClientState(ResetReason reason);
  85. // Registers the specified |provider| to provide additional metrics into the
  86. // UKM log. Should be called during MetricsService initialization only.
  87. virtual void RegisterMetricsProvider(
  88. std::unique_ptr<metrics::MetricsProvider> provider);
  89. // Registers the |filter| that is guaranteed to be applied to all subsequent
  90. // events that are recorded via this UkmService.
  91. void RegisterEventFilter(std::unique_ptr<UkmEntryFilter> filter);
  92. // Registers the names of all of the preferences used by UkmService in
  93. // the provided PrefRegistry.
  94. static void RegisterPrefs(PrefRegistrySimple* registry);
  95. int32_t report_count() const { return report_count_; }
  96. uint64_t client_id() const { return client_id_; }
  97. // Enables adding the synced user's noised birth year and gender to the UKM
  98. // report. For more details, see doc of metrics::DemographicMetricsProvider in
  99. // components/metrics/demographics/demographic_metrics_provider.h.
  100. static const base::Feature kReportUserNoisedUserBirthYearAndGender;
  101. // Makes sure that the serialized UKM report can be parsed.
  102. static bool LogCanBeParsed(const std::string& serialized_data);
  103. // Serializes the input UKM report into a string and validates it.
  104. static std::string SerializeReportProtoToString(Report* report);
  105. private:
  106. friend ::metrics::UkmBrowserTestBase;
  107. friend ::ukm::UkmTestHelper;
  108. friend ::ukm::debug::UkmDebugDataExtractor;
  109. friend ::ukm::UkmUtilsForTest;
  110. FRIEND_TEST_ALL_PREFIXES(::ChromeMetricsServiceClientTest,
  111. TestRegisterUKMProviders);
  112. FRIEND_TEST_ALL_PREFIXES(::IOSChromeMetricsServiceClientTest,
  113. TestRegisterUkmProvidersWhenUKMFeatureEnabled);
  114. FRIEND_TEST_ALL_PREFIXES(UkmServiceTest,
  115. PurgeExtensionDataFromUnsentLogStore);
  116. FRIEND_TEST_ALL_PREFIXES(UkmServiceTest, PurgeAppDataFromUnsentLogStore);
  117. // Starts metrics client initialization.
  118. void StartInitTask();
  119. // Called when initialization tasks are complete, to notify the scheduler
  120. // that it can begin calling RotateLog.
  121. void FinishedInitTask();
  122. // Periodically called by scheduler_ to advance processing of logs.
  123. void RotateLog();
  124. // Constructs a new Report from available data and stores it in
  125. // unsent_log_store_.
  126. void BuildAndStoreLog();
  127. // Starts an upload of the next log from unsent_log_store_.
  128. void StartScheduledUpload();
  129. // Called by log_uploader_ when the an upload is completed.
  130. void OnLogUploadComplete(int response_code);
  131. // Adds the user's birth year and gender to the UKM |report| only if (1) the
  132. // provider is registered and (2) the feature is enabled. For more details,
  133. // see doc of metrics::DemographicMetricsProvider in
  134. // components/metrics/demographics/demographic_metrics_provider.h.
  135. void AddSyncedUserNoiseBirthYearAndGenderToReport(Report* report);
  136. void SetInitializationCompleteCallbackForTesting(base::OnceClosure callback);
  137. // A weak pointer to the PrefService used to read and write preferences.
  138. raw_ptr<PrefService> pref_service_;
  139. // The UKM client id stored in prefs.
  140. uint64_t client_id_ = 0;
  141. // External client id. If specified client_id will be set to this
  142. // instead of generated. This is currently only used in Lacros.
  143. uint64_t external_client_id_ = 0;
  144. // The UKM session id stored in prefs.
  145. int32_t session_id_ = 0;
  146. // The number of reports generated this session.
  147. int32_t report_count_ = 0;
  148. // Used to interact with the embedder. Weak pointer; must outlive |this|
  149. // instance.
  150. const raw_ptr<metrics::MetricsServiceClient> client_;
  151. // Registered metrics providers.
  152. metrics::DelegatingProvider metrics_providers_;
  153. // Provider of the synced user's noised birth and gender.
  154. std::unique_ptr<metrics::UkmDemographicMetricsProvider>
  155. demographics_provider_;
  156. // Log reporting service.
  157. ukm::UkmReportingService reporting_service_;
  158. // The scheduler for determining when uploads should happen.
  159. std::unique_ptr<metrics::MetricsRotationScheduler> scheduler_;
  160. base::TimeTicks log_creation_time_;
  161. bool initialize_started_ = false;
  162. bool initialize_complete_ = false;
  163. // A callback invoked when initialization of the service is complete.
  164. base::OnceClosure initialization_complete_callback_;
  165. SEQUENCE_CHECKER(sequence_checker_);
  166. // Weak pointers factory used to post task on different threads. All weak
  167. // pointers managed by this factory have the same lifetime as UkmService.
  168. base::WeakPtrFactory<UkmService> self_ptr_factory_{this};
  169. };
  170. } // namespace ukm
  171. #endif // COMPONENTS_UKM_UKM_SERVICE_H_