diff options
author | rsimha@chromium.org <rsimha@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2010-10-26 21:17:32 +0000 |
---|---|---|
committer | rsimha@chromium.org <rsimha@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2010-10-26 21:17:32 +0000 |
commit | daed5ecdf85e983a9ff2aa0d7db5c7fdd34b71ab (patch) | |
tree | 5a4224b03b958b7bf6eece7c9ad92530a77688c3 /chrome/browser/sync | |
parent | 44d8ce76bed0ef853a28dc55164b8e2246f3eddc (diff) | |
download | chromium_src-daed5ecdf85e983a9ff2aa0d7db5c7fdd34b71ab.zip chromium_src-daed5ecdf85e983a9ff2aa0d7db5c7fdd34b71ab.tar.gz chromium_src-daed5ecdf85e983a9ff2aa0d7db5c7fdd34b71ab.tar.bz2 |
Take 3: Refactor, relocate and rename ProfileSyncServiceTestHarness.
ProfileSyncServiceTestHarness is an automation helper class that lives in chrome/test. It contains methods that allow you to wait on various sync events, and is used by the sync integration tests.
We now need to re-use ProfileSyncServiceTestHarness to support sync operations in TestingAutomationProvider, a class that lives in chrome/browser. In order to accomplish this, we do the following things in this patch:
1) Move ProfileSyncServiceTestHarness to chrome/browser, so that TestingAutomationProvider can re-use its functionality, and rename it to ProfileSyncServiceHarness (a less wordy name that reflects the purpose of the class).
2) Since TestingAutomationProvider relies on the fact that the UI message loop is always running, we must change the default behavior of ProfileSyncServiceHarness to not start/stop the UI message loop. We make 2 key wait methods pure virtual: SignalStateComplete() and AwaitStatusChange().
3) The integration tests use a specialization of ProfileSyncServiceHarness that start/stop the UI message loop.
4) TestingAutomationProvider can go on to use a specialization of ProfileSyncServiceHarness that uses WaitableEvents. (coming up in another patch)
NOTE: There were 2 earlier attempts at checking in this patch -- See
http://codereview.chromium.org/3492005/show and
http://codereview.chromium.org/3419029/show.
BUG=56460
TEST=sync_integration_tests
Review URL: http://codereview.chromium.org/4145003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@63951 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'chrome/browser/sync')
-rw-r--r-- | chrome/browser/sync/profile_sync_service.h | 2 | ||||
-rw-r--r-- | chrome/browser/sync/profile_sync_service_harness.cc | 496 | ||||
-rw-r--r-- | chrome/browser/sync/profile_sync_service_harness.h | 195 |
3 files changed, 692 insertions, 1 deletions
diff --git a/chrome/browser/sync/profile_sync_service.h b/chrome/browser/sync/profile_sync_service.h index 6e9ac00..65f18f5 100644 --- a/chrome/browser/sync/profile_sync_service.h +++ b/chrome/browser/sync/profile_sync_service.h @@ -355,6 +355,7 @@ class ProfileSyncService : public browser_sync::SyncFrontend, const GURL& sync_service_url() const { return sync_service_url_; } + SigninManager* signin() { return &signin_; } protected: // Used by ProfileSyncServiceMock only. // @@ -407,7 +408,6 @@ class ProfileSyncService : public browser_sync::SyncFrontend, friend class ProfileSyncServicePasswordTest; friend class ProfileSyncServicePreferenceTest; friend class ProfileSyncServiceSessionTest; - friend class ProfileSyncServiceTestHarness; FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest, InitialState); FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest, UnrecoverableErrorSuspendsService); diff --git a/chrome/browser/sync/profile_sync_service_harness.cc b/chrome/browser/sync/profile_sync_service_harness.cc new file mode 100644 index 0000000..3ecafb7 --- /dev/null +++ b/chrome/browser/sync/profile_sync_service_harness.cc @@ -0,0 +1,496 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/message_loop.h" +#include "chrome/browser/browser.h" +#include "chrome/browser/defaults.h" +#include "chrome/browser/prefs/pref_service.h" +#include "chrome/browser/profile.h" +#include "chrome/browser/net/gaia/token_service.h" +#include "chrome/browser/sync/glue/sync_backend_host.h" +#include "chrome/browser/sync/profile_sync_service_harness.h" +#include "chrome/browser/sync/sessions/session_state.h" +#include "chrome/browser/tab_contents/tab_contents.h" +#include "chrome/common/net/gaia/gaia_constants.h" +#include "chrome/common/net/gaia/google_service_auth_error.h" +#include "chrome/common/pref_names.h" + +// The default value for min_timestamp_needed_ when we're not in the +// WAITING_FOR_UPDATES state. +static const int kMinTimestampNeededNone = -1; + +// The amount of time for which we wait for a live sync operation to complete. +static const int kLiveSyncOperationTimeoutMs = 30000; + +// Simple class to implement a timeout using PostDelayedTask. If it is not +// aborted before picked up by a message queue, then it asserts with the message +// provided. This class is not thread safe. +class StateChangeTimeoutEvent + : public base::RefCountedThreadSafe<StateChangeTimeoutEvent> { + public: + StateChangeTimeoutEvent(ProfileSyncServiceHarness* caller, + const std::string& message); + + // The entry point to the class from PostDelayedTask. + void Callback(); + + // Cancels the actions of the callback. Returns true if success, false + // if the callback has already timed out. + bool Abort(); + + private: + friend class base::RefCountedThreadSafe<StateChangeTimeoutEvent>; + + ~StateChangeTimeoutEvent(); + + bool aborted_; + bool did_timeout_; + + // Due to synchronization of the IO loop, the caller will always be alive + // if the class is not aborted. + ProfileSyncServiceHarness* caller_; + + // Informative message to assert in the case of a timeout. + std::string message_; + + DISALLOW_COPY_AND_ASSIGN(StateChangeTimeoutEvent); +}; + +StateChangeTimeoutEvent::StateChangeTimeoutEvent( + ProfileSyncServiceHarness* caller, + const std::string& message) + : aborted_(false), did_timeout_(false), caller_(caller), message_(message) { +} + +StateChangeTimeoutEvent::~StateChangeTimeoutEvent() { +} + +void StateChangeTimeoutEvent::Callback() { + if (!aborted_) { + if (!caller_->RunStateChangeMachine()) { + // Report the message. + did_timeout_ = true; + DCHECK(!aborted_) << message_; + caller_->SignalStateComplete(); + } + } +} + +bool StateChangeTimeoutEvent::Abort() { + aborted_ = true; + caller_ = NULL; + return !did_timeout_; +} + +ProfileSyncServiceHarness::ProfileSyncServiceHarness( + Profile* p, + const std::string& username, + const std::string& password, + int id) + : wait_state_(WAITING_FOR_ON_BACKEND_INITIALIZED), + profile_(p), + service_(NULL), + last_timestamp_(0), + min_timestamp_needed_(kMinTimestampNeededNone), + username_(username), + password_(password), + id_(id) {} + +bool ProfileSyncServiceHarness::SetupSync() { + syncable::ModelTypeSet synced_datatypes; + for (int i = syncable::FIRST_REAL_MODEL_TYPE; + i < syncable::MODEL_TYPE_COUNT; ++i) { + synced_datatypes.insert(syncable::ModelTypeFromInt(i)); + } + return SetupSync(synced_datatypes); +} + +bool ProfileSyncServiceHarness::SetupSync( + const syncable::ModelTypeSet& synced_datatypes) { + // Initialize the sync client's profile sync service object. + service_ = profile_->GetProfileSyncService(""); + if (service_ == NULL) { + LOG(ERROR) << "SetupSync(): service_ is null."; + return false; + } + + // Subscribe sync client to notifications from the profile sync service. + if (!service_->HasObserver(this)) + service_->AddObserver(this); + + // Authenticate sync client using GAIA credentials. + service_->signin()->StartSignIn(username_, password_, "", ""); + + // Wait for the OnBackendInitialized() callback. + DCHECK_EQ(wait_state_, WAITING_FOR_ON_BACKEND_INITIALIZED); + if (!AwaitStatusChangeWithTimeout(kLiveSyncOperationTimeoutMs, + "Waiting for OnBackendInitialized().")) { + LOG(ERROR) << "OnBackendInitialized() not seen after " + << kLiveSyncOperationTimeoutMs / 1000 + << " seconds."; + return false; + } + + // Choose the datatypes to be synced. If all datatypes are to be synced, + // set sync_everything to true; otherwise, set it to false. + bool sync_everything = (synced_datatypes.size() == + (syncable::MODEL_TYPE_COUNT - syncable::FIRST_REAL_MODEL_TYPE)); + service()->OnUserChoseDatatypes(sync_everything, synced_datatypes); + + // Wait for initial sync cycle to complete. + DCHECK_EQ(wait_state_, WAITING_FOR_INITIAL_SYNC); + if (!AwaitStatusChangeWithTimeout(kLiveSyncOperationTimeoutMs, + "Waiting for initial sync cycle to complete.")) { + LOG(ERROR) << "Initial sync cycle did not complete after " + << kLiveSyncOperationTimeoutMs / 1000 + << " seconds."; + return false; + } + + return true; +} + +void ProfileSyncServiceHarness::SignalStateCompleteWithNextState( + WaitState next_state) { + wait_state_ = next_state; + SignalStateComplete(); +} + +bool ProfileSyncServiceHarness::RunStateChangeMachine() { + WaitState original_wait_state = wait_state_; + switch (wait_state_) { + case WAITING_FOR_ON_BACKEND_INITIALIZED: { + LogClientInfo("WAITING_FOR_ON_BACKEND_INITIALIZED"); + if (service()->sync_initialized()) { + // The sync backend is initialized. Start waiting for the first sync + // cycle to complete. + SignalStateCompleteWithNextState(WAITING_FOR_INITIAL_SYNC); + } + break; + } + case WAITING_FOR_INITIAL_SYNC: { + LogClientInfo("WAITING_FOR_INITIAL_SYNC"); + if (IsSynced()) { + // The first sync cycle is now complete. We can start running tests. + SignalStateCompleteWithNextState(FULLY_SYNCED); + } + break; + } + case WAITING_FOR_SYNC_TO_FINISH: { + LogClientInfo("WAITING_FOR_SYNC_TO_FINISH"); + if (!IsSynced()) { + // The client is not yet fully synced. Continue waiting. + if (!GetStatus().server_reachable) { + // The client cannot reach the sync server because the network is + // disabled. There is no need to wait anymore. + SignalStateCompleteWithNextState(SERVER_UNREACHABLE); + } + break; + } + GetUpdatedTimestamp(); + SignalStateCompleteWithNextState(FULLY_SYNCED); + break; + } + case WAITING_FOR_UPDATES: { + LogClientInfo("WAITING_FOR_UPDATES"); + if (!IsSynced() || GetUpdatedTimestamp() < min_timestamp_needed_) { + // The client is not yet fully synced. Continue waiting until the client + // is at the required minimum timestamp. + break; + } + SignalStateCompleteWithNextState(FULLY_SYNCED); + break; + } + case SERVER_UNREACHABLE: { + LogClientInfo("SERVER_UNREACHABLE"); + if (GetStatus().server_reachable) { + // The client was offline due to the network being disabled, but is now + // back online. Wait for the pending sync cycle to complete. + SignalStateCompleteWithNextState(WAITING_FOR_SYNC_TO_FINISH); + } + break; + } + case FULLY_SYNCED: { + // The client is online and fully synced. There is nothing to do. + LogClientInfo("FULLY_SYNCED"); + break; + } + case WAITING_FOR_PASSPHRASE_ACCEPTED: { + LogClientInfo("WAITING_FOR_PASSPHRASE_ACCEPTED"); + if (!service()->observed_passphrase_required()) + SignalStateCompleteWithNextState(FULLY_SYNCED); + break; + } + case SYNC_DISABLED: { + // Syncing is disabled for the client. There is nothing to do. + LogClientInfo("SYNC_DISABLED"); + break; + } + default: + // Invalid state during observer callback which may be triggered by other + // classes using the the UI message loop. Defer to their handling. + break; + } + return original_wait_state != wait_state_; +} + +void ProfileSyncServiceHarness::OnStateChanged() { + RunStateChangeMachine(); +} + +bool ProfileSyncServiceHarness::AwaitPassphraseAccepted() { + LogClientInfo("AwaitPassphraseAccepted"); + if (wait_state_ == SYNC_DISABLED) { + LOG(ERROR) << "Sync disabled for Client " << id_ << "."; + return false; + } + if (!service()->observed_passphrase_required()) + return true; + wait_state_ = WAITING_FOR_PASSPHRASE_ACCEPTED; + return AwaitStatusChangeWithTimeout(kLiveSyncOperationTimeoutMs, + "Waiting for passphrase accepted."); +} + +bool ProfileSyncServiceHarness::AwaitSyncCycleCompletion( + const std::string& reason) { + LogClientInfo("AwaitSyncCycleCompletion"); + if (wait_state_ == SYNC_DISABLED) { + LOG(ERROR) << "Sync disabled for Client " << id_ << "."; + return false; + } + if (!IsSynced()) { + if (wait_state_ == SERVER_UNREACHABLE) { + // Client was offline; wait for it to go online, and then wait for sync. + AwaitStatusChangeWithTimeout(kLiveSyncOperationTimeoutMs, reason); + DCHECK_EQ(wait_state_, WAITING_FOR_SYNC_TO_FINISH); + return AwaitStatusChangeWithTimeout(kLiveSyncOperationTimeoutMs, reason); + } else { + DCHECK(service()->sync_initialized()); + wait_state_ = WAITING_FOR_SYNC_TO_FINISH; + AwaitStatusChangeWithTimeout(kLiveSyncOperationTimeoutMs, reason); + if (wait_state_ == FULLY_SYNCED) { + // Client is online; sync was successful. + return true; + } else if (wait_state_ == SERVER_UNREACHABLE){ + // Client is offline; sync was unsuccessful. + return false; + } else { + LOG(ERROR) << "Invalid wait state:" << wait_state_; + return false; + } + } + } else { + // Client is already synced; don't wait. + GetUpdatedTimestamp(); + return true; + } +} + +bool ProfileSyncServiceHarness::AwaitMutualSyncCycleCompletion( + ProfileSyncServiceHarness* partner) { + LogClientInfo("AwaitMutualSyncCycleCompletion"); + if (!AwaitSyncCycleCompletion("Sync cycle completion on active client.")) + return false; + return partner->WaitUntilTimestampIsAtLeast(last_timestamp_, + "Sync cycle completion on passive client."); +} + +bool ProfileSyncServiceHarness::AwaitGroupSyncCycleCompletion( + std::vector<ProfileSyncServiceHarness*>& partners) { + LogClientInfo("AwaitGroupSyncCycleCompletion"); + if (!AwaitSyncCycleCompletion("Sync cycle completion on active client.")) + return false; + bool return_value = true; + for (std::vector<ProfileSyncServiceHarness*>::iterator it = + partners.begin(); it != partners.end(); ++it) { + if ((this != *it) && ((*it)->wait_state_ != SYNC_DISABLED)) { + return_value = return_value && + (*it)->WaitUntilTimestampIsAtLeast(last_timestamp_, + "Sync cycle completion on partner client."); + } + } + return return_value; +} + +// static +bool ProfileSyncServiceHarness::AwaitQuiescence( + std::vector<ProfileSyncServiceHarness*>& clients) { + VLOG(1) << "AwaitQuiescence."; + bool return_value = true; + for (std::vector<ProfileSyncServiceHarness*>::iterator it = + clients.begin(); it != clients.end(); ++it) { + if ((*it)->wait_state_ != SYNC_DISABLED) + return_value = return_value && + (*it)->AwaitGroupSyncCycleCompletion(clients); + } + return return_value; +} + +bool ProfileSyncServiceHarness::WaitUntilTimestampIsAtLeast( + int64 timestamp, const std::string& reason) { + LogClientInfo("WaitUntilTimestampIsAtLeast"); + if (wait_state_ == SYNC_DISABLED) { + LOG(ERROR) << "Sync disabled for Client " << id_ << "."; + return false; + } + min_timestamp_needed_ = timestamp; + if (GetUpdatedTimestamp() < min_timestamp_needed_) { + wait_state_ = WAITING_FOR_UPDATES; + return AwaitStatusChangeWithTimeout(kLiveSyncOperationTimeoutMs, reason); + } else { + return true; + } +} + +bool ProfileSyncServiceHarness::AwaitStatusChangeWithTimeout( + int timeout_milliseconds, + const std::string& reason) { + LogClientInfo("AwaitStatusChangeWithTimeout"); + if (wait_state_ == SYNC_DISABLED) { + LOG(ERROR) << "Sync disabled for Client " << id_ << "."; + return false; + } + scoped_refptr<StateChangeTimeoutEvent> timeout_signal( + new StateChangeTimeoutEvent(this, reason)); + MessageLoopForUI* loop = MessageLoopForUI::current(); + loop->PostDelayedTask( + FROM_HERE, + NewRunnableMethod(timeout_signal.get(), + &StateChangeTimeoutEvent::Callback), + timeout_milliseconds); + AwaitStatusChange(); + LogClientInfo("AwaitStatusChangeWithTimeout succeeded"); + return timeout_signal->Abort(); +} + +ProfileSyncService::Status ProfileSyncServiceHarness::GetStatus() { + DCHECK(service() != NULL) << "GetStatus(): service() is NULL."; + return service()->QueryDetailedSyncStatus(); +} + +bool ProfileSyncServiceHarness::IsSynced() { + const SyncSessionSnapshot* snap = GetLastSessionSnapshot(); + // TODO(rsimha): Remove additional checks of snap->has_more_to_sync and + // snap->unsynced_count once http://crbug.com/48989 is fixed. + return (service() && + snap && + ServiceIsPushingChanges() && + GetStatus().notifications_enabled && + !service()->backend()->HasUnsyncedItems() && + !snap->has_more_to_sync && + snap->unsynced_count == 0); +} + +const SyncSessionSnapshot* + ProfileSyncServiceHarness::GetLastSessionSnapshot() const { + DCHECK(service_ != NULL) << "Sync service has not yet been set up."; + if (service_->backend()) { + return service_->backend()->GetLastSessionSnapshot(); + } + return NULL; +} + +void ProfileSyncServiceHarness::EnableSyncForDatatype( + syncable::ModelType datatype) { + LogClientInfo("EnableSyncForDatatype"); + syncable::ModelTypeSet synced_datatypes; + if (wait_state_ == SYNC_DISABLED) { + wait_state_ = WAITING_FOR_ON_BACKEND_INITIALIZED; + synced_datatypes.insert(datatype); + DCHECK(SetupSync(synced_datatypes)) << "Reinitialization of Client " << id_ + << " failed."; + } else { + DCHECK(service() != NULL) << "EnableSyncForDatatype(): service() is null."; + service()->GetPreferredDataTypes(&synced_datatypes); + syncable::ModelTypeSet::iterator it = synced_datatypes.find( + syncable::ModelTypeFromInt(datatype)); + if (it == synced_datatypes.end()) { + synced_datatypes.insert(syncable::ModelTypeFromInt(datatype)); + service()->OnUserChoseDatatypes(false, synced_datatypes); + wait_state_ = WAITING_FOR_SYNC_TO_FINISH; + AwaitSyncCycleCompletion("Waiting for datatype configuration."); + VLOG(1) << "EnableSyncForDatatype(): Enabled sync for datatype " + << syncable::ModelTypeToString(datatype) << " on Client " << id_; + } else { + VLOG(1) << "EnableSyncForDatatype(): Sync already enabled for datatype " + << syncable::ModelTypeToString(datatype) << " on Client " << id_; + } + } +} + +void ProfileSyncServiceHarness::DisableSyncForDatatype( + syncable::ModelType datatype) { + LogClientInfo("DisableSyncForDatatype"); + syncable::ModelTypeSet synced_datatypes; + DCHECK(service() != NULL) << "DisableSyncForDatatype(): service() is null."; + service()->GetPreferredDataTypes(&synced_datatypes); + syncable::ModelTypeSet::iterator it = synced_datatypes.find(datatype); + if (it != synced_datatypes.end()) { + synced_datatypes.erase(it); + service()->OnUserChoseDatatypes(false, synced_datatypes); + AwaitSyncCycleCompletion("Waiting for datatype configuration."); + VLOG(1) << "DisableSyncForDatatype(): Disabled sync for datatype " + << syncable::ModelTypeToString(datatype) << " on Client " << id_; + } else { + VLOG(1) << "DisableSyncForDatatype(): Sync already disabled for datatype " + << syncable::ModelTypeToString(datatype) << " on Client " << id_; + } +} + +void ProfileSyncServiceHarness::EnableSyncForAllDatatypes() { + LogClientInfo("EnableSyncForAllDatatypes"); + if (wait_state_ == SYNC_DISABLED) { + wait_state_ = WAITING_FOR_ON_BACKEND_INITIALIZED; + DCHECK(SetupSync()) << "Reinitialization of Client " << id_ << " failed."; + } else { + syncable::ModelTypeSet synced_datatypes; + for (int i = syncable::FIRST_REAL_MODEL_TYPE; + i < syncable::MODEL_TYPE_COUNT; ++i) { + synced_datatypes.insert(syncable::ModelTypeFromInt(i)); + } + DCHECK(service() != NULL) << "EnableSyncForAllDatatypes(): service() is " + " null."; + service()->OnUserChoseDatatypes(true, synced_datatypes); + wait_state_ = WAITING_FOR_SYNC_TO_FINISH; + AwaitSyncCycleCompletion("Waiting for datatype configuration."); + VLOG(1) << "EnableSyncForAllDatatypes(): Enabled sync for all datatypes on " + "Client " << id_; + } +} + +void ProfileSyncServiceHarness::DisableSyncForAllDatatypes() { + LogClientInfo("DisableSyncForAllDatatypes"); + DCHECK(service() != NULL) << "EnableSyncForAllDatatypes(): service() is " + "null."; + service()->DisableForUser(); + wait_state_ = SYNC_DISABLED; + VLOG(1) << "DisableSyncForAllDatatypes(): Disabled sync for all datatypes on " + "Client " << id_; +} + +int64 ProfileSyncServiceHarness::GetUpdatedTimestamp() { + const SyncSessionSnapshot* snap = GetLastSessionSnapshot(); + DCHECK(snap != NULL) << "GetUpdatedTimestamp(): Sync snapshot is NULL."; + DCHECK_LE(last_timestamp_, snap->max_local_timestamp); + last_timestamp_ = snap->max_local_timestamp; + return last_timestamp_; +} + +void ProfileSyncServiceHarness::LogClientInfo(std::string message) { + const SyncSessionSnapshot* snap = GetLastSessionSnapshot(); + if (snap) { + VLOG(1) << "Client " << id_ << ": " << message + << ": max_local_timestamp: " << snap->max_local_timestamp + << ", has_more_to_sync: " << snap->has_more_to_sync + << ", unsynced_count: " << snap->unsynced_count + << ", has_unsynced_items: " + << service()->backend()->HasUnsyncedItems() + << ", notifications_enabled: " + << GetStatus().notifications_enabled + << ", service_is_pushing_changes: " << ServiceIsPushingChanges(); + } else { + VLOG(1) << "Client " << id_ << ": " << message + << ": Sync session snapshot not available."; + } +} diff --git a/chrome/browser/sync/profile_sync_service_harness.h b/chrome/browser/sync/profile_sync_service_harness.h new file mode 100644 index 0000000..90f4540 --- /dev/null +++ b/chrome/browser/sync/profile_sync_service_harness.h @@ -0,0 +1,195 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_HARNESS_H_ +#define CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_HARNESS_H_ +#pragma once + +#include <string> +#include <vector> + +#include "base/time.h" +#include "chrome/browser/sync/profile_sync_service.h" + +using browser_sync::sessions::SyncSessionSnapshot; + +class Profile; + +// An instance of this class is basically our notion of a "sync client" for +// automation purposes. It harnesses the ProfileSyncService member of the +// profile passed to it on construction and automates certain things like setup +// and authentication. It provides ways to "wait" adequate periods of time for +// several clients to get to the same state. In order to use this class for +// automation, derived classes must implement 2 methods: SignalStateComplete() +// and AwaitStatusChange(). +class ProfileSyncServiceHarness : public ProfileSyncServiceObserver { + public: + ProfileSyncServiceHarness(Profile* p, + const std::string& username, + const std::string& password, + int id); + + virtual ~ProfileSyncServiceHarness() {} + + // Creates a ProfileSyncService for the profile passed at construction and + // enables sync for all available datatypes. Returns true only after sync has + // been fully initialized and authenticated, and we are ready to process + // changes. + bool SetupSync(); + + // Same as the above method, but enables sync only for the datatypes contained + // in |synced_datatypes|. + bool SetupSync(const syncable::ModelTypeSet& synced_datatypes); + + // ProfileSyncServiceObserver implementation. + virtual void OnStateChanged(); + + // Blocks the caller until this harness has completed a single sync cycle + // since the previous one. Returns true if a sync cycle has completed. + bool AwaitSyncCycleCompletion(const std::string& reason); + + // Blocks the caller until this harness has observed that the sync engine + // has "synced" up to at least the specified local timestamp. + bool WaitUntilTimestampIsAtLeast(int64 timestamp, const std::string& reason); + + // Calling this acts as a barrier and blocks the caller until |this| and + // |partner| have both completed a sync cycle. When calling this method, + // the |partner| should be the passive responder who responds to the actions + // of |this|. This method relies upon the synchronization of callbacks + // from the message queue. Returns true if two sync cycles have completed. + // Note: Use this method when exactly one client makes local change(s), and + // exactly one client is waiting to receive those changes. + bool AwaitMutualSyncCycleCompletion(ProfileSyncServiceHarness* partner); + + // Blocks the caller until |this| completes its ongoing sync cycle and every + // other client in |partners| has a timestamp that is greater than or equal to + // the timestamp of |this|. Note: Use this method when exactly one client + // makes local change(s), and more than one client is waiting to receive those + // changes. + bool AwaitGroupSyncCycleCompletion( + std::vector<ProfileSyncServiceHarness*>& partners); + + // Blocks the caller until every client in |clients| completes its ongoing + // sync cycle and all the clients' timestamps match. Note: Use this method + // when more than one client makes local change(s), and more than one client + // is waiting to receive those changes. + static bool AwaitQuiescence( + std::vector<ProfileSyncServiceHarness*>& clients); + + // If a SetPassphrase call has been issued with a valid passphrase, this + // will wait until the Cryptographer broadcasts SYNC_PASSPHRASE_ACCEPTED. + bool AwaitPassphraseAccepted(); + + // Returns the ProfileSyncService member of the the sync client. + ProfileSyncService* service() { return service_; } + + // Returns the status of the ProfileSyncService member of the the sync client. + ProfileSyncService::Status GetStatus(); + + // See ProfileSyncService::ShouldPushChanges(). + bool ServiceIsPushingChanges() { return service_->ShouldPushChanges(); } + + // Enables sync for a particular sync datatype. + void EnableSyncForDatatype(syncable::ModelType datatype); + + // Disables sync for a particular sync datatype. + void DisableSyncForDatatype(syncable::ModelType datatype); + + // Enables sync for all sync datatypes. + void EnableSyncForAllDatatypes(); + + // Disables sync for all sync datatypes. + void DisableSyncForAllDatatypes(); + + // Returns a snapshot of the current sync session. + const SyncSessionSnapshot* GetLastSessionSnapshot() const; + + private: + friend class StateChangeTimeoutEvent; + + enum WaitState { + // The sync client awaits the OnBackendInitialized() callback. + WAITING_FOR_ON_BACKEND_INITIALIZED = 0, + + // The sync client is waiting for the first sync cycle to complete. + WAITING_FOR_INITIAL_SYNC, + + // The sync client is waiting for an ongoing sync cycle to complete. + WAITING_FOR_SYNC_TO_FINISH, + + // The sync client anticipates incoming updates leading to a new sync cycle. + WAITING_FOR_UPDATES, + + // The sync client cannot reach the server. + SERVER_UNREACHABLE, + + // The sync client is fully synced and there are no pending updates. + FULLY_SYNCED, + + // Waiting for a set passphrase to be accepted by the cryptographer. + WAITING_FOR_PASSPHRASE_ACCEPTED, + + // Syncing is disabled for the client. + SYNC_DISABLED, + + NUMBER_OF_STATES, + }; + + // Called from the observer when the current wait state has been completed. + void SignalStateCompleteWithNextState(WaitState next_state); + + // Indicates that the operation being waited on is complete. Derived classes + // may implement this either by quitting the UI message loop, or by signaling + // a WaitableEvent object. + virtual void SignalStateComplete() = 0; + + // Finite state machine for controlling state. Returns true only if a state + // change has taken place. + bool RunStateChangeMachine(); + + // Returns true if a status change took place, false on timeout. + bool AwaitStatusChangeWithTimeout(int timeout_milliseconds, + const std::string& reason); + + // Waits until the sync client's status changes. Derived classes may implement + // this either by running the UI message loop, or by waiting on a + // WaitableEvent object. + virtual void AwaitStatusChange() = 0; + + // Returns true if the sync client has no unsynced items. + bool IsSynced(); + + // Logs message with relevant info about client's sync state (if available). + void LogClientInfo(std::string message); + + WaitState wait_state_; + + Profile* profile_; + ProfileSyncService* service_; + + // Updates |last_timestamp_| with the timestamp of the current sync session. + // Returns the new value of |last_timestamp_|. + int64 GetUpdatedTimestamp(); + + // This value tracks the max sync timestamp (e.g. synced-to revision) inside + // the sync engine. It gets updated when a sync cycle ends and the session + // snapshot implies syncing is "done". + int64 last_timestamp_; + + // The minimum value of the 'max_local_timestamp' member of a + // SyncSessionSnapshot we need to wait to observe in OnStateChanged when told + // to WaitUntilTimestampIsAtLeast(...). + int64 min_timestamp_needed_; + + // Credentials used for GAIA authentication. + std::string username_; + std::string password_; + + // Client ID, used for logging purposes. + int id_; + + DISALLOW_COPY_AND_ASSIGN(ProfileSyncServiceHarness); +}; + +#endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_HARNESS_H_ |