Upload upstream chromium 114.0.5735.31
[platform/framework/web/chromium-efl.git] / components / ukm / ukm_service.h
1 // Copyright 2017 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 #ifndef COMPONENTS_UKM_UKM_SERVICE_H_
6 #define COMPONENTS_UKM_UKM_SERVICE_H_
7
8 #include <stddef.h>
9 #include <memory>
10
11 #include "base/callback_list.h"
12 #include "base/feature_list.h"
13 #include "base/gtest_prod_util.h"
14 #include "base/memory/raw_ptr.h"
15 #include "base/memory/weak_ptr.h"
16 #include "base/sequence_checker.h"
17 #include "base/time/time.h"
18 #include "build/build_config.h"
19 #include "components/metrics/delegating_provider.h"
20 #include "components/metrics/metrics_logs_event_manager.h"
21 #include "components/metrics/metrics_provider.h"
22 #include "components/metrics/metrics_rotation_scheduler.h"
23 #include "components/metrics/ukm_demographic_metrics_provider.h"
24 #include "components/ukm/ukm_entry_filter.h"
25 #include "components/ukm/ukm_recorder_impl.h"
26 #include "components/ukm/ukm_reporting_service.h"
27
28 class PrefRegistrySimple;
29 class PrefService;
30 FORWARD_DECLARE_TEST(ChromeMetricsServiceClientTest, TestRegisterUKMProviders);
31 FORWARD_DECLARE_TEST(IOSChromeMetricsServiceClientTest,
32                      TestRegisterUkmProvidersWhenUKMFeatureEnabled);
33 class ChromeMetricsServiceClientTestIgnoredForAppMetrics;
34
35 namespace metrics {
36 class MetricsServiceClient;
37 class UkmBrowserTestBase;
38 class UkmRecorderClientInterfaceRegistry;
39 }  // namespace metrics
40
41 namespace ukm {
42 class Report;
43 class UkmTestHelper;
44
45 namespace debug {
46 class UkmDebugDataExtractor;
47 }
48
49 // These values are persisted to logs. Entries should not be renumbered and
50 // numeric values should never be reused. This maps to the enum UkmResetReason.
51 enum class ResetReason {
52   kOnUkmAllowedStateChanged = 0,
53   kUpdatePermissions = 1,
54   kClonedInstall = 2,
55   kMaxValue = kClonedInstall,
56 };
57
58 // Enables adding the synced user's noised birth year and gender to the UKM
59 // report. For more details, see doc of metrics::DemographicMetricsProvider in
60 // components/metrics/demographics/demographic_metrics_provider.h.
61 BASE_DECLARE_FEATURE(kReportUserNoisedUserBirthYearAndGender);
62
63 // The URL-Keyed Metrics (UKM) service is responsible for gathering and
64 // uploading reports that contain fine grained performance metrics including
65 // URLs for top-level navigations.
66 class UkmService : public UkmRecorderImpl {
67  public:
68   // Constructs a UkmService.
69   // Calling code is responsible for ensuring that the lifetime of
70   // |pref_service| is longer than the lifetime of UkmService. The parameters
71   // |pref_service|, |client| must not be null. |demographics_provider| may be
72   // null.
73   UkmService(PrefService* pref_service,
74              metrics::MetricsServiceClient* client,
75              std::unique_ptr<metrics::UkmDemographicMetricsProvider>
76                  demographics_provider,
77              uint64_t external_client_id = 0);
78
79   UkmService(const UkmService&) = delete;
80   UkmService& operator=(const UkmService&) = delete;
81
82   ~UkmService() override;
83
84   // Initializes the UKM service.
85   void Initialize();
86
87   // Enables/disables transmission of accumulated logs. Logs that have already
88   // been created will remain persisted to disk.
89   void EnableReporting();
90   void DisableReporting();
91
92 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
93   void OnAppEnterBackground();
94   void OnAppEnterForeground();
95 #endif
96
97   // Records all collected data into logs, and writes to disk.
98   void Flush(metrics::MetricsLogsEventManager::CreateReason reason);
99
100   // Deletes all unsent local data (Sources, Events, aggregate info for
101   // collected event metrics, etc.).
102   void Purge();
103
104   // Deletes all unsent local data related to Chrome extensions.
105   void PurgeExtensionsData();
106
107   // Deletes all unsent local data related to Apps.
108   void PurgeAppsData();
109
110   // Deletes all unsent local data related to MSBB.
111   void PurgeMsbbData();
112
113   // Resets the client prefs (client_id/session_id). |reason| should be passed
114   // to provide the reason of the reset - this is only used for UMA logging.
115   void ResetClientState(ResetReason reason);
116
117   // Called if this install is detected as cloned.
118   void OnClonedInstallDetected();
119
120   // Registers the specified |provider| to provide additional metrics into the
121   // UKM log. Should be called during MetricsService initialization only.
122   virtual void RegisterMetricsProvider(
123       std::unique_ptr<metrics::MetricsProvider> provider);
124
125   // Registers the |filter| that is guaranteed to be applied to all subsequent
126   // events that are recorded via this UkmService.
127   void RegisterEventFilter(std::unique_ptr<UkmEntryFilter> filter);
128
129   // Registers the names of all of the preferences used by UkmService in
130   // the provided PrefRegistry.
131   static void RegisterPrefs(PrefRegistrySimple* registry);
132
133   int32_t report_count() const { return report_count_; }
134
135   uint64_t client_id() const { return client_id_; }
136
137   ukm::UkmReportingService& reporting_service_for_testing() {
138     return reporting_service_;
139   }
140
141   // Makes sure that the serialized UKM report can be parsed.
142   static bool LogCanBeParsed(const std::string& serialized_data);
143
144   // Serializes the input UKM report into a string and validates it.
145   static std::string SerializeReportProtoToString(Report* report);
146
147  private:
148   friend ::metrics::UkmBrowserTestBase;
149   friend ::ukm::UkmTestHelper;
150   friend ::ukm::debug::UkmDebugDataExtractor;
151   friend ::ukm::UkmUtilsForTest;
152
153   FRIEND_TEST_ALL_PREFIXES(::ChromeMetricsServiceClientTest,
154                            TestRegisterUKMProviders);
155   friend ::ChromeMetricsServiceClientTestIgnoredForAppMetrics;
156   FRIEND_TEST_ALL_PREFIXES(::IOSChromeMetricsServiceClientTest,
157                            TestRegisterUkmProvidersWhenUKMFeatureEnabled);
158   FRIEND_TEST_ALL_PREFIXES(UkmServiceTest,
159                            PurgeExtensionDataFromUnsentLogStore);
160   FRIEND_TEST_ALL_PREFIXES(UkmServiceTest, PurgeAppDataFromUnsentLogStore);
161   FRIEND_TEST_ALL_PREFIXES(UkmServiceTest, PurgeMsbbDataFromUnsentLogStore);
162
163   // Updates the |recorder_client_registry_| about the changes in
164   // UkmRecorderParameters. Thread-safe.
165   void OnRecorderParametersChanged() override;
166
167   void OnRecorderParametersChangedImpl();
168
169   // Starts metrics client initialization.
170   void StartInitTask();
171
172   // Called when initialization tasks are complete, to notify the scheduler
173   // that it can begin calling RotateLog.
174   void FinishedInitTask();
175
176   // Periodically called by scheduler_ to advance processing of logs.
177   void RotateLog();
178
179   // Constructs a new Report from available data and stores it in
180   // unsent_log_store_.
181   void BuildAndStoreLog(metrics::MetricsLogsEventManager::CreateReason reason);
182
183   // Starts an upload of the next log from unsent_log_store_.
184   void StartScheduledUpload();
185
186   // Called by log_uploader_ when the an upload is completed.
187   void OnLogUploadComplete(int response_code);
188
189   // Adds the user's birth year and gender to the UKM |report| only if (1) the
190   // provider is registered and (2) the feature is enabled. For more details,
191   // see doc of metrics::DemographicMetricsProvider in
192   // components/metrics/demographics/demographic_metrics_provider.h.
193   void AddSyncedUserNoiseBirthYearAndGenderToReport(Report* report);
194
195   void SetInitializationCompleteCallbackForTesting(base::OnceClosure callback);
196
197   // UkmRecorderClientInterfaceRegistry keeps track of attached MojoUkmRecorder
198   // clients. This registry can be used to update all the attached clients with
199   // the new UkmRecorderParameters, which then can be used by clients to decide
200   // whether UkmInterface::AddEntry IPC needs to be sent or not.
201   std::unique_ptr<metrics::UkmRecorderClientInterfaceRegistry>
202       recorder_client_registry_;
203
204   // A weak pointer to the PrefService used to read and write preferences.
205   raw_ptr<PrefService> pref_service_;
206
207   // The UKM client id stored in prefs.
208   uint64_t client_id_ = 0;
209
210   // External client id. If specified client_id will be set to this
211   // instead of generated. This is currently only used in Lacros.
212   uint64_t external_client_id_ = 0;
213
214   // The UKM session id stored in prefs.
215   int32_t session_id_ = 0;
216
217   // The number of reports generated this session.
218   int32_t report_count_ = 0;
219
220   // Used to interact with the embedder. Weak pointer; must outlive |this|
221   // instance.
222   const raw_ptr<metrics::MetricsServiceClient> client_;
223
224   // Registered metrics providers.
225   metrics::DelegatingProvider metrics_providers_;
226
227   // Provider of the synced user's noised birth and gender.
228   std::unique_ptr<metrics::UkmDemographicMetricsProvider>
229       demographics_provider_;
230
231   // Log reporting service.
232   ukm::UkmReportingService reporting_service_;
233
234   // The scheduler for determining when uploads should happen.
235   std::unique_ptr<metrics::MetricsRotationScheduler> scheduler_;
236
237   base::TimeTicks log_creation_time_;
238
239   bool initialize_started_ = false;
240   bool initialize_complete_ = false;
241
242   // A callback invoked when initialization of the service is complete.
243   base::OnceClosure initialization_complete_callback_;
244
245   // Subscription for a callback that runs if this install is detected as
246   // cloned.
247   base::CallbackListSubscription cloned_install_subscription_;
248
249   SEQUENCE_CHECKER(sequence_checker_);
250
251   // SequencedTaskRunner is used to dispatch OnRecorderParametersChanged() on
252   // the correct sequence, set on construction using the instance assigned to
253   // the current thread.
254   scoped_refptr<base::SequencedTaskRunner> task_runner_;
255
256   // Weak pointers factory used to post task on different threads. All weak
257   // pointers managed by this factory have the same lifetime as UkmService.
258   base::WeakPtrFactory<UkmService> self_ptr_factory_{this};
259 };
260
261 }  // namespace ukm
262
263 #endif  // COMPONENTS_UKM_UKM_SERVICE_H_