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.
5 #ifndef COMPONENTS_VARIATIONS_SERVICE_VARIATIONS_SERVICE_H_
6 #define COMPONENTS_VARIATIONS_SERVICE_VARIATIONS_SERVICE_H_
10 #include "base/compiler_specific.h"
11 #include "base/gtest_prod_util.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/memory/weak_ptr.h"
14 #include "base/metrics/field_trial.h"
15 #include "base/observer_list.h"
16 #include "base/threading/thread_checker.h"
17 #include "base/time/time.h"
18 #include "components/variations/service/variations_service_client.h"
19 #include "components/variations/variations_request_scheduler.h"
20 #include "components/variations/variations_seed_simulator.h"
21 #include "components/variations/variations_seed_store.h"
22 #include "components/web_resource/resource_request_allowed_notifier.h"
23 #include "net/url_request/url_fetcher_delegate.h"
27 class PrefRegistrySimple
;
34 class MetricsStateManager
;
37 namespace user_prefs
{
38 class PrefRegistrySyncable
;
41 namespace variations
{
45 namespace variations
{
47 // Used to setup field trials based on stored variations seed data, and fetch
48 // new seed data from the variations server.
49 class VariationsService
50 : public net::URLFetcherDelegate
,
51 public web_resource::ResourceRequestAllowedNotifier::Observer
{
55 // How critical a detected experiment change is. Whether it should be
56 // handled on a "best-effort" basis or, for a more critical change, if it
57 // should be given higher priority.
63 // Called when the VariationsService detects that there will be significant
64 // experiment changes on a restart. This notification can then be used to
65 // update UI (i.e. badging an icon).
66 virtual void OnExperimentChangesDetected(Severity severity
) = 0;
69 virtual ~Observer() {}
72 ~VariationsService() override
;
74 // Creates field trials based on Variations Seed loaded from local prefs. If
75 // there is a problem loading the seed data, all trials specified by the seed
76 // may not be created.
77 bool CreateTrialsFromSeed();
79 // Should be called before startup of the main message loop.
80 void PerformPreMainMessageLoopStartup();
82 // Calls FetchVariationsSeed once and repeats this periodically. See
83 // implementation for details on the period. Must be called after
84 // |CreateTrialsFromSeed|.
85 void StartRepeatedVariationsSeedFetch();
87 // Adds an observer to listen for detected experiment changes.
88 void AddObserver(Observer
* observer
);
90 // Removes a previously-added observer.
91 void RemoveObserver(Observer
* observer
);
93 // Called when the application enters foreground. This may trigger a
94 // FetchVariationsSeed call.
95 // TODO(rkaplow): Handle this and the similar event in metrics_service by
96 // observing an 'OnAppEnterForeground' event instead of requiring the frontend
97 // code to notify each service individually.
98 void OnAppEnterForeground();
100 // Sets the value of the "restrict" URL param to the variations service that
101 // should be used for variation seed requests. This takes precedence over any
102 // value coming from policy prefs. This should be called prior to any calls
103 // to |StartRepeatedVariationsSeedFetch|.
104 void SetRestrictMode(const std::string
& restrict_mode
);
106 // Exposed for testing.
107 void SetCreateTrialsFromSeedCalledForTesting(bool called
);
109 // Returns the variations server URL, which can vary if a command-line flag is
110 // set and/or the variations restrict pref is set in |local_prefs|. Declared
111 // static for test purposes.
112 GURL
GetVariationsServerURL(PrefService
* local_prefs
,
113 const std::string
& restrict_mode_override
);
115 // Exposed for testing.
116 static std::string
GetDefaultVariationsServerURLForTesting();
118 // Register Variations related prefs in Local State.
119 static void RegisterPrefs(PrefRegistrySimple
* registry
);
121 // Register Variations related prefs in the Profile prefs.
122 static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable
* registry
);
124 // Factory method for creating a VariationsService. Does not take ownership of
125 // |state_manager|. Caller should ensure that |state_manager| is valid for the
126 // lifetime of this class.
127 static scoped_ptr
<VariationsService
> Create(
128 scoped_ptr
<VariationsServiceClient
> client
,
129 PrefService
* local_state
,
130 metrics::MetricsStateManager
* state_manager
,
131 const char* disable_network_switch
);
133 // Factory method for creating a VariationsService in a testing context.
134 static scoped_ptr
<VariationsService
> CreateForTesting(
135 scoped_ptr
<VariationsServiceClient
> client
,
136 PrefService
* local_state
);
138 // Set the PrefService responsible for getting policy-related preferences,
139 // such as the restrict parameter.
140 void set_policy_pref_service(PrefService
* service
) {
142 policy_pref_service_
= service
;
145 // Returns the invalid variations seed signature in base64 format, or an empty
146 // string if the signature was valid, missing, or if signature verification is
148 std::string
GetInvalidVariationsSeedSignature() const;
151 // Starts the fetching process once, where |OnURLFetchComplete| is called with
153 virtual void DoActualFetch();
155 // Stores the seed to prefs. Set as virtual and protected so that it can be
156 // overridden by tests.
157 virtual bool StoreSeed(const std::string
& seed_data
,
158 const std::string
& seed_signature
,
159 const std::string
& country_code
,
160 const base::Time
& date_fetched
,
161 bool is_delta_compressed
);
163 // Creates the VariationsService with the given |local_state| prefs service
164 // and |state_manager|. Does not take ownership of |state_manager|. Caller
165 // should ensure that |state_manager| is valid for the lifetime of this class.
166 // Use the |Create| factory method to create a VariationsService.
168 scoped_ptr
<VariationsServiceClient
> client
,
169 scoped_ptr
<web_resource::ResourceRequestAllowedNotifier
> notifier
,
170 PrefService
* local_state
,
171 metrics::MetricsStateManager
* state_manager
);
174 FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest
, Observer
);
175 FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest
, SeedStoredWhenOKStatus
);
176 FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest
, SeedNotStoredWhenNonOKStatus
);
177 FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest
, SeedDateUpdatedOn304Status
);
178 FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest
,
179 LoadPermanentConsistencyCountry
);
180 FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest
, CountryHeader
);
181 FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest
, GetVariationsServerURL
);
183 // Set of different possible values to report for the
184 // Variations.LoadPermanentConsistencyCountryResult histogram. This enum must
185 // be kept consistent with its counterpart in histograms.xml.
186 enum LoadPermanentConsistencyCountryResult
{
187 LOAD_COUNTRY_NO_PREF_NO_SEED
= 0,
188 LOAD_COUNTRY_NO_PREF_HAS_SEED
,
189 LOAD_COUNTRY_INVALID_PREF_NO_SEED
,
190 LOAD_COUNTRY_INVALID_PREF_HAS_SEED
,
191 LOAD_COUNTRY_HAS_PREF_NO_SEED_VERSION_EQ
,
192 LOAD_COUNTRY_HAS_PREF_NO_SEED_VERSION_NEQ
,
193 LOAD_COUNTRY_HAS_BOTH_VERSION_EQ_COUNTRY_EQ
,
194 LOAD_COUNTRY_HAS_BOTH_VERSION_EQ_COUNTRY_NEQ
,
195 LOAD_COUNTRY_HAS_BOTH_VERSION_NEQ_COUNTRY_EQ
,
196 LOAD_COUNTRY_HAS_BOTH_VERSION_NEQ_COUNTRY_NEQ
,
200 // Checks if prerequisites for fetching the Variations seed are met, and if
201 // so, performs the actual fetch using |DoActualFetch|.
202 void FetchVariationsSeed();
204 // Notify any observers of this service based on the simulation |result|.
205 void NotifyObservers(
206 const variations::VariationsSeedSimulator::Result
& result
);
208 // net::URLFetcherDelegate implementation:
209 void OnURLFetchComplete(const net::URLFetcher
* source
) override
;
211 // ResourceRequestAllowedNotifier::Observer implementation:
212 void OnResourceRequestsAllowed() override
;
214 // Performs a variations seed simulation with the given |seed| and |version|
215 // and logs the simulation results as histograms.
216 void PerformSimulationWithVersion(scoped_ptr
<variations::VariationsSeed
> seed
,
217 const base::Version
& version
);
219 // Record the time of the most recent successful fetch.
220 void RecordLastFetchTime();
222 // Loads the country code to use for filtering permanent consistency studies,
223 // updating the stored country code if the stored value was for a different
224 // Chrome version. The country used for permanent consistency studies is kept
225 // consistent between Chrome upgrades in order to avoid annoying the user due
226 // to experiment churn while traveling.
227 std::string
LoadPermanentConsistencyCountry(
228 const base::Version
& version
,
229 const std::string
& latest_country
);
231 scoped_ptr
<VariationsServiceClient
> client_
;
233 // The pref service used to store persist the variations seed.
234 PrefService
* local_state_
;
236 // Used for instantiating entropy providers for variations seed simulation.
238 metrics::MetricsStateManager
* state_manager_
;
240 // Used to obtain policy-related preferences. Depending on the platform, will
241 // either be Local State or Profile prefs.
242 PrefService
* policy_pref_service_
;
244 VariationsSeedStore seed_store_
;
246 // Contains the scheduler instance that handles timing for requests to the
247 // server. Initially NULL and instantiated when the initial fetch is
249 scoped_ptr
<VariationsRequestScheduler
> request_scheduler_
;
251 // Contains the current seed request. Will only have a value while a request
252 // is pending, and will be reset by |OnURLFetchComplete|.
253 scoped_ptr
<net::URLFetcher
> pending_seed_request_
;
255 // The value of the "restrict" URL param to the variations server that has
256 // been specified via |SetRestrictMode|. If empty, the URL param will be set
257 // based on policy prefs.
258 std::string restrict_mode_
;
260 // The URL to use for querying the variations server.
261 GURL variations_server_url_
;
263 // Tracks whether |CreateTrialsFromSeed| has been called, to ensure that
264 // it gets called prior to |StartRepeatedVariationsSeedFetch|.
265 bool create_trials_from_seed_called_
;
267 // Tracks whether the initial request to the variations server had completed.
268 bool initial_request_completed_
;
270 // Indicates that the next request to the variations service shouldn't specify
271 // that it supports delta compression. Set to true when a delta compressed
272 // response encountered an error.
273 bool disable_deltas_for_next_request_
;
275 // Helper class used to tell this service if it's allowed to make network
276 // resource requests.
277 scoped_ptr
<web_resource::ResourceRequestAllowedNotifier
>
278 resource_request_allowed_notifier_
;
280 // The start time of the last seed request. This is used to measure the
281 // latency of seed requests. Initially zero.
282 base::TimeTicks last_request_started_time_
;
284 // The number of requests to the variations server that have been performed.
287 // List of observers of the VariationsService.
288 base::ObserverList
<Observer
> observer_list_
;
290 base::ThreadChecker thread_checker_
;
292 base::WeakPtrFactory
<VariationsService
> weak_ptr_factory_
;
294 DISALLOW_COPY_AND_ASSIGN(VariationsService
);
297 } // namespace variations
299 #endif // COMPONENTS_VARIATIONS_SERVICE_VARIATIONS_SERVICE_H_