Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / sync / glue / frontend_data_type_controller.cc
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
5 #include "chrome/browser/sync/glue/frontend_data_type_controller.h"
6
7 #include "base/logging.h"
8 #include "chrome/browser/profiles/profile.h"
9 #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"
10 #include "chrome/browser/sync/profile_sync_components_factory.h"
11 #include "chrome/browser/sync/profile_sync_service.h"
12 #include "components/sync_driver/change_processor.h"
13 #include "components/sync_driver/model_associator.h"
14 #include "content/public/browser/browser_thread.h"
15 #include "sync/api/sync_error.h"
16 #include "sync/internal_api/public/base/model_type.h"
17 #include "sync/util/data_type_histogram.h"
18
19 using content::BrowserThread;
20
21 namespace browser_sync {
22
23 // TODO(tim): Legacy controllers are being left behind in componentization
24 // effort for now, hence passing null DisableTypeCallback and still having
25 // a dependency on ProfileSyncService.  That dep can probably be removed
26 // without too much work.
27 FrontendDataTypeController::FrontendDataTypeController(
28     scoped_refptr<base::MessageLoopProxy> ui_thread,
29     const base::Closure& error_callback,
30     ProfileSyncComponentsFactory* profile_sync_factory,
31     Profile* profile,
32     ProfileSyncService* sync_service)
33     : DataTypeController(ui_thread, error_callback),
34       profile_sync_factory_(profile_sync_factory),
35       profile_(profile),
36       sync_service_(sync_service),
37       state_(NOT_RUNNING) {
38   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
39   DCHECK(profile_sync_factory);
40   DCHECK(profile);
41   DCHECK(sync_service);
42 }
43
44 void FrontendDataTypeController::LoadModels(
45     const ModelLoadCallback& model_load_callback) {
46   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
47   DCHECK(!model_load_callback.is_null());
48
49   if (state_ != NOT_RUNNING) {
50     model_load_callback.Run(type(),
51                             syncer::SyncError(FROM_HERE,
52                                               syncer::SyncError::DATATYPE_ERROR,
53                                               "Model already running",
54                                               type()));
55     return;
56   }
57
58   DCHECK(model_load_callback_.is_null());
59
60   model_load_callback_ = model_load_callback;
61   state_ = MODEL_STARTING;
62   if (!StartModels()) {
63     // If we are waiting for some external service to load before associating
64     // or we failed to start the models, we exit early. state_ will control
65     // what we perform next.
66     DCHECK(state_ == NOT_RUNNING || state_ == MODEL_STARTING);
67     return;
68   }
69
70   OnModelLoaded();
71 }
72
73 void FrontendDataTypeController::OnModelLoaded() {
74   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
75   DCHECK(!model_load_callback_.is_null());
76   DCHECK_EQ(state_, MODEL_STARTING);
77
78   state_ = MODEL_LOADED;
79   ModelLoadCallback model_load_callback = model_load_callback_;
80   model_load_callback_.Reset();
81   model_load_callback.Run(type(), syncer::SyncError());
82 }
83
84 void FrontendDataTypeController::StartAssociating(
85     const StartCallback& start_callback) {
86   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
87   DCHECK(!start_callback.is_null());
88   DCHECK_EQ(state_, MODEL_LOADED);
89
90   start_callback_ = start_callback;
91   state_ = ASSOCIATING;
92   if (!Associate()) {
93     // It's possible StartDone(..) resulted in a Stop() call, or that
94     // association failed, so we just verify that the state has moved forward.
95     DCHECK_NE(state_, ASSOCIATING);
96     return;
97   }
98   DCHECK_EQ(state_, RUNNING);
99 }
100
101 void FrontendDataTypeController::Stop() {
102   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
103
104   if (state_ == NOT_RUNNING)
105     return;
106
107   State prev_state = state_;
108   state_ = STOPPING;
109
110   // If Stop() is called while Start() is waiting for the datatype model to
111   // load, abort the start.
112   if (prev_state == MODEL_STARTING) {
113     AbortModelLoad();
114     // We can just return here since we haven't performed association if we're
115     // still in MODEL_STARTING.
116     return;
117   }
118
119   CleanUpState();
120
121   sync_service_->DeactivateDataType(type());
122
123   if (model_associator()) {
124     syncer::SyncError error;  // Not used.
125     error = model_associator()->DisassociateModels();
126   }
127
128   set_model_associator(NULL);
129   change_processor_.reset();
130
131   state_ = NOT_RUNNING;
132 }
133
134 syncer::ModelSafeGroup FrontendDataTypeController::model_safe_group()
135     const {
136   return syncer::GROUP_UI;
137 }
138
139 std::string FrontendDataTypeController::name() const {
140   // For logging only.
141   return syncer::ModelTypeToString(type());
142 }
143
144 sync_driver::DataTypeController::State FrontendDataTypeController::state()
145     const {
146   return state_;
147 }
148
149 void FrontendDataTypeController::OnSingleDataTypeUnrecoverableError(
150     const syncer::SyncError& error) {
151   DCHECK_EQ(type(), error.model_type());
152   RecordUnrecoverableError(error.location(), error.message());
153   if (!start_callback_.is_null()) {
154     syncer::SyncMergeResult local_merge_result(type());
155     local_merge_result.set_error(error);
156     base::MessageLoop::current()->PostTask(
157         FROM_HERE,
158         base::Bind(start_callback_,
159                    RUNTIME_ERROR,
160                    local_merge_result,
161                    syncer::SyncMergeResult(type())));
162   }
163 }
164
165 FrontendDataTypeController::FrontendDataTypeController()
166     : DataTypeController(base::MessageLoopProxy::current(), base::Closure()),
167       profile_sync_factory_(NULL),
168       profile_(NULL),
169       sync_service_(NULL),
170       state_(NOT_RUNNING) {
171 }
172
173 FrontendDataTypeController::~FrontendDataTypeController() {
174   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
175 }
176
177 bool FrontendDataTypeController::StartModels() {
178   DCHECK_EQ(state_, MODEL_STARTING);
179   // By default, no additional services need to be started before we can proceed
180   // with model association.
181   return true;
182 }
183
184 void FrontendDataTypeController::RecordUnrecoverableError(
185     const tracked_objects::Location& from_here,
186     const std::string& message) {
187   DVLOG(1) << "Datatype Controller failed for type "
188            << ModelTypeToString(type()) << "  "
189            << message << " at location "
190            << from_here.ToString();
191   UMA_HISTOGRAM_ENUMERATION("Sync.DataTypeRunFailures",
192                             ModelTypeToHistogramInt(type()),
193                             syncer::MODEL_TYPE_COUNT);
194
195   if (!error_callback_.is_null())
196     error_callback_.Run();
197 }
198
199 bool FrontendDataTypeController::Associate() {
200   DCHECK_EQ(state_, ASSOCIATING);
201   syncer::SyncMergeResult local_merge_result(type());
202   syncer::SyncMergeResult syncer_merge_result(type());
203   CreateSyncComponents();
204   if (!model_associator()->CryptoReadyIfNecessary()) {
205     StartDone(NEEDS_CRYPTO, local_merge_result, syncer_merge_result);
206     return false;
207   }
208
209   bool sync_has_nodes = false;
210   if (!model_associator()->SyncModelHasUserCreatedNodes(&sync_has_nodes)) {
211     syncer::SyncError error(FROM_HERE,
212                             syncer::SyncError::UNRECOVERABLE_ERROR,
213                             "Failed to load sync nodes",
214                             type());
215     local_merge_result.set_error(error);
216     StartDone(UNRECOVERABLE_ERROR, local_merge_result, syncer_merge_result);
217     return false;
218   }
219
220   // TODO(zea): Have AssociateModels fill the local and syncer merge results.
221   base::TimeTicks start_time = base::TimeTicks::Now();
222   syncer::SyncError error;
223   error = model_associator()->AssociateModels(
224       &local_merge_result,
225       &syncer_merge_result);
226   // TODO(lipalani): crbug.com/122690 - handle abort.
227   RecordAssociationTime(base::TimeTicks::Now() - start_time);
228   if (error.IsSet()) {
229     local_merge_result.set_error(error);
230     StartDone(ASSOCIATION_FAILED, local_merge_result, syncer_merge_result);
231     return false;
232   }
233
234   state_ = RUNNING;
235   // FinishStart() invokes the DataTypeManager callback, which can lead to a
236   // call to Stop() if one of the other data types being started generates an
237   // error.
238   StartDone(!sync_has_nodes ? OK_FIRST_RUN : OK,
239             local_merge_result,
240             syncer_merge_result);
241   // Return false if we're not in the RUNNING state (due to Stop() being called
242   // from FinishStart()).
243   // TODO(zea/atwilson): Should we maybe move the call to FinishStart() out of
244   // Associate() and into Start(), so we don't need this logic here? It seems
245   // cleaner to call FinishStart() from Start().
246   return state_ == RUNNING;
247 }
248
249 void FrontendDataTypeController::CleanUpState() {
250   // Do nothing by default.
251 }
252
253 void FrontendDataTypeController::CleanUp() {
254   CleanUpState();
255   set_model_associator(NULL);
256   change_processor_.reset();
257 }
258
259 void FrontendDataTypeController::AbortModelLoad() {
260   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
261   CleanUp();
262   state_ = NOT_RUNNING;
263   ModelLoadCallback model_load_callback = model_load_callback_;
264   model_load_callback_.Reset();
265   model_load_callback.Run(type(),
266                           syncer::SyncError(FROM_HERE,
267                                             syncer::SyncError::DATATYPE_ERROR,
268                                             "Aborted",
269                                             type()));
270 }
271
272 void FrontendDataTypeController::StartDone(
273     ConfigureResult start_result,
274     const syncer::SyncMergeResult& local_merge_result,
275     const syncer::SyncMergeResult& syncer_merge_result) {
276   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
277   if (!IsSuccessfulResult(start_result)) {
278     if (IsUnrecoverableResult(start_result))
279       RecordUnrecoverableError(FROM_HERE, "StartFailed");
280
281     CleanUp();
282     if (start_result == ASSOCIATION_FAILED) {
283       state_ = DISABLED;
284     } else {
285       state_ = NOT_RUNNING;
286     }
287     RecordStartFailure(start_result);
288   }
289
290   start_callback_.Run(start_result, local_merge_result, syncer_merge_result);
291 }
292
293 void FrontendDataTypeController::RecordAssociationTime(base::TimeDelta time) {
294   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
295 #define PER_DATA_TYPE_MACRO(type_str) \
296     UMA_HISTOGRAM_TIMES("Sync." type_str "AssociationTime", time);
297   SYNC_DATA_TYPE_HISTOGRAM(type());
298 #undef PER_DATA_TYPE_MACRO
299 }
300
301 void FrontendDataTypeController::RecordStartFailure(ConfigureResult result) {
302   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
303   UMA_HISTOGRAM_ENUMERATION("Sync.DataTypeStartFailures",
304                             ModelTypeToHistogramInt(type()),
305                             syncer::MODEL_TYPE_COUNT);
306 #define PER_DATA_TYPE_MACRO(type_str) \
307     UMA_HISTOGRAM_ENUMERATION("Sync." type_str "StartFailure", result, \
308                               MAX_START_RESULT);
309   SYNC_DATA_TYPE_HISTOGRAM(type());
310 #undef PER_DATA_TYPE_MACRO
311 }
312
313 sync_driver::AssociatorInterface* FrontendDataTypeController::model_associator()
314     const {
315   return model_associator_.get();
316 }
317
318 void FrontendDataTypeController::set_model_associator(
319     sync_driver::AssociatorInterface* model_associator) {
320   model_associator_.reset(model_associator);
321 }
322
323 sync_driver::ChangeProcessor* FrontendDataTypeController::GetChangeProcessor()
324     const {
325   return change_processor_.get();
326 }
327
328 void FrontendDataTypeController::set_change_processor(
329     sync_driver::ChangeProcessor* change_processor) {
330   change_processor_.reset(change_processor);
331 }
332
333 }  // namespace browser_sync