1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
|
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sync_sessions/session_store.h"
#include <map>
#include <utility>
#include <vector>
#include "base/cancelable_callback.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/run_loop.h"
#include "base/test/mock_callback.h"
#include "base/test/task_environment.h"
#include "components/prefs/testing_pref_service.h"
#include "components/sync/base/hash_util.h"
#include "components/sync/protocol/entity_data.h"
#include "components/sync/protocol/entity_metadata.pb.h"
#include "components/sync/protocol/session_specifics.pb.h"
#include "components/sync/test/data_type_store_test_util.h"
#include "components/sync/test/test_matchers.h"
#include "components/sync_device_info/local_device_info_util.h"
#include "components/sync_sessions/mock_sync_sessions_client.h"
#include "components/sync_sessions/session_sync_prefs.h"
#include "components/sync_sessions/test_matchers.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace sync_sessions {
namespace {
using sync_pb::SessionSpecifics;
using syncer::DataBatch;
using syncer::DataTypeStore;
using syncer::EntityData;
using syncer::EntityMetadataMap;
using syncer::HasEncryptionKeyName;
using syncer::IsEmptyMetadataBatch;
using syncer::MetadataBatch;
using syncer::MetadataBatchContains;
using syncer::NoModelError;
using testing::_;
using testing::ElementsAre;
using testing::Eq;
using testing::IsEmpty;
using testing::Matcher;
using testing::NiceMock;
using testing::NotNull;
using testing::Pair;
using testing::Return;
using testing::UnorderedElementsAre;
const char kLocalCacheGuid[] = "SomeCacheGuid";
// A mock callback that a) can be used as mock to verify call expectations and
// b) conveniently exposes the last instantiated session store.
class MockOpenCallback {
public:
MOCK_METHOD(void,
Run,
(const std::optional<syncer::ModelError>& error,
SessionStore* store,
MetadataBatch* metadata_batch),
());
SessionStore::OpenCallback Get() {
return base::BindOnce(
[](MockOpenCallback* callback,
const std::optional<syncer::ModelError>& error,
std::unique_ptr<SessionStore> store,
std::unique_ptr<MetadataBatch> metadata_batch) {
// Store a copy of the pointer for GetResult().
callback->store_ = std::move(store);
// Call mock method.
callback->Run(error, callback->store_.get(), metadata_batch.get());
callback->loop_.Quit();
},
base::Unretained(this));
}
// Waits until the callback gets triggered.
void Wait() { loop_.Run(); }
SessionStore* GetResult() { return store_.get(); }
std::unique_ptr<SessionStore> StealResult() { return std::move(store_); }
private:
base::RunLoop loop_;
std::unique_ptr<SessionStore> store_;
};
MATCHER_P(EntityDataHasSpecifics, session_specifics_matcher, "") {
return session_specifics_matcher.MatchAndExplain(arg.specifics.session(),
result_listener);
}
std::map<std::string, EntityData> BatchToEntityDataMap(
std::unique_ptr<DataBatch> batch) {
std::map<std::string, EntityData> storage_key_to_data;
while (batch && batch->HasNext()) {
auto [storage_key, entity_data] = batch->Next();
EXPECT_THAT(entity_data, NotNull());
if (entity_data) {
storage_key_to_data.emplace(storage_key, std::move(*entity_data));
}
}
return storage_key_to_data;
}
std::unique_ptr<MetadataBatch> ReadAllPersistedMetadataFrom(
DataTypeStore* store) {
std::unique_ptr<MetadataBatch> batch;
base::RunLoop loop;
store->ReadAllMetadata(base::BindOnce(
[](std::unique_ptr<MetadataBatch>* output_batch, base::RunLoop* loop,
const std::optional<syncer::ModelError>& error,
std::unique_ptr<MetadataBatch> input_batch) {
EXPECT_FALSE(error) << error->ToString();
EXPECT_THAT(input_batch, NotNull());
*output_batch = std::move(input_batch);
loop->Quit();
},
&batch, &loop));
loop.Run();
return batch;
}
std::map<std::string, SessionSpecifics> ReadAllPersistedDataFrom(
DataTypeStore* store) {
return syncer::DataTypeStoreTestUtil::ReadAllDataAsProtoAndWait<
SessionSpecifics>(*store);
}
class SessionStoreOpenTest : public ::testing::Test {
protected:
SessionStoreOpenTest()
: session_sync_prefs_(&pref_service_),
underlying_store_(
syncer::DataTypeStoreTestUtil::CreateInMemoryStoreForTest(
syncer::SESSIONS)) {
SessionSyncPrefs::RegisterProfilePrefs(pref_service_.registry());
mock_sync_sessions_client_ =
std::make_unique<testing::NiceMock<MockSyncSessionsClient>>();
ON_CALL(*mock_sync_sessions_client_, GetSessionSyncPrefs())
.WillByDefault(Return(&session_sync_prefs_));
ON_CALL(*mock_sync_sessions_client_, GetStoreFactory())
.WillByDefault(
Return(syncer::DataTypeStoreTestUtil::FactoryForForwardingStore(
underlying_store_.get())));
}
~SessionStoreOpenTest() override = default;
base::test::SingleThreadTaskEnvironment task_environment_;
TestingPrefServiceSimple pref_service_;
SessionSyncPrefs session_sync_prefs_;
std::unique_ptr<MockSyncSessionsClient> mock_sync_sessions_client_;
std::unique_ptr<DataTypeStore> underlying_store_;
};
TEST_F(SessionStoreOpenTest, ShouldCreateStore) {
ASSERT_THAT(session_sync_prefs_.GetLegacySyncSessionsGUID(), IsEmpty());
MockOpenCallback completion;
EXPECT_CALL(completion, Run(NoModelError(), /*store=*/NotNull(),
MetadataBatchContains(_, IsEmpty())));
SessionStore::Open(kLocalCacheGuid, mock_sync_sessions_client_.get(),
completion.Get());
completion.Wait();
ASSERT_THAT(completion.GetResult(), NotNull());
EXPECT_THAT(completion.GetResult()->local_session_info().client_name,
Eq(syncer::GetPersonalizableDeviceNameBlocking()));
EXPECT_THAT(completion.GetResult()->local_session_info().session_tag,
Eq(kLocalCacheGuid));
EXPECT_THAT(session_sync_prefs_.GetLegacySyncSessionsGUID(), IsEmpty());
}
TEST_F(SessionStoreOpenTest, ShouldReadLegacySessionsGuidFromPrefs) {
const std::string kLegacySyncSessionsGUID = "sessiontag1";
session_sync_prefs_.SetLegacySyncSessionsGUIDForTesting(
kLegacySyncSessionsGUID);
NiceMock<MockOpenCallback> completion;
SessionStore::Open(kLocalCacheGuid, mock_sync_sessions_client_.get(),
completion.Get());
completion.Wait();
ASSERT_THAT(completion.GetResult(), NotNull());
EXPECT_THAT(completion.GetResult()->local_session_info().session_tag,
Eq(kLegacySyncSessionsGUID));
EXPECT_THAT(session_sync_prefs_.GetLegacySyncSessionsGUID(),
Eq(kLegacySyncSessionsGUID));
}
TEST_F(SessionStoreOpenTest, ShouldNotUseClientIfCancelled) {
// Mimics a caller that uses a weak pointer.
class Caller {
public:
explicit Caller(SessionStore::OpenCallback cb) : cb_(std::move(cb)) {}
SessionStore::OpenCallback GetCancelableCallback() {
return base::BindOnce(&Caller::Completed, weak_ptr_factory_.GetWeakPtr());
}
private:
void Completed(const std::optional<syncer::ModelError>& error,
std::unique_ptr<SessionStore> store,
std::unique_ptr<syncer::MetadataBatch> metadata_batch) {
std::move(cb_).Run(error, std::move(store), std::move(metadata_batch));
}
SessionStore::OpenCallback cb_;
base::WeakPtrFactory<Caller> weak_ptr_factory_{this};
};
NiceMock<MockOpenCallback> mock_completion;
auto caller = std::make_unique<Caller>(mock_completion.Get());
EXPECT_CALL(mock_completion, Run).Times(0);
SessionStore::Open(kLocalCacheGuid, mock_sync_sessions_client_.get(),
caller->GetCancelableCallback());
// The client gets destroyed before callback completion.
mock_sync_sessions_client_.reset();
caller.reset();
// Run until idle to test for crashes due to use-after-free.
base::RunLoop().RunUntilIdle();
}
// Test fixture that creates an initial session store.
class SessionStoreTest : public SessionStoreOpenTest {
protected:
SessionStoreTest() { session_store_ = CreateSessionStore(); }
std::unique_ptr<SessionStore> CreateSessionStore() {
NiceMock<MockOpenCallback> completion;
SessionStore::Open(kLocalCacheGuid, mock_sync_sessions_client_.get(),
completion.Get());
completion.Wait();
EXPECT_THAT(completion.GetResult(), NotNull());
return completion.StealResult();
}
SessionStore* session_store() { return session_store_.get(); }
std::unique_ptr<SessionStore> TakeSessionStore() {
return std::move(session_store_);
}
private:
std::unique_ptr<SessionStore> session_store_;
};
TEST_F(SessionStoreTest, ShouldClearLegacySessionsGuidFromPrefs) {
const std::string kLegacySyncSessionsGUID = "sessiontag1";
session_sync_prefs_.SetLegacySyncSessionsGUIDForTesting(
kLegacySyncSessionsGUID);
ASSERT_THAT(session_sync_prefs_.GetLegacySyncSessionsGUID(),
Eq(kLegacySyncSessionsGUID));
SessionStore::DeleteAllDataAndMetadata(TakeSessionStore());
EXPECT_THAT(session_sync_prefs_.GetLegacySyncSessionsGUID(), IsEmpty());
}
TEST_F(SessionStoreTest, ShouldRecreateEmptyStore) {
const SessionStore::SessionInfo original_local_session_info =
session_store()->local_session_info();
// Put some data into the store.
std::unique_ptr<SessionStore::WriteBatch> batch =
session_store()->CreateWriteBatch(/*error_handler=*/base::DoNothing());
ASSERT_THAT(batch, NotNull());
SessionSpecifics header;
header.set_session_tag(kLocalCacheGuid);
header.mutable_header()->add_window()->set_window_id(1);
header.mutable_header()->mutable_window(0)->add_tab(2);
ASSERT_TRUE(SessionStore::AreValidSpecifics(header));
batch->PutAndUpdateTracker(header, base::Time::Now());
SessionStore::WriteBatch::Commit(std::move(batch));
ASSERT_THAT(ReadAllPersistedDataFrom(underlying_store_.get()),
Not(IsEmpty()));
auto recreate_store_callback =
SessionStore::DeleteAllDataAndMetadata(TakeSessionStore());
// Re-create the store with a new cache GUID / session tag.
const std::string kNewLocalCacheGuid = "new_cache_guid";
ASSERT_NE(kLocalCacheGuid, kNewLocalCacheGuid);
std::unique_ptr<SessionStore> new_store =
std::move(recreate_store_callback)
.Run(kNewLocalCacheGuid, mock_sync_sessions_client_.get());
// The newly (re)created store should be empty.
EXPECT_THAT(ReadAllPersistedDataFrom(underlying_store_.get()), IsEmpty());
const SessionStore::SessionInfo new_local_session_info =
new_store->local_session_info();
// The session tag (aka cache GUID) should've been updated.
EXPECT_EQ(new_local_session_info.session_tag, kNewLocalCacheGuid);
// The remaining local session fields should be unchanged.
EXPECT_EQ(original_local_session_info.client_name,
new_local_session_info.client_name);
EXPECT_EQ(original_local_session_info.device_type,
new_local_session_info.device_type);
EXPECT_EQ(original_local_session_info.device_form_factor,
new_local_session_info.device_form_factor);
}
TEST_F(SessionStoreTest, ShouldCreateLocalSession) {
const std::string header_storage_key =
SessionStore::GetHeaderStorageKey(kLocalCacheGuid);
EXPECT_THAT(BatchToEntityDataMap(session_store()->GetAllSessionData()),
ElementsAre(Pair(header_storage_key,
EntityDataHasSpecifics(MatchesHeader(
kLocalCacheGuid, /*window_ids=*/{},
/*tab_ids=*/{})))));
// Verify that GetSessionDataForKeys() returns the header entity.
EXPECT_THAT(BatchToEntityDataMap(
session_store()->GetSessionDataForKeys({header_storage_key})),
ElementsAre(Pair(header_storage_key,
EntityDataHasSpecifics(MatchesHeader(
kLocalCacheGuid, /*window_ids=*/{},
/*tab_ids=*/{})))));
// Verify the underlying storage does NOT contain the data.
EXPECT_THAT(ReadAllPersistedDataFrom(underlying_store_.get()), IsEmpty());
// Verify the underlying storage does NOT contain metadata.
EXPECT_THAT(ReadAllPersistedMetadataFrom(underlying_store_.get()),
IsEmptyMetadataBatch());
}
TEST_F(SessionStoreTest, ShouldWriteAndRestoreMetadata) {
const std::string kStorageKey1 = "TestStorageKey1";
const std::string kServerId1 = "TestServerId1";
const std::string kEncryptionKeyName1 = "TestEncryptionKey1";
// Populate with metadata.
std::unique_ptr<SessionStore::WriteBatch> batch =
session_store()->CreateWriteBatch(/*error_handler=*/base::DoNothing());
ASSERT_THAT(batch, NotNull());
sync_pb::EntityMetadata metadata1;
metadata1.set_server_id(kServerId1);
batch->GetMetadataChangeList()->UpdateMetadata(kStorageKey1, metadata1);
sync_pb::DataTypeState data_type_state;
data_type_state.set_encryption_key_name(kEncryptionKeyName1);
batch->GetMetadataChangeList()->UpdateDataTypeState(data_type_state);
SessionStore::WriteBatch::Commit(std::move(batch));
// Verify the underlying storage contains the metadata.
EXPECT_THAT(ReadAllPersistedMetadataFrom(underlying_store_.get()),
MetadataBatchContains(HasEncryptionKeyName(kEncryptionKeyName1),
ElementsAre(Pair(kStorageKey1, _))));
// Create second session store.
NiceMock<MockOpenCallback> completion;
EXPECT_CALL(completion, Run(NoModelError(), /*store=*/NotNull(),
MetadataBatchContains(
HasEncryptionKeyName(kEncryptionKeyName1),
ElementsAre(Pair(kStorageKey1, _)))));
SessionStore::Open(kLocalCacheGuid, mock_sync_sessions_client_.get(),
completion.Get());
completion.Wait();
EXPECT_THAT(completion.GetResult(), NotNull());
EXPECT_NE(session_store(), completion.GetResult());
}
TEST_F(SessionStoreTest, ShouldUpdateTrackerWithForeignData) {
const std::string kForeignSessionTag = "SomeForeignTag";
const int kWindowId = 5;
const int kTabId1 = 7;
const int kTabId2 = 8;
const int kTabNodeId1 = 2;
const int kTabNodeId2 = 3;
ASSERT_THAT(session_store()->tracker()->LookupAllForeignSessions(
SyncedSessionTracker::RAW),
IsEmpty());
const std::string header_storage_key =
SessionStore::GetHeaderStorageKey(kForeignSessionTag);
const std::string tab_storage_key1 =
SessionStore::GetTabStorageKey(kForeignSessionTag, kTabNodeId1);
const std::string tab_storage_key2 =
SessionStore::GetTabStorageKey(kForeignSessionTag, kTabNodeId2);
ASSERT_THAT(BatchToEntityDataMap(session_store()->GetSessionDataForKeys(
{header_storage_key, tab_storage_key1, tab_storage_key2})),
IsEmpty());
// Populate with data.
SessionSpecifics header;
header.set_session_tag(kForeignSessionTag);
header.mutable_header()->add_window()->set_window_id(kWindowId);
header.mutable_header()->mutable_window(0)->add_tab(kTabId1);
header.mutable_header()->mutable_window(0)->add_tab(kTabId2);
ASSERT_TRUE(SessionStore::AreValidSpecifics(header));
SessionSpecifics tab1;
tab1.set_session_tag(kForeignSessionTag);
tab1.set_tab_node_id(kTabNodeId1);
tab1.mutable_tab()->set_window_id(kWindowId);
tab1.mutable_tab()->set_tab_id(kTabId1);
ASSERT_TRUE(SessionStore::AreValidSpecifics(tab1));
SessionSpecifics tab2;
tab2.set_session_tag(kForeignSessionTag);
tab2.set_tab_node_id(kTabNodeId2);
tab2.mutable_tab()->set_window_id(kWindowId);
tab2.mutable_tab()->set_tab_id(kTabId2);
ASSERT_TRUE(SessionStore::AreValidSpecifics(tab2));
std::unique_ptr<SessionStore::WriteBatch> batch =
session_store()->CreateWriteBatch(/*error_handler=*/base::DoNothing());
ASSERT_THAT(batch, NotNull());
batch->PutAndUpdateTracker(header, base::Time::Now());
batch->PutAndUpdateTracker(tab1, base::Time::Now());
batch->PutAndUpdateTracker(tab2, base::Time::Now());
SessionStore::WriteBatch::Commit(std::move(batch));
EXPECT_THAT(session_store()->tracker()->LookupAllForeignSessions(
SyncedSessionTracker::RAW),
ElementsAre(MatchesSyncedSession(
kForeignSessionTag, {{kWindowId, {kTabId1, kTabId2}}})));
EXPECT_THAT(
BatchToEntityDataMap(session_store()->GetSessionDataForKeys(
{header_storage_key, tab_storage_key1, tab_storage_key2})),
UnorderedElementsAre(
Pair(header_storage_key,
EntityDataHasSpecifics(MatchesHeader(
kForeignSessionTag, {kWindowId}, {kTabId1, kTabId2}))),
Pair(tab_storage_key1,
EntityDataHasSpecifics(MatchesTab(kForeignSessionTag, kWindowId,
kTabId1, kTabNodeId1,
/*urls=*/_))),
Pair(tab_storage_key2,
EntityDataHasSpecifics(MatchesTab(kForeignSessionTag, kWindowId,
kTabId2, kTabNodeId2,
/*urls=*/_)))));
}
TEST_F(SessionStoreTest, ShouldUpdateTrackerWithForeignDataAndInvalidURL) {
const std::string kForeignSessionTag = "SomeForeignTag";
const int kWindowId = 5;
const int kTabId1 = 7;
const int kTabNodeId1 = 2;
const GURL kValidURL("http://validurl.com/");
const GURL kInvalidURL("http:google.com:foo");
ASSERT_TRUE(kValidURL.is_valid());
ASSERT_FALSE(kInvalidURL.is_empty());
ASSERT_FALSE(kInvalidURL.is_valid());
ASSERT_FALSE(kInvalidURL.possibly_invalid_spec().empty());
ASSERT_THAT(session_store()->tracker()->LookupAllForeignSessions(
SyncedSessionTracker::RAW),
IsEmpty());
const std::string header_storage_key =
SessionStore::GetHeaderStorageKey(kForeignSessionTag);
const std::string tab_storage_key1 =
SessionStore::GetTabStorageKey(kForeignSessionTag, kTabNodeId1);
ASSERT_THAT(BatchToEntityDataMap(session_store()->GetSessionDataForKeys(
{header_storage_key, tab_storage_key1})),
IsEmpty());
// Populate with data.
SessionSpecifics header;
header.set_session_tag(kForeignSessionTag);
header.mutable_header()->add_window()->set_window_id(kWindowId);
header.mutable_header()->mutable_window(0)->add_tab(kTabId1);
ASSERT_TRUE(SessionStore::AreValidSpecifics(header));
SessionSpecifics tab1;
tab1.set_session_tag(kForeignSessionTag);
tab1.set_tab_node_id(kTabNodeId1);
tab1.mutable_tab()->set_window_id(kWindowId);
tab1.mutable_tab()->set_tab_id(kTabId1);
// Having a non-empty, invalid URL in storage is unlikely, but may happen if
// there was disk corruption.
tab1.mutable_tab()->add_navigation()->set_virtual_url(
kInvalidURL.possibly_invalid_spec());
tab1.mutable_tab()->add_navigation()->set_virtual_url(kValidURL.spec());
ASSERT_TRUE(SessionStore::AreValidSpecifics(tab1));
std::unique_ptr<SessionStore::WriteBatch> batch =
session_store()->CreateWriteBatch(/*error_handler=*/base::DoNothing());
ASSERT_THAT(batch, NotNull());
batch->PutAndUpdateTracker(header, base::Time::Now());
batch->PutAndUpdateTracker(tab1, base::Time::Now());
SessionStore::WriteBatch::Commit(std::move(batch));
EXPECT_THAT(
session_store()->tracker()->LookupAllForeignSessions(
SyncedSessionTracker::RAW),
ElementsAre(MatchesSyncedSession(
kForeignSessionTag, {{kWindowId, std::vector<int>{kTabId1}}})));
EXPECT_THAT(BatchToEntityDataMap(session_store()->GetSessionDataForKeys(
{header_storage_key, tab_storage_key1})),
UnorderedElementsAre(
Pair(header_storage_key,
EntityDataHasSpecifics(MatchesHeader(
kForeignSessionTag, {kWindowId}, {kTabId1}))),
Pair(tab_storage_key1,
EntityDataHasSpecifics(MatchesTab(
kForeignSessionTag, kWindowId, kTabId1, kTabNodeId1,
ElementsAre("", kValidURL.spec()))))));
}
TEST_F(SessionStoreTest, ShouldWriteAndRestoreForeignData) {
const std::string kForeignSessionTag = "SomeForeignTag";
const int kWindowId = 5;
const int kTabId1 = 7;
const int kTabNodeId1 = 2;
const std::string local_header_storage_key =
SessionStore::GetHeaderStorageKey(kLocalCacheGuid);
ASSERT_THAT(session_store()->tracker()->LookupAllForeignSessions(
SyncedSessionTracker::RAW),
IsEmpty());
// Local session is automatically created.
ASSERT_THAT(BatchToEntityDataMap(session_store()->GetAllSessionData()),
ElementsAre(Pair(local_header_storage_key, _)));
ASSERT_THAT(ReadAllPersistedDataFrom(underlying_store_.get()), IsEmpty());
// Populate with data.
SessionSpecifics header;
header.set_session_tag(kForeignSessionTag);
header.mutable_header()->add_window()->set_window_id(kWindowId);
header.mutable_header()->mutable_window(0)->add_tab(kTabId1);
ASSERT_TRUE(SessionStore::AreValidSpecifics(header));
SessionSpecifics tab1;
tab1.set_session_tag(kForeignSessionTag);
tab1.set_tab_node_id(kTabNodeId1);
tab1.mutable_tab()->set_window_id(kWindowId);
tab1.mutable_tab()->set_tab_id(kTabId1);
ASSERT_TRUE(SessionStore::AreValidSpecifics(tab1));
std::unique_ptr<SessionStore::WriteBatch> batch =
session_store()->CreateWriteBatch(/*error_handler=*/base::DoNothing());
ASSERT_THAT(batch, NotNull());
batch->PutAndUpdateTracker(header, base::Time::Now());
batch->PutAndUpdateTracker(tab1, base::Time::Now());
const std::string header_storage_key =
SessionStore::GetHeaderStorageKey(kForeignSessionTag);
const std::string tab_storage_key1 =
SessionStore::GetTabStorageKey(kForeignSessionTag, kTabNodeId1);
sync_pb::EntityMetadata header_metadata;
header_metadata.set_server_id("someserverid1");
batch->GetMetadataChangeList()->UpdateMetadata(header_storage_key,
header_metadata);
sync_pb::EntityMetadata tab1_metadata;
tab1_metadata.set_server_id("someserverid2");
batch->GetMetadataChangeList()->UpdateMetadata(tab_storage_key1,
tab1_metadata);
SessionStore::WriteBatch::Commit(std::move(batch));
// Verify the underlying storage contains the data.
ASSERT_THAT(
ReadAllPersistedDataFrom(underlying_store_.get()),
UnorderedElementsAre(
Pair(header_storage_key,
MatchesHeader(kForeignSessionTag, {kWindowId}, {kTabId1})),
Pair(tab_storage_key1,
MatchesTab(kForeignSessionTag, kWindowId, kTabId1, kTabNodeId1,
/*urls=*/_))));
// Verify tracker exposes the foreign tabs.
ASSERT_THAT(
session_store()->tracker()->LookupAllForeignSessions(
SyncedSessionTracker::RAW),
ElementsAre(MatchesSyncedSession(
kForeignSessionTag, {{kWindowId, std::vector<int>{kTabId1}}})));
// Create second session store to verify that the persisted state is restored,
// by mimicing a Chrome restart and using |underlying_store_| (in-memory) as a
// replacement for on-disk persistence.
std::unique_ptr<SessionStore> restored_store = CreateSessionStore();
ASSERT_THAT(restored_store, NotNull());
ASSERT_NE(session_store(), restored_store.get());
// Verify tracker was restored.
EXPECT_THAT(
restored_store->tracker()->LookupAllForeignSessions(
SyncedSessionTracker::RAW),
ElementsAre(MatchesSyncedSession(
kForeignSessionTag, {{kWindowId, std::vector<int>{kTabId1}}})));
EXPECT_THAT(BatchToEntityDataMap(restored_store->GetAllSessionData()),
UnorderedElementsAre(
Pair(local_header_storage_key, _),
Pair(header_storage_key,
EntityDataHasSpecifics(MatchesHeader(
kForeignSessionTag, {kWindowId}, {kTabId1}))),
Pair(tab_storage_key1,
EntityDataHasSpecifics(MatchesTab(
kForeignSessionTag, kWindowId, kTabId1, kTabNodeId1,
/*urls=*/_)))));
EXPECT_THAT(BatchToEntityDataMap(session_store()->GetSessionDataForKeys(
{header_storage_key, tab_storage_key1})),
UnorderedElementsAre(
Pair(header_storage_key,
EntityDataHasSpecifics(MatchesHeader(
kForeignSessionTag, {kWindowId}, {kTabId1}))),
Pair(tab_storage_key1,
EntityDataHasSpecifics(MatchesTab(
kForeignSessionTag, kWindowId, kTabId1, kTabNodeId1,
/*urls=*/_)))));
}
TEST_F(SessionStoreTest, ShouldDeleteForeignData) {
const std::string kForeignSessionTag = "SomeForeignTag";
const int kWindowId = 5;
const int kTabId1 = 7;
const int kTabId2 = 8;
const int kTabNodeId1 = 1;
const int kTabNodeId2 = 2;
const std::string local_header_storage_key =
SessionStore::GetHeaderStorageKey(kLocalCacheGuid);
// Local session is automatically created.
ASSERT_THAT(BatchToEntityDataMap(session_store()->GetAllSessionData()),
ElementsAre(Pair(local_header_storage_key, _)));
ASSERT_THAT(ReadAllPersistedDataFrom(underlying_store_.get()), IsEmpty());
// Populate with foreign data: one header entity and two tabs.
SessionSpecifics header;
header.set_session_tag(kForeignSessionTag);
header.mutable_header()->add_window()->set_window_id(kWindowId);
header.mutable_header()->mutable_window(0)->add_tab(kTabId1);
header.mutable_header()->mutable_window(0)->add_tab(kTabId2);
ASSERT_TRUE(SessionStore::AreValidSpecifics(header));
SessionSpecifics tab1;
tab1.set_session_tag(kForeignSessionTag);
tab1.set_tab_node_id(kTabNodeId1);
tab1.mutable_tab()->set_window_id(kWindowId);
tab1.mutable_tab()->set_tab_id(kTabId1);
ASSERT_TRUE(SessionStore::AreValidSpecifics(tab1));
SessionSpecifics tab2;
tab2.set_session_tag(kForeignSessionTag);
tab2.set_tab_node_id(kTabNodeId2);
tab2.mutable_tab()->set_window_id(kWindowId);
tab2.mutable_tab()->set_tab_id(kTabId2);
ASSERT_TRUE(SessionStore::AreValidSpecifics(tab2));
const std::string header_storage_key =
SessionStore::GetHeaderStorageKey(kForeignSessionTag);
const std::string tab_storage_key1 =
SessionStore::GetTabStorageKey(kForeignSessionTag, kTabNodeId1);
const std::string tab_storage_key2 =
SessionStore::GetTabStorageKey(kForeignSessionTag, kTabNodeId2);
// Write data and update the tracker.
{
std::unique_ptr<SessionStore::WriteBatch> batch =
session_store()->CreateWriteBatch(/*error_handler=*/base::DoNothing());
ASSERT_THAT(batch, NotNull());
batch->PutAndUpdateTracker(header, base::Time::Now());
batch->PutAndUpdateTracker(tab1, base::Time::Now());
batch->PutAndUpdateTracker(tab2, base::Time::Now());
sync_pb::EntityMetadata header_metadata;
header_metadata.set_server_id("someserverid1");
batch->GetMetadataChangeList()->UpdateMetadata(header_storage_key,
header_metadata);
sync_pb::EntityMetadata tab1_metadata;
tab1_metadata.set_server_id("someserverid2");
batch->GetMetadataChangeList()->UpdateMetadata(tab_storage_key1,
tab1_metadata);
sync_pb::EntityMetadata tab2_metadata;
tab2_metadata.set_server_id("someserverid3");
batch->GetMetadataChangeList()->UpdateMetadata(tab_storage_key2,
tab2_metadata);
SessionStore::WriteBatch::Commit(std::move(batch));
}
// Verify the underlying storage contains the data.
ASSERT_THAT(
ReadAllPersistedDataFrom(underlying_store_.get()),
UnorderedElementsAre(
Pair(header_storage_key,
MatchesHeader(kForeignSessionTag, {kWindowId},
{kTabId1, kTabId2})),
Pair(tab_storage_key1,
MatchesTab(kForeignSessionTag, kWindowId, kTabId1, kTabNodeId1,
/*urls=*/_)),
Pair(tab_storage_key2,
MatchesTab(kForeignSessionTag, kWindowId, kTabId2, kTabNodeId2,
/*urls=*/_))));
// Verify tracker exposes the foreign tabs.
ASSERT_THAT(session_store()->tracker()->LookupAllForeignSessions(
SyncedSessionTracker::RAW),
ElementsAre(MatchesSyncedSession(
kForeignSessionTag,
{{kWindowId, std::vector<int>{kTabId1, kTabId2}}})));
// Mimic receiving a tab deletion for |tab1|, which should only affect that
// entity.
{
std::unique_ptr<SessionStore::WriteBatch> batch =
session_store()->CreateWriteBatch(/*error_handler=*/base::DoNothing());
EXPECT_THAT(batch->DeleteForeignEntityAndUpdateTracker(tab_storage_key1),
ElementsAre(tab_storage_key1));
SessionStore::WriteBatch::Commit(std::move(batch));
}
EXPECT_THAT(
ReadAllPersistedDataFrom(underlying_store_.get()),
UnorderedElementsAre(
Pair(header_storage_key,
MatchesHeader(kForeignSessionTag, {kWindowId},
{kTabId1, kTabId2})),
Pair(tab_storage_key2,
MatchesTab(kForeignSessionTag, kWindowId, kTabId2, kTabNodeId2,
/*urls=*/_))));
// Mimic receiving a header deletion (which should delete all remaining
// entities for that session).
{
std::unique_ptr<SessionStore::WriteBatch> batch =
session_store()->CreateWriteBatch(/*error_handler=*/base::DoNothing());
EXPECT_THAT(batch->DeleteForeignEntityAndUpdateTracker(header_storage_key),
ElementsAre(header_storage_key, tab_storage_key2));
SessionStore::WriteBatch::Commit(std::move(batch));
}
EXPECT_THAT(session_store()->tracker()->LookupAllForeignSessions(
SyncedSessionTracker::RAW),
IsEmpty());
EXPECT_THAT(ReadAllPersistedDataFrom(underlying_store_.get()), IsEmpty());
}
TEST_F(SessionStoreTest, ShouldReturnForeignUnmappedTabs) {
const std::string kForeignSessionTag = "SomeForeignTag";
const int kWindowId = 5;
const int kTabId1 = 7;
const int kTabNodeId1 = 2;
const std::string local_header_storage_key =
SessionStore::GetHeaderStorageKey(kLocalCacheGuid);
const std::string foreign_header_storage_key =
SessionStore::GetHeaderStorageKey(kForeignSessionTag);
const std::string foreign_tab_storage_key =
SessionStore::GetTabStorageKey(kForeignSessionTag, kTabNodeId1);
// Local header entity is present initially.
ASSERT_THAT(BatchToEntityDataMap(session_store()->GetAllSessionData()),
ElementsAre(Pair(local_header_storage_key, _)));
SessionSpecifics tab1;
tab1.set_session_tag(kForeignSessionTag);
tab1.set_tab_node_id(kTabNodeId1);
tab1.mutable_tab()->set_window_id(kWindowId);
tab1.mutable_tab()->set_tab_id(kTabId1);
ASSERT_TRUE(SessionStore::AreValidSpecifics(tab1));
std::unique_ptr<SessionStore::WriteBatch> batch =
session_store()->CreateWriteBatch(/*error_handler=*/base::DoNothing());
ASSERT_THAT(batch, NotNull());
batch->PutAndUpdateTracker(tab1, base::Time::Now());
SessionStore::WriteBatch::Commit(std::move(batch));
EXPECT_THAT(BatchToEntityDataMap(session_store()->GetAllSessionData()),
UnorderedElementsAre(
Pair(local_header_storage_key, _),
Pair(foreign_header_storage_key,
EntityDataHasSpecifics(MatchesHeader(kForeignSessionTag,
/*window_ids=*/{},
/*tab_ids=*/{}))),
Pair(foreign_tab_storage_key,
EntityDataHasSpecifics(MatchesTab(
kForeignSessionTag, kWindowId, kTabId1, kTabNodeId1,
/*urls=*/_)))));
}
TEST_F(SessionStoreTest, ShouldIgnoreForeignOrphanTabs) {
const std::string kForeignSessionTag = "SomeForeignTag";
const int kWindowId = 5;
const int kTabId = 7;
// Both tab nodes point to the same tab ID, so the second one should prevail.
const int kTabNodeId1 = 2;
const int kTabNodeId2 = 3;
const std::string local_header_storage_key =
SessionStore::GetHeaderStorageKey(kLocalCacheGuid);
const std::string foreign_header_storage_key =
SessionStore::GetHeaderStorageKey(kForeignSessionTag);
const std::string foreign_tab_storage_key2 =
SessionStore::GetTabStorageKey(kForeignSessionTag, kTabNodeId2);
// Local header entity is present initially.
ASSERT_THAT(BatchToEntityDataMap(session_store()->GetAllSessionData()),
ElementsAre(Pair(local_header_storage_key, _)));
SessionSpecifics tab1;
tab1.set_session_tag(kForeignSessionTag);
tab1.set_tab_node_id(kTabNodeId1);
tab1.mutable_tab()->set_window_id(kWindowId);
tab1.mutable_tab()->set_tab_id(kTabId);
ASSERT_TRUE(SessionStore::AreValidSpecifics(tab1));
SessionSpecifics tab2;
tab2.set_session_tag(kForeignSessionTag);
tab2.set_tab_node_id(kTabNodeId2);
tab2.mutable_tab()->set_window_id(kWindowId);
tab2.mutable_tab()->set_tab_id(kTabId);
ASSERT_TRUE(SessionStore::AreValidSpecifics(tab2));
// Store the two foreign tabs, in order.
std::unique_ptr<SessionStore::WriteBatch> batch =
session_store()->CreateWriteBatch(/*error_handler=*/base::DoNothing());
ASSERT_THAT(batch, NotNull());
batch->PutAndUpdateTracker(tab1, base::Time::Now());
batch->PutAndUpdateTracker(tab2, base::Time::Now());
SessionStore::WriteBatch::Commit(std::move(batch));
// The first foreign tab should have been overwritten by the second one,
// because they shared a tab ID.
EXPECT_THAT(BatchToEntityDataMap(session_store()->GetAllSessionData()),
UnorderedElementsAre(
Pair(local_header_storage_key, _),
Pair(foreign_header_storage_key,
EntityDataHasSpecifics(MatchesHeader(kForeignSessionTag,
/*window_ids=*/{},
/*tab_ids=*/{}))),
Pair(foreign_tab_storage_key2,
EntityDataHasSpecifics(MatchesTab(
kForeignSessionTag, kWindowId, kTabId, kTabNodeId2,
/*urls=*/_)))));
}
} // namespace
} // namespace sync_sessions
|