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

Side by Side Diff: google_apis/gcm/engine/gcm_store_impl.cc

Issue 215363007: [GCM] Adding basic G-services handling (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Adding unit tests and addressing CR feedback Created 6 years, 8 months 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 | Annotate | Revision Log
OLDNEW
1 // Copyright 2014 The Chromium Authors. All rights reserved. 1 // Copyright 2014 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 "google_apis/gcm/engine/gcm_store_impl.h" 5 #include "google_apis/gcm/engine/gcm_store_impl.h"
6 6
7 #include "base/basictypes.h" 7 #include "base/basictypes.h"
8 #include "base/bind.h" 8 #include "base/bind.h"
9 #include "base/callback.h" 9 #include "base/callback.h"
10 #include "base/file_util.h" 10 #include "base/file_util.h"
11 #include "base/files/file_path.h" 11 #include "base/files/file_path.h"
12 #include "base/logging.h" 12 #include "base/logging.h"
13 #include "base/message_loop/message_loop_proxy.h" 13 #include "base/message_loop/message_loop_proxy.h"
14 #include "base/metrics/histogram.h" 14 #include "base/metrics/histogram.h"
15 #include "base/sequenced_task_runner.h" 15 #include "base/sequenced_task_runner.h"
16 #include "base/stl_util.h" 16 #include "base/stl_util.h"
17 #include "base/strings/string_number_conversions.h" 17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/string_piece.h" 18 #include "base/strings/string_piece.h"
19 #include "base/time/time.h"
19 #include "base/tracked_objects.h" 20 #include "base/tracked_objects.h"
20 #include "components/os_crypt/os_crypt.h" 21 #include "components/os_crypt/os_crypt.h"
21 #include "google_apis/gcm/base/mcs_message.h" 22 #include "google_apis/gcm/base/mcs_message.h"
22 #include "google_apis/gcm/base/mcs_util.h" 23 #include "google_apis/gcm/base/mcs_util.h"
23 #include "google_apis/gcm/protocol/mcs.pb.h" 24 #include "google_apis/gcm/protocol/mcs.pb.h"
24 #include "third_party/leveldatabase/src/include/leveldb/db.h" 25 #include "third_party/leveldatabase/src/include/leveldb/db.h"
26 #include "third_party/leveldatabase/src/include/leveldb/write_batch.h"
25 27
26 namespace gcm { 28 namespace gcm {
27 29
28 namespace { 30 namespace {
29 31
30 // Limit to the number of outstanding messages per app. 32 // Limit to the number of outstanding messages per app.
31 const int kMessagesPerAppLimit = 20; 33 const int kMessagesPerAppLimit = 20;
32 34
33 // ---- LevelDB keys. ---- 35 // ---- LevelDB keys. ----
34 // Key for this device's android id. 36 // Key for this device's android id.
(...skipping 11 matching lines...) Expand all
46 const char kIncomingMsgKeyStart[] = "incoming1-"; 48 const char kIncomingMsgKeyStart[] = "incoming1-";
47 // Key guaranteed to be higher than all incoming message keys. 49 // Key guaranteed to be higher than all incoming message keys.
48 // Used for limiting iteration. 50 // Used for limiting iteration.
49 const char kIncomingMsgKeyEnd[] = "incoming2-"; 51 const char kIncomingMsgKeyEnd[] = "incoming2-";
50 // Lowest lexicographically ordered outgoing message key. 52 // Lowest lexicographically ordered outgoing message key.
51 // Used for prefixing outgoing messages. 53 // Used for prefixing outgoing messages.
52 const char kOutgoingMsgKeyStart[] = "outgoing1-"; 54 const char kOutgoingMsgKeyStart[] = "outgoing1-";
53 // Key guaranteed to be higher than all outgoing message keys. 55 // Key guaranteed to be higher than all outgoing message keys.
54 // Used for limiting iteration. 56 // Used for limiting iteration.
55 const char kOutgoingMsgKeyEnd[] = "outgoing2-"; 57 const char kOutgoingMsgKeyEnd[] = "outgoing2-";
58 // Lowest lexicographically ordered G service settings key.
59 // Used for prefixing G services settings.
60 const char kGServiceSettingKeyStart[] = "Gservice1-";
61 // Key guaranteed to be higher than all G services settings keys.
62 // Used for limiting iteration.
63 const char kGServiceSettingKeyEnd[] = "Gservice2-";
64 // Key used to timestamp last checkin (marked with G services settings update).
65 const char kLastCheckinTimeKey[] = "last_checkin_time";
56 66
57 std::string MakeRegistrationKey(const std::string& app_id) { 67 std::string MakeRegistrationKey(const std::string& app_id) {
58 return kRegistrationKeyStart + app_id; 68 return kRegistrationKeyStart + app_id;
59 } 69 }
60 70
61 std::string ParseRegistrationKey(const std::string& key) { 71 std::string ParseRegistrationKey(const std::string& key) {
62 return key.substr(arraysize(kRegistrationKeyStart) - 1); 72 return key.substr(arraysize(kRegistrationKeyStart) - 1);
63 } 73 }
64 74
65 std::string MakeIncomingKey(const std::string& persistent_id) { 75 std::string MakeIncomingKey(const std::string& persistent_id) {
66 return kIncomingMsgKeyStart + persistent_id; 76 return kIncomingMsgKeyStart + persistent_id;
67 } 77 }
68 78
69 std::string MakeOutgoingKey(const std::string& persistent_id) { 79 std::string MakeOutgoingKey(const std::string& persistent_id) {
70 return kOutgoingMsgKeyStart + persistent_id; 80 return kOutgoingMsgKeyStart + persistent_id;
71 } 81 }
72 82
73 std::string ParseOutgoingKey(const std::string& key) { 83 std::string ParseOutgoingKey(const std::string& key) {
74 return key.substr(arraysize(kOutgoingMsgKeyStart) - 1); 84 return key.substr(arraysize(kOutgoingMsgKeyStart) - 1);
75 } 85 }
76 86
87 std::string MakeGServiceSettingKey(const std::string& setting_name) {
88 return kGServiceSettingKeyStart + setting_name;
89 }
90
91 std::string ParseGServiceSettingKey(const std::string& key) {
92 return key.substr(arraysize(kGServiceSettingKeyStart) - 1);
93 }
94
77 // Note: leveldb::Slice keeps a pointer to the data in |s|, which must therefore 95 // Note: leveldb::Slice keeps a pointer to the data in |s|, which must therefore
78 // outlive the slice. 96 // outlive the slice.
79 // For example: MakeSlice(MakeOutgoingKey(x)) is invalid. 97 // For example: MakeSlice(MakeOutgoingKey(x)) is invalid.
80 leveldb::Slice MakeSlice(const base::StringPiece& s) { 98 leveldb::Slice MakeSlice(const base::StringPiece& s) {
81 return leveldb::Slice(s.begin(), s.size()); 99 return leveldb::Slice(s.begin(), s.size());
82 } 100 }
83 101
84 } // namespace 102 } // namespace
85 103
86 class GCMStoreImpl::Backend 104 class GCMStoreImpl::Backend
(...skipping 24 matching lines...) Expand all
111 void RemoveOutgoingMessages( 129 void RemoveOutgoingMessages(
112 const PersistentIdList& persistent_ids, 130 const PersistentIdList& persistent_ids,
113 const base::Callback<void(bool, const AppIdToMessageCountMap&)> 131 const base::Callback<void(bool, const AppIdToMessageCountMap&)>
114 callback); 132 callback);
115 void AddUserSerialNumber(const std::string& username, 133 void AddUserSerialNumber(const std::string& username,
116 int64 serial_number, 134 int64 serial_number,
117 const UpdateCallback& callback); 135 const UpdateCallback& callback);
118 void RemoveUserSerialNumber(const std::string& username, 136 void RemoveUserSerialNumber(const std::string& username,
119 const UpdateCallback& callback); 137 const UpdateCallback& callback);
120 void SetNextSerialNumber(int64 serial_number, const UpdateCallback& callback); 138 void SetNextSerialNumber(int64 serial_number, const UpdateCallback& callback);
139 void UpdateGServicesSettings(
140 const std::vector<std::string>& settings_to_remove,
141 const std::map<std::string, std::string>& settings_to_add,
142 const base::Time& last_checkin_time,
143 const UpdateCallback& callback);
121 144
122 private: 145 private:
123 friend class base::RefCountedThreadSafe<Backend>; 146 friend class base::RefCountedThreadSafe<Backend>;
124 ~Backend(); 147 ~Backend();
125 148
126 bool LoadDeviceCredentials(uint64* android_id, uint64* security_token); 149 bool LoadDeviceCredentials(uint64* android_id, uint64* security_token);
127 bool LoadRegistrations(RegistrationInfoMap* registrations); 150 bool LoadRegistrations(RegistrationInfoMap* registrations);
128 bool LoadIncomingMessages(std::vector<std::string>* incoming_messages); 151 bool LoadIncomingMessages(std::vector<std::string>* incoming_messages);
129 bool LoadOutgoingMessages(OutgoingMessageMap* outgoing_messages); 152 bool LoadOutgoingMessages(OutgoingMessageMap* outgoing_messages);
153 bool LoadGServicesSettings(std::map<std::string, std::string>* settings,
154 base::Time* last_checkin_time);
130 155
131 const base::FilePath path_; 156 const base::FilePath path_;
132 scoped_refptr<base::SequencedTaskRunner> foreground_task_runner_; 157 scoped_refptr<base::SequencedTaskRunner> foreground_task_runner_;
133 158
134 scoped_ptr<leveldb::DB> db_; 159 scoped_ptr<leveldb::DB> db_;
135 }; 160 };
136 161
137 GCMStoreImpl::Backend::Backend( 162 GCMStoreImpl::Backend::Backend(
138 const base::FilePath& path, 163 const base::FilePath& path,
139 scoped_refptr<base::SequencedTaskRunner> foreground_task_runner) 164 scoped_refptr<base::SequencedTaskRunner> foreground_task_runner)
(...skipping 24 matching lines...) Expand all
164 base::Bind(callback, 189 base::Bind(callback,
165 base::Passed(&result))); 190 base::Passed(&result)));
166 return; 191 return;
167 } 192 }
168 db_.reset(db); 193 db_.reset(db);
169 194
170 if (!LoadDeviceCredentials(&result->device_android_id, 195 if (!LoadDeviceCredentials(&result->device_android_id,
171 &result->device_security_token) || 196 &result->device_security_token) ||
172 !LoadRegistrations(&result->registrations) || 197 !LoadRegistrations(&result->registrations) ||
173 !LoadIncomingMessages(&result->incoming_messages) || 198 !LoadIncomingMessages(&result->incoming_messages) ||
174 !LoadOutgoingMessages(&result->outgoing_messages)) { 199 !LoadOutgoingMessages(&result->outgoing_messages) ||
200 !LoadGServicesSettings(&result->gservices_settings,
201 &result->last_checkin_time)) {
175 result->device_android_id = 0; 202 result->device_android_id = 0;
176 result->device_security_token = 0; 203 result->device_security_token = 0;
177 result->registrations.clear(); 204 result->registrations.clear();
178 result->incoming_messages.clear(); 205 result->incoming_messages.clear();
179 result->outgoing_messages.clear(); 206 result->outgoing_messages.clear();
207 result->last_checkin_time = base::Time::FromInternalValue(0LL);
180 foreground_task_runner_->PostTask(FROM_HERE, 208 foreground_task_runner_->PostTask(FROM_HERE,
181 base::Bind(callback, 209 base::Bind(callback,
182 base::Passed(&result))); 210 base::Passed(&result)));
183 return; 211 return;
184 } 212 }
185 213
186 // Only record histograms if GCM had already been set up for this device. 214 // Only record histograms if GCM had already been set up for this device.
187 if (result->device_android_id != 0 && result->device_security_token != 0) { 215 if (result->device_android_id != 0 && result->device_security_token != 0) {
188 int64 file_size = 0; 216 int64 file_size = 0;
189 if (base::GetFileSize(path_, &file_size)) { 217 if (base::GetFileSize(path_, &file_size)) {
(...skipping 248 matching lines...) Expand 10 before | Expand all | Expand 10 after
438 removed_message_counts)); 466 removed_message_counts));
439 return; 467 return;
440 } 468 }
441 LOG(ERROR) << "LevelDB remove failed: " << s.ToString(); 469 LOG(ERROR) << "LevelDB remove failed: " << s.ToString();
442 foreground_task_runner_->PostTask(FROM_HERE, 470 foreground_task_runner_->PostTask(FROM_HERE,
443 base::Bind(callback, 471 base::Bind(callback,
444 false, 472 false,
445 AppIdToMessageCountMap())); 473 AppIdToMessageCountMap()));
446 } 474 }
447 475
476 void GCMStoreImpl::Backend::UpdateGServicesSettings(
jianli 2014/03/31 17:45:35 It seems that the whole update logic becomes quite
fgorski 2014/03/31 21:50:08 Done, this has been simplified based on our conver
477 const std::vector<std::string>& settings_to_remove,
478 const std::map<std::string, std::string>& settings_to_add,
479 const base::Time& last_checkin_time,
480 const UpdateCallback& callback) {
481 leveldb::WriteBatch write_batch;
482
483 // Delete settings to remove.
484 for (std::vector<std::string>::const_iterator iter =
485 settings_to_remove.begin();
486 iter != settings_to_remove.end(); ++iter) {
487 write_batch.Delete(MakeSlice(MakeGServiceSettingKey(*iter)));
488 }
489
490 // Add settings to add.
491 for (std::map<std::string, std::string>::const_iterator iter =
492 settings_to_add.begin();
493 iter != settings_to_add.end(); ++iter) {
494 write_batch.Put(MakeSlice(MakeGServiceSettingKey(iter->first)),
495 MakeSlice(iter->second));
496 }
497
498 // Update last checkin time.
499 int64 last_checkin_time_internal = last_checkin_time.ToInternalValue();
500 write_batch.Put(MakeSlice(kLastCheckinTimeKey),
501 MakeSlice(base::Int64ToString(last_checkin_time_internal)));
502
503 // Write it all in batch.
504 leveldb::WriteOptions write_options;
505 write_options.sync = true;
506
507 leveldb::Status s = db_->Write(write_options, &write_batch);
508 if (!s.ok())
509 LOG(ERROR) << "LevelDB GService Settings update failed: " << s.ToString();
510 foreground_task_runner_->PostTask(FROM_HERE, base::Bind(callback, s.ok()));
511 }
512
448 bool GCMStoreImpl::Backend::LoadDeviceCredentials(uint64* android_id, 513 bool GCMStoreImpl::Backend::LoadDeviceCredentials(uint64* android_id,
449 uint64* security_token) { 514 uint64* security_token) {
450 leveldb::ReadOptions read_options; 515 leveldb::ReadOptions read_options;
451 read_options.verify_checksums = true; 516 read_options.verify_checksums = true;
452 517
453 std::string result; 518 std::string result;
454 leveldb::Status s = db_->Get(read_options, MakeSlice(kDeviceAIDKey), &result); 519 leveldb::Status s = db_->Get(read_options, MakeSlice(kDeviceAIDKey), &result);
455 if (s.ok()) { 520 if (s.ok()) {
456 if (!base::StringToUint64(result, android_id)) { 521 if (!base::StringToUint64(result, android_id)) {
457 LOG(ERROR) << "Failed to restore device id."; 522 LOG(ERROR) << "Failed to restore device id.";
(...skipping 95 matching lines...) Expand 10 before | Expand all | Expand 10 after
553 return false; 618 return false;
554 } 619 }
555 DVLOG(1) << "Found outgoing message with id " << id << " of type " 620 DVLOG(1) << "Found outgoing message with id " << id << " of type "
556 << base::IntToString(tag); 621 << base::IntToString(tag);
557 (*outgoing_messages)[id] = make_linked_ptr(message.release()); 622 (*outgoing_messages)[id] = make_linked_ptr(message.release());
558 } 623 }
559 624
560 return true; 625 return true;
561 } 626 }
562 627
628 bool GCMStoreImpl::Backend::LoadGServicesSettings(
629 std::map<std::string, std::string>* settings,
630 base::Time* last_checkin_time) {
631 leveldb::ReadOptions read_options;
632 read_options.verify_checksums = true;
633
634 scoped_ptr<leveldb::Iterator> iter(db_->NewIterator(read_options));
635 for (iter->Seek(MakeSlice(kGServiceSettingKeyStart));
636 iter->Valid() && iter->key().ToString() < kGServiceSettingKeyEnd;
637 iter->Next()) {
638 std::string value = iter->value().ToString();
639 if (value.empty()) {
640 LOG(ERROR) << "Error reading GService Settings " << value;
641 return false;
642 }
643 std::string id = ParseGServiceSettingKey(iter->key().ToString());
644 (*settings)[id] = value;
645 DVLOG(1) << "Found G Service setting with key: " << id
646 << ", and value: " << value;
647 }
648
649 std::string result;
650 leveldb::Status s = db_->Get(read_options,
651 MakeSlice(kLastCheckinTimeKey),
652 &result);
653 int64 time_internal = 0LL;
654 if (s.ok()) {
655 if (!base::StringToInt64(result, &time_internal)) {
656 LOG(ERROR) << "Failed to restore last checkin time.";
657 return false;
658 }
659 }
660
661 // In case we cannot read last checkin time, we default it to 0, as we don't
662 // want that situation to cause the whole load to fail.
663 *last_checkin_time = base::Time::FromInternalValue(time_internal);
664
665 return true;
666 }
667
563 GCMStoreImpl::GCMStoreImpl( 668 GCMStoreImpl::GCMStoreImpl(
564 bool use_mock_keychain, 669 bool use_mock_keychain,
565 const base::FilePath& path, 670 const base::FilePath& path,
566 scoped_refptr<base::SequencedTaskRunner> blocking_task_runner) 671 scoped_refptr<base::SequencedTaskRunner> blocking_task_runner)
567 : backend_(new Backend(path, base::MessageLoopProxy::current())), 672 : backend_(new Backend(path, base::MessageLoopProxy::current())),
568 blocking_task_runner_(blocking_task_runner), 673 blocking_task_runner_(blocking_task_runner),
569 weak_ptr_factory_(this) { 674 weak_ptr_factory_(this) {
570 // On OSX, prevent the Keychain permissions popup during unit tests. 675 // On OSX, prevent the Keychain permissions popup during unit tests.
571 #if defined(OS_MACOSX) 676 #if defined(OS_MACOSX)
572 OSCrypt::UseMockKeychain(use_mock_keychain); 677 OSCrypt::UseMockKeychain(use_mock_keychain);
(...skipping 154 matching lines...) Expand 10 before | Expand all | Expand 10 after
727 blocking_task_runner_->PostTask( 832 blocking_task_runner_->PostTask(
728 FROM_HERE, 833 FROM_HERE,
729 base::Bind(&GCMStoreImpl::Backend::RemoveOutgoingMessages, 834 base::Bind(&GCMStoreImpl::Backend::RemoveOutgoingMessages,
730 backend_, 835 backend_,
731 persistent_ids, 836 persistent_ids,
732 base::Bind(&GCMStoreImpl::RemoveOutgoingMessagesContinuation, 837 base::Bind(&GCMStoreImpl::RemoveOutgoingMessagesContinuation,
733 weak_ptr_factory_.GetWeakPtr(), 838 weak_ptr_factory_.GetWeakPtr(),
734 callback))); 839 callback)));
735 } 840 }
736 841
842 void GCMStoreImpl::UpdateGServicesSettings(
843 const std::vector<std::string>& settings_to_remove,
844 const std::map<std::string, std::string>& settings_to_add,
845 const base::Time& last_checkin_time,
846 const UpdateCallback& callback) {
847 blocking_task_runner_->PostTask(
848 FROM_HERE,
849 base::Bind(&GCMStoreImpl::Backend::UpdateGServicesSettings,
850 backend_,
851 settings_to_remove,
852 settings_to_add,
853 last_checkin_time,
854 callback));
855 }
856
737 void GCMStoreImpl::LoadContinuation(const LoadCallback& callback, 857 void GCMStoreImpl::LoadContinuation(const LoadCallback& callback,
738 scoped_ptr<LoadResult> result) { 858 scoped_ptr<LoadResult> result) {
739 if (!result->success) { 859 if (!result->success) {
740 callback.Run(result.Pass()); 860 callback.Run(result.Pass());
741 return; 861 return;
742 } 862 }
743 int num_throttled_apps = 0; 863 int num_throttled_apps = 0;
744 for (OutgoingMessageMap::const_iterator 864 for (OutgoingMessageMap::const_iterator
745 iter = result->outgoing_messages.begin(); 865 iter = result->outgoing_messages.begin();
746 iter != result->outgoing_messages.end(); ++iter) { 866 iter != result->outgoing_messages.end(); ++iter) {
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
781 removed_message_counts.begin(); 901 removed_message_counts.begin();
782 iter != removed_message_counts.end(); ++iter) { 902 iter != removed_message_counts.end(); ++iter) {
783 DCHECK_NE(app_message_counts_.count(iter->first), 0U); 903 DCHECK_NE(app_message_counts_.count(iter->first), 0U);
784 app_message_counts_[iter->first] -= iter->second; 904 app_message_counts_[iter->first] -= iter->second;
785 DCHECK_GE(app_message_counts_[iter->first], 0); 905 DCHECK_GE(app_message_counts_[iter->first], 0);
786 } 906 }
787 callback.Run(true); 907 callback.Run(true);
788 } 908 }
789 909
790 } // namespace gcm 910 } // namespace gcm
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698