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

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

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