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

Side by Side Diff: components/sync_sessions/sessions_sync_manager.cc

Issue 2683263002: Reland v4 of Session refactor (Closed)
Patch Set: Better handle possible corruption in sync node and add some testing Created 3 years, 10 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
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 "components/sync_sessions/sessions_sync_manager.h" 5 #include "components/sync_sessions/sessions_sync_manager.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 #include <utility> 8 #include <utility>
9 9
10 #include "base/format_macros.h"
11 #include "base/logging.h"
10 #include "base/memory/ptr_util.h" 12 #include "base/memory/ptr_util.h"
11 #include "base/metrics/field_trial.h" 13 #include "base/metrics/field_trial.h"
12 #include "base/metrics/histogram_macros.h" 14 #include "base/metrics/histogram_macros.h"
15 #include "base/strings/stringprintf.h"
13 #include "build/build_config.h" 16 #include "build/build_config.h"
14 #include "components/sync/base/hash_util.h" 17 #include "components/sync/base/hash_util.h"
15 #include "components/sync/device_info/local_device_info_provider.h" 18 #include "components/sync/device_info/local_device_info_provider.h"
16 #include "components/sync/model/sync_error.h" 19 #include "components/sync/model/sync_error.h"
17 #include "components/sync/model/sync_error_factory.h" 20 #include "components/sync/model/sync_error_factory.h"
18 #include "components/sync/model/sync_merge_result.h" 21 #include "components/sync/model/sync_merge_result.h"
19 #include "components/sync/model/time.h" 22 #include "components/sync/model/time.h"
20 #include "components/sync_sessions/sync_sessions_client.h" 23 #include "components/sync_sessions/sync_sessions_client.h"
21 #include "components/sync_sessions/synced_tab_delegate.h" 24 #include "components/sync_sessions/synced_tab_delegate.h"
22 #include "components/sync_sessions/synced_window_delegate.h" 25 #include "components/sync_sessions/synced_window_delegate.h"
23 #include "components/sync_sessions/synced_window_delegates_getter.h" 26 #include "components/sync_sessions/synced_window_delegates_getter.h"
27 #include "components/sync_sessions/tab_node_pool.h"
24 #include "components/variations/variations_associated_data.h" 28 #include "components/variations/variations_associated_data.h"
25 29
26 using sessions::SerializedNavigationEntry; 30 using sessions::SerializedNavigationEntry;
27 using syncer::DeviceInfo; 31 using syncer::DeviceInfo;
28 using syncer::LocalDeviceInfoProvider; 32 using syncer::LocalDeviceInfoProvider;
29 using syncer::SyncChange; 33 using syncer::SyncChange;
30 using syncer::SyncData; 34 using syncer::SyncData;
31 35
32 namespace sync_sessions { 36 namespace sync_sessions {
33 37
(...skipping 21 matching lines...) Expand all
55 return t1->timestamp > t2->timestamp; 59 return t1->timestamp > t2->timestamp;
56 } 60 }
57 61
58 // Comparator function for use with std::sort that will sort sessions by 62 // Comparator function for use with std::sort that will sort sessions by
59 // descending modified_time (i.e., most recent first). 63 // descending modified_time (i.e., most recent first).
60 bool SessionsRecencyComparator(const SyncedSession* s1, 64 bool SessionsRecencyComparator(const SyncedSession* s1,
61 const SyncedSession* s2) { 65 const SyncedSession* s2) {
62 return s1->modified_time > s2->modified_time; 66 return s1->modified_time > s2->modified_time;
63 } 67 }
64 68
69 std::string TabNodeIdToTag(const std::string& machine_tag, int tab_node_id) {
70 CHECK_GT(tab_node_id, TabNodePool::kInvalidTabNodeID) << "crbug.com/673618";
71 return base::StringPrintf("%s %d", machine_tag.c_str(), tab_node_id);
72 }
73
65 std::string TagFromSpecifics(const sync_pb::SessionSpecifics& specifics) { 74 std::string TagFromSpecifics(const sync_pb::SessionSpecifics& specifics) {
66 if (specifics.has_header()) { 75 if (specifics.has_header()) {
67 return specifics.session_tag(); 76 return specifics.session_tag();
68 } else if (specifics.has_tab()) { 77 } else if (specifics.has_tab()) {
69 return TabNodePool::TabIdToTag(specifics.session_tag(), 78 return TabNodeIdToTag(specifics.session_tag(), specifics.tab_node_id());
70 specifics.tab_node_id());
71 } else { 79 } else {
72 return std::string(); 80 return std::string();
73 } 81 }
74 } 82 }
75 83
84 sync_pb::SessionSpecifics SessionTabToSpecifics(
85 const sessions::SessionTab& session_tab,
86 const std::string& local_tag,
87 int tab_node_id) {
88 sync_pb::SessionSpecifics specifics;
89 specifics.mutable_tab()->CopyFrom(session_tab.ToSyncData());
90 specifics.set_session_tag(local_tag);
91 specifics.set_tab_node_id(tab_node_id);
92 return specifics;
93 }
94
95 void AppendDeletionsForTabNodes(const std::set<int>& tab_node_ids,
96 const std::string& machine_tag,
97 syncer::SyncChangeList* change_output) {
98 for (std::set<int>::const_iterator it = tab_node_ids.begin();
99 it != tab_node_ids.end(); ++it) {
100 change_output->push_back(syncer::SyncChange(
101 FROM_HERE, SyncChange::ACTION_DELETE,
102 SyncData::CreateLocalDelete(TabNodeIdToTag(machine_tag, *it),
103 syncer::SESSIONS)));
104 }
105 }
106
107 // Ensure that the tab id is not invalid and is not already synced (which
108 // can confuse the logic that tracks whether tabs are mapped or unmapped).
109 bool ShouldSyncTabId(
110 SessionID::id_type tab_id,
111 const google::protobuf::RepeatedField<int>& synced_tab_ids) {
112 if (tab_id == TabNodePool::kInvalidTabID)
113 return false;
114
115 for (auto synced_tab_id : synced_tab_ids) {
116 if (tab_id == synced_tab_id)
117 return false;
118 }
119
120 return true;
121 }
122
76 } // namespace 123 } // namespace
77 124
78 // |local_device| is owned by ProfileSyncService, its lifetime exceeds 125 // |local_device| is owned by ProfileSyncService, its lifetime exceeds
79 // lifetime of SessionSyncManager. 126 // lifetime of SessionSyncManager.
80 SessionsSyncManager::SessionsSyncManager( 127 SessionsSyncManager::SessionsSyncManager(
81 sync_sessions::SyncSessionsClient* sessions_client, 128 sync_sessions::SyncSessionsClient* sessions_client,
82 syncer::SyncPrefs* sync_prefs, 129 syncer::SyncPrefs* sync_prefs,
83 LocalDeviceInfoProvider* local_device, 130 LocalDeviceInfoProvider* local_device,
84 std::unique_ptr<LocalSessionEventRouter> router, 131 std::unique_ptr<LocalSessionEventRouter> router,
85 const base::Closure& sessions_updated_callback, 132 const base::Closure& sessions_updated_callback,
(...skipping 24 matching lines...) Expand all
110 return machine_tag; 157 return machine_tag;
111 } 158 }
112 159
113 syncer::SyncMergeResult SessionsSyncManager::MergeDataAndStartSyncing( 160 syncer::SyncMergeResult SessionsSyncManager::MergeDataAndStartSyncing(
114 syncer::ModelType type, 161 syncer::ModelType type,
115 const syncer::SyncDataList& initial_sync_data, 162 const syncer::SyncDataList& initial_sync_data,
116 std::unique_ptr<syncer::SyncChangeProcessor> sync_processor, 163 std::unique_ptr<syncer::SyncChangeProcessor> sync_processor,
117 std::unique_ptr<syncer::SyncErrorFactory> error_handler) { 164 std::unique_ptr<syncer::SyncErrorFactory> error_handler) {
118 syncer::SyncMergeResult merge_result(type); 165 syncer::SyncMergeResult merge_result(type);
119 DCHECK(session_tracker_.Empty()); 166 DCHECK(session_tracker_.Empty());
120 DCHECK_EQ(0U, local_tab_pool_.Capacity());
121 167
122 error_handler_ = std::move(error_handler); 168 error_handler_ = std::move(error_handler);
123 sync_processor_ = std::move(sync_processor); 169 sync_processor_ = std::move(sync_processor);
124 170
125 // SessionDataTypeController ensures that the local device info 171 // SessionDataTypeController ensures that the local device info
126 // is available before activating this datatype. 172 // is available before activating this datatype.
127 DCHECK(local_device_); 173 DCHECK(local_device_);
128 const DeviceInfo* local_device_info = local_device_->GetLocalDeviceInfo(); 174 const DeviceInfo* local_device_info = local_device_->GetLocalDeviceInfo();
129 if (!local_device_info) { 175 if (!local_device_info) {
130 merge_result.set_error(error_handler_->CreateAndUploadError( 176 merge_result.set_error(error_handler_->CreateAndUploadError(
(...skipping 15 matching lines...) Expand all
146 192
147 local_session_header_node_id_ = TabNodePool::kInvalidTabNodeID; 193 local_session_header_node_id_ = TabNodePool::kInvalidTabNodeID;
148 194
149 // Make sure we have a machine tag. We do this now (versus earlier) as it's 195 // Make sure we have a machine tag. We do this now (versus earlier) as it's
150 // a conveniently safe time to assert sync is ready and the cache_guid is 196 // a conveniently safe time to assert sync is ready and the cache_guid is
151 // initialized. 197 // initialized.
152 if (current_machine_tag_.empty()) { 198 if (current_machine_tag_.empty()) {
153 InitializeCurrentMachineTag(local_device_->GetLocalSyncCacheGUID()); 199 InitializeCurrentMachineTag(local_device_->GetLocalSyncCacheGUID());
154 } 200 }
155 201
156 session_tracker_.SetLocalSessionTag(current_machine_tag_); 202 session_tracker_.SetLocalSessionTag(current_machine_tag());
157 203
158 syncer::SyncChangeList new_changes; 204 syncer::SyncChangeList new_changes;
159 205
160 // First, we iterate over sync data to update our session_tracker_. 206 // First, we iterate over sync data to update our session_tracker_.
161 syncer::SyncDataList restored_tabs; 207 if (!InitFromSyncModel(initial_sync_data, &new_changes)) {
162 if (!InitFromSyncModel(initial_sync_data, &restored_tabs, &new_changes)) {
163 // The sync db didn't have a header node for us. Create one. 208 // The sync db didn't have a header node for us. Create one.
164 sync_pb::EntitySpecifics specifics; 209 sync_pb::EntitySpecifics specifics;
165 sync_pb::SessionSpecifics* base_specifics = specifics.mutable_session(); 210 sync_pb::SessionSpecifics* base_specifics = specifics.mutable_session();
166 base_specifics->set_session_tag(current_machine_tag()); 211 base_specifics->set_session_tag(current_machine_tag());
167 sync_pb::SessionHeader* header_s = base_specifics->mutable_header(); 212 sync_pb::SessionHeader* header_s = base_specifics->mutable_header();
168 header_s->set_client_name(current_session_name_); 213 header_s->set_client_name(current_session_name_);
169 header_s->set_device_type(current_device_type_); 214 header_s->set_device_type(current_device_type_);
170 syncer::SyncData data = syncer::SyncData::CreateLocalData( 215 syncer::SyncData data = syncer::SyncData::CreateLocalData(
171 current_machine_tag(), current_session_name_, specifics); 216 current_machine_tag(), current_session_name_, specifics);
172 new_changes.push_back( 217 new_changes.push_back(
173 syncer::SyncChange(FROM_HERE, syncer::SyncChange::ACTION_ADD, data)); 218 syncer::SyncChange(FROM_HERE, syncer::SyncChange::ACTION_ADD, data));
174 } 219 }
175 220
176 #if defined(OS_ANDROID) 221 #if defined(OS_ANDROID)
177 std::string sync_machine_tag( 222 std::string sync_machine_tag(
178 BuildMachineTag(local_device_->GetLocalSyncCacheGUID())); 223 BuildMachineTag(local_device_->GetLocalSyncCacheGUID()));
179 if (current_machine_tag_.compare(sync_machine_tag) != 0) 224 if (current_machine_tag().compare(sync_machine_tag) != 0)
180 DeleteForeignSessionInternal(sync_machine_tag, &new_changes); 225 DeleteForeignSessionInternal(sync_machine_tag, &new_changes);
181 #endif 226 #endif
182 227
183 // Check if anything has changed on the local client side. 228 // Check if anything has changed on the local client side.
184 AssociateWindows(RELOAD_TABS, restored_tabs, &new_changes); 229 AssociateWindows(RELOAD_TABS, &new_changes);
185 local_tab_pool_out_of_sync_ = false; 230 local_tab_pool_out_of_sync_ = false;
186 231
187 merge_result.set_error( 232 merge_result.set_error(
188 sync_processor_->ProcessSyncChanges(FROM_HERE, new_changes)); 233 sync_processor_->ProcessSyncChanges(FROM_HERE, new_changes));
189 234
190 local_event_router_->StartRoutingTo(this); 235 local_event_router_->StartRoutingTo(this);
191 return merge_result; 236 return merge_result;
192 } 237 }
193 238
194 void SessionsSyncManager::AssociateWindows( 239 void SessionsSyncManager::AssociateWindows(
195 ReloadTabsOption option, 240 ReloadTabsOption option,
196 const syncer::SyncDataList& restored_tabs,
197 syncer::SyncChangeList* change_output) { 241 syncer::SyncChangeList* change_output) {
198 const std::string local_tag = current_machine_tag(); 242 const std::string local_tag = current_machine_tag();
199 sync_pb::SessionSpecifics specifics; 243 sync_pb::SessionSpecifics specifics;
200 specifics.set_session_tag(local_tag); 244 specifics.set_session_tag(local_tag);
201 sync_pb::SessionHeader* header_s = specifics.mutable_header(); 245 sync_pb::SessionHeader* header_s = specifics.mutable_header();
202 SyncedSession* current_session = session_tracker_.GetSession(local_tag); 246 SyncedSession* current_session = session_tracker_.GetSession(local_tag);
203 current_session->modified_time = base::Time::Now(); 247 current_session->modified_time = base::Time::Now();
204 header_s->set_client_name(current_session_name_); 248 header_s->set_client_name(current_session_name_);
205 header_s->set_device_type(current_device_type_); 249 header_s->set_device_type(current_device_type_);
206 250
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
254 298
255 bool found_tabs = false; 299 bool found_tabs = false;
256 for (int j = 0; j < window_delegate->GetTabCount(); ++j) { 300 for (int j = 0; j < window_delegate->GetTabCount(); ++j) {
257 SessionID::id_type tab_id = window_delegate->GetTabIdAt(j); 301 SessionID::id_type tab_id = window_delegate->GetTabIdAt(j);
258 SyncedTabDelegate* synced_tab = window_delegate->GetTabAt(j); 302 SyncedTabDelegate* synced_tab = window_delegate->GetTabAt(j);
259 303
260 // GetTabAt can return a null tab; in that case just skip it. 304 // GetTabAt can return a null tab; in that case just skip it.
261 if (!synced_tab) 305 if (!synced_tab)
262 continue; 306 continue;
263 307
308 if (!ShouldSyncTabId(tab_id, window_s.tab())) {
309 LOG(ERROR) << "Not syncing invalid/duplicate tab with id " << tab_id;
310 continue;
311 }
312
313 // Placeholder tabs are those without WebContents, either because they
314 // were never loaded into memory or they were evicted from memory
315 // (typically only on Android devices). They only have a tab id, window
316 // id, and a saved synced id (corresponding to the tab node id). Note
317 // that only placeholders have this sync id, as it's necessary to
318 // properly reassociate the tab with the entity that was backing it.
264 if (synced_tab->IsPlaceholderTab()) { 319 if (synced_tab->IsPlaceholderTab()) {
265 // For tabs without WebContents update the |tab_id| and |window_id|, 320 // For tabs without WebContents update the |tab_id| and |window_id|,
266 // as it could have changed after a session restore. 321 // as it could have changed after a session restore.
267 // Note: We cannot check if a tab is valid if it has no WebContents. 322 if (synced_tab->GetSyncId() > TabNodePool::kInvalidTabNodeID) {
268 // We assume any such tab is valid and leave the contents of
269 // corresponding sync node unchanged.
270 if (synced_tab->GetSyncId() > TabNodePool::kInvalidTabNodeID &&
271 tab_id > TabNodePool::kInvalidTabID) {
272 AssociateRestoredPlaceholderTab(*synced_tab, tab_id, window_id, 323 AssociateRestoredPlaceholderTab(*synced_tab, tab_id, window_id,
273 restored_tabs, change_output); 324 change_output);
274 found_tabs = true;
275 window_s.add_tab(tab_id);
276 } 325 }
277 continue; 326 } else if (RELOAD_TABS == option) {
327 AssociateTab(synced_tab, change_output);
278 } 328 }
279 329
280 if (RELOAD_TABS == option) 330 // If the tab was syncable, it would have been added to the tracker
281 AssociateTab(synced_tab, change_output); 331 // either by the above Associate[RestoredPlaceholder]Tab call or by the
282 332 // OnLocalTabModified method invoking AssociateTab directly. Therefore,
283 // If the tab is valid, it would have been added to the tracker either 333 // we can key whether this window has valid tabs based on the tab's
284 // by the above AssociateTab call (at association time), or by the 334 // presence in the tracker.
285 // change processor calling AssociateTab for all modified tabs.
286 // Therefore, we can key whether this window has valid tabs based on
287 // the tab's presence in the tracker.
288 const sessions::SessionTab* tab = nullptr; 335 const sessions::SessionTab* tab = nullptr;
289 if (session_tracker_.LookupSessionTab(local_tag, tab_id, &tab)) { 336 if (session_tracker_.LookupSessionTab(local_tag, tab_id, &tab)) {
290 found_tabs = true; 337 found_tabs = true;
291 window_s.add_tab(tab_id); 338 window_s.add_tab(tab_id);
292 } 339 }
293 } 340 }
294 if (found_tabs) { 341 if (found_tabs) {
295 sync_pb::SessionWindow* header_window = header_s->add_window(); 342 sync_pb::SessionWindow* header_window = header_s->add_window();
296 *header_window = window_s; 343 *header_window = window_s;
297 344
298 // Update this window's representation in the synced session tracker. 345 // Update this window's representation in the synced session tracker.
299 session_tracker_.PutWindowInSession(local_tag, window_id); 346 session_tracker_.PutWindowInSession(local_tag, window_id);
300 BuildSyncedSessionFromSpecifics( 347 BuildSyncedSessionFromSpecifics(
301 local_tag, window_s, current_session->modified_time, 348 local_tag, window_s, current_session->modified_time,
302 current_session->windows[window_id].get()); 349 current_session->windows[window_id].get());
303 } 350 }
304 } 351 }
305 } 352 }
306 local_tab_pool_.DeleteUnassociatedTabNodes(change_output); 353 std::set<int> deleted_tab_node_ids;
307 session_tracker_.CleanupSession(local_tag); 354 session_tracker_.CleanupLocalTabs(&deleted_tab_node_ids);
355 AppendDeletionsForTabNodes(deleted_tab_node_ids, current_machine_tag(),
356 change_output);
308 357
309 // Always update the header. Sync takes care of dropping this update 358 // Always update the header. Sync takes care of dropping this update
310 // if the entity specifics are identical (i.e windows, client name did 359 // if the entity specifics are identical (i.e windows, client name did
311 // not change). 360 // not change).
312 sync_pb::EntitySpecifics entity; 361 sync_pb::EntitySpecifics entity;
313 entity.mutable_session()->CopyFrom(specifics); 362 entity.mutable_session()->CopyFrom(specifics);
314 syncer::SyncData data = syncer::SyncData::CreateLocalData( 363 syncer::SyncData data = syncer::SyncData::CreateLocalData(
315 current_machine_tag(), current_session_name_, entity); 364 current_machine_tag(), current_session_name_, entity);
316 change_output->push_back( 365 change_output->push_back(
317 syncer::SyncChange(FROM_HERE, syncer::SyncChange::ACTION_UPDATE, data)); 366 syncer::SyncChange(FROM_HERE, syncer::SyncChange::ACTION_UPDATE, data));
318 } 367 }
319 368
320 void SessionsSyncManager::AssociateTab(SyncedTabDelegate* const tab, 369 void SessionsSyncManager::AssociateTab(SyncedTabDelegate* const tab_delegate,
321 syncer::SyncChangeList* change_output) { 370 syncer::SyncChangeList* change_output) {
322 DCHECK(!tab->IsPlaceholderTab()); 371 DCHECK(!tab_delegate->IsPlaceholderTab());
323 SessionID::id_type tab_id = tab->GetSessionId();
324 372
325 if (tab->IsBeingDestroyed()) { 373 if (tab_delegate->IsBeingDestroyed()) {
326 // This tab is closing. 374 // Do nothing. By not proactively adding the tab to the session, it will be
327 TabLinksMap::iterator tab_iter = local_tab_map_.find(tab_id); 375 // removed if necessary during subsequent cleanup.
328 if (tab_iter == local_tab_map_.end()) {
329 // We aren't tracking this tab (for example, sync setting page).
330 return;
331 }
332 local_tab_pool_.FreeTabNode(tab_iter->second->tab_node_id(), change_output);
333 local_tab_map_.erase(tab_iter);
334 return; 376 return;
335 } 377 }
336 378
337 if (!tab->ShouldSync(sessions_client_)) 379 if (!tab_delegate->ShouldSync(sessions_client_))
338 return; 380 return;
339 381
340 TabLinksMap::iterator local_tab_map_iter = local_tab_map_.find(tab_id); 382 SessionID::id_type tab_id = tab_delegate->GetSessionId();
341 TabLink* tab_link = nullptr; 383 DVLOG(1) << "Syncing tab " << tab_id << " from window "
384 << tab_delegate->GetWindowId();
342 385
343 if (local_tab_map_iter == local_tab_map_.end()) { 386 int tab_node_id = TabNodePool::kInvalidTabNodeID;
344 int tab_node_id = tab->GetSyncId(); 387 bool existing_tab_node =
345 // If there is an old sync node for the tab, reuse it. If this is a new 388 session_tracker_.GetTabNodeFromLocalTabId(tab_id, &tab_node_id);
346 // tab, get a sync node for it. 389 CHECK_NE(TabNodePool::kInvalidTabNodeID, tab_node_id) << "crbug.com/673618";
347 if (!local_tab_pool_.IsUnassociatedTabNode(tab_node_id)) { 390 tab_delegate->SetSyncId(tab_node_id);
348 tab_node_id = local_tab_pool_.GetFreeTabNode(change_output); 391 sessions::SessionTab* session_tab =
349 tab->SetSyncId(tab_node_id); 392 session_tracker_.GetTab(current_machine_tag(), tab_id);
350 }
351 local_tab_pool_.AssociateTabNode(tab_node_id, tab_id);
352 tab_link = new TabLink(tab_node_id, tab);
353 local_tab_map_[tab_id] = make_linked_ptr<TabLink>(tab_link);
354 } else {
355 // This tab is already associated with a sync node, reuse it.
356 // Note: on some platforms the tab object may have changed, so we ensure
357 // the tab link is up to date.
358 tab_link = local_tab_map_iter->second.get();
359 local_tab_map_iter->second->set_tab(tab);
360 }
361 DCHECK(tab_link);
362 DCHECK_NE(tab_link->tab_node_id(), TabNodePool::kInvalidTabNodeID);
363 DVLOG(1) << "Reloading tab " << tab_id << " from window "
364 << tab->GetWindowId();
365 393
366 // Write to sync model. 394 // Get the previously synced url.
367 sync_pb::EntitySpecifics specifics; 395 int old_index = session_tab->normalized_navigation_index();
368 LocalTabDelegateToSpecifics(*tab, specifics.mutable_session()); 396 GURL old_url;
369 syncer::SyncData data = syncer::SyncData::CreateLocalData( 397 if (session_tab->navigations.size() > static_cast<size_t>(old_index))
370 TabNodePool::TabIdToTag(current_machine_tag_, tab_link->tab_node_id()), 398 old_url = session_tab->navigations[old_index].virtual_url();
371 current_session_name_, specifics);
372 change_output->push_back(
373 syncer::SyncChange(FROM_HERE, syncer::SyncChange::ACTION_UPDATE, data));
374 399
375 int current_index = tab->GetCurrentEntryIndex(); 400 // Update the tracker's session representation.
376 const GURL new_url = tab->GetVirtualURLAtIndex(current_index); 401 SetSessionTabFromDelegate(*tab_delegate, base::Time::Now(), session_tab);
377 if (new_url != tab_link->url()) { 402 SetVariationIds(session_tab);
378 tab_link->set_url(new_url);
379 favicon_cache_.OnFaviconVisited(new_url,
380 tab->GetFaviconURLAtIndex(current_index));
381 page_revisit_broadcaster_.OnPageVisit(
382 new_url, tab->GetTransitionAtIndex(current_index));
383 }
384
385 session_tracker_.GetSession(current_machine_tag())->modified_time = 403 session_tracker_.GetSession(current_machine_tag())->modified_time =
386 base::Time::Now(); 404 base::Time::Now();
405
406 // Write to the sync model itself.
407 sync_pb::EntitySpecifics specifics;
408 specifics.mutable_session()->CopyFrom(
409 SessionTabToSpecifics(*session_tab, current_machine_tag(), tab_node_id));
410 syncer::SyncData data = syncer::SyncData::CreateLocalData(
411 TabNodeIdToTag(current_machine_tag(), tab_node_id), current_session_name_,
412 specifics);
413 change_output->push_back(syncer::SyncChange(
414 FROM_HERE, existing_tab_node ? syncer::SyncChange::ACTION_UPDATE
415 : syncer::SyncChange::ACTION_ADD,
416 data));
417
418 int current_index = tab_delegate->GetCurrentEntryIndex();
419 const GURL new_url = tab_delegate->GetVirtualURLAtIndex(current_index);
420 if (new_url != old_url) {
421 favicon_cache_.OnFaviconVisited(
422 new_url, tab_delegate->GetFaviconURLAtIndex(current_index));
423 page_revisit_broadcaster_.OnPageVisit(
424 new_url, tab_delegate->GetTransitionAtIndex(current_index));
425 }
387 } 426 }
388 427
389 bool SessionsSyncManager::RebuildAssociations() { 428 bool SessionsSyncManager::RebuildAssociations() {
390 syncer::SyncDataList data(sync_processor_->GetAllSyncData(syncer::SESSIONS)); 429 syncer::SyncDataList data(sync_processor_->GetAllSyncData(syncer::SESSIONS));
391 std::unique_ptr<syncer::SyncErrorFactory> error_handler( 430 std::unique_ptr<syncer::SyncErrorFactory> error_handler(
392 std::move(error_handler_)); 431 std::move(error_handler_));
393 std::unique_ptr<syncer::SyncChangeProcessor> processor( 432 std::unique_ptr<syncer::SyncChangeProcessor> processor(
394 std::move(sync_processor_)); 433 std::move(sync_processor_));
395 434
396 StopSyncing(syncer::SESSIONS); 435 StopSyncing(syncer::SESSIONS);
(...skipping 39 matching lines...) Expand 10 before | Expand all | Expand 10 after
436 DCHECK(!rebuild_association_succeeded || !local_tab_pool_out_of_sync_); 475 DCHECK(!rebuild_association_succeeded || !local_tab_pool_out_of_sync_);
437 return; 476 return;
438 } 477 }
439 478
440 syncer::SyncChangeList changes; 479 syncer::SyncChangeList changes;
441 AssociateTab(modified_tab, &changes); 480 AssociateTab(modified_tab, &changes);
442 // Note, we always associate windows because it's possible a tab became 481 // Note, we always associate windows because it's possible a tab became
443 // "interesting" by going to a valid URL, in which case it needs to be added 482 // "interesting" by going to a valid URL, in which case it needs to be added
444 // to the window's tab information. Similarly, if a tab became 483 // to the window's tab information. Similarly, if a tab became
445 // "uninteresting", we remove it from the window's tab information. 484 // "uninteresting", we remove it from the window's tab information.
446 AssociateWindows(DONT_RELOAD_TABS, syncer::SyncDataList(), &changes); 485 AssociateWindows(DONT_RELOAD_TABS, &changes);
447 sync_processor_->ProcessSyncChanges(FROM_HERE, changes); 486 sync_processor_->ProcessSyncChanges(FROM_HERE, changes);
448 } 487 }
449 488
450 void SessionsSyncManager::OnFaviconsChanged(const std::set<GURL>& page_urls, 489 void SessionsSyncManager::OnFaviconsChanged(const std::set<GURL>& page_urls,
451 const GURL& /* icon_url */) { 490 const GURL& /* icon_url */) {
452 // TODO(zea): consider a separate container for tabs with outstanding favicon 491 for (const GURL& page_url : page_urls)
453 // loads so we don't have to iterate through all tabs comparing urls. 492 favicon_cache_.OnPageFaviconUpdated(page_url);
454 for (const GURL& page_url : page_urls) {
455 for (TabLinksMap::iterator tab_iter = local_tab_map_.begin();
456 tab_iter != local_tab_map_.end(); ++tab_iter) {
457 if (tab_iter->second->url() == page_url)
458 favicon_cache_.OnPageFaviconUpdated(page_url);
459 }
460 }
461 } 493 }
462 494
463 void SessionsSyncManager::StopSyncing(syncer::ModelType type) { 495 void SessionsSyncManager::StopSyncing(syncer::ModelType type) {
464 local_event_router_->Stop(); 496 local_event_router_->Stop();
465 if (sync_processor_.get() && lost_navigations_recorder_.get()) { 497 if (sync_processor_.get() && lost_navigations_recorder_.get()) {
466 sync_processor_->RemoveLocalChangeObserver( 498 sync_processor_->RemoveLocalChangeObserver(
467 lost_navigations_recorder_.get()); 499 lost_navigations_recorder_.get());
468 lost_navigations_recorder_.reset(); 500 lost_navigations_recorder_.reset();
469 } 501 }
470 sync_processor_.reset(nullptr); 502 sync_processor_.reset(nullptr);
471 error_handler_.reset(); 503 error_handler_.reset();
472 session_tracker_.Clear(); 504 session_tracker_.Clear();
473 local_tab_map_.clear();
474 local_tab_pool_.Clear();
475 current_machine_tag_.clear(); 505 current_machine_tag_.clear();
476 current_session_name_.clear(); 506 current_session_name_.clear();
477 local_session_header_node_id_ = TabNodePool::kInvalidTabNodeID; 507 local_session_header_node_id_ = TabNodePool::kInvalidTabNodeID;
478 } 508 }
479 509
480 syncer::SyncDataList SessionsSyncManager::GetAllSyncData( 510 syncer::SyncDataList SessionsSyncManager::GetAllSyncData(
481 syncer::ModelType type) const { 511 syncer::ModelType type) const {
482 syncer::SyncDataList list; 512 syncer::SyncDataList list;
483 const SyncedSession* session = nullptr; 513 const SyncedSession* session = nullptr;
484 if (!session_tracker_.LookupLocalSession(&session)) 514 if (!session_tracker_.LookupLocalSession(&session))
485 return syncer::SyncDataList(); 515 return syncer::SyncDataList();
486 516
487 // First construct the header node. 517 // First construct the header node.
488 sync_pb::EntitySpecifics header_entity; 518 sync_pb::EntitySpecifics header_entity;
489 header_entity.mutable_session()->set_session_tag(current_machine_tag()); 519 header_entity.mutable_session()->set_session_tag(current_machine_tag());
490 sync_pb::SessionHeader* header_specifics = 520 sync_pb::SessionHeader* header_specifics =
491 header_entity.mutable_session()->mutable_header(); 521 header_entity.mutable_session()->mutable_header();
492 header_specifics->MergeFrom(session->ToSessionHeader()); 522 header_specifics->MergeFrom(session->ToSessionHeader());
493 syncer::SyncData data = syncer::SyncData::CreateLocalData( 523 syncer::SyncData data = syncer::SyncData::CreateLocalData(
494 current_machine_tag(), current_session_name_, header_entity); 524 current_machine_tag(), current_session_name_, header_entity);
495 list.push_back(data); 525 list.push_back(data);
496 526
497 for (auto win_iter = session->windows.begin(); 527 for (auto& win_iter : session->windows) {
498 win_iter != session->windows.end(); ++win_iter) { 528 for (auto& tab : win_iter.second->tabs) {
499 for (auto tabs_iter = win_iter->second->tabs.begin(); 529 // TODO(zea): replace with with the correct tab node id once there's a
500 tabs_iter != win_iter->second->tabs.end(); ++tabs_iter) { 530 // sync specific wrapper for SessionTab. This method is only used in
531 // tests though, so it's fine for now. crbug.com/662597
532 int tab_node_id = 0;
501 sync_pb::EntitySpecifics entity; 533 sync_pb::EntitySpecifics entity;
502 sync_pb::SessionSpecifics* specifics = entity.mutable_session(); 534 entity.mutable_session()->CopyFrom(
503 specifics->mutable_tab()->MergeFrom((*tabs_iter)->ToSyncData()); 535 SessionTabToSpecifics(*tab, current_machine_tag(), tab_node_id));
504 specifics->set_session_tag(current_machine_tag_);
505
506 TabLinksMap::const_iterator tab_map_iter =
507 local_tab_map_.find((*tabs_iter)->tab_id.id());
508 DCHECK(tab_map_iter != local_tab_map_.end());
509 specifics->set_tab_node_id(tab_map_iter->second->tab_node_id());
510 syncer::SyncData data = syncer::SyncData::CreateLocalData( 536 syncer::SyncData data = syncer::SyncData::CreateLocalData(
511 TabNodePool::TabIdToTag(current_machine_tag_, 537 TabNodeIdToTag(current_machine_tag(), tab_node_id),
512 specifics->tab_node_id()),
513 current_session_name_, entity); 538 current_session_name_, entity);
514 list.push_back(data); 539 list.push_back(data);
515 } 540 }
516 } 541 }
517 return list; 542 return list;
518 } 543 }
519 544
520 bool SessionsSyncManager::GetLocalSession(const SyncedSession** local_session) { 545 bool SessionsSyncManager::GetLocalSession(const SyncedSession** local_session) {
521 if (current_machine_tag_.empty()) 546 if (current_machine_tag().empty())
522 return false; 547 return false;
523 *local_session = session_tracker_.GetSession(current_machine_tag()); 548 *local_session = session_tracker_.GetSession(current_machine_tag());
524 return true; 549 return true;
525 } 550 }
526 551
527 syncer::SyncError SessionsSyncManager::ProcessSyncChanges( 552 syncer::SyncError SessionsSyncManager::ProcessSyncChanges(
528 const tracked_objects::Location& from_here, 553 const tracked_objects::Location& from_here,
529 const syncer::SyncChangeList& change_list) { 554 const syncer::SyncChangeList& change_list) {
530 if (!sync_processor_.get()) { 555 if (!sync_processor_.get()) {
531 syncer::SyncError error(FROM_HERE, syncer::SyncError::DATATYPE_ERROR, 556 syncer::SyncError error(FROM_HERE, syncer::SyncError::DATATYPE_ERROR,
(...skipping 39 matching lines...) Expand 10 before | Expand all | Expand 10 after
571 break; 596 break;
572 case syncer::SyncChange::ACTION_ADD: 597 case syncer::SyncChange::ACTION_ADD:
573 case syncer::SyncChange::ACTION_UPDATE: 598 case syncer::SyncChange::ACTION_UPDATE:
574 if (current_machine_tag() == session.session_tag()) { 599 if (current_machine_tag() == session.session_tag()) {
575 // We should only ever receive a change to our own machine's session 600 // We should only ever receive a change to our own machine's session
576 // info if encryption was turned on. In that case, the data is still 601 // info if encryption was turned on. In that case, the data is still
577 // the same, so we can ignore. 602 // the same, so we can ignore.
578 LOG(WARNING) << "Dropping modification to local session."; 603 LOG(WARNING) << "Dropping modification to local session.";
579 return syncer::SyncError(); 604 return syncer::SyncError();
580 } 605 }
581 UpdateTrackerWithForeignSession( 606 UpdateTrackerWithSpecifics(
582 session, syncer::SyncDataRemote(it->sync_data()).GetModifiedTime()); 607 session, syncer::SyncDataRemote(it->sync_data()).GetModifiedTime());
583 break; 608 break;
584 default: 609 default:
585 NOTREACHED() << "Processing sync changes failed, unknown change type."; 610 NOTREACHED() << "Processing sync changes failed, unknown change type.";
586 } 611 }
587 } 612 }
588 613
589 if (!sessions_updated_callback_.is_null()) 614 if (!sessions_updated_callback_.is_null())
590 sessions_updated_callback_.Run(); 615 sessions_updated_callback_.Run();
591 return syncer::SyncError(); 616 return syncer::SyncError();
592 } 617 }
593 618
594 syncer::SyncChange SessionsSyncManager::TombstoneTab( 619 syncer::SyncChange SessionsSyncManager::TombstoneTab(
595 const sync_pb::SessionSpecifics& tab) { 620 const sync_pb::SessionSpecifics& tab) {
596 if (!tab.has_tab_node_id()) { 621 if (!tab.has_tab_node_id()) {
597 LOG(WARNING) << "Old sessions node without tab node id; can't tombstone."; 622 LOG(WARNING) << "Old sessions node without tab node id; can't tombstone.";
598 return syncer::SyncChange(); 623 return syncer::SyncChange();
599 } else { 624 } else {
600 return syncer::SyncChange( 625 return syncer::SyncChange(
601 FROM_HERE, SyncChange::ACTION_DELETE, 626 FROM_HERE, SyncChange::ACTION_DELETE,
602 SyncData::CreateLocalDelete( 627 SyncData::CreateLocalDelete(
603 TabNodePool::TabIdToTag(current_machine_tag(), tab.tab_node_id()), 628 TabNodeIdToTag(current_machine_tag(), tab.tab_node_id()),
604 syncer::SESSIONS)); 629 syncer::SESSIONS));
605 } 630 }
606 } 631 }
607 632
608 bool SessionsSyncManager::GetAllForeignSessions( 633 bool SessionsSyncManager::GetAllForeignSessions(
609 std::vector<const SyncedSession*>* sessions) { 634 std::vector<const SyncedSession*>* sessions) {
610 if (!session_tracker_.LookupAllForeignSessions( 635 if (!session_tracker_.LookupAllForeignSessions(
611 sessions, SyncedSessionTracker::PRESENTABLE)) 636 sessions, SyncedSessionTracker::PRESENTABLE))
612 return false; 637 return false;
613 std::sort(sessions->begin(), sessions->end(), SessionsRecencyComparator); 638 std::sort(sessions->begin(), sessions->end(), SessionsRecencyComparator);
614 return true; 639 return true;
615 } 640 }
616 641
617 bool SessionsSyncManager::InitFromSyncModel( 642 bool SessionsSyncManager::InitFromSyncModel(
618 const syncer::SyncDataList& sync_data, 643 const syncer::SyncDataList& sync_data,
619 syncer::SyncDataList* restored_tabs,
620 syncer::SyncChangeList* new_changes) { 644 syncer::SyncChangeList* new_changes) {
621 bool found_current_header = false; 645 bool found_current_header = false;
622 int bad_foreign_hash_count = 0; 646 int bad_foreign_hash_count = 0;
623 for (syncer::SyncDataList::const_iterator it = sync_data.begin(); 647 for (syncer::SyncDataList::const_iterator it = sync_data.begin();
624 it != sync_data.end(); ++it) { 648 it != sync_data.end(); ++it) {
625 const syncer::SyncData& data = *it; 649 const syncer::SyncData& data = *it;
626 DCHECK(data.GetSpecifics().has_session()); 650 DCHECK(data.GetSpecifics().has_session());
627 syncer::SyncDataRemote remote(data); 651 syncer::SyncDataRemote remote(data);
628 const sync_pb::SessionSpecifics& specifics = data.GetSpecifics().session(); 652 const sync_pb::SessionSpecifics& specifics = data.GetSpecifics().session();
629 if (specifics.session_tag().empty() || 653 if (specifics.session_tag().empty() ||
630 (specifics.has_tab() && 654 (specifics.has_tab() &&
631 (!specifics.has_tab_node_id() || !specifics.tab().has_tab_id()))) { 655 (!specifics.has_tab_node_id() || !specifics.tab().has_tab_id()))) {
632 syncer::SyncChange tombstone(TombstoneTab(specifics)); 656 syncer::SyncChange tombstone(TombstoneTab(specifics));
633 if (tombstone.IsValid()) 657 if (tombstone.IsValid())
634 new_changes->push_back(tombstone); 658 new_changes->push_back(tombstone);
635 } else if (specifics.session_tag() != current_machine_tag()) { 659 } else if (specifics.session_tag() != current_machine_tag()) {
636 if (TagHashFromSpecifics(specifics) == remote.GetClientTagHash()) { 660 if (TagHashFromSpecifics(specifics) == remote.GetClientTagHash()) {
637 UpdateTrackerWithForeignSession(specifics, remote.GetModifiedTime()); 661 UpdateTrackerWithSpecifics(specifics, remote.GetModifiedTime());
638 } else { 662 } else {
639 // In the past, like years ago, we believe that some session data was 663 // In the past, like years ago, we believe that some session data was
640 // created with bad tag hashes. This causes any change this client makes 664 // created with bad tag hashes. This causes any change this client makes
641 // to that foreign data (like deletion through garbage collection) to 665 // to that foreign data (like deletion through garbage collection) to
642 // trigger a data type error because the tag looking mechanism fails. So 666 // trigger a data type error because the tag looking mechanism fails. So
643 // look for these and delete via remote SyncData, which uses a server id 667 // look for these and delete via remote SyncData, which uses a server id
644 // lookup mechanism instead, see crbug.com/604657. 668 // lookup mechanism instead, see crbug.com/604657.
645 bad_foreign_hash_count++; 669 bad_foreign_hash_count++;
646 new_changes->push_back( 670 new_changes->push_back(
647 syncer::SyncChange(FROM_HERE, SyncChange::ACTION_DELETE, remote)); 671 syncer::SyncChange(FROM_HERE, SyncChange::ACTION_DELETE, remote));
648 } 672 }
649 } else { 673 } else {
650 // This is previously stored local session information. 674 // This is previously stored local session information.
651 if (specifics.has_header() && !found_current_header) { 675 if (specifics.has_header() && !found_current_header) {
652 // This is our previous header node, reuse it. 676 // This is our previous header node, reuse it.
653 found_current_header = true; 677 found_current_header = true;
654 if (specifics.header().has_client_name()) 678 if (specifics.header().has_client_name())
655 current_session_name_ = specifics.header().client_name(); 679 current_session_name_ = specifics.header().client_name();
680
681 // TODO(zea): crbug.com/639009 update the tracker with the specifics
682 // from the header node as well. This will be necessary to preserve
683 // the set of open tabs when a custom tab is opened.
656 } else { 684 } else {
657 if (specifics.has_header() || !specifics.has_tab()) { 685 if (specifics.has_header() || !specifics.has_tab()) {
658 LOG(WARNING) << "Found more than one session header node with local " 686 LOG(WARNING) << "Found more than one session header node with local "
659 << "tag."; 687 << "tag.";
660 syncer::SyncChange tombstone(TombstoneTab(specifics)); 688 syncer::SyncChange tombstone(TombstoneTab(specifics));
661 if (tombstone.IsValid()) 689 if (tombstone.IsValid())
662 new_changes->push_back(tombstone); 690 new_changes->push_back(tombstone);
691 } else if (specifics.tab().tab_id() == TabNodePool::kInvalidTabID) {
692 LOG(WARNING) << "Found tab node with invalid tab id.";
693 syncer::SyncChange tombstone(TombstoneTab(specifics));
694 if (tombstone.IsValid())
695 new_changes->push_back(tombstone);
663 } else { 696 } else {
664 // This is a valid old tab node, add it to the pool so it can be 697 // This is a valid old tab node, add it to the tracker and associate
665 // reused for reassociation. 698 // it.
666 local_tab_pool_.AddTabNode(specifics.tab_node_id()); 699 DVLOG(1) << "Associating local tab " << specifics.tab().tab_id()
667 restored_tabs->push_back(*it); 700 << " with node " << specifics.tab_node_id();
701 session_tracker_.ReassociateLocalTab(specifics.tab_node_id(),
702 specifics.tab().tab_id());
703 UpdateTrackerWithSpecifics(specifics, remote.GetModifiedTime());
668 } 704 }
669 } 705 }
670 } 706 }
671 } 707 }
672 708
673 // Cleanup all foreign sessions, since orphaned tabs may have been added after 709 // Cleanup all foreign sessions, since orphaned tabs may have been added after
674 // the header. 710 // the header.
675 std::vector<const SyncedSession*> sessions; 711 std::vector<const SyncedSession*> sessions;
676 session_tracker_.LookupAllForeignSessions(&sessions, 712 session_tracker_.LookupAllForeignSessions(&sessions,
677 SyncedSessionTracker::RAW); 713 SyncedSessionTracker::RAW);
678 for (const auto* session : sessions) { 714 for (const auto* session : sessions) {
679 session_tracker_.CleanupSession(session->session_tag); 715 session_tracker_.CleanupForeignSession(session->session_tag);
680 } 716 }
681 717
682 UMA_HISTOGRAM_COUNTS_100("Sync.SessionsBadForeignHashOnMergeCount", 718 UMA_HISTOGRAM_COUNTS_100("Sync.SessionsBadForeignHashOnMergeCount",
683 bad_foreign_hash_count); 719 bad_foreign_hash_count);
684 720
685 return found_current_header; 721 return found_current_header;
686 } 722 }
687 723
688 void SessionsSyncManager::UpdateTrackerWithForeignSession( 724 void SessionsSyncManager::UpdateTrackerWithSpecifics(
689 const sync_pb::SessionSpecifics& specifics, 725 const sync_pb::SessionSpecifics& specifics,
690 const base::Time& modification_time) { 726 const base::Time& modification_time) {
691 std::string foreign_session_tag = specifics.session_tag(); 727 std::string session_tag = specifics.session_tag();
692 DCHECK_NE(foreign_session_tag, current_machine_tag()); 728 SyncedSession* session = session_tracker_.GetSession(session_tag);
693
694 SyncedSession* foreign_session =
695 session_tracker_.GetSession(foreign_session_tag);
696 if (specifics.has_header()) { 729 if (specifics.has_header()) {
697 // Read in the header data for this foreign session. Header data is 730 // Read in the header data for this session. Header data is
698 // essentially a collection of windows, each of which has an ordered id list 731 // essentially a collection of windows, each of which has an ordered id list
699 // for their tabs. 732 // for their tabs.
700 733
701 if (!IsValidSessionHeader(specifics.header())) { 734 if (!IsValidSessionHeader(specifics.header())) {
702 LOG(WARNING) << "Ignoring foreign session node with invalid header " 735 LOG(WARNING) << "Ignoring session node with invalid header "
703 << "and tag " << foreign_session_tag << "."; 736 << "and tag " << session_tag << ".";
704 return; 737 return;
705 } 738 }
706 739
707 // Load (or create) the SyncedSession object for this client. 740 // Load (or create) the SyncedSession object for this client.
708 const sync_pb::SessionHeader& header = specifics.header(); 741 const sync_pb::SessionHeader& header = specifics.header();
709 PopulateSessionHeaderFromSpecifics(header, modification_time, 742 PopulateSessionHeaderFromSpecifics(header, modification_time, session);
710 foreign_session);
711 743
712 // Reset the tab/window tracking for this session (must do this before 744 // Reset the tab/window tracking for this session (must do this before
713 // we start calling PutWindowInSession and PutTabInWindow so that all 745 // we start calling PutWindowInSession and PutTabInWindow so that all
714 // unused tabs/windows get cleared by the CleanupSession(...) call). 746 // unused tabs/windows get cleared by the CleanupSession(...) call).
715 session_tracker_.ResetSessionTracking(foreign_session_tag); 747 session_tracker_.ResetSessionTracking(session_tag);
716 748
717 // Process all the windows and their tab information. 749 // Process all the windows and their tab information.
718 int num_windows = header.window_size(); 750 int num_windows = header.window_size();
719 DVLOG(1) << "Associating " << foreign_session_tag << " with " << num_windows 751 DVLOG(1) << "Populating " << session_tag << " with " << num_windows
720 << " windows."; 752 << " windows.";
721 753
722 for (int i = 0; i < num_windows; ++i) { 754 for (int i = 0; i < num_windows; ++i) {
723 const sync_pb::SessionWindow& window_s = header.window(i); 755 const sync_pb::SessionWindow& window_s = header.window(i);
724 SessionID::id_type window_id = window_s.window_id(); 756 SessionID::id_type window_id = window_s.window_id();
725 session_tracker_.PutWindowInSession(foreign_session_tag, window_id); 757 session_tracker_.PutWindowInSession(session_tag, window_id);
726 BuildSyncedSessionFromSpecifics( 758 BuildSyncedSessionFromSpecifics(session_tag, window_s, modification_time,
727 foreign_session_tag, window_s, modification_time, 759 session->windows[window_id].get());
728 foreign_session->windows[window_id].get());
729 } 760 }
730 // Delete any closed windows and unused tabs as necessary. 761 // Delete any closed windows and unused tabs as necessary.
731 session_tracker_.CleanupSession(foreign_session_tag); 762 session_tracker_.CleanupForeignSession(session_tag);
732 } else if (specifics.has_tab()) { 763 } else if (specifics.has_tab()) {
733 const sync_pb::SessionTab& tab_s = specifics.tab(); 764 const sync_pb::SessionTab& tab_s = specifics.tab();
734 SessionID::id_type tab_id = tab_s.tab_id(); 765 SessionID::id_type tab_id = tab_s.tab_id();
766 DVLOG(1) << "Populating " << session_tag << "'s tab id " << tab_id
767 << " from node " << specifics.tab_node_id();
735 768
736 const sessions::SessionTab* existing_tab; 769 // Ensure the tracker is aware of the tab node id. Deleting foreign sessions
737 if (session_tracker_.LookupSessionTab(foreign_session_tag, tab_id, 770 // requires deleting all relevant tab nodes, and it's easier to track the
738 &existing_tab) && 771 // tab node ids themselves separately from the tab ids.
739 existing_tab->timestamp > modification_time) { 772 //
740 // Force the tracker to remember this tab node id, even if it isn't 773 // Note that TabIDs are not stable across restarts of a client. Consider
741 // currently being used. 774 // this example with two tabs:
742 session_tracker_.GetTab(foreign_session_tag, tab_id, 775 //
743 specifics.tab_node_id()); 776 // http://a.com TabID1 --> NodeIDA
744 DVLOG(1) << "Ignoring " << foreign_session_tag << "'s session tab " 777 // http://b.com TabID2 --> NodeIDB
745 << tab_id << " with earlier modification time"; 778 //
779 // After restart, tab ids are reallocated. e.g, one possibility:
780 // http://a.com TabID2 --> NodeIDA
781 // http://b.com TabID1 --> NodeIDB
782 //
783 // If that happened on a remote client, here we will see an update to
784 // TabID1 with tab_node_id changing from NodeIDA to NodeIDB, and TabID2
785 // with tab_node_id changing from NodeIDB to NodeIDA.
786 //
787 // We can also wind up here if we created this tab as an out-of-order
788 // update to the header node for this session before actually associating
789 // the tab itself, so the tab node id wasn't available at the time and
790 // is currently kInvalidTabNodeID.
791 //
792 // In both cases, we can safely throw it into the set of node ids.
793 session_tracker_.OnTabNodeSeen(session_tag, specifics.tab_node_id());
794 sessions::SessionTab* tab = session_tracker_.GetTab(session_tag, tab_id);
795 if (!tab->timestamp.is_null() && tab->timestamp > modification_time) {
796 DVLOG(1) << "Ignoring " << session_tag << "'s session tab " << tab_id
797 << " with earlier modification time: " << tab->timestamp
798 << " vs " << modification_time;
746 return; 799 return;
747 } 800 }
748 801
749 sessions::SessionTab* tab = session_tracker_.GetTab(
750 foreign_session_tag, tab_id, specifics.tab_node_id());
751
752 // Update SessionTab based on protobuf. 802 // Update SessionTab based on protobuf.
753 tab->SetFromSyncData(tab_s, modification_time); 803 tab->SetFromSyncData(tab_s, modification_time);
754 804
755 // If a favicon or favicon urls are present, load the URLs and visit 805 // If a favicon or favicon urls are present, load the URLs and visit
756 // times into the in-memory favicon cache. 806 // times into the in-memory favicon cache.
757 RefreshFaviconVisitTimesFromForeignTab(tab_s, modification_time); 807 RefreshFaviconVisitTimesFromForeignTab(tab_s, modification_time);
758 808
759 // Update the last modified time. 809 // Update the last modified time.
760 if (foreign_session->modified_time < modification_time) 810 if (session->modified_time < modification_time)
761 foreign_session->modified_time = modification_time; 811 session->modified_time = modification_time;
762 } else { 812 } else {
763 LOG(WARNING) << "Ignoring foreign session node with missing header/tab " 813 LOG(WARNING) << "Ignoring session node with missing header/tab "
764 << "fields and tag " << foreign_session_tag << "."; 814 << "fields and tag " << session_tag << ".";
765 } 815 }
766 } 816 }
767 817
768 void SessionsSyncManager::InitializeCurrentMachineTag( 818 void SessionsSyncManager::InitializeCurrentMachineTag(
769 const std::string& cache_guid) { 819 const std::string& cache_guid) {
770 DCHECK(current_machine_tag_.empty()); 820 DCHECK(current_machine_tag_.empty());
771 std::string persisted_guid; 821 std::string persisted_guid;
772 persisted_guid = sync_prefs_->GetSyncSessionsGUID(); 822 persisted_guid = sync_prefs_->GetSyncSessionsGUID();
773 if (!persisted_guid.empty()) { 823 if (!persisted_guid.empty()) {
774 current_machine_tag_ = persisted_guid; 824 current_machine_tag_ = persisted_guid;
775 DVLOG(1) << "Restoring persisted session sync guid: " << persisted_guid; 825 DVLOG(1) << "Restoring persisted session sync guid: " << persisted_guid;
776 } else { 826 } else {
777 DCHECK(!cache_guid.empty()); 827 DCHECK(!cache_guid.empty());
778 current_machine_tag_ = BuildMachineTag(cache_guid); 828 current_machine_tag_ = BuildMachineTag(cache_guid);
779 DVLOG(1) << "Creating session sync guid: " << current_machine_tag_; 829 DVLOG(1) << "Creating session sync guid: " << current_machine_tag_;
780 sync_prefs_->SetSyncSessionsGUID(current_machine_tag_); 830 sync_prefs_->SetSyncSessionsGUID(current_machine_tag_);
781 } 831 }
782
783 local_tab_pool_.SetMachineTag(current_machine_tag_);
784 } 832 }
785 833
786 // static 834 // static
787 void SessionsSyncManager::PopulateSessionHeaderFromSpecifics( 835 void SessionsSyncManager::PopulateSessionHeaderFromSpecifics(
788 const sync_pb::SessionHeader& header_specifics, 836 const sync_pb::SessionHeader& header_specifics,
789 base::Time mtime, 837 base::Time mtime,
790 SyncedSession* session_header) { 838 SyncedSession* session_header) {
791 if (header_specifics.has_client_name()) 839 if (header_specifics.has_client_name())
792 session_header->session_name = header_specifics.client_name(); 840 session_header->session_name = header_specifics.client_name();
793 if (header_specifics.has_device_type()) { 841 if (header_specifics.has_device_type()) {
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
837 if (specifics.browser_type() == 885 if (specifics.browser_type() ==
838 sync_pb::SessionWindow_BrowserType_TYPE_TABBED) { 886 sync_pb::SessionWindow_BrowserType_TYPE_TABBED) {
839 session_window->type = sessions::SessionWindow::TYPE_TABBED; 887 session_window->type = sessions::SessionWindow::TYPE_TABBED;
840 } else { 888 } else {
841 // Note: custom tabs are treated like popup windows on restore, as you can 889 // Note: custom tabs are treated like popup windows on restore, as you can
842 // restore a custom tab on a platform that doesn't support them. 890 // restore a custom tab on a platform that doesn't support them.
843 session_window->type = sessions::SessionWindow::TYPE_POPUP; 891 session_window->type = sessions::SessionWindow::TYPE_POPUP;
844 } 892 }
845 } 893 }
846 session_window->timestamp = mtime; 894 session_window->timestamp = mtime;
847 session_window->tabs.resize(specifics.tab_size()); 895 session_window->tabs.clear();
848 for (int i = 0; i < specifics.tab_size(); i++) { 896 for (int i = 0; i < specifics.tab_size(); i++) {
849 SessionID::id_type tab_id = specifics.tab(i); 897 SessionID::id_type tab_id = specifics.tab(i);
850 session_tracker_.PutTabInWindow(session_tag, session_window->window_id.id(), 898 session_tracker_.PutTabInWindow(session_tag, session_window->window_id.id(),
851 tab_id, i); 899 tab_id);
852 } 900 }
853 } 901 }
854 902
855 void SessionsSyncManager::RefreshFaviconVisitTimesFromForeignTab( 903 void SessionsSyncManager::RefreshFaviconVisitTimesFromForeignTab(
856 const sync_pb::SessionTab& tab, 904 const sync_pb::SessionTab& tab,
857 const base::Time& modification_time) { 905 const base::Time& modification_time) {
858 // First go through and iterate over all the navigations, checking if any 906 // First go through and iterate over all the navigations, checking if any
859 // have valid favicon urls. 907 // have valid favicon urls.
860 for (int i = 0; i < tab.navigation_size(); ++i) { 908 for (int i = 0; i < tab.navigation_size(); ++i) {
861 if (!tab.navigation(i).favicon_url().empty()) { 909 if (!tab.navigation(i).favicon_url().empty()) {
(...skipping 21 matching lines...) Expand all
883 void SessionsSyncManager::DeleteForeignSessionInternal( 931 void SessionsSyncManager::DeleteForeignSessionInternal(
884 const std::string& tag, 932 const std::string& tag,
885 syncer::SyncChangeList* change_output) { 933 syncer::SyncChangeList* change_output) {
886 if (tag == current_machine_tag()) { 934 if (tag == current_machine_tag()) {
887 LOG(ERROR) << "Attempting to delete local session. This is not currently " 935 LOG(ERROR) << "Attempting to delete local session. This is not currently "
888 << "supported."; 936 << "supported.";
889 return; 937 return;
890 } 938 }
891 939
892 std::set<int> tab_node_ids_to_delete; 940 std::set<int> tab_node_ids_to_delete;
893 session_tracker_.LookupTabNodeIds(tag, &tab_node_ids_to_delete); 941 session_tracker_.LookupForeignTabNodeIds(tag, &tab_node_ids_to_delete);
894 if (DisassociateForeignSession(tag)) { 942 if (DisassociateForeignSession(tag)) {
895 // Only tell sync to delete the header if there was one. 943 // Only tell sync to delete the header if there was one.
896 change_output->push_back( 944 change_output->push_back(
897 syncer::SyncChange(FROM_HERE, SyncChange::ACTION_DELETE, 945 syncer::SyncChange(FROM_HERE, SyncChange::ACTION_DELETE,
898 SyncData::CreateLocalDelete(tag, syncer::SESSIONS))); 946 SyncData::CreateLocalDelete(tag, syncer::SESSIONS)));
899 } 947 }
900 for (std::set<int>::const_iterator it = tab_node_ids_to_delete.begin(); 948 AppendDeletionsForTabNodes(tab_node_ids_to_delete, tag, change_output);
901 it != tab_node_ids_to_delete.end(); ++it) {
902 change_output->push_back(syncer::SyncChange(
903 FROM_HERE, SyncChange::ACTION_DELETE,
904 SyncData::CreateLocalDelete(TabNodePool::TabIdToTag(tag, *it),
905 syncer::SESSIONS)));
906 }
907 if (!sessions_updated_callback_.is_null()) 949 if (!sessions_updated_callback_.is_null())
908 sessions_updated_callback_.Run(); 950 sessions_updated_callback_.Run();
909 } 951 }
910 952
911 bool SessionsSyncManager::DisassociateForeignSession( 953 bool SessionsSyncManager::DisassociateForeignSession(
912 const std::string& foreign_session_tag) { 954 const std::string& foreign_session_tag) {
913 DCHECK_NE(foreign_session_tag, current_machine_tag()); 955 DCHECK_NE(foreign_session_tag, current_machine_tag());
914 DVLOG(1) << "Disassociating session " << foreign_session_tag; 956 DVLOG(1) << "Disassociating session " << foreign_session_tag;
915 return session_tracker_.DeleteSession(foreign_session_tag); 957 return session_tracker_.DeleteForeignSession(foreign_session_tag);
916 } 958 }
917 959
918 bool SessionsSyncManager::GetForeignSession( 960 bool SessionsSyncManager::GetForeignSession(
919 const std::string& tag, 961 const std::string& tag,
920 std::vector<const sessions::SessionWindow*>* windows) { 962 std::vector<const sessions::SessionWindow*>* windows) {
921 return session_tracker_.LookupSessionWindows(tag, windows); 963 return session_tracker_.LookupSessionWindows(tag, windows);
922 } 964 }
923 965
924 bool SessionsSyncManager::GetForeignSessionTabs( 966 bool SessionsSyncManager::GetForeignSessionTabs(
925 const std::string& tag, 967 const std::string& tag,
(...skipping 25 matching lines...) Expand all
951 bool SessionsSyncManager::GetForeignTab(const std::string& tag, 993 bool SessionsSyncManager::GetForeignTab(const std::string& tag,
952 const SessionID::id_type tab_id, 994 const SessionID::id_type tab_id,
953 const sessions::SessionTab** tab) { 995 const sessions::SessionTab** tab) {
954 const sessions::SessionTab* synced_tab = nullptr; 996 const sessions::SessionTab* synced_tab = nullptr;
955 bool success = session_tracker_.LookupSessionTab(tag, tab_id, &synced_tab); 997 bool success = session_tracker_.LookupSessionTab(tag, tab_id, &synced_tab);
956 if (success) 998 if (success)
957 *tab = synced_tab; 999 *tab = synced_tab;
958 return success; 1000 return success;
959 } 1001 }
960 1002
961 void SessionsSyncManager::LocalTabDelegateToSpecifics(
962 const SyncedTabDelegate& tab_delegate,
963 sync_pb::SessionSpecifics* specifics) {
964 sessions::SessionTab* session_tab = nullptr;
965 session_tab = session_tracker_.GetTab(current_machine_tag(),
966 tab_delegate.GetSessionId(),
967 tab_delegate.GetSyncId());
968 SetSessionTabFromDelegate(tab_delegate, base::Time::Now(), session_tab);
969 SetVariationIds(session_tab);
970 sync_pb::SessionTab tab_s = session_tab->ToSyncData();
971 specifics->set_session_tag(current_machine_tag_);
972 specifics->set_tab_node_id(tab_delegate.GetSyncId());
973 specifics->mutable_tab()->CopyFrom(tab_s);
974 }
975
976 void SessionsSyncManager::AssociateRestoredPlaceholderTab( 1003 void SessionsSyncManager::AssociateRestoredPlaceholderTab(
977 const SyncedTabDelegate& tab_delegate, 1004 const SyncedTabDelegate& tab_delegate,
978 SessionID::id_type new_tab_id, 1005 SessionID::id_type new_tab_id,
979 SessionID::id_type new_window_id, 1006 SessionID::id_type new_window_id,
980 const syncer::SyncDataList& restored_tabs,
981 syncer::SyncChangeList* change_output) { 1007 syncer::SyncChangeList* change_output) {
982 DCHECK_NE(tab_delegate.GetSyncId(), TabNodePool::kInvalidTabNodeID); 1008 DCHECK_NE(tab_delegate.GetSyncId(), TabNodePool::kInvalidTabNodeID);
983 // Rewrite the tab using |restored_tabs| to retrieve the specifics. 1009
984 if (restored_tabs.empty()) { 1010 // It's possible the placeholder tab is associated with a tab node that's
985 DLOG(WARNING) << "Can't Update tab ID."; 1011 // since been deleted. If that's the case, there's no way to reassociate it,
1012 // so just return now without adding the tab to the session tracker.
1013 if (!session_tracker_.IsLocalTabNodeAssociated(tab_delegate.GetSyncId())) {
1014 DVLOG(1) << "Restored placeholder tab's node " << tab_delegate.GetSyncId()
1015 << " deleted.";
986 return; 1016 return;
987 } 1017 }
988 1018
989 for (syncer::SyncDataList::const_iterator it = restored_tabs.begin(); 1019 // Update tracker with the new association (and inform it of the tab node
990 it != restored_tabs.end(); ++it) { 1020 // in the process).
991 if (it->GetSpecifics().session().tab_node_id() != 1021 session_tracker_.ReassociateLocalTab(tab_delegate.GetSyncId(), new_tab_id);
992 tab_delegate.GetSyncId()) {
993 continue;
994 }
995 1022
996 sync_pb::EntitySpecifics entity; 1023 // Update the window id on the SessionTab itself.
997 sync_pb::SessionSpecifics* specifics = entity.mutable_session(); 1024 sessions::SessionTab* local_tab =
998 specifics->CopyFrom(it->GetSpecifics().session()); 1025 session_tracker_.GetTab(current_machine_tag(), new_tab_id);
999 DCHECK(specifics->has_tab()); 1026 local_tab->window_id.set_id(new_window_id);
1000 1027
1001 // Update tab node pool with the new association. 1028 // Rewrite the specifics based on the reassociated SessionTab to preserve
1002 local_tab_pool_.ReassociateTabNode(tab_delegate.GetSyncId(), new_tab_id); 1029 // the new tab and window ids.
1003 TabLink* tab_link = new TabLink(tab_delegate.GetSyncId(), &tab_delegate); 1030 sync_pb::EntitySpecifics entity;
1004 local_tab_map_[new_tab_id] = make_linked_ptr<TabLink>(tab_link); 1031 entity.mutable_session()->CopyFrom(SessionTabToSpecifics(
1005 1032 *local_tab, current_machine_tag(), tab_delegate.GetSyncId()));
1006 if (specifics->tab().tab_id() == new_tab_id && 1033 syncer::SyncData data = syncer::SyncData::CreateLocalData(
1007 specifics->tab().window_id() == new_window_id) 1034 TabNodeIdToTag(current_machine_tag(), tab_delegate.GetSyncId()),
1008 return; 1035 current_session_name_, entity);
1009 1036 change_output->push_back(
1010 // Either the tab_id or window_id changed (e.g due to session restore), so 1037 syncer::SyncChange(FROM_HERE, syncer::SyncChange::ACTION_UPDATE, data));
1011 // update the sync node.
1012 specifics->mutable_tab()->set_tab_id(new_tab_id);
1013 specifics->mutable_tab()->set_window_id(new_window_id);
1014 syncer::SyncData data = syncer::SyncData::CreateLocalData(
1015 TabNodePool::TabIdToTag(current_machine_tag_, specifics->tab_node_id()),
1016 current_session_name_, entity);
1017 change_output->push_back(
1018 syncer::SyncChange(FROM_HERE, syncer::SyncChange::ACTION_UPDATE, data));
1019 return;
1020 }
1021 } 1038 }
1022 1039
1023 // static 1040 // static
1024 void SessionsSyncManager::SetSessionTabFromDelegate( 1041 void SessionsSyncManager::SetSessionTabFromDelegate(
1025 const SyncedTabDelegate& tab_delegate, 1042 const SyncedTabDelegate& tab_delegate,
1026 base::Time mtime, 1043 base::Time mtime,
1027 sessions::SessionTab* session_tab) { 1044 sessions::SessionTab* session_tab) {
1028 DCHECK(session_tab); 1045 DCHECK(session_tab);
1029 session_tab->window_id.set_id(tab_delegate.GetWindowId()); 1046 session_tab->window_id.set_id(tab_delegate.GetWindowId());
1030 session_tab->tab_id.set_id(tab_delegate.GetSessionId()); 1047 session_tab->tab_id.set_id(tab_delegate.GetSessionId());
(...skipping 98 matching lines...) Expand 10 before | Expand all | Expand 10 after
1129 } 1146 }
1130 1147
1131 // static 1148 // static
1132 std::string SessionsSyncManager::TagHashFromSpecifics( 1149 std::string SessionsSyncManager::TagHashFromSpecifics(
1133 const sync_pb::SessionSpecifics& specifics) { 1150 const sync_pb::SessionSpecifics& specifics) {
1134 return syncer::GenerateSyncableHash(syncer::SESSIONS, 1151 return syncer::GenerateSyncableHash(syncer::SESSIONS,
1135 TagFromSpecifics(specifics)); 1152 TagFromSpecifics(specifics));
1136 } 1153 }
1137 1154
1138 }; // namespace sync_sessions 1155 }; // namespace sync_sessions
OLDNEW
« no previous file with comments | « components/sync_sessions/sessions_sync_manager.h ('k') | components/sync_sessions/synced_session_tracker.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698