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.
5 #ifndef COMPONENTS_METRICS_METRICS_SERVICE_CLIENT_H_
6 #define COMPONENTS_METRICS_METRICS_SERVICE_CLIENT_H_
12 #include "base/callback_list.h"
13 #include "base/functional/callback.h"
14 #include "base/metrics/field_trial_params.h"
15 #include "base/time/time.h"
16 #include "components/metrics/metrics_log_store.h"
17 #include "components/metrics/metrics_log_uploader.h"
18 #include "components/metrics/metrics_reporting_default_state.h"
19 #include "third_party/metrics_proto/system_profile.pb.h"
26 namespace network_time {
27 class NetworkTimeTracker;
30 namespace variations {
31 class SyntheticTrialRegistry;
36 class MetricsLogUploader;
39 namespace structured {
40 class StructuredMetricsService;
43 // The minimum number bytes of the queue to be persisted before logs are
44 // dropped. This will be applied to both log queues (initial/ongoing). This
45 // ensures that a reasonable amount of history will be stored even if there is a
46 // long series of very small logs.
48 // Refer to //components/metrics/unsent_log_store.h for more details on when
50 extern const base::FeatureParam<int> kMinLogQueueBytes;
52 // The minimum number of ongoing logs to persist in the queue before logs are
55 // Note that each ongoing log may be pretty large, since "initial" logs must
56 // first be sent before any ongoing logs are transmitted. "Initial" logs will
57 // not be sent if a user is offline. As a result, the current ongoing log will
58 // accumulate until the "initial" log can be transmitted. We don't want to save
59 // too many of these mega-logs (this should be capped by kMaxLogQueueBytes).
61 // A "standard shutdown" will create a small log, including just the data that
62 // was not yet been transmitted, and that is normal (to have exactly one
63 // ongoing_log_ at startup).
65 // Refer to //components/metrics/unsent_log_store.h for more details on when
67 extern const base::FeatureParam<int> kMinOngoingLogQueueCount;
69 // An abstraction of operations that depend on the embedder's (e.g. Chrome)
71 class MetricsServiceClient {
73 MetricsServiceClient();
75 MetricsServiceClient(const MetricsServiceClient&) = delete;
76 MetricsServiceClient& operator=(const MetricsServiceClient&) = delete;
78 virtual ~MetricsServiceClient();
80 // Returns the synthetic trial registry shared by MetricsService and
82 virtual variations::SyntheticTrialRegistry* GetSyntheticTrialRegistry() = 0;
84 // Returns the MetricsService instance that this client is associated with.
85 // With the exception of testing contexts, the returned instance must be valid
86 // for the lifetime of this object (typically, the embedder's client
87 // implementation will own the MetricsService instance being returned).
88 virtual MetricsService* GetMetricsService() = 0;
90 // Returns the UkmService instance that this client is associated with.
91 virtual ukm::UkmService* GetUkmService();
93 // Returns the StructuredMetricsService instance that this client is
95 virtual structured::StructuredMetricsService* GetStructuredMetricsService();
97 // Returns true if metrics should be uploaded for the given |user_id|, which
98 // corresponds to the |user_id| field in ChromeUserMetricsExtension.
99 virtual bool ShouldUploadMetricsForUserId(uint64_t user_id);
101 // Registers the client id with other services (e.g. crash reporting), called
102 // when metrics recording gets enabled.
103 virtual void SetMetricsClientId(const std::string& client_id) = 0;
105 // Returns the product value to use in uploaded reports, which will be used to
106 // set the ChromeUserMetricsExtension.product field. See comments on that
107 // field on why it's an int32_t rather than an enum.
108 virtual int32_t GetProduct() = 0;
110 // Returns the current application locale (e.g. "en-US").
111 virtual std::string GetApplicationLocale() = 0;
113 // Return a NetworkTimeTracker for access to a server-provided clock.
114 virtual const network_time::NetworkTimeTracker* GetNetworkTimeTracker() = 0;
116 // Retrieves the brand code string associated with the install, returning
117 // false if no brand code is available.
118 virtual bool GetBrand(std::string* brand_code) = 0;
120 // Returns the release channel (e.g. stable, beta, etc) of the application.
121 virtual SystemProfileProto::Channel GetChannel() = 0;
123 // Returns true if the application is on the extended stable channel.
124 virtual bool IsExtendedStableChannel() = 0;
126 // Returns the version of the application as a string.
127 virtual std::string GetVersionString() = 0;
129 // Called by the metrics service when a new environment has been recorded.
130 // Takes the serialized environment as a parameter. The contents of
131 // |serialized_environment| are consumed by the call, but the caller maintains
133 virtual void OnEnvironmentUpdate(std::string* serialized_environment) {}
135 // Collects child process histograms and merges them into StatisticsRecorder.
136 // Called when child process histograms need to be merged ASAP. For example,
137 // on Android, when the browser was backgrounded.
138 virtual void MergeSubprocessHistograms() {}
140 // Called prior to a metrics log being closed, allowing the client to collect
141 // extra histograms that will go in that log. Asynchronous API - the client
142 // implementation should call |done_callback| when complete.
143 virtual void CollectFinalMetricsForLog(base::OnceClosure done_callback) = 0;
145 // Get the URL of the metrics server.
146 virtual GURL GetMetricsServerUrl();
148 // Get the fallback HTTP URL of the metrics server.
149 virtual GURL GetInsecureMetricsServerUrl();
151 // Creates a MetricsLogUploader with the specified parameters (see comments on
152 // MetricsLogUploader for details).
153 virtual std::unique_ptr<MetricsLogUploader> CreateUploader(
154 const GURL& server_url,
155 const GURL& insecure_server_url,
156 base::StringPiece mime_type,
157 metrics::MetricsLogUploader::MetricServiceType service_type,
158 const MetricsLogUploader::UploadCallback& on_upload_complete) = 0;
160 // Returns the interval between upload attempts. Checks if debugging flags
161 // have been set, otherwise defaults to GetStandardUploadInterval().
162 base::TimeDelta GetUploadInterval();
164 // Returns the standard interval between upload attempts.
165 virtual base::TimeDelta GetStandardUploadInterval() = 0;
167 // Whether or not the MetricsService should start up quickly and upload the
168 // initial report quickly. By default, this work may be delayed by some
169 // amount. Only the default behavior should be used in production, but clients
170 // can override this in tests if tests need to make assertions on the log
172 virtual bool ShouldStartUpFastForTesting() const;
174 // Called when loading state changed, e.g. start/stop loading.
175 virtual void LoadingStateChanged(bool is_loading) {}
177 // Returns whether metrics reporting is managed by policy.
178 virtual bool IsReportingPolicyManaged();
180 // Gets information about the default value for the metrics reporting checkbox
181 // shown during first-run.
182 virtual EnableMetricsDefault GetMetricsReportingDefaultState();
184 // Return true iff the system is currently on a cellular connection.
185 virtual bool IsOnCellularConnection();
187 // Returns whether the allowlist for external experiment ids is enabled. Some
188 // embedders like WebLayer disable it. For Chrome, it should be enabled.
189 virtual bool IsExternalExperimentAllowlistEnabled();
191 // Returns true iff UKM is allowed for all profiles.
192 // See //components/ukm/observers/ukm_consent_state_observer.h for details.
193 virtual bool IsUkmAllowedForAllProfiles();
195 // Returns whether UKM notification listeners were attached to all profiles.
196 virtual bool AreNotificationListenersEnabledOnAllProfiles();
198 // Gets the app package name (as defined by the embedder). Since package name
199 // is only meaningful for Android, other platforms should return the empty
200 // string (this is the same as the default behavior). If the package name
201 // should not be logged for privacy/fingerprintability reasons, the embedder
202 // should return the empty string.
203 virtual std::string GetAppPackageNameIfLoggable();
205 // Gets the key used to sign metrics uploads. This will be used to compute an
206 // HMAC-SHA256 signature of an uploaded log.
207 virtual std::string GetUploadSigningKey();
209 // Checks if the cloned install detector says that client ids should be reset.
210 virtual bool ShouldResetClientIdsOnClonedInstall();
212 virtual base::CallbackListSubscription AddOnClonedInstallDetectedCallback(
213 base::OnceClosure callback);
215 // Specifies local log storage requirements and restrictions.
216 virtual MetricsLogStore::StorageLimits GetStorageLimits() const;
218 // Sets the callback to run MetricsServiceManager::UpdateRunningServices.
219 void SetUpdateRunningServicesCallback(const base::RepeatingClosure& callback);
221 // Notify MetricsServiceManager to UpdateRunningServices using callback.
222 void UpdateRunningServices();
224 // Checks if the user has forced metrics collection on via the override flag.
225 bool IsMetricsReportingForceEnabled() const;
227 // Initializes per-user metrics collection. For more details what per-user
228 // metrics collection is, refer to MetricsService::InitPerUserMetrics.
230 // Since the concept of a user is only applicable in Ash Chrome, this function
231 // should no-op for other platforms.
232 virtual void InitPerUserMetrics() {}
234 // Updates the current user's metrics consent. This allows embedders to update
235 // the user consent. If there is no current user, then this function will
238 // Since the concept of a user is only applicable on Ash Chrome, this function
239 // should no-op for other platforms.
240 virtual void UpdateCurrentUserMetricsConsent(bool user_metrics_consent) {}
242 // Returns the current user metrics consent if it should be applied to decide
243 // the current metrics reporting state. This allows embedders to determine
244 // when a user metric consent state should not be applied (ie no logged in
245 // user or managed policy).
247 // Will return absl::nullopt if there is no current user or current user
248 // metrics consent should not be applied to determine metrics reporting state.
250 // Not all platforms support per-user consent. If per-user consent is not
251 // supported, this function should return absl::nullopt.
252 virtual absl::optional<bool> GetCurrentUserMetricsConsent() const;
254 // Returns the current user id.
256 // Will return absl::nullopt if there is no current user, metrics reporting is
257 // disabled, or current user should not have a user id.
259 // Not all platforms support per-user consent. If per-user consent is not
260 // supported, this function should return absl::nullopt.
261 virtual absl::optional<std::string> GetCurrentUserId() const;
264 base::RepeatingClosure update_running_services_;
267 } // namespace metrics
269 #endif // COMPONENTS_METRICS_METRICS_SERVICE_CLIENT_H_