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.
5 #ifndef COMPONENTS_UKM_UKM_SERVICE_H_
6 #define COMPONENTS_UKM_UKM_SERVICE_H_
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"
28 class PrefRegistrySimple;
30 FORWARD_DECLARE_TEST(ChromeMetricsServiceClientTest, TestRegisterUKMProviders);
31 FORWARD_DECLARE_TEST(IOSChromeMetricsServiceClientTest,
32 TestRegisterUkmProvidersWhenUKMFeatureEnabled);
33 class ChromeMetricsServiceClientTestIgnoredForAppMetrics;
36 class MetricsServiceClient;
37 class UkmBrowserTestBase;
38 class UkmRecorderClientInterfaceRegistry;
39 } // namespace metrics
46 class UkmDebugDataExtractor;
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,
55 kMaxValue = kClonedInstall,
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);
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 {
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
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);
79 UkmService(const UkmService&) = delete;
80 UkmService& operator=(const UkmService&) = delete;
82 ~UkmService() override;
84 // Initializes the UKM service.
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();
92 #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
93 void OnAppEnterBackground();
94 void OnAppEnterForeground();
97 // Records all collected data into logs, and writes to disk.
98 void Flush(metrics::MetricsLogsEventManager::CreateReason reason);
100 // Deletes all unsent local data (Sources, Events, aggregate info for
101 // collected event metrics, etc.).
104 // Deletes all unsent local data related to Chrome extensions.
105 void PurgeExtensionsData();
107 // Deletes all unsent local data related to Apps.
108 void PurgeAppsData();
110 // Deletes all unsent local data related to MSBB.
111 void PurgeMsbbData();
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);
117 // Called if this install is detected as cloned.
118 void OnClonedInstallDetected();
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);
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);
129 // Registers the names of all of the preferences used by UkmService in
130 // the provided PrefRegistry.
131 static void RegisterPrefs(PrefRegistrySimple* registry);
133 int32_t report_count() const { return report_count_; }
135 uint64_t client_id() const { return client_id_; }
137 ukm::UkmReportingService& reporting_service_for_testing() {
138 return reporting_service_;
141 // Makes sure that the serialized UKM report can be parsed.
142 static bool LogCanBeParsed(const std::string& serialized_data);
144 // Serializes the input UKM report into a string and validates it.
145 static std::string SerializeReportProtoToString(Report* report);
148 friend ::metrics::UkmBrowserTestBase;
149 friend ::ukm::UkmTestHelper;
150 friend ::ukm::debug::UkmDebugDataExtractor;
151 friend ::ukm::UkmUtilsForTest;
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);
163 // Updates the |recorder_client_registry_| about the changes in
164 // UkmRecorderParameters. Thread-safe.
165 void OnRecorderParametersChanged() override;
167 void OnRecorderParametersChangedImpl();
169 // Starts metrics client initialization.
170 void StartInitTask();
172 // Called when initialization tasks are complete, to notify the scheduler
173 // that it can begin calling RotateLog.
174 void FinishedInitTask();
176 // Periodically called by scheduler_ to advance processing of logs.
179 // Constructs a new Report from available data and stores it in
180 // unsent_log_store_.
181 void BuildAndStoreLog(metrics::MetricsLogsEventManager::CreateReason reason);
183 // Starts an upload of the next log from unsent_log_store_.
184 void StartScheduledUpload();
186 // Called by log_uploader_ when the an upload is completed.
187 void OnLogUploadComplete(int response_code);
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);
195 void SetInitializationCompleteCallbackForTesting(base::OnceClosure callback);
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_;
204 // A weak pointer to the PrefService used to read and write preferences.
205 raw_ptr<PrefService> pref_service_;
207 // The UKM client id stored in prefs.
208 uint64_t client_id_ = 0;
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;
214 // The UKM session id stored in prefs.
215 int32_t session_id_ = 0;
217 // The number of reports generated this session.
218 int32_t report_count_ = 0;
220 // Used to interact with the embedder. Weak pointer; must outlive |this|
222 const raw_ptr<metrics::MetricsServiceClient> client_;
224 // Registered metrics providers.
225 metrics::DelegatingProvider metrics_providers_;
227 // Provider of the synced user's noised birth and gender.
228 std::unique_ptr<metrics::UkmDemographicMetricsProvider>
229 demographics_provider_;
231 // Log reporting service.
232 ukm::UkmReportingService reporting_service_;
234 // The scheduler for determining when uploads should happen.
235 std::unique_ptr<metrics::MetricsRotationScheduler> scheduler_;
237 base::TimeTicks log_creation_time_;
239 bool initialize_started_ = false;
240 bool initialize_complete_ = false;
242 // A callback invoked when initialization of the service is complete.
243 base::OnceClosure initialization_complete_callback_;
245 // Subscription for a callback that runs if this install is detected as
247 base::CallbackListSubscription cloned_install_subscription_;
249 SEQUENCE_CHECKER(sequence_checker_);
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_;
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};
263 #endif // COMPONENTS_UKM_UKM_SERVICE_H_