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

Side by Side Diff: components/syncable_prefs/pref_model_associator.cc

Issue 2459823002: [Sync] Rename syncable_prefs to sync_preferences. (Closed)
Patch Set: Created 4 years, 1 month 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
(Empty)
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 "components/syncable_prefs/pref_model_associator.h"
6
7 #include <utility>
8
9 #include "base/auto_reset.h"
10 #include "base/json/json_reader.h"
11 #include "base/json/json_string_value_serializer.h"
12 #include "base/location.h"
13 #include "base/logging.h"
14 #include "base/memory/ptr_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/values.h"
17 #include "components/prefs/pref_service.h"
18 #include "components/sync/model/sync_change.h"
19 #include "components/sync/model/sync_error_factory.h"
20 #include "components/sync/protocol/preference_specifics.pb.h"
21 #include "components/sync/protocol/sync.pb.h"
22 #include "components/syncable_prefs/pref_model_associator_client.h"
23 #include "components/syncable_prefs/pref_service_syncable.h"
24
25 using syncer::PREFERENCES;
26 using syncer::PRIORITY_PREFERENCES;
27
28 namespace syncable_prefs {
29
30 namespace {
31
32 const sync_pb::PreferenceSpecifics& GetSpecifics(const syncer::SyncData& pref) {
33 DCHECK(pref.GetDataType() == syncer::PREFERENCES ||
34 pref.GetDataType() == syncer::PRIORITY_PREFERENCES);
35 if (pref.GetDataType() == syncer::PRIORITY_PREFERENCES) {
36 return pref.GetSpecifics().priority_preference().preference();
37 } else {
38 return pref.GetSpecifics().preference();
39 }
40 }
41
42 sync_pb::PreferenceSpecifics* GetMutableSpecifics(
43 const syncer::ModelType type,
44 sync_pb::EntitySpecifics* specifics) {
45 if (type == syncer::PRIORITY_PREFERENCES) {
46 DCHECK(!specifics->has_preference());
47 return specifics->mutable_priority_preference()->mutable_preference();
48 } else {
49 DCHECK(!specifics->has_priority_preference());
50 return specifics->mutable_preference();
51 }
52 }
53
54 } // namespace
55
56 PrefModelAssociator::PrefModelAssociator(
57 const PrefModelAssociatorClient* client,
58 syncer::ModelType type)
59 : models_associated_(false),
60 processing_syncer_changes_(false),
61 pref_service_(NULL),
62 type_(type),
63 client_(client) {
64 DCHECK(CalledOnValidThread());
65 DCHECK(type_ == PREFERENCES || type_ == PRIORITY_PREFERENCES);
66 }
67
68 PrefModelAssociator::~PrefModelAssociator() {
69 DCHECK(CalledOnValidThread());
70 pref_service_ = NULL;
71
72 synced_pref_observers_.clear();
73 }
74
75 void PrefModelAssociator::InitPrefAndAssociate(
76 const syncer::SyncData& sync_pref,
77 const std::string& pref_name,
78 syncer::SyncChangeList* sync_changes) {
79 const base::Value* user_pref_value = pref_service_->GetUserPrefValue(
80 pref_name.c_str());
81 VLOG(1) << "Associating preference " << pref_name;
82
83 if (sync_pref.IsValid()) {
84 const sync_pb::PreferenceSpecifics& preference = GetSpecifics(sync_pref);
85 DCHECK(pref_name == preference.name());
86 base::JSONReader reader;
87 std::unique_ptr<base::Value> sync_value(
88 reader.ReadToValue(preference.value()));
89 if (!sync_value.get()) {
90 LOG(ERROR) << "Failed to deserialize preference value: "
91 << reader.GetErrorMessage();
92 return;
93 }
94
95 if (user_pref_value) {
96 DVLOG(1) << "Found user pref value for " << pref_name;
97 // We have both server and local values. Merge them.
98 std::unique_ptr<base::Value> new_value(
99 MergePreference(pref_name, *user_pref_value, *sync_value));
100
101 // Update the local preference based on what we got from the
102 // sync server. Note: this only updates the user value store, which is
103 // ignored if the preference is policy controlled.
104 if (new_value->IsType(base::Value::TYPE_NULL)) {
105 LOG(WARNING) << "Sync has null value for pref " << pref_name.c_str();
106 pref_service_->ClearPref(pref_name.c_str());
107 } else if (!new_value->IsType(user_pref_value->GetType())) {
108 LOG(WARNING) << "Synced value for " << preference.name()
109 << " is of type " << new_value->GetType()
110 << " which doesn't match pref type "
111 << user_pref_value->GetType();
112 } else if (!user_pref_value->Equals(new_value.get())) {
113 pref_service_->Set(pref_name.c_str(), *new_value);
114 }
115
116 // If the merge resulted in an updated value, inform the syncer.
117 if (!sync_value->Equals(new_value.get())) {
118 syncer::SyncData sync_data;
119 if (!CreatePrefSyncData(pref_name, *new_value, &sync_data)) {
120 LOG(ERROR) << "Failed to update preference.";
121 return;
122 }
123
124 sync_changes->push_back(
125 syncer::SyncChange(FROM_HERE,
126 syncer::SyncChange::ACTION_UPDATE,
127 sync_data));
128 }
129 } else if (!sync_value->IsType(base::Value::TYPE_NULL)) {
130 // Only a server value exists. Just set the local user value.
131 pref_service_->Set(pref_name.c_str(), *sync_value);
132 } else {
133 LOG(WARNING) << "Sync has null value for pref " << pref_name.c_str();
134 }
135 synced_preferences_.insert(preference.name());
136 } else if (user_pref_value) {
137 // The server does not know about this preference and should be added
138 // to the syncer's database.
139 syncer::SyncData sync_data;
140 if (!CreatePrefSyncData(pref_name, *user_pref_value, &sync_data)) {
141 LOG(ERROR) << "Failed to update preference.";
142 return;
143 }
144 sync_changes->push_back(
145 syncer::SyncChange(FROM_HERE,
146 syncer::SyncChange::ACTION_ADD,
147 sync_data));
148 synced_preferences_.insert(pref_name);
149 }
150
151 // Else this pref does not have a sync value but also does not have a user
152 // controlled value (either it's a default value or it's policy controlled,
153 // either way it's not interesting). We can ignore it. Once it gets changed,
154 // we'll send the new user controlled value to the syncer.
155 }
156
157 void PrefModelAssociator::RegisterMergeDataFinishedCallback(
158 const base::Closure& callback) {
159 if (!models_associated_)
160 callback_list_.push_back(callback);
161 else
162 callback.Run();
163 }
164
165 syncer::SyncMergeResult PrefModelAssociator::MergeDataAndStartSyncing(
166 syncer::ModelType type,
167 const syncer::SyncDataList& initial_sync_data,
168 std::unique_ptr<syncer::SyncChangeProcessor> sync_processor,
169 std::unique_ptr<syncer::SyncErrorFactory> sync_error_factory) {
170 DCHECK_EQ(type_, type);
171 DCHECK(CalledOnValidThread());
172 DCHECK(pref_service_);
173 DCHECK(!sync_processor_.get());
174 DCHECK(sync_processor.get());
175 DCHECK(sync_error_factory.get());
176 syncer::SyncMergeResult merge_result(type);
177 sync_processor_ = std::move(sync_processor);
178 sync_error_factory_ = std::move(sync_error_factory);
179
180 syncer::SyncChangeList new_changes;
181 std::set<std::string> remaining_preferences = registered_preferences_;
182
183 // Go through and check for all preferences we care about that sync already
184 // knows about.
185 for (syncer::SyncDataList::const_iterator sync_iter =
186 initial_sync_data.begin();
187 sync_iter != initial_sync_data.end();
188 ++sync_iter) {
189 DCHECK_EQ(type_, sync_iter->GetDataType());
190
191 const sync_pb::PreferenceSpecifics& preference = GetSpecifics(*sync_iter);
192 std::string sync_pref_name = preference.name();
193
194 if (remaining_preferences.count(sync_pref_name) == 0) {
195 // We're not syncing this preference locally, ignore the sync data.
196 // TODO(zea): Eventually we want to be able to have the syncable service
197 // reconstruct all sync data for its datatype (therefore having
198 // GetAllSyncData be a complete representation). We should store this
199 // data somewhere, even if we don't use it.
200 continue;
201 }
202
203 remaining_preferences.erase(sync_pref_name);
204 InitPrefAndAssociate(*sync_iter, sync_pref_name, &new_changes);
205 }
206
207 // Go through and build sync data for any remaining preferences.
208 for (std::set<std::string>::iterator pref_name_iter =
209 remaining_preferences.begin();
210 pref_name_iter != remaining_preferences.end();
211 ++pref_name_iter) {
212 InitPrefAndAssociate(syncer::SyncData(), *pref_name_iter, &new_changes);
213 }
214
215 // Push updates to sync.
216 merge_result.set_error(
217 sync_processor_->ProcessSyncChanges(FROM_HERE, new_changes));
218 if (merge_result.error().IsSet())
219 return merge_result;
220
221 for (const auto& callback : callback_list_)
222 callback.Run();
223 callback_list_.clear();
224
225 models_associated_ = true;
226 pref_service_->OnIsSyncingChanged();
227 return merge_result;
228 }
229
230 void PrefModelAssociator::StopSyncing(syncer::ModelType type) {
231 DCHECK_EQ(type_, type);
232 models_associated_ = false;
233 sync_processor_.reset();
234 sync_error_factory_.reset();
235 pref_service_->OnIsSyncingChanged();
236 }
237
238 std::unique_ptr<base::Value> PrefModelAssociator::MergePreference(
239 const std::string& name,
240 const base::Value& local_value,
241 const base::Value& server_value) {
242 // This function special cases preferences individually, so don't attempt
243 // to merge for all migrated values.
244 if (client_) {
245 std::string new_pref_name;
246 if (client_->IsMergeableListPreference(name))
247 return base::WrapUnique(MergeListValues(local_value, server_value));
248 if (client_->IsMergeableDictionaryPreference(name))
249 return base::WrapUnique(MergeDictionaryValues(local_value, server_value));
250 }
251
252 // If this is not a specially handled preference, server wins.
253 return base::WrapUnique(server_value.DeepCopy());
254 }
255
256 bool PrefModelAssociator::CreatePrefSyncData(
257 const std::string& name,
258 const base::Value& value,
259 syncer::SyncData* sync_data) const {
260 if (value.IsType(base::Value::TYPE_NULL)) {
261 LOG(ERROR) << "Attempting to sync a null pref value for " << name;
262 return false;
263 }
264
265 std::string serialized;
266 // TODO(zea): consider JSONWriter::Write since you don't have to check
267 // failures to deserialize.
268 JSONStringValueSerializer json(&serialized);
269 if (!json.Serialize(value)) {
270 LOG(ERROR) << "Failed to serialize preference value.";
271 return false;
272 }
273
274 sync_pb::EntitySpecifics specifics;
275 sync_pb::PreferenceSpecifics* pref_specifics =
276 GetMutableSpecifics(type_, &specifics);
277
278 pref_specifics->set_name(name);
279 pref_specifics->set_value(serialized);
280 *sync_data = syncer::SyncData::CreateLocalData(name, name, specifics);
281 return true;
282 }
283
284 base::Value* PrefModelAssociator::MergeListValues(const base::Value& from_value,
285 const base::Value& to_value) {
286 if (from_value.GetType() == base::Value::TYPE_NULL)
287 return to_value.DeepCopy();
288 if (to_value.GetType() == base::Value::TYPE_NULL)
289 return from_value.DeepCopy();
290
291 DCHECK(from_value.GetType() == base::Value::TYPE_LIST);
292 DCHECK(to_value.GetType() == base::Value::TYPE_LIST);
293 const base::ListValue& from_list_value =
294 static_cast<const base::ListValue&>(from_value);
295 const base::ListValue& to_list_value =
296 static_cast<const base::ListValue&>(to_value);
297 base::ListValue* result = to_list_value.DeepCopy();
298
299 for (const auto& value : from_list_value) {
300 result->AppendIfNotPresent(value->CreateDeepCopy());
301 }
302 return result;
303 }
304
305 base::Value* PrefModelAssociator::MergeDictionaryValues(
306 const base::Value& from_value,
307 const base::Value& to_value) {
308 if (from_value.GetType() == base::Value::TYPE_NULL)
309 return to_value.DeepCopy();
310 if (to_value.GetType() == base::Value::TYPE_NULL)
311 return from_value.DeepCopy();
312
313 DCHECK_EQ(from_value.GetType(), base::Value::TYPE_DICTIONARY);
314 DCHECK_EQ(to_value.GetType(), base::Value::TYPE_DICTIONARY);
315 const base::DictionaryValue& from_dict_value =
316 static_cast<const base::DictionaryValue&>(from_value);
317 const base::DictionaryValue& to_dict_value =
318 static_cast<const base::DictionaryValue&>(to_value);
319 base::DictionaryValue* result = to_dict_value.DeepCopy();
320
321 for (base::DictionaryValue::Iterator it(from_dict_value); !it.IsAtEnd();
322 it.Advance()) {
323 const base::Value* from_key_value = &it.value();
324 base::Value* to_key_value;
325 if (result->GetWithoutPathExpansion(it.key(), &to_key_value)) {
326 if (from_key_value->GetType() == base::Value::TYPE_DICTIONARY &&
327 to_key_value->GetType() == base::Value::TYPE_DICTIONARY) {
328 base::Value* merged_value =
329 MergeDictionaryValues(*from_key_value, *to_key_value);
330 result->SetWithoutPathExpansion(it.key(), merged_value);
331 }
332 // Note that for all other types we want to preserve the "to"
333 // values so we do nothing here.
334 } else {
335 result->SetWithoutPathExpansion(it.key(), from_key_value->DeepCopy());
336 }
337 }
338 return result;
339 }
340
341 // Note: This will build a model of all preferences registered as syncable
342 // with user controlled data. We do not track any information for preferences
343 // not registered locally as syncable and do not inform the syncer of
344 // non-user controlled preferences.
345 syncer::SyncDataList PrefModelAssociator::GetAllSyncData(
346 syncer::ModelType type)
347 const {
348 DCHECK_EQ(type_, type);
349 syncer::SyncDataList current_data;
350 for (PreferenceSet::const_iterator iter = synced_preferences_.begin();
351 iter != synced_preferences_.end();
352 ++iter) {
353 std::string name = *iter;
354 const PrefService::Preference* pref =
355 pref_service_->FindPreference(name.c_str());
356 DCHECK(pref);
357 if (!pref->IsUserControlled() || pref->IsDefaultValue())
358 continue; // This is not data we care about.
359 // TODO(zea): plumb a way to read the user controlled value.
360 syncer::SyncData sync_data;
361 if (!CreatePrefSyncData(name, *pref->GetValue(), &sync_data))
362 continue;
363 current_data.push_back(sync_data);
364 }
365 return current_data;
366 }
367
368 syncer::SyncError PrefModelAssociator::ProcessSyncChanges(
369 const tracked_objects::Location& from_here,
370 const syncer::SyncChangeList& change_list) {
371 if (!models_associated_) {
372 syncer::SyncError error(FROM_HERE,
373 syncer::SyncError::DATATYPE_ERROR,
374 "Models not yet associated.",
375 PREFERENCES);
376 return error;
377 }
378 base::AutoReset<bool> processing_changes(&processing_syncer_changes_, true);
379 syncer::SyncChangeList::const_iterator iter;
380 for (iter = change_list.begin(); iter != change_list.end(); ++iter) {
381 DCHECK_EQ(type_, iter->sync_data().GetDataType());
382
383 const sync_pb::PreferenceSpecifics& pref_specifics =
384 GetSpecifics(iter->sync_data());
385
386 std::string name = pref_specifics.name();
387 // It is possible that we may receive a change to a preference we do not
388 // want to sync. For example if the user is syncing a Mac client and a
389 // Windows client, the Windows client does not support
390 // kConfirmToQuitEnabled. Ignore updates from these preferences.
391 std::string pref_name = pref_specifics.name();
392 if (!IsPrefRegistered(pref_name.c_str()))
393 continue;
394
395 if (iter->change_type() == syncer::SyncChange::ACTION_DELETE) {
396 pref_service_->ClearPref(pref_name);
397 continue;
398 }
399
400 std::unique_ptr<base::Value> value(ReadPreferenceSpecifics(pref_specifics));
401 if (!value.get()) {
402 // Skip values we can't deserialize.
403 // TODO(zea): consider taking some further action such as erasing the bad
404 // data.
405 continue;
406 }
407
408 // This will only modify the user controlled value store, which takes
409 // priority over the default value but is ignored if the preference is
410 // policy controlled.
411 pref_service_->Set(pref_name, *value);
412
413 NotifySyncedPrefObservers(pref_specifics.name(), true /*from_sync*/);
414
415 // Keep track of any newly synced preferences.
416 if (iter->change_type() == syncer::SyncChange::ACTION_ADD) {
417 synced_preferences_.insert(pref_specifics.name());
418 }
419 }
420 return syncer::SyncError();
421 }
422
423 base::Value* PrefModelAssociator::ReadPreferenceSpecifics(
424 const sync_pb::PreferenceSpecifics& preference) {
425 base::JSONReader reader;
426 std::unique_ptr<base::Value> value(reader.ReadToValue(preference.value()));
427 if (!value.get()) {
428 std::string err = "Failed to deserialize preference value: " +
429 reader.GetErrorMessage();
430 LOG(ERROR) << err;
431 return NULL;
432 }
433 return value.release();
434 }
435
436 bool PrefModelAssociator::IsPrefSynced(const std::string& name) const {
437 return synced_preferences_.find(name) != synced_preferences_.end();
438 }
439
440 void PrefModelAssociator::AddSyncedPrefObserver(const std::string& name,
441 SyncedPrefObserver* observer) {
442 std::unique_ptr<SyncedPrefObserverList>& observers =
443 synced_pref_observers_[name];
444 if (!observers)
445 observers = base::MakeUnique<SyncedPrefObserverList>();
446
447 observers->AddObserver(observer);
448 }
449
450 void PrefModelAssociator::RemoveSyncedPrefObserver(const std::string& name,
451 SyncedPrefObserver* observer) {
452 auto observer_iter = synced_pref_observers_.find(name);
453 if (observer_iter == synced_pref_observers_.end())
454 return;
455 SyncedPrefObserverList* observers = observer_iter->second.get();
456 observers->RemoveObserver(observer);
457 }
458
459 void PrefModelAssociator::SetPrefModelAssociatorClientForTesting(
460 const PrefModelAssociatorClient* client) {
461 DCHECK(!client_);
462 client_ = client;
463 }
464
465 std::set<std::string> PrefModelAssociator::registered_preferences() const {
466 return registered_preferences_;
467 }
468
469 void PrefModelAssociator::RegisterPref(const char* name) {
470 DCHECK(!models_associated_ && registered_preferences_.count(name) == 0);
471 registered_preferences_.insert(name);
472 }
473
474 bool PrefModelAssociator::IsPrefRegistered(const char* name) {
475 return registered_preferences_.count(name) > 0;
476 }
477
478 void PrefModelAssociator::ProcessPrefChange(const std::string& name) {
479 if (processing_syncer_changes_)
480 return; // These are changes originating from us, ignore.
481
482 // We only process changes if we've already associated models.
483 if (!models_associated_)
484 return;
485
486 const PrefService::Preference* preference =
487 pref_service_->FindPreference(name.c_str());
488 if (!preference)
489 return;
490
491 if (!IsPrefRegistered(name.c_str()))
492 return; // We are not syncing this preference.
493
494 syncer::SyncChangeList changes;
495
496 if (!preference->IsUserModifiable()) {
497 // If the preference is no longer user modifiable, it must now be controlled
498 // by policy, whose values we do not sync. Just return. If the preference
499 // stops being controlled by policy, it will revert back to the user value
500 // (which we continue to update with sync changes).
501 return;
502 }
503
504 base::AutoReset<bool> processing_changes(&processing_syncer_changes_, true);
505
506 NotifySyncedPrefObservers(name, false /*from_sync*/);
507
508 if (synced_preferences_.count(name) == 0) {
509 // Not in synced_preferences_ means no synced data. InitPrefAndAssociate(..)
510 // will determine if we care about its data (e.g. if it has a default value
511 // and hasn't been changed yet we don't) and take care syncing any new data.
512 InitPrefAndAssociate(syncer::SyncData(), name, &changes);
513 } else {
514 // We are already syncing this preference, just update it's sync node.
515 syncer::SyncData sync_data;
516 if (!CreatePrefSyncData(name, *preference->GetValue(), &sync_data)) {
517 LOG(ERROR) << "Failed to update preference.";
518 return;
519 }
520 changes.push_back(
521 syncer::SyncChange(FROM_HERE,
522 syncer::SyncChange::ACTION_UPDATE,
523 sync_data));
524 }
525
526 syncer::SyncError error =
527 sync_processor_->ProcessSyncChanges(FROM_HERE, changes);
528 }
529
530 void PrefModelAssociator::SetPrefService(PrefServiceSyncable* pref_service) {
531 DCHECK(pref_service_ == NULL);
532 pref_service_ = pref_service;
533 }
534
535 void PrefModelAssociator::NotifySyncedPrefObservers(const std::string& path,
536 bool from_sync) const {
537 auto observer_iter = synced_pref_observers_.find(path);
538 if (observer_iter == synced_pref_observers_.end())
539 return;
540 SyncedPrefObserverList* observers = observer_iter->second.get();
541 for (auto& observer : *observers)
542 observer.OnSyncedPrefChanged(path, from_sync);
543 }
544
545 } // namespace syncable_prefs
OLDNEW
« no previous file with comments | « components/syncable_prefs/pref_model_associator.h ('k') | components/syncable_prefs/pref_model_associator_client.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698