variations_service.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. // Copyright (c) 2012 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_VARIATIONS_SERVICE_VARIATIONS_SERVICE_H_
  5. #define COMPONENTS_VARIATIONS_SERVICE_VARIATIONS_SERVICE_H_
  6. #include <memory>
  7. #include <string>
  8. #include <vector>
  9. #include "base/compiler_specific.h"
  10. #include "base/gtest_prod_util.h"
  11. #include "base/memory/raw_ptr.h"
  12. #include "base/memory/weak_ptr.h"
  13. #include "base/metrics/field_trial.h"
  14. #include "base/observer_list.h"
  15. #include "base/time/time.h"
  16. #include "build/chromeos_buildflags.h"
  17. #include "components/variations/client_filterable_state.h"
  18. #include "components/variations/service/safe_seed_manager.h"
  19. #include "components/variations/service/ui_string_overrider.h"
  20. #include "components/variations/service/variations_field_trial_creator.h"
  21. #include "components/variations/service/variations_service_client.h"
  22. #include "components/variations/variations_request_scheduler.h"
  23. #include "components/variations/variations_seed_simulator.h"
  24. #include "components/variations/variations_seed_store.h"
  25. #include "components/version_info/version_info.h"
  26. #include "components/web_resource/resource_request_allowed_notifier.h"
  27. #include "url/gurl.h"
  28. class PrefService;
  29. class PrefRegistrySimple;
  30. namespace base {
  31. class FeatureList;
  32. class Version;
  33. }
  34. namespace metrics {
  35. class MetricsStateManager;
  36. }
  37. namespace network {
  38. class SimpleURLLoader;
  39. }
  40. namespace user_prefs {
  41. class PrefRegistrySyncable;
  42. }
  43. namespace variations {
  44. class VariationsSeed;
  45. }
  46. namespace variations {
  47. #if BUILDFLAG(IS_CHROMEOS_ASH)
  48. class DeviceVariationsRestrictionByPolicyApplicator;
  49. #endif
  50. // Used to (a) set up field trials based on stored variations seed data and (b)
  51. // fetch new seed data from the variations server.
  52. class VariationsService
  53. : public web_resource::ResourceRequestAllowedNotifier::Observer {
  54. public:
  55. class Observer {
  56. public:
  57. // How critical a detected experiment change is. Whether it should be
  58. // handled on a "best-effort" basis or, for a more critical change, if it
  59. // should be given higher priority.
  60. enum Severity {
  61. BEST_EFFORT,
  62. CRITICAL,
  63. };
  64. // Called when the VariationsService detects that there will be significant
  65. // experiment changes on a restart. This notification can then be used to
  66. // update UI (i.e. badging an icon).
  67. virtual void OnExperimentChangesDetected(Severity severity) = 0;
  68. protected:
  69. virtual ~Observer() {}
  70. };
  71. VariationsService(const VariationsService&) = delete;
  72. VariationsService& operator=(const VariationsService&) = delete;
  73. ~VariationsService() override;
  74. // Enum used to choose whether GetVariationsServerURL will return an HTTPS
  75. // URL or an HTTP one. The HTTP URL is used as a fallback for seed retrieval
  76. // in cases where an HTTPS connection fails.
  77. enum HttpOptions { USE_HTTP, USE_HTTPS };
  78. // Should be called before startup of the main message loop.
  79. void PerformPreMainMessageLoopStartup();
  80. // Adds an observer to listen for detected experiment changes.
  81. void AddObserver(Observer* observer);
  82. // Removes a previously-added observer.
  83. void RemoveObserver(Observer* observer);
  84. // Called when the application enters foreground. This may trigger a
  85. // FetchVariationsSeed call.
  86. // TODO(rkaplow): Handle this and the similar event in metrics_service by
  87. // observing an 'OnAppEnterForeground' event instead of requiring the frontend
  88. // code to notify each service individually.
  89. void OnAppEnterForeground();
  90. // Sets the value of the "restrict" URL param to the variations service that
  91. // should be used for variation seed requests. This takes precedence over any
  92. // value coming from policy prefs. This should be called prior to any calls
  93. // to |StartRepeatedVariationsSeedFetch|.
  94. void SetRestrictMode(const std::string& restrict_mode);
  95. // Returns the variations server URL. |http_options| determines whether to
  96. // use the http or https URL. This function will return an empty GURL when
  97. // the restrict param exists for USE_HTTP, to indicate that no HTTP fallback
  98. // should happen in that case.
  99. GURL GetVariationsServerURL(HttpOptions http_options);
  100. // Returns the permanent overridden country code stored for this client. This
  101. // value will not be updated on Chrome updates.
  102. std::string GetOverriddenPermanentCountry();
  103. // Returns the permanent country code stored for this client. Country code is
  104. // in the format of lowercase ISO 3166-1 alpha-2. Example: us, br, in
  105. std::string GetStoredPermanentCountry();
  106. // Forces an override of the stored permanent country. Returns true
  107. // if the variable has been updated. Return false if the override country is
  108. // the same as the stored variable, or if the update failed for any other
  109. // reason.
  110. bool OverrideStoredPermanentCountry(const std::string& override_country);
  111. // Returns what variations will consider to be the latest country. Returns
  112. // empty if it is not available.
  113. std::string GetLatestCountry() const;
  114. // Ensures the locale that was used for evaluating variations matches the
  115. // passed |locale|. This is used to ensure that the locale determined after
  116. // loading the resource bundle (which is passed here) corresponds to what
  117. // was used for variations during an earlier stage of start up.
  118. void EnsureLocaleEquals(const std::string& locale);
  119. // Exposed for testing.
  120. static std::string GetDefaultVariationsServerURLForTesting();
  121. // Register Variations related prefs in Local State.
  122. static void RegisterPrefs(PrefRegistrySimple* registry);
  123. // Register Variations related prefs in the Profile prefs.
  124. static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
  125. // Factory method for creating a VariationsService. Does not take ownership of
  126. // |state_manager|. Caller should ensure that |state_manager| is valid for the
  127. // lifetime of this class.
  128. static std::unique_ptr<VariationsService> Create(
  129. std::unique_ptr<VariationsServiceClient> client,
  130. PrefService* local_state,
  131. metrics::MetricsStateManager* state_manager,
  132. const char* disable_network_switch,
  133. const UIStringOverrider& ui_string_overrider,
  134. web_resource::ResourceRequestAllowedNotifier::
  135. NetworkConnectionTrackerGetter network_connection_tracker_getter);
  136. // Enables fetching the seed for testing, even for unofficial builds. This
  137. // should be used along with overriding |DoActualFetch| or using
  138. // |net::TestURLLoaderFactory|.
  139. static void EnableFetchForTesting();
  140. // Set the PrefService responsible for getting policy-related preferences,
  141. // such as the restrict parameter.
  142. void set_policy_pref_service(PrefService* service) {
  143. DCHECK(service);
  144. policy_pref_service_ = service;
  145. }
  146. // Exposed for testing.
  147. void GetClientFilterableStateForVersionCalledForTesting();
  148. web_resource::ResourceRequestAllowedNotifier*
  149. GetResourceRequestAllowedNotifierForTesting() {
  150. return resource_request_allowed_notifier_.get();
  151. }
  152. // Wrapper around VariationsFieldTrialCreator::SetUpFieldTrials().
  153. bool SetUpFieldTrials(
  154. const std::vector<std::string>& variation_ids,
  155. const std::string& command_line_variation_ids,
  156. const std::vector<base::FeatureList::FeatureOverrideInfo>&
  157. extra_overrides,
  158. std::unique_ptr<base::FeatureList> feature_list,
  159. variations::PlatformFieldTrials* platform_field_trials);
  160. // Overrides cached UI strings on the resource bundle once it is initialized.
  161. void OverrideCachedUIStrings();
  162. int request_count() const { return request_count_; }
  163. // Cancels the currently pending fetch request.
  164. void CancelCurrentRequestForTesting();
  165. // Exposes StartRepeatedVariationsSeedFetch for testing.
  166. void StartRepeatedVariationsSeedFetchForTesting();
  167. // Allows the embedder to override the platform and override the OS name in
  168. // the variations server url. This is useful for android webview and weblayer
  169. // which are distinct from regular android chrome.
  170. void OverridePlatform(Study::Platform platform,
  171. const std::string& osname_server_param_override);
  172. protected:
  173. // Gets the serial number of the most recent Finch seed. Virtual for testing.
  174. virtual const std::string& GetLatestSerialNumber();
  175. // Starts the fetching process once, where |OnURLFetchComplete| is called with
  176. // the response. This calls DoFetchToURL with the set url.
  177. virtual void DoActualFetch();
  178. // Attempts a seed fetch from the set |url|. Returns true if the fetch was
  179. // started successfully, false otherwise. |is_http_retry| should be true if
  180. // this is a retry over HTTP, false otherwise.
  181. virtual bool DoFetchFromURL(const GURL& url, bool is_http_retry);
  182. // Stores the seed to prefs. Set as virtual and protected so that it can be
  183. // overridden by tests.
  184. virtual bool StoreSeed(const std::string& seed_data,
  185. const std::string& seed_signature,
  186. const std::string& country_code,
  187. base::Time date_fetched,
  188. bool is_delta_compressed,
  189. bool is_gzip_compressed);
  190. // Create an entropy provider based on low entropy. This is used to create
  191. // trials for studies that should only depend on low entropy, such as studies
  192. // that send experiment IDs to Google web properties. Virtual for testing.
  193. virtual std::unique_ptr<const base::FieldTrial::EntropyProvider>
  194. CreateLowEntropyProvider();
  195. // Creates the VariationsService with the given |local_state| prefs service
  196. // and |state_manager|. Does not take ownership of |state_manager|. Caller
  197. // should ensure that |state_manager| is valid for the lifetime of this class.
  198. // Use the |Create| factory method to create a VariationsService.
  199. VariationsService(
  200. std::unique_ptr<VariationsServiceClient> client,
  201. std::unique_ptr<web_resource::ResourceRequestAllowedNotifier> notifier,
  202. PrefService* local_state,
  203. metrics::MetricsStateManager* state_manager,
  204. const UIStringOverrider& ui_string_overrider);
  205. // Sets the URL for querying the variations server. Used for testing.
  206. void set_variations_server_url(const GURL& url) {
  207. variations_server_url_ = url;
  208. }
  209. // Sets the URL for querying the variations server when doing HTTP retries.
  210. // Used for testing.
  211. void set_insecure_variations_server_url(const GURL& url) {
  212. insecure_variations_server_url_ = url;
  213. }
  214. // Sets the |last_request_was_http_retry_| flag. Used for testing.
  215. void set_last_request_was_http_retry(bool was_http_retry) {
  216. last_request_was_http_retry_ = was_http_retry;
  217. }
  218. // The client that provides access to the embedder's environment.
  219. // Protected so testing subclasses can access it.
  220. VariationsServiceClient* client() { return client_.get(); }
  221. // Exposes MaybeRetryOverHTTP for testing.
  222. bool CallMaybeRetryOverHTTPForTesting();
  223. // Records a successful fetch:
  224. // (1) Resets failure streaks for Safe Mode.
  225. // (2) Records the time of this fetch as the most recent successful fetch.
  226. // Protected so testing subclasses can call it.
  227. void RecordSuccessfulFetch();
  228. private:
  229. FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest, Observer);
  230. FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest, SeedStoredWhenOKStatus);
  231. FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest, SeedNotStoredWhenNonOKStatus);
  232. FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest, InstanceManipulations);
  233. FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest,
  234. LoadPermanentConsistencyCountry);
  235. FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest, CountryHeader);
  236. FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest, GetVariationsServerURL);
  237. FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest, VariationsURLHasParams);
  238. FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest, RequestsInitiallyAllowed);
  239. FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest, RequestsInitiallyNotAllowed);
  240. FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest,
  241. SafeMode_SuccessfulFetchClearsFailureStreaks);
  242. FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest,
  243. SafeMode_NotModifiedFetchClearsFailureStreaks);
  244. FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest, InsecurelyFetchedSetWhenHTTP);
  245. FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest,
  246. InsecurelyFetchedNotSetWhenHTTPS);
  247. FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest, DoNotRetryAfterARetry);
  248. FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest,
  249. DoNotRetryIfInsecureURLIsHTTPS);
  250. void InitResourceRequestedAllowedNotifier();
  251. // Calls FetchVariationsSeed once and repeats this periodically. See
  252. // implementation for details on the period.
  253. void StartRepeatedVariationsSeedFetch();
  254. // Checks if prerequisites for fetching the Variations seed are met, and if
  255. // so, performs the actual fetch using |DoActualFetch|.
  256. void FetchVariationsSeed();
  257. // Notify any observers of this service based on the simulation |result|.
  258. void NotifyObservers(
  259. const variations::VariationsSeedSimulator::Result& result);
  260. // Called by SimpleURLLoader when |pending_seed_request_| load completes.
  261. void OnSimpleLoaderComplete(std::unique_ptr<std::string> response_body);
  262. // Retry the fetch over HTTP, called by OnSimpleLoaderComplete when a request
  263. // fails. Returns true is the fetch was successfully started, this does not
  264. // imply the actual fetch was successful.
  265. bool MaybeRetryOverHTTP();
  266. // ResourceRequestAllowedNotifier::Observer implementation:
  267. void OnResourceRequestsAllowed() override;
  268. // Performs a variations seed simulation with the given |seed| and |version|
  269. // and logs the simulation results as histograms.
  270. void PerformSimulationWithVersion(
  271. std::unique_ptr<variations::VariationsSeed> seed,
  272. const base::Version& version);
  273. // Encrypts a string using the encrypted_messages component, input is passed
  274. // in as |plaintext|, outputs a serialized EncryptedMessage protobuf as
  275. // |encrypted|. Returns true on success, false on failure. The encryption can
  276. // be done in-place.
  277. bool EncryptString(const std::string& plaintext, std::string* encrypted);
  278. // Loads the country code to use for filtering permanent consistency studies,
  279. // updating the stored country code if the stored value was for a different
  280. // Chrome version. The country used for permanent consistency studies is kept
  281. // consistent between Chrome upgrades in order to avoid annoying the user due
  282. // to experiment churn while traveling.
  283. std::string LoadPermanentConsistencyCountry(
  284. const base::Version& version,
  285. const std::string& latest_country);
  286. std::unique_ptr<VariationsServiceClient> client_;
  287. // The pref service used to store persist the variations seed.
  288. raw_ptr<PrefService> local_state_;
  289. // Used for instantiating entropy providers for variations seed simulation.
  290. // Weak pointer.
  291. raw_ptr<metrics::MetricsStateManager> state_manager_;
  292. // Used to obtain policy-related preferences. Depending on the platform, will
  293. // either be Local State or Profile prefs.
  294. raw_ptr<PrefService> policy_pref_service_;
  295. // Contains the scheduler instance that handles timing for requests to the
  296. // server. Initially NULL and instantiated when the initial fetch is
  297. // requested.
  298. std::unique_ptr<VariationsRequestScheduler> request_scheduler_;
  299. // Contains the current seed request. Will only have a value while a request
  300. // is pending, and will be reset by |OnURLFetchComplete|.
  301. std::unique_ptr<network::SimpleURLLoader> pending_seed_request_;
  302. // The value of the "restrict" URL param to the variations server that has
  303. // been specified via |SetRestrictMode|. If empty, the URL param will be set
  304. // based on policy prefs.
  305. std::string restrict_mode_;
  306. // The URL to use for querying the variations server.
  307. GURL variations_server_url_;
  308. // HTTP URL used as a fallback if HTTPS fetches fail. If not set, retries
  309. // over HTTP will not be attempted.
  310. GURL insecure_variations_server_url_;
  311. // Tracks whether the initial request to the variations server had completed.
  312. bool initial_request_completed_ = false;
  313. // Tracks whether any errors resolving delta compression were encountered
  314. // since the last time a seed was fetched successfully.
  315. bool delta_error_since_last_success_ = false;
  316. // Helper class used to tell this service if it's allowed to make network
  317. // resource requests.
  318. std::unique_ptr<web_resource::ResourceRequestAllowedNotifier>
  319. resource_request_allowed_notifier_;
  320. // The start time of the last seed request. This is used to measure the
  321. // latency of seed requests. Initially zero.
  322. base::TimeTicks last_request_started_time_;
  323. // The number of requests to the variations server that have been performed.
  324. int request_count_ = 0;
  325. // List of observers of the VariationsService.
  326. base::ObserverList<Observer>::Unchecked observer_list_;
  327. // The main entry point for managing safe mode state.
  328. SafeSeedManager safe_seed_manager_;
  329. // Member responsible for creating trials from a variations seed.
  330. VariationsFieldTrialCreator field_trial_creator_;
  331. // True if the last request was a retry over http.
  332. bool last_request_was_http_retry_ = false;
  333. // When not empty, contains an override for the os name in the variations
  334. // server url.
  335. std::string osname_server_param_override_;
  336. #if BUILDFLAG(IS_CHROMEOS_ASH)
  337. std::unique_ptr<DeviceVariationsRestrictionByPolicyApplicator>
  338. device_variations_restrictions_by_policy_applicator_;
  339. #endif
  340. SEQUENCE_CHECKER(sequence_checker_);
  341. base::WeakPtrFactory<VariationsService> weak_ptr_factory_{this};
  342. };
  343. } // namespace variations
  344. #endif // COMPONENTS_VARIATIONS_SERVICE_VARIATIONS_SERVICE_H_