Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(689)

Side by Side Diff: components/browser_sync/profile_sync_service.cc

Issue 2559123002: [Sync] SyncEngine refactor part 2: SyncServiceBase. (Closed)
Patch Set: Self-review (added comments). Created 4 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "components/browser_sync/profile_sync_service.h" 5 #include "components/browser_sync/profile_sync_service.h"
6 6
7 #include <stddef.h> 7 #include <stddef.h>
8 8
9 #include <cstddef> 9 #include <cstddef>
10 #include <map> 10 #include <map>
11 #include <utility> 11 #include <utility>
12 12
13 #include "base/bind.h" 13 #include "base/bind.h"
14 #include "base/bind_helpers.h" 14 #include "base/bind_helpers.h"
15 #include "base/callback.h" 15 #include "base/callback.h"
16 #include "base/command_line.h" 16 #include "base/command_line.h"
17 #include "base/feature_list.h" 17 #include "base/feature_list.h"
18 #include "base/files/file_util.h" 18 #include "base/files/file_util.h"
19 #include "base/logging.h" 19 #include "base/logging.h"
20 #include "base/memory/ptr_util.h" 20 #include "base/memory/ptr_util.h"
21 #include "base/memory/ref_counted.h" 21 #include "base/memory/ref_counted.h"
22 #include "base/metrics/histogram.h" 22 #include "base/metrics/histogram.h"
23 #include "base/path_service.h"
24 #include "base/profiler/scoped_tracker.h" 23 #include "base/profiler/scoped_tracker.h"
25 #include "base/single_thread_task_runner.h" 24 #include "base/single_thread_task_runner.h"
26 #include "base/strings/stringprintf.h" 25 #include "base/strings/stringprintf.h"
27 #include "base/threading/thread_restrictions.h" 26 #include "base/threading/thread_restrictions.h"
28 #include "base/threading/thread_task_runner_handle.h" 27 #include "base/threading/thread_task_runner_handle.h"
29 #include "components/autofill/core/common/autofill_pref_names.h" 28 #include "components/autofill/core/common/autofill_pref_names.h"
30 #include "components/browser_sync/browser_sync_switches.h" 29 #include "components/browser_sync/browser_sync_switches.h"
31 #include "components/history/core/browser/typed_url_data_type_controller.h" 30 #include "components/history/core/browser/typed_url_data_type_controller.h"
32 #include "components/invalidation/impl/invalidation_prefs.h" 31 #include "components/invalidation/impl/invalidation_prefs.h"
33 #include "components/invalidation/public/invalidation_service.h" 32 #include "components/invalidation/public/invalidation_service.h"
(...skipping 128 matching lines...) Expand 10 before | Expand all | Expand 10 after
162 1000 * 3600 * 4, // 4 hours. 161 1000 * 3600 * 4, // 4 hours.
163 162
164 // Time to keep an entry from being discarded even when it 163 // Time to keep an entry from being discarded even when it
165 // has no significant state, -1 to never discard. 164 // has no significant state, -1 to never discard.
166 -1, 165 -1,
167 166
168 // Don't use initial delay unless the last request was an error. 167 // Don't use initial delay unless the last request was an error.
169 false, 168 false,
170 }; 169 };
171 170
172 const base::FilePath::CharType kSyncDataFolderName[] =
173 FILE_PATH_LITERAL("Sync Data");
174 const base::FilePath::CharType kLevelDBFolderName[] = 171 const base::FilePath::CharType kLevelDBFolderName[] =
175 FILE_PATH_LITERAL("LevelDB"); 172 FILE_PATH_LITERAL("LevelDB");
176 173
177 #if defined(OS_WIN)
178 const base::FilePath::CharType kLoopbackServerBackendFilename[] =
179 FILE_PATH_LITERAL("profile.pb");
180 #endif
181
182 // Perform the actual sync data folder deletion. 174 // Perform the actual sync data folder deletion.
183 // This should only be called on the sync thread. 175 // This should only be called on the sync thread.
184 void DeleteSyncDataFolder(const base::FilePath& directory_path) { 176 void DeleteSyncDataFolder(const base::FilePath& directory_path) {
185 if (base::DirectoryExists(directory_path)) { 177 if (base::DirectoryExists(directory_path)) {
186 if (!base::DeleteFile(directory_path, true)) 178 if (!base::DeleteFile(directory_path, true))
187 LOG(DFATAL) << "Could not delete the Sync Data folder."; 179 LOG(DFATAL) << "Could not delete the Sync Data folder.";
188 } 180 }
189 } 181 }
190 182
191 } // namespace 183 } // namespace
192 184
193 ProfileSyncService::InitParams::InitParams() = default; 185 ProfileSyncService::InitParams::InitParams() = default;
186 ProfileSyncService::InitParams::InitParams(InitParams&& other) = default;
194 ProfileSyncService::InitParams::~InitParams() = default; 187 ProfileSyncService::InitParams::~InitParams() = default;
195 ProfileSyncService::InitParams::InitParams(InitParams&& other) // NOLINT
196 : sync_client(std::move(other.sync_client)),
197 signin_wrapper(std::move(other.signin_wrapper)),
198 oauth2_token_service(other.oauth2_token_service),
199 gaia_cookie_manager_service(other.gaia_cookie_manager_service),
200 start_behavior(other.start_behavior),
201 network_time_update_callback(
202 std::move(other.network_time_update_callback)),
203 base_directory(std::move(other.base_directory)),
204 url_request_context(std::move(other.url_request_context)),
205 debug_identifier(std::move(other.debug_identifier)),
206 channel(other.channel),
207 blocking_pool(other.blocking_pool) {}
208 188
209 ProfileSyncService::ProfileSyncService(InitParams init_params) 189 ProfileSyncService::ProfileSyncService(InitParams init_params)
210 : OAuth2TokenService::Consumer("sync"), 190 : SyncServiceBase(std::move(init_params.sync_client),
191 std::move(init_params.signin_wrapper),
192 init_params.channel,
193 init_params.base_directory,
194 init_params.debug_identifier),
195 OAuth2TokenService::Consumer("sync"),
211 last_auth_error_(AuthError::AuthErrorNone()), 196 last_auth_error_(AuthError::AuthErrorNone()),
212 passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED), 197 passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED),
213 sync_client_(std::move(init_params.sync_client)),
214 sync_prefs_(sync_client_->GetPrefService()),
215 sync_service_url_( 198 sync_service_url_(
216 syncer::GetSyncServiceURL(*base::CommandLine::ForCurrentProcess(), 199 syncer::GetSyncServiceURL(*base::CommandLine::ForCurrentProcess(),
217 init_params.channel)), 200 init_params.channel)),
218 network_time_update_callback_( 201 network_time_update_callback_(
219 std::move(init_params.network_time_update_callback)), 202 std::move(init_params.network_time_update_callback)),
220 base_directory_(init_params.base_directory),
221 url_request_context_(init_params.url_request_context), 203 url_request_context_(init_params.url_request_context),
222 debug_identifier_(std::move(init_params.debug_identifier)),
223 channel_(init_params.channel),
224 blocking_pool_(init_params.blocking_pool), 204 blocking_pool_(init_params.blocking_pool),
225 is_first_time_sync_configure_(false), 205 is_first_time_sync_configure_(false),
226 engine_initialized_(false), 206 engine_initialized_(false),
227 sync_disabled_by_admin_(false), 207 sync_disabled_by_admin_(false),
228 is_auth_in_progress_(false), 208 is_auth_in_progress_(false),
229 signin_(std::move(init_params.signin_wrapper)),
230 unrecoverable_error_reason_(ERROR_REASON_UNSET), 209 unrecoverable_error_reason_(ERROR_REASON_UNSET),
231 expect_sync_configuration_aborted_(false), 210 expect_sync_configuration_aborted_(false),
232 encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()), 211 encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()),
233 encrypt_everything_allowed_(true), 212 encrypt_everything_allowed_(true),
234 encrypt_everything_(false), 213 encrypt_everything_(false),
235 encryption_pending_(false), 214 encryption_pending_(false),
236 configure_status_(DataTypeManager::UNKNOWN), 215 configure_status_(DataTypeManager::UNKNOWN),
237 oauth2_token_service_(init_params.oauth2_token_service), 216 oauth2_token_service_(init_params.oauth2_token_service),
238 request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy), 217 request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy),
239 connection_status_(syncer::CONNECTION_NOT_ATTEMPTED), 218 connection_status_(syncer::CONNECTION_NOT_ATTEMPTED),
240 last_get_token_error_(GoogleServiceAuthError::AuthErrorNone()), 219 last_get_token_error_(GoogleServiceAuthError::AuthErrorNone()),
241 gaia_cookie_manager_service_(init_params.gaia_cookie_manager_service), 220 gaia_cookie_manager_service_(init_params.gaia_cookie_manager_service),
242 network_resources_(new syncer::HttpBridgeNetworkResources), 221 network_resources_(new syncer::HttpBridgeNetworkResources),
243 start_behavior_(init_params.start_behavior), 222 start_behavior_(init_params.start_behavior),
244 directory_path_(
245 base_directory_.Append(base::FilePath(kSyncDataFolderName))),
246 catch_up_configure_in_progress_(false), 223 catch_up_configure_in_progress_(false),
247 passphrase_prompt_triggered_by_version_(false), 224 passphrase_prompt_triggered_by_version_(false),
248 sync_enabled_weak_factory_(this), 225 sync_enabled_weak_factory_(this),
249 weak_factory_(this) { 226 weak_factory_(this) {
250 DCHECK(thread_checker_.CalledOnValidThread()); 227 DCHECK(thread_checker_.CalledOnValidThread());
251 DCHECK(sync_client_); 228 DCHECK(sync_client_);
252 std::string last_version = sync_prefs_.GetLastRunVersion(); 229 std::string last_version = sync_prefs_.GetLastRunVersion();
253 std::string current_version = PRODUCT_VERSION; 230 std::string current_version = PRODUCT_VERSION;
254 sync_prefs_.SetLastRunVersion(current_version); 231 sync_prefs_.SetLastRunVersion(current_version);
255 232
(...skipping 256 matching lines...) Expand 10 before | Expand all | Expand 10 after
512 credentials.sync_token = access_token_; 489 credentials.sync_token = access_token_;
513 490
514 if (credentials.sync_token.empty()) 491 if (credentials.sync_token.empty())
515 credentials.sync_token = "credentials_lost"; 492 credentials.sync_token = "credentials_lost";
516 493
517 credentials.scope_set.insert(signin_->GetSyncScopeToUse()); 494 credentials.scope_set.insert(signin_->GetSyncScopeToUse());
518 495
519 return credentials; 496 return credentials;
520 } 497 }
521 498
522 bool ProfileSyncService::ShouldDeleteSyncFolder() { 499 syncer::WeakHandle<syncer::JsEventHandler>
523 return !IsFirstSetupComplete(); 500 ProfileSyncService::GetJsEventHandler() {
501 return syncer::MakeWeakHandle(sync_js_controller_.AsWeakPtr());
524 } 502 }
525 503
526 void ProfileSyncService::InitializeEngine(bool delete_stale_data) { 504 syncer::SyncEngine::HttpPostProviderFactoryGetter
527 if (!engine_) { 505 ProfileSyncService::MakeHttpPostProviderFactoryGetter() {
528 NOTREACHED(); 506 return base::Bind(&syncer::NetworkResources::GetHttpPostProviderFactory,
529 return; 507 base::Unretained(network_resources_.get()),
530 } 508 url_request_context_, network_time_update_callback_);
509 }
531 510
532 if (!sync_thread_) { 511 std::unique_ptr<syncer::SyncEncryptionHandler::NigoriState>
533 sync_thread_ = base::MakeUnique<base::Thread>("Chrome_SyncThread"); 512 ProfileSyncService::MoveSavedNigoriState() {
534 base::Thread::Options options; 513 return std::move(saved_nigori_state_);
535 options.timer_slack = base::TIMER_SLACK_MAXIMUM; 514 }
536 CHECK(sync_thread_->StartWithOptions(options));
537 }
538 515
539 SyncCredentials credentials = GetCredentials(); 516 syncer::WeakHandle<syncer::UnrecoverableErrorHandler>
540 517 ProfileSyncService::GetUnrecoverableErrorHandler() {
541 if (delete_stale_data) 518 return syncer::MakeWeakHandle(sync_enabled_weak_factory_.GetWeakPtr());
542 ClearStaleErrors();
543
544 bool enable_local_sync_backend = false;
545 base::FilePath local_sync_backend_folder =
546 sync_prefs_.GetLocalSyncBackendDir();
547 #if defined(OS_WIN)
548 enable_local_sync_backend = sync_prefs_.IsLocalSyncEnabled();
549 if (local_sync_backend_folder.empty()) {
550 // TODO(pastarmovj): Add DIR_ROAMING_USER_DATA to PathService to simplify
551 // this code and move the logic in its right place. See crbug/657810.
552 CHECK(
553 base::PathService::Get(base::DIR_APP_DATA, &local_sync_backend_folder));
554 local_sync_backend_folder =
555 local_sync_backend_folder.Append(FILE_PATH_LITERAL("Chrome/User Data"));
556 }
557 // This code as it is now will assume the same profile order is present on all
558 // machines, which is not a given. It is to be defined if only the Default
559 // profile should get this treatment or all profile as is the case now. The
560 // solution for now will be to assume profiles are created in the same order
561 // on all machines and in the future decide if only the Default one should be
562 // considered roamed.
563 local_sync_backend_folder =
564 local_sync_backend_folder.Append(base_directory_.BaseName());
565 local_sync_backend_folder =
566 local_sync_backend_folder.Append(kLoopbackServerBackendFilename);
567 #endif // defined(OS_WIN)
568
569 SyncEngine::HttpPostProviderFactoryGetter http_post_provider_factory_getter =
570 base::Bind(&syncer::NetworkResources::GetHttpPostProviderFactory,
571 base::Unretained(network_resources_.get()),
572 url_request_context_, network_time_update_callback_);
573
574 engine_->Initialize(
575 this, sync_thread_->task_runner(), GetJsEventHandler(), sync_service_url_,
576 local_device_->GetSyncUserAgent(), credentials, delete_stale_data,
577 enable_local_sync_backend, local_sync_backend_folder,
578 base::MakeUnique<syncer::SyncManagerFactory>(),
579 MakeWeakHandle(sync_enabled_weak_factory_.GetWeakPtr()),
580 base::Bind(syncer::ReportUnrecoverableError, channel_),
581 http_post_provider_factory_getter, std::move(saved_nigori_state_));
582 } 519 }
583 520
584 bool ProfileSyncService::IsEncryptedDatatypeEnabled() const { 521 bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
585 if (encryption_pending()) 522 if (encryption_pending())
586 return true; 523 return true;
587 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes(); 524 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes();
588 const syncer::ModelTypeSet encrypted_types = GetEncryptedDataTypes(); 525 const syncer::ModelTypeSet encrypted_types = GetEncryptedDataTypes();
589 DCHECK(encrypted_types.Has(syncer::PASSWORDS)); 526 DCHECK(encrypted_types.Has(syncer::PASSWORDS));
590 return !Intersection(preferred_types, encrypted_types).Empty(); 527 return !Intersection(preferred_types, encrypted_types).Empty();
591 } 528 }
(...skipping 60 matching lines...) Expand 10 before | Expand all | Expand 10 after
652 } 589 }
653 590
654 void ProfileSyncService::StartUpSlowEngineComponents() { 591 void ProfileSyncService::StartUpSlowEngineComponents() {
655 invalidation::InvalidationService* invalidator = 592 invalidation::InvalidationService* invalidator =
656 sync_client_->GetInvalidationService(); 593 sync_client_->GetInvalidationService();
657 594
658 engine_.reset(sync_client_->GetSyncApiComponentFactory()->CreateSyncEngine( 595 engine_.reset(sync_client_->GetSyncApiComponentFactory()->CreateSyncEngine(
659 debug_identifier_, invalidator, sync_prefs_.AsWeakPtr(), 596 debug_identifier_, invalidator, sync_prefs_.AsWeakPtr(),
660 directory_path_)); 597 directory_path_));
661 598
662 // Initialize the engine. Every time we start up a new SyncEngine, we'll want 599 if (!IsFirstSetupComplete())
skym 2016/12/14 19:02:35 What's going on here? Is this copied from somewher
maxbogue 2016/12/14 19:38:09 It was moved from inside InitializeEngine (line 54
663 // to start from a fresh SyncDB, so delete any old one that might be there. 600 ClearStaleErrors();
664 InitializeEngine(ShouldDeleteSyncFolder()); 601
602 InitializeEngine();
665 603
666 UpdateFirstSyncTimePref(); 604 UpdateFirstSyncTimePref();
667 605
668 ReportPreviousSessionMemoryWarningCount(); 606 ReportPreviousSessionMemoryWarningCount();
669 } 607 }
670 608
671 void ProfileSyncService::OnGetTokenSuccess( 609 void ProfileSyncService::OnGetTokenSuccess(
672 const OAuth2TokenService::Request* request, 610 const OAuth2TokenService::Request* request,
673 const std::string& access_token, 611 const std::string& access_token,
674 const base::Time& expiration_time) { 612 const base::Time& expiration_time) {
(...skipping 1845 matching lines...) Expand 10 before | Expand all | Expand 10 after
2520 bool ProfileSyncService::IsRetryingAccessTokenFetchForTest() const { 2458 bool ProfileSyncService::IsRetryingAccessTokenFetchForTest() const {
2521 DCHECK(thread_checker_.CalledOnValidThread()); 2459 DCHECK(thread_checker_.CalledOnValidThread());
2522 return request_access_token_retry_timer_.IsRunning(); 2460 return request_access_token_retry_timer_.IsRunning();
2523 } 2461 }
2524 2462
2525 std::string ProfileSyncService::GetAccessTokenForTest() const { 2463 std::string ProfileSyncService::GetAccessTokenForTest() const {
2526 DCHECK(thread_checker_.CalledOnValidThread()); 2464 DCHECK(thread_checker_.CalledOnValidThread());
2527 return access_token_; 2465 return access_token_;
2528 } 2466 }
2529 2467
2530 WeakHandle<syncer::JsEventHandler> ProfileSyncService::GetJsEventHandler() {
2531 return MakeWeakHandle(sync_js_controller_.AsWeakPtr());
2532 }
2533
2534 syncer::SyncableService* ProfileSyncService::GetSessionsSyncableService() { 2468 syncer::SyncableService* ProfileSyncService::GetSessionsSyncableService() {
2535 DCHECK(thread_checker_.CalledOnValidThread()); 2469 DCHECK(thread_checker_.CalledOnValidThread());
2536 return sessions_sync_manager_.get(); 2470 return sessions_sync_manager_.get();
2537 } 2471 }
2538 2472
2539 syncer::SyncableService* ProfileSyncService::GetDeviceInfoSyncableService() { 2473 syncer::SyncableService* ProfileSyncService::GetDeviceInfoSyncableService() {
2540 DCHECK(thread_checker_.CalledOnValidThread()); 2474 DCHECK(thread_checker_.CalledOnValidThread());
2541 return device_info_sync_service_.get(); 2475 return device_info_sync_service_.get();
2542 } 2476 }
2543 2477
(...skipping 131 matching lines...) Expand 10 before | Expand all | Expand 10 after
2675 2609
2676 DCHECK(startup_controller_->IsSetupInProgress()); 2610 DCHECK(startup_controller_->IsSetupInProgress());
2677 startup_controller_->SetSetupInProgress(false); 2611 startup_controller_->SetSetupInProgress(false);
2678 2612
2679 if (IsEngineInitialized()) 2613 if (IsEngineInitialized())
2680 ReconfigureDatatypeManager(); 2614 ReconfigureDatatypeManager();
2681 NotifyObservers(); 2615 NotifyObservers();
2682 } 2616 }
2683 2617
2684 } // namespace browser_sync 2618 } // namespace browser_sync
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698