[Metrics] Make MetricsStateManager take a callback param to check if UMA is enabled.
[chromium-blink-merge.git] / chrome / browser / invalidation / ticl_invalidation_service.cc
blobd2bb8e7f308cf0081e55568f8455efe17b883edb
1 // Copyright (c) 2013 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 #include "chrome/browser/invalidation/ticl_invalidation_service.h"
7 #include "base/command_line.h"
8 #include "base/metrics/histogram.h"
9 #include "chrome/browser/invalidation/gcm_invalidation_bridge.h"
10 #include "chrome/browser/services/gcm/gcm_driver.h"
11 #include "chrome/common/chrome_content_client.h"
12 #include "components/invalidation/invalidation_service_util.h"
13 #include "google_apis/gaia/gaia_constants.h"
14 #include "net/url_request/url_request_context_getter.h"
15 #include "sync/notifier/gcm_network_channel_delegate.h"
16 #include "sync/notifier/invalidation_util.h"
17 #include "sync/notifier/invalidator.h"
18 #include "sync/notifier/invalidator_state.h"
19 #include "sync/notifier/non_blocking_invalidator.h"
20 #include "sync/notifier/object_id_invalidation_map.h"
22 static const char* kOAuth2Scopes[] = {
23 GaiaConstants::kGoogleTalkOAuth2Scope
26 static const net::BackoffEntry::Policy kRequestAccessTokenBackoffPolicy = {
27 // Number of initial errors (in sequence) to ignore before applying
28 // exponential back-off rules.
31 // Initial delay for exponential back-off in ms.
32 2000,
34 // Factor by which the waiting time will be multiplied.
37 // Fuzzing percentage. ex: 10% will spread requests randomly
38 // between 90%-100% of the calculated time.
39 0.2, // 20%
41 // Maximum amount of time we are willing to delay our request in ms.
42 // TODO(pavely): crbug.com/246686 ProfileSyncService should retry
43 // RequestAccessToken on connection state change after backoff
44 1000 * 3600 * 4, // 4 hours.
46 // Time to keep an entry from being discarded even when it
47 // has no significant state, -1 to never discard.
48 -1,
50 // Don't use initial delay unless the last request was an error.
51 false,
54 namespace invalidation {
56 TiclInvalidationService::TiclInvalidationService(
57 scoped_ptr<IdentityProvider> identity_provider,
58 scoped_ptr<TiclSettingsProvider> settings_provider,
59 gcm::GCMDriver* gcm_driver,
60 const scoped_refptr<net::URLRequestContextGetter>& request_context)
61 : OAuth2TokenService::Consumer("ticl_invalidation"),
62 identity_provider_(identity_provider.Pass()),
63 settings_provider_(settings_provider.Pass()),
64 invalidator_registrar_(new syncer::InvalidatorRegistrar()),
65 request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy),
66 network_channel_type_(PUSH_CLIENT_CHANNEL),
67 gcm_driver_(gcm_driver),
68 request_context_(request_context),
69 logger_() {}
71 TiclInvalidationService::~TiclInvalidationService() {
72 DCHECK(CalledOnValidThread());
75 void TiclInvalidationService::Init(
76 scoped_ptr<syncer::InvalidationStateTracker> invalidation_state_tracker) {
77 DCHECK(CalledOnValidThread());
78 invalidation_state_tracker_ = invalidation_state_tracker.Pass();
80 if (invalidation_state_tracker_->GetInvalidatorClientId().empty()) {
81 invalidation_state_tracker_->ClearAndSetNewClientId(
82 GenerateInvalidatorClientId());
85 UpdateInvalidationNetworkChannel();
86 if (IsReadyToStart()) {
87 StartInvalidator(network_channel_type_);
90 identity_provider_->AddObserver(this);
91 identity_provider_->AddActiveAccountRefreshTokenObserver(this);
92 settings_provider_->AddObserver(this);
95 void TiclInvalidationService::InitForTest(
96 scoped_ptr<syncer::InvalidationStateTracker> invalidation_state_tracker,
97 syncer::Invalidator* invalidator) {
98 // Here we perform the equivalent of Init() and StartInvalidator(), but with
99 // some minor changes to account for the fact that we're injecting the
100 // invalidator.
101 invalidation_state_tracker_ = invalidation_state_tracker.Pass();
102 invalidator_.reset(invalidator);
104 invalidator_->RegisterHandler(this);
105 invalidator_->UpdateRegisteredIds(
106 this,
107 invalidator_registrar_->GetAllRegisteredIds());
110 void TiclInvalidationService::RegisterInvalidationHandler(
111 syncer::InvalidationHandler* handler) {
112 DCHECK(CalledOnValidThread());
113 DVLOG(2) << "Registering an invalidation handler";
114 invalidator_registrar_->RegisterHandler(handler);
115 logger_.OnRegistration(handler->GetOwnerName());
118 void TiclInvalidationService::UpdateRegisteredInvalidationIds(
119 syncer::InvalidationHandler* handler,
120 const syncer::ObjectIdSet& ids) {
121 DCHECK(CalledOnValidThread());
122 DVLOG(2) << "Registering ids: " << ids.size();
123 invalidator_registrar_->UpdateRegisteredIds(handler, ids);
124 if (invalidator_) {
125 invalidator_->UpdateRegisteredIds(
126 this,
127 invalidator_registrar_->GetAllRegisteredIds());
129 logger_.OnUpdateIds(invalidator_registrar_->GetSanitizedHandlersIdsMap());
132 void TiclInvalidationService::UnregisterInvalidationHandler(
133 syncer::InvalidationHandler* handler) {
134 DCHECK(CalledOnValidThread());
135 DVLOG(2) << "Unregistering";
136 invalidator_registrar_->UnregisterHandler(handler);
137 if (invalidator_) {
138 invalidator_->UpdateRegisteredIds(
139 this,
140 invalidator_registrar_->GetAllRegisteredIds());
142 logger_.OnUnregistration(handler->GetOwnerName());
145 syncer::InvalidatorState TiclInvalidationService::GetInvalidatorState() const {
146 DCHECK(CalledOnValidThread());
147 if (invalidator_) {
148 DVLOG(2) << "GetInvalidatorState returning "
149 << invalidator_->GetInvalidatorState();
150 return invalidator_->GetInvalidatorState();
151 } else {
152 DVLOG(2) << "Invalidator currently stopped";
153 return syncer::TRANSIENT_INVALIDATION_ERROR;
157 std::string TiclInvalidationService::GetInvalidatorClientId() const {
158 DCHECK(CalledOnValidThread());
159 return invalidation_state_tracker_->GetInvalidatorClientId();
162 InvalidationLogger* TiclInvalidationService::GetInvalidationLogger() {
163 return &logger_;
166 IdentityProvider* TiclInvalidationService::GetIdentityProvider() {
167 return identity_provider_.get();
170 void TiclInvalidationService::RequestDetailedStatus(
171 base::Callback<void(const base::DictionaryValue&)> return_callback) const {
172 if (IsStarted()) {
173 return_callback.Run(network_channel_options_);
174 invalidator_->RequestDetailedStatus(return_callback);
178 void TiclInvalidationService::RequestAccessToken() {
179 // Only one active request at a time.
180 if (access_token_request_ != NULL)
181 return;
182 request_access_token_retry_timer_.Stop();
183 OAuth2TokenService::ScopeSet oauth2_scopes;
184 for (size_t i = 0; i < arraysize(kOAuth2Scopes); i++)
185 oauth2_scopes.insert(kOAuth2Scopes[i]);
186 // Invalidate previous token, otherwise token service will return the same
187 // token again.
188 const std::string& account_id = identity_provider_->GetActiveAccountId();
189 OAuth2TokenService* token_service = identity_provider_->GetTokenService();
190 token_service->InvalidateToken(account_id, oauth2_scopes, access_token_);
191 access_token_.clear();
192 access_token_request_ =
193 token_service->StartRequest(account_id, oauth2_scopes, this);
196 void TiclInvalidationService::OnGetTokenSuccess(
197 const OAuth2TokenService::Request* request,
198 const std::string& access_token,
199 const base::Time& expiration_time) {
200 DCHECK_EQ(access_token_request_, request);
201 access_token_request_.reset();
202 // Reset backoff time after successful response.
203 request_access_token_backoff_.Reset();
204 access_token_ = access_token;
205 if (!IsStarted() && IsReadyToStart()) {
206 StartInvalidator(network_channel_type_);
207 } else {
208 UpdateInvalidatorCredentials();
212 void TiclInvalidationService::OnGetTokenFailure(
213 const OAuth2TokenService::Request* request,
214 const GoogleServiceAuthError& error) {
215 DCHECK_EQ(access_token_request_, request);
216 DCHECK_NE(error.state(), GoogleServiceAuthError::NONE);
217 access_token_request_.reset();
218 switch (error.state()) {
219 case GoogleServiceAuthError::CONNECTION_FAILED:
220 case GoogleServiceAuthError::SERVICE_UNAVAILABLE: {
221 // Transient error. Retry after some time.
222 request_access_token_backoff_.InformOfRequest(false);
223 request_access_token_retry_timer_.Start(
224 FROM_HERE,
225 request_access_token_backoff_.GetTimeUntilRelease(),
226 base::Bind(&TiclInvalidationService::RequestAccessToken,
227 base::Unretained(this)));
228 break;
230 case GoogleServiceAuthError::SERVICE_ERROR:
231 case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS: {
232 invalidator_registrar_->UpdateInvalidatorState(
233 syncer::INVALIDATION_CREDENTIALS_REJECTED);
234 break;
236 default: {
237 // We have no way to notify the user of this. Do nothing.
242 void TiclInvalidationService::OnRefreshTokenAvailable(
243 const std::string& account_id) {
244 if (!IsStarted() && IsReadyToStart())
245 StartInvalidator(network_channel_type_);
248 void TiclInvalidationService::OnRefreshTokenRevoked(
249 const std::string& account_id) {
250 access_token_.clear();
251 if (IsStarted())
252 UpdateInvalidatorCredentials();
255 void TiclInvalidationService::OnActiveAccountLogout() {
256 access_token_request_.reset();
257 request_access_token_retry_timer_.Stop();
259 if (IsStarted()) {
260 StopInvalidator();
263 // This service always expects to have a valid invalidation state. Thus, we
264 // must generate a new client ID to replace the existing one. Setting a new
265 // client ID also clears all other state.
266 invalidation_state_tracker_->
267 ClearAndSetNewClientId(GenerateInvalidatorClientId());
270 void TiclInvalidationService::OnUseGCMChannelChanged() {
271 UpdateInvalidationNetworkChannel();
274 void TiclInvalidationService::OnInvalidatorStateChange(
275 syncer::InvalidatorState state) {
276 if (state == syncer::INVALIDATION_CREDENTIALS_REJECTED) {
277 // This may be due to normal OAuth access token expiration. If so, we must
278 // fetch a new one using our refresh token. Resetting the invalidator's
279 // access token will not reset the invalidator's exponential backoff, so
280 // it's safe to try to update the token every time we receive this signal.
282 // We won't be receiving any invalidations while the refresh is in progress,
283 // we set our state to TRANSIENT_INVALIDATION_ERROR. If the credentials
284 // really are invalid, the refresh request should fail and
285 // OnGetTokenFailure() will put us into a INVALIDATION_CREDENTIALS_REJECTED
286 // state.
287 invalidator_registrar_->UpdateInvalidatorState(
288 syncer::TRANSIENT_INVALIDATION_ERROR);
289 RequestAccessToken();
290 } else {
291 invalidator_registrar_->UpdateInvalidatorState(state);
293 logger_.OnStateChange(state);
296 void TiclInvalidationService::OnIncomingInvalidation(
297 const syncer::ObjectIdInvalidationMap& invalidation_map) {
298 invalidator_registrar_->DispatchInvalidationsToHandlers(invalidation_map);
300 logger_.OnInvalidation(invalidation_map);
303 std::string TiclInvalidationService::GetOwnerName() const { return "TICL"; }
305 void TiclInvalidationService::Shutdown() {
306 DCHECK(CalledOnValidThread());
307 settings_provider_->RemoveObserver(this);
308 identity_provider_->RemoveActiveAccountRefreshTokenObserver(this);
309 identity_provider_->RemoveObserver(this);
310 if (IsStarted()) {
311 StopInvalidator();
313 invalidation_state_tracker_.reset();
314 invalidator_registrar_.reset();
317 bool TiclInvalidationService::IsReadyToStart() {
318 if (identity_provider_->GetActiveAccountId().empty()) {
319 DVLOG(2) << "Not starting TiclInvalidationService: User is not signed in.";
320 return false;
323 OAuth2TokenService* token_service = identity_provider_->GetTokenService();
324 if (!token_service) {
325 DVLOG(2)
326 << "Not starting TiclInvalidationService: "
327 << "OAuth2TokenService unavailable.";
328 return false;
331 if (!token_service->RefreshTokenIsAvailable(
332 identity_provider_->GetActiveAccountId())) {
333 DVLOG(2)
334 << "Not starting TiclInvalidationServce: Waiting for refresh token.";
335 return false;
338 return true;
341 bool TiclInvalidationService::IsStarted() const {
342 return invalidator_.get() != NULL;
345 void TiclInvalidationService::StartInvalidator(
346 InvalidationNetworkChannel network_channel) {
347 DCHECK(CalledOnValidThread());
348 DCHECK(!invalidator_);
349 DCHECK(invalidation_state_tracker_);
350 DCHECK(!invalidation_state_tracker_->GetInvalidatorClientId().empty());
352 // Request access token for PushClientChannel. GCMNetworkChannel will request
353 // access token before sending message to server.
354 if (network_channel == PUSH_CLIENT_CHANNEL && access_token_.empty()) {
355 DVLOG(1)
356 << "TiclInvalidationService: "
357 << "Deferring start until we have an access token.";
358 RequestAccessToken();
359 return;
362 syncer::NetworkChannelCreator network_channel_creator;
364 switch (network_channel) {
365 case PUSH_CLIENT_CHANNEL: {
366 notifier::NotifierOptions options =
367 ParseNotifierOptions(*CommandLine::ForCurrentProcess());
368 options.request_context_getter = request_context_;
369 options.auth_mechanism = "X-OAUTH2";
370 network_channel_options_.SetString("Options.HostPort",
371 options.xmpp_host_port.ToString());
372 network_channel_options_.SetString("Options.AuthMechanism",
373 options.auth_mechanism);
374 DCHECK_EQ(notifier::NOTIFICATION_SERVER, options.notification_method);
375 network_channel_creator =
376 syncer::NonBlockingInvalidator::MakePushClientChannelCreator(options);
377 break;
379 case GCM_NETWORK_CHANNEL: {
380 gcm_invalidation_bridge_.reset(new GCMInvalidationBridge(
381 gcm_driver_, identity_provider_.get()));
382 network_channel_creator =
383 syncer::NonBlockingInvalidator::MakeGCMNetworkChannelCreator(
384 request_context_,
385 gcm_invalidation_bridge_->CreateDelegate().Pass());
386 break;
388 default: {
389 NOTREACHED();
390 return;
394 UMA_HISTOGRAM_ENUMERATION(
395 "Invalidations.NetworkChannel", network_channel, NETWORK_CHANNELS_COUNT);
396 invalidator_.reset(new syncer::NonBlockingInvalidator(
397 network_channel_creator,
398 invalidation_state_tracker_->GetInvalidatorClientId(),
399 invalidation_state_tracker_->GetSavedInvalidations(),
400 invalidation_state_tracker_->GetBootstrapData(),
401 invalidation_state_tracker_.get(),
402 GetUserAgent(),
403 request_context_));
405 UpdateInvalidatorCredentials();
407 invalidator_->RegisterHandler(this);
408 invalidator_->UpdateRegisteredIds(
409 this,
410 invalidator_registrar_->GetAllRegisteredIds());
413 void TiclInvalidationService::UpdateInvalidationNetworkChannel() {
414 const InvalidationNetworkChannel network_channel_type =
415 settings_provider_->UseGCMChannel() ? GCM_NETWORK_CHANNEL
416 : PUSH_CLIENT_CHANNEL;
417 if (network_channel_type_ == network_channel_type)
418 return;
419 network_channel_type_ = network_channel_type;
420 if (IsStarted()) {
421 StopInvalidator();
422 StartInvalidator(network_channel_type_);
426 void TiclInvalidationService::UpdateInvalidatorCredentials() {
427 std::string email = identity_provider_->GetActiveAccountId();
429 DCHECK(!email.empty()) << "Expected user to be signed in.";
431 DVLOG(2) << "UpdateCredentials: " << email;
432 invalidator_->UpdateCredentials(email, access_token_);
435 void TiclInvalidationService::StopInvalidator() {
436 DCHECK(invalidator_);
437 gcm_invalidation_bridge_.reset();
438 invalidator_->UnregisterHandler(this);
439 invalidator_.reset();
442 } // namespace invalidation