1. Token CRCs are not handled correctly. This adds the corrected Whispernet binary...
[chromium-blink-merge.git] / chrome / browser / sync / sessions / sessions_sync_manager.h
blobcae754d8d27aef289447cd362dec350e2fc477e6
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
3 // found in the LICENSE file.
5 #ifndef CHROME_BROWSER_SYNC_SESSIONS_SESSIONS_SYNC_MANAGER_H_
6 #define CHROME_BROWSER_SYNC_SESSIONS_SESSIONS_SYNC_MANAGER_H_
8 #include <map>
9 #include <set>
10 #include <string>
11 #include <vector>
13 #include "base/basictypes.h"
14 #include "base/gtest_prod_util.h"
15 #include "base/memory/scoped_vector.h"
16 #include "base/memory/weak_ptr.h"
17 #include "base/time/time.h"
18 #include "chrome/browser/sync/glue/favicon_cache.h"
19 #include "chrome/browser/sync/glue/synced_session.h"
20 #include "chrome/browser/sync/glue/synced_session_tracker.h"
21 #include "chrome/browser/sync/open_tabs_ui_delegate.h"
22 #include "chrome/browser/sync/sessions/tab_node_pool.h"
23 #include "components/sessions/session_id.h"
24 #include "components/sessions/session_types.h"
25 #include "components/sync_driver/device_info.h"
26 #include "components/sync_driver/sync_prefs.h"
27 #include "components/variations/variations_associated_data.h"
28 #include "sync/api/syncable_service.h"
30 class Profile;
32 namespace syncer {
33 class SyncErrorFactory;
36 namespace sync_driver {
37 class LocalDeviceInfoProvider;
40 namespace sync_pb {
41 class SessionHeader;
42 class SessionSpecifics;
43 class SessionTab;
44 class SessionWindow;
45 class TabNavigation;
46 } // namespace sync_pb
48 namespace browser_sync {
50 class DataTypeErrorHandler;
51 class SyncedTabDelegate;
52 class SyncedWindowDelegate;
53 class SyncedWindowDelegatesGetter;
55 // An interface defining the ways in which local open tab events can interact
56 // with session sync. All local tab events flow to sync via this interface.
57 // In that way it is analogous to sync changes flowing to the local model
58 // via ProcessSyncChanges, just with a more granular breakdown.
59 class LocalSessionEventHandler {
60 public:
61 // A local navigation event took place that affects the synced session
62 // for this instance of Chrome.
63 virtual void OnLocalTabModified(SyncedTabDelegate* modified_tab) = 0;
65 // A local navigation occurred that triggered updates to favicon data for
66 // each URL in |updated_page_urls|. This is routed through Sessions Sync so
67 // that we can filter (exclude) favicon updates for pages that aren't
68 // currently part of the set of local open tabs, and pass relevant updates
69 // on to FaviconCache for out-of-band favicon syncing.
70 virtual void OnFaviconPageUrlsUpdated(
71 const std::set<GURL>& updated_page_urls) = 0;
74 // The LocalSessionEventRouter is responsible for hooking itself up to various
75 // notification sources in the browser process and forwarding relevant
76 // events to a handler as defined in the LocalSessionEventHandler contract.
77 class LocalSessionEventRouter {
78 public:
79 virtual ~LocalSessionEventRouter();
80 virtual void StartRoutingTo(LocalSessionEventHandler* handler) = 0;
81 virtual void Stop() = 0;
84 // Contains all logic for associating the Chrome sessions model and
85 // the sync sessions model.
86 class SessionsSyncManager : public syncer::SyncableService,
87 public OpenTabsUIDelegate,
88 public LocalSessionEventHandler {
89 public:
90 SessionsSyncManager(Profile* profile,
91 sync_driver::LocalDeviceInfoProvider* local_device,
92 scoped_ptr<LocalSessionEventRouter> router);
93 ~SessionsSyncManager() override;
95 // syncer::SyncableService implementation.
96 syncer::SyncMergeResult MergeDataAndStartSyncing(
97 syncer::ModelType type,
98 const syncer::SyncDataList& initial_sync_data,
99 scoped_ptr<syncer::SyncChangeProcessor> sync_processor,
100 scoped_ptr<syncer::SyncErrorFactory> error_handler) override;
101 void StopSyncing(syncer::ModelType type) override;
102 syncer::SyncDataList GetAllSyncData(syncer::ModelType type) const override;
103 syncer::SyncError ProcessSyncChanges(
104 const tracked_objects::Location& from_here,
105 const syncer::SyncChangeList& change_list) override;
107 // OpenTabsUIDelegate implementation.
108 bool GetSyncedFaviconForPageURL(
109 const std::string& pageurl,
110 scoped_refptr<base::RefCountedMemory>* favicon_png) const override;
111 bool GetAllForeignSessions(
112 std::vector<const SyncedSession*>* sessions) override;
113 bool GetForeignSession(
114 const std::string& tag,
115 std::vector<const sessions::SessionWindow*>* windows) override;
116 bool GetForeignTab(const std::string& tag,
117 const SessionID::id_type tab_id,
118 const sessions::SessionTab** tab) override;
119 void DeleteForeignSession(const std::string& tag) override;
120 bool GetLocalSession(const SyncedSession** local_session) override;
122 // LocalSessionEventHandler implementation.
123 void OnLocalTabModified(SyncedTabDelegate* modified_tab) override;
124 void OnFaviconPageUrlsUpdated(
125 const std::set<GURL>& updated_favicon_page_urls) override;
127 // Returns the tag used to uniquely identify this machine's session in the
128 // sync model.
129 const std::string& current_machine_tag() const {
130 DCHECK(!current_machine_tag_.empty());
131 return current_machine_tag_;
134 // Return the virtual URL of the current tab, even if it's pending.
135 static GURL GetCurrentVirtualURL(const SyncedTabDelegate& tab_delegate);
137 // Return the favicon url of the current tab, even if it's pending.
138 static GURL GetCurrentFaviconURL(const SyncedTabDelegate& tab_delegate);
140 FaviconCache* GetFaviconCache();
142 SyncedWindowDelegatesGetter* GetSyncedWindowDelegatesGetter() const;
144 // Triggers garbage collection of stale sessions (as defined by
145 // |stale_session_threshold_days_|). This is called automatically every
146 // time we start up (via AssociateModels) and when new sessions data is
147 // downloaded (sync cycles complete).
148 void DoGarbageCollection();
150 private:
151 // Keep all the links to local tab data in one place. A tab_node_id and tab
152 // must be passed at creation. The tab_node_id is not mutable, although
153 // all other fields are.
154 class TabLink {
155 public:
156 TabLink(int tab_node_id, const SyncedTabDelegate* tab)
157 : tab_node_id_(tab_node_id),
158 tab_(tab) {}
160 void set_tab(const SyncedTabDelegate* tab) { tab_ = tab; }
161 void set_url(const GURL& url) { url_ = url; }
163 int tab_node_id() const { return tab_node_id_; }
164 const SyncedTabDelegate* tab() const { return tab_; }
165 const GURL& url() const { return url_; }
167 private:
168 // The id for the sync node this tab is stored in.
169 const int tab_node_id_;
171 // The tab object itself.
172 const SyncedTabDelegate* tab_;
174 // The currently visible url of the tab (used for syncing favicons).
175 GURL url_;
177 DISALLOW_COPY_AND_ASSIGN(TabLink);
180 // Container for accessing local tab data by tab id.
181 typedef std::map<SessionID::id_type, linked_ptr<TabLink> > TabLinksMap;
183 FRIEND_TEST_ALL_PREFIXES(SessionsSyncManagerTest, PopulateSessionHeader);
184 FRIEND_TEST_ALL_PREFIXES(SessionsSyncManagerTest, PopulateSessionWindow);
185 FRIEND_TEST_ALL_PREFIXES(SessionsSyncManagerTest, ValidTabs);
186 FRIEND_TEST_ALL_PREFIXES(SessionsSyncManagerTest, SetSessionTabFromDelegate);
187 FRIEND_TEST_ALL_PREFIXES(SessionsSyncManagerTest,
188 SetSessionTabFromDelegateNavigationIndex);
189 FRIEND_TEST_ALL_PREFIXES(SessionsSyncManagerTest,
190 SetSessionTabFromDelegateCurrentInvalid);
191 FRIEND_TEST_ALL_PREFIXES(SessionsSyncManagerTest, BlockedNavigations);
192 FRIEND_TEST_ALL_PREFIXES(SessionsSyncManagerTest, DeleteForeignSession);
193 FRIEND_TEST_ALL_PREFIXES(SessionsSyncManagerTest,
194 SaveUnassociatedNodesForReassociation);
195 FRIEND_TEST_ALL_PREFIXES(SessionsSyncManagerTest, MergeDeletesCorruptNode);
196 FRIEND_TEST_ALL_PREFIXES(SessionsSyncManagerTest,
197 MergeLocalSessionExistingTabs);
198 FRIEND_TEST_ALL_PREFIXES(SessionsSyncManagerTest,
199 CheckPrerenderedWebContentsSwap);
200 FRIEND_TEST_ALL_PREFIXES(SessionsSyncManagerTest,
201 AssociateWindowsDontReloadTabs);
202 FRIEND_TEST_ALL_PREFIXES(SessionsSyncManagerTest,
203 SwappedOutOnRestore);
204 FRIEND_TEST_ALL_PREFIXES(SessionsSyncManagerTest,
205 ProcessRemoteDeleteOfLocalSession);
206 FRIEND_TEST_ALL_PREFIXES(SessionsSyncManagerTest,
207 SetVariationIds);
209 void InitializeCurrentMachineTag();
211 // Load and add window or tab data for a foreign session to our internal
212 // tracking.
213 void UpdateTrackerWithForeignSession(
214 const sync_pb::SessionSpecifics& specifics,
215 const base::Time& modification_time);
217 // Returns true if |sync_data| contained a header node for the current
218 // machine, false otherwise. |restored_tabs| is a filtered tab-only
219 // subset of |sync_data| returned by this function for convenience.
220 // |new_changes| is a link to the SyncChange pipeline that exists in the
221 // caller's context. This function will append necessary changes for
222 // processing later.
223 bool InitFromSyncModel(const syncer::SyncDataList& sync_data,
224 syncer::SyncDataList* restored_tabs,
225 syncer::SyncChangeList* new_changes);
227 // Helper to construct a deletion SyncChange for a *tab node*.
228 // Caller should check IsValid() on the returned change, as it's possible
229 // this node could not be deleted.
230 syncer::SyncChange TombstoneTab(const sync_pb::SessionSpecifics& tab);
232 // Helper method to load the favicon data from the tab specifics. If the
233 // favicon is valid, stores the favicon data into the favicon cache.
234 void RefreshFaviconVisitTimesFromForeignTab(
235 const sync_pb::SessionTab& tab, const base::Time& modification_time);
237 // Removes a foreign session from our internal bookkeeping.
238 // Returns true if the session was found and deleted, false if no data was
239 // found for that session. This will *NOT* trigger sync deletions. See
240 // DeleteForeignSession below.
241 bool DisassociateForeignSession(const std::string& foreign_session_tag);
243 // Delete a foreign session and all its sync data.
244 // |change_output| *must* be provided as a link to the SyncChange pipeline
245 // that exists in the caller's context. This function will append necessary
246 // changes for processing later.
247 void DeleteForeignSessionInternal(const std::string& tag,
248 syncer::SyncChangeList* change_output);
250 // Used to populate a session header from the session specifics header
251 // provided.
252 static void PopulateSessionHeaderFromSpecifics(
253 const sync_pb::SessionHeader& header_specifics,
254 base::Time mtime,
255 SyncedSession* session_header);
257 // Builds |session_window| from the session specifics window
258 // provided and updates the SessionTracker with foreign session data created.
259 void BuildSyncedSessionFromSpecifics(
260 const std::string& session_tag,
261 const sync_pb::SessionWindow& specifics,
262 base::Time mtime,
263 sessions::SessionWindow* session_window);
265 // Resync local window information. Updates the local sessions header node
266 // with the status of open windows and the order of tabs they contain. Should
267 // only be called for changes that affect a window, not a change within a
268 // single tab.
270 // RELOAD_TABS will additionally cause a resync of all tabs (same as calling
271 // AssociateTabs with a vector of all tabs).
273 // |restored_tabs| is a filtered tab-only subset of initial sync data, if
274 // available (during MergeDataAndStartSyncing). It can be used to obtain
275 // baseline SessionSpecifics for tabs we can't fully associate any other
276 // way because they don't yet have a WebContents.
278 // Returns: false if the local session's sync nodes were deleted and
279 // reassociation is necessary, true otherwise.
281 // |change_output| *must* be provided as a link to the SyncChange pipeline
282 // that exists in the caller's context. This function will append necessary
283 // changes for processing later.
284 enum ReloadTabsOption {
285 RELOAD_TABS,
286 DONT_RELOAD_TABS
288 void AssociateWindows(ReloadTabsOption option,
289 const syncer::SyncDataList& restored_tabs,
290 syncer::SyncChangeList* change_output);
292 // Loads and reassociates the local tabs referenced in |tabs|.
293 // |change_output| *must* be provided as a link to the SyncChange pipeline
294 // that exists in the caller's context. This function will append necessary
295 // changes for processing later.
296 void AssociateTab(SyncedTabDelegate* const tab,
297 syncer::SyncChangeList* change_output);
299 // Set |session_tab| from |tab_delegate| and |mtime|.
300 static void SetSessionTabFromDelegate(
301 const SyncedTabDelegate& tab_delegate,
302 base::Time mtime,
303 sessions::SessionTab* session_tab);
305 // Sets |variation_ids| field of |session_tab| with the ids of the currently
306 // assigned variations which should be sent to sync.
307 static void SetVariationIds(sessions::SessionTab* session_tab);
309 // Populates |specifics| based on the data in |tab_delegate|.
310 void LocalTabDelegateToSpecifics(const SyncedTabDelegate& tab_delegate,
311 sync_pb::SessionSpecifics* specifics);
313 // It's possible that when we associate windows, tabs aren't all loaded
314 // into memory yet (e.g on android) and we don't have a WebContents. In this
315 // case we can't do a full association, but we still want to update tab IDs
316 // as they may have changed after a session was restored. This method
317 // compares new_tab_id against the previously persisted tab ID (from
318 // our TabNodePool) and updates it if it differs.
319 // |restored_tabs| is a filtered tab-only subset of initial sync data, if
320 // available (during MergeDataAndStartSyncing). It can be used to obtain
321 // baseline SessionSpecifics for tabs we can't fully associate any other
322 // way because they don't yet have a WebContents.
323 // TODO(tim): Bug 98892. We should be able to test this for this on android
324 // even though we didn't have tests for old API-based sessions sync.
325 void AssociateRestoredPlaceholderTab(
326 const SyncedTabDelegate& tab_delegate,
327 SessionID::id_type new_tab_id,
328 const syncer::SyncDataList& restored_tabs,
329 syncer::SyncChangeList* change_output);
331 // Stops and re-starts syncing to rebuild association mappings.
332 // See |local_tab_pool_out_of_sync_|.
333 void RebuildAssociations();
335 // Validates the content of a SessionHeader protobuf.
336 // Returns false if validation fails.
337 static bool IsValidSessionHeader(const sync_pb::SessionHeader& header);
339 // Mapping of current open (local) tabs to their sync identifiers.
340 TabLinksMap local_tab_map_;
342 SyncedSessionTracker session_tracker_;
343 FaviconCache favicon_cache_;
345 // Pool of used/available sync nodes associated with local tabs.
346 TabNodePool local_tab_pool_;
348 // Tracks whether our local representation of which sync nodes map to what
349 // tabs (belonging to the current local session) is inconsistent. This can
350 // happen if a foreign client deems our session as "stale" and decides to
351 // delete it. Rather than respond by bullishly re-creating our nodes
352 // immediately, which could lead to ping-pong sequences, we give the benefit
353 // of the doubt and hold off until another local navigation occurs, which
354 // proves that we are still relevant.
355 bool local_tab_pool_out_of_sync_;
357 sync_driver::SyncPrefs sync_prefs_;
359 const Profile* const profile_;
361 scoped_ptr<syncer::SyncErrorFactory> error_handler_;
362 scoped_ptr<syncer::SyncChangeProcessor> sync_processor_;
364 // Local device info provider, owned by ProfileSyncService.
365 const sync_driver::LocalDeviceInfoProvider* const local_device_;
367 // Unique client tag.
368 std::string current_machine_tag_;
370 // User-visible machine name.
371 std::string current_session_name_;
373 // SyncID for the sync node containing all the window information for this
374 // client.
375 int local_session_header_node_id_;
377 // Number of days without activity after which we consider a session to be
378 // stale and a candidate for garbage collection.
379 size_t stale_session_threshold_days_;
381 scoped_ptr<LocalSessionEventRouter> local_event_router_;
382 scoped_ptr<SyncedWindowDelegatesGetter> synced_window_getter_;
384 DISALLOW_COPY_AND_ASSIGN(SessionsSyncManager);
387 } // namespace browser_sync
389 #endif // CHROME_BROWSER_SYNC_SESSIONS_SESSIONS_SYNC_MANAGER_H_