1 // Copyright 2013 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_FILE_SYSTEM_DRIVE_BACKEND_METADATA_DATABASE_H_
6 #define CHROME_BROWSER_SYNC_FILE_SYSTEM_DRIVE_BACKEND_METADATA_DATABASE_H_
13 #include "base/containers/hash_tables.h"
14 #include "base/containers/scoped_ptr_hash_map.h"
15 #include "base/files/file_path.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/memory/scoped_vector.h"
18 #include "base/memory/weak_ptr.h"
19 #include "base/sequence_checker.h"
20 #include "base/values.h"
21 #include "chrome/browser/sync_file_system/drive_backend/tracker_id_set.h"
22 #include "chrome/browser/sync_file_system/sync_status_code.h"
28 namespace google_apis
{
33 namespace tracked_objects
{
37 namespace sync_file_system
{
38 namespace drive_backend
{
44 class MetadataDatabaseIndexInterface
;
45 class ServiceMetadata
;
47 // MetadataDatabase holds and maintains a LevelDB instance and its indexes,
48 // which holds 1)ServiceMetadata, 2)FileMetadata and 3)FileTracker.
49 // 1) ServiceMetadata is a singleton in the database which holds information for
51 // 2) FileMetadata represents a remote-side file and holds latest known
52 // metadata of the remote file.
53 // 3) FileTracker represents a synced or to-be-synced file and maintains
54 // the local-side folder tree.
56 // The term "file" includes files, folders and other resources on Drive.
58 // FileTrackers form a tree structure on the database, which represents the
59 // FileSystem trees of SyncFileSystem. The tree has a FileTracker named
60 // sync-root as its root node, and a set of FileTracker named app-root. An
61 // app-root represents a remote folder for an installed Chrome App and holds all
62 // synced contents for the App.
64 // One FileMetadata is created for each tracked remote file, which is identified
66 // One FileTracker is created for every different {parent tracker, FileID} pair,
67 // excluding non-app-root inactive parent trackers. Multiple trackers may be
68 // associated to one FileID when the file has multiple parents. Multiple
69 // trackers may have the same {parent tracker, title} pair when the associated
70 // remote files have the same title.
72 // Files have following state:
74 // - Has a dirty inactive tracker and empty synced_details.
75 // - Is initial state of a tracker, only file_id and parent_tracker_id field
78 // - Is either one of sync-root folder, app-root folder or a regular folder.
79 // - Sync-root folder holds app-root folders as its direct children, and
80 // holds entire SyncFileSystem files as its descentants. Its tracker
81 // should be stored in ServiceMetadata by its tracker_id.
82 // - App-root folder holds all files for an application as its descendants.
85 // - Represents unsupported files such as hosted documents. Must be
89 // - Any tracker in the database must either:
91 // - have an app-root as its parent tracker, or
92 // - have an active tracker as its parent.
93 // That is, all trackers must be reachable from sync-root via app-root folders
94 // and active trackers.
96 // - Any active tracker must either:
97 // - have |needs_folder_listing| flag and dirty flag, or
98 // - have all children at the stored largest change ID.
100 // - If multiple trackers have the same parent tracker and same title, they
101 // must not have same |file_id|, and at most one of them may be active.
102 // - If multiple trackers have the same |file_id|, at most one of them may be
105 class MetadataDatabase
{
107 typedef std::vector
<std::string
> FileIDList
;
109 enum ActivationStatus
{
111 ACTIVATION_FAILED_ANOTHER_ACTIVE_TRACKER
,
115 UPDATE_TRACKER_FOR_UNSYNCED_FILE
,
116 UPDATE_TRACKER_FOR_SYNCED_FILE
,
119 // The entry point of the MetadataDatabase for production code.
120 // If |env_override| is non-NULL, internal LevelDB uses |env_override| instead
121 // of leveldb::Env::Default(). Use leveldb::MemEnv in test code for faster
123 static scoped_ptr
<MetadataDatabase
> Create(
124 const base::FilePath
& database_path
,
125 leveldb::Env
* env_override
,
126 SyncStatusCode
* status
);
127 static scoped_ptr
<MetadataDatabase
> CreateInternal(
128 const base::FilePath
& database_path
,
129 leveldb::Env
* env_override
,
130 bool enable_on_disk_index
,
131 SyncStatusCode
* status
);
132 static SyncStatusCode
CreateForTesting(
133 scoped_ptr
<LevelDBWrapper
> db
,
134 bool enable_on_disk_index
,
135 scoped_ptr
<MetadataDatabase
>* metadata_database_out
);
139 static void ClearDatabase(scoped_ptr
<MetadataDatabase
> metadata_database
);
141 int64
GetLargestFetchedChangeID() const;
142 int64
GetSyncRootTrackerID() const;
143 bool HasSyncRoot() const;
145 // Returns all file metadata for the given |app_id|.
146 scoped_ptr
<base::ListValue
> DumpFiles(const std::string
& app_id
);
148 // Returns all database data.
149 scoped_ptr
<base::ListValue
> DumpDatabase();
151 // TODO(tzik): Move GetLargestKnownChangeID() to private section, and hide its
152 // handling in the class, instead of letting user do.
154 // Gets / updates the largest known change ID.
155 // The largest known change ID is on-memory and not persist over restart.
156 // This is supposed to use when a task fetches ChangeList in parallel to other
157 // operation. When a task starts fetching paged ChangeList one by one, it
158 // should update the largest known change ID on the first round and background
159 // remaining fetch job.
160 // Then, when other tasks that update FileMetadata by UpdateByFileResource,
161 // it should use largest known change ID as the |change_id| that prevents
162 // FileMetadata from overwritten by ChangeList.
163 // Also if other tasks try to update a remote resource whose change is not yet
164 // retrieved the task should fail due to etag check, so we should be fine.
165 int64
GetLargestKnownChangeID() const;
166 void UpdateLargestKnownChangeID(int64 change_id
);
168 // Populates empty database with initial data.
169 // Adds a file metadata and a file tracker for |sync_root_folder|, and adds
170 // file metadata and file trackers for each |app_root_folders|.
171 // Newly added tracker for |sync_root_folder| is active and non-dirty.
172 // Newly added trackers for |app_root_folders| are inactive and non-dirty.
173 // Trackers for |app_root_folders| are not yet registered as app-roots, but
174 // are ready to register.
175 SyncStatusCode
PopulateInitialData(
176 int64 largest_change_id
,
177 const google_apis::FileResource
& sync_root_folder
,
178 const ScopedVector
<google_apis::FileResource
>& app_root_folders
);
180 // Returns true if the folder associated to |app_id| is enabled.
181 bool IsAppEnabled(const std::string
& app_id
) const;
183 // Registers existing folder as the app-root for |app_id|. The folder
184 // must be an inactive folder that does not yet associated to any App.
185 // This method associates the folder with |app_id| and activates it.
186 SyncStatusCode
RegisterApp(const std::string
& app_id
,
187 const std::string
& folder_id
);
189 // Inactivates the folder associated to the app to disable |app_id|.
190 // Does nothing if |app_id| is already disabled.
191 SyncStatusCode
DisableApp(const std::string
& app_id
);
193 // Activates the folder associated to |app_id| to enable |app_id|.
194 // Does nothing if |app_id| is already enabled.
195 SyncStatusCode
EnableApp(const std::string
& app_id
);
197 // Unregisters the folder as the app-root for |app_id|. If |app_id| does not
198 // exist, does nothing. The folder is left as an inactive regular folder.
199 // Note that the inactivation drops all descendant files since they are no
200 // longer reachable from sync-root via active folder or app-root.
201 SyncStatusCode
UnregisterApp(const std::string
& app_id
);
203 // Finds the app-root folder for |app_id|. Returns true if exists.
204 // Copies the result to |tracker| if it is non-NULL.
205 bool FindAppRootTracker(const std::string
& app_id
,
206 FileTracker
* tracker
) const;
208 // Finds the file identified by |file_id|. Returns true if the file is found.
209 // Copies the metadata identified by |file_id| into |file| if exists and
210 // |file| is non-NULL.
211 bool FindFileByFileID(const std::string
& file_id
, FileMetadata
* file
) const;
213 // Finds the tracker identified by |tracker_id|. Returns true if the tracker
215 // Copies the tracker identified by |tracker_id| into |tracker| if exists and
216 // |tracker| is non-NULL.
217 bool FindTrackerByTrackerID(int64 tracker_id
, FileTracker
* tracker
) const;
219 // Finds the trackers tracking |file_id|. Returns true if the trackers are
221 bool FindTrackersByFileID(const std::string
& file_id
,
222 TrackerIDSet
* trackers
) const;
224 // Finds the set of trackers whose parent's tracker ID is |parent_tracker_id|,
225 // and who has |title| as its title in the synced_details.
226 // Copies the tracker set to |trackers| if it is non-NULL.
227 // Returns true if the trackers are found.
228 bool FindTrackersByParentAndTitle(
229 int64 parent_tracker_id
,
230 const std::string
& title
,
231 TrackerIDSet
* trackers
) const;
233 // Builds the file path for the given tracker. Returns true on success.
234 // |path| can be NULL.
235 // The file path is relative to app-root and have a leading path separator.
236 bool BuildPathForTracker(int64 tracker_id
, base::FilePath
* path
) const;
238 // Builds the file path for the given tracker for display purpose.
239 // This may return a path ending with '<unknown>' if the given tracker does
240 // not have title information (yet). This may return an empty path.
241 base::FilePath
BuildDisplayPathForTracker(const FileTracker
& tracker
) const;
243 // Returns false if no registered app exists associated to |app_id|.
244 // If |full_path| is active, assigns the tracker of |full_path| to |tracker|.
245 // Otherwise, assigns the nearest active ancestor to |full_path| to |tracker|.
246 // Also, assigns the full path of |tracker| to |path|.
247 bool FindNearestActiveAncestor(const std::string
& app_id
,
248 const base::FilePath
& full_path
,
249 FileTracker
* tracker
,
250 base::FilePath
* path
) const;
252 // Updates database by |changes|.
253 // Marks each tracker for modified file as dirty and adds new trackers if
255 SyncStatusCode
UpdateByChangeList(
256 int64 largest_change_id
,
257 ScopedVector
<google_apis::ChangeResource
> changes
);
259 // Updates database by |resource|.
260 // Marks each tracker for modified file as dirty and adds new trackers if
262 SyncStatusCode
UpdateByFileResource(
263 const google_apis::FileResource
& resource
);
264 SyncStatusCode
UpdateByFileResourceList(
265 ScopedVector
<google_apis::FileResource
> resources
);
267 SyncStatusCode
UpdateByDeletedRemoteFile(const std::string
& file_id
);
268 SyncStatusCode
UpdateByDeletedRemoteFileList(const FileIDList
& file_ids
);
270 // Adds new FileTracker and FileMetadata. The database must not have
271 // |resource| beforehand.
272 // The newly added tracker under |parent_tracker_id| is active and non-dirty.
273 // Deactivates existing active tracker if exists that has the same title and
274 // parent_tracker to the newly added tracker.
275 SyncStatusCode
ReplaceActiveTrackerWithNewResource(
276 int64 parent_tracker_id
,
277 const google_apis::FileResource
& resource
);
279 // Adds |child_file_ids| to |folder_id| as its children.
280 // This method affects the active tracker only.
281 // If the tracker has no further change to sync, unmarks its dirty flag.
282 SyncStatusCode
PopulateFolderByChildList(const std::string
& folder_id
,
283 const FileIDList
& child_file_ids
);
285 // Updates |synced_details| of the tracker with |updated_details|.
286 SyncStatusCode
UpdateTracker(int64 tracker_id
,
287 const FileDetails
& updated_details
);
289 // Activates a tracker identified by |parent_tracker_id| and |file_id| if the
290 // tracker can be activated without inactivating other trackers that have the
291 // same |file_id| but different paths.
292 // If |file_id| has another active tracker, the function returns
293 // ACTIVATION_FAILED_ANOTHER_ACTIVE_TRACKER and does not invoke |callback|.
294 // If there is another active tracker that has the same path but different
295 // |file_id|, inactivates the tracker.
296 // In success case, returns ACTIVATION_PENDING and invokes |callback| upon
299 // The tracker to be activated must:
300 // - have a tracked metadata in the database,
301 // - have |synced_details| with valid |title|.
302 ActivationStatus
TryActivateTracker(int64 parent_tracker_id
,
303 const std::string
& file_id
,
304 SyncStatusCode
* status
);
306 // Changes the priority of the tracker to low.
307 void DemoteTracker(int64 tracker_id
);
308 bool PromoteDemotedTrackers();
309 void PromoteDemotedTracker(int64 tracker_id
);
311 // Returns true if there is a normal priority dirty tracker.
312 // Assigns the dirty tracker if exists and |tracker| is non-NULL.
313 bool GetDirtyTracker(FileTracker
* tracker
) const;
315 // Returns true if there is a low priority dirty tracker.
316 bool HasDemotedDirtyTracker() const;
318 bool HasDirtyTracker() const;
319 size_t CountDirtyTracker() const;
320 size_t CountFileMetadata() const;
321 size_t CountFileTracker() const;
323 bool GetMultiParentFileTrackers(std::string
* file_id
,
324 TrackerIDSet
* trackers
);
325 bool GetConflictingTrackers(TrackerIDSet
* trackers
);
327 // Sets |app_ids| to a list of all registered app ids.
328 void GetRegisteredAppIDs(std::vector
<std::string
>* app_ids
);
330 // Clears dirty flag of trackers that can be cleared without external
332 SyncStatusCode
SweepDirtyTrackers(const std::vector
<std::string
>& file_ids
);
335 friend class MetadataDatabaseTest
;
337 MetadataDatabase(const base::FilePath
& database_path
,
338 bool enable_on_disk_index
,
339 leveldb::Env
* env_override
);
340 SyncStatusCode
Initialize();
342 // Database manipulation methods.
343 void RegisterTrackerAsAppRoot(const std::string
& app_id
,
346 void CreateTrackerForParentAndFileID(const FileTracker
& parent_tracker
,
347 const std::string
& file_id
);
348 void CreateTrackerForParentAndFileMetadata(const FileTracker
& parent_tracker
,
349 const FileMetadata
& file_metadata
,
350 UpdateOption option
);
351 void CreateTrackerInternal(const FileTracker
& parent_tracker
,
352 const std::string
& file_id
,
353 const FileDetails
* details
,
354 UpdateOption option
);
356 void MaybeAddTrackersForNewFile(const FileMetadata
& file
,
357 UpdateOption option
);
359 int64
IncrementTrackerID();
361 bool CanActivateTracker(const FileTracker
& tracker
);
362 bool ShouldKeepDirty(const FileTracker
& tracker
) const;
364 bool HasDisabledAppRoot(const FileTracker
& tracker
) const;
365 bool HasActiveTrackerForFileID(const std::string
& file_id
) const;
366 bool HasActiveTrackerForPath(int64 parent_tracker
,
367 const std::string
& title
) const;
369 void RemoveUnneededTrackersForMissingFile(const std::string
& file_id
);
370 void UpdateByFileMetadata(const tracked_objects::Location
& from_where
,
371 scoped_ptr
<FileMetadata
> file
,
372 UpdateOption option
);
374 SyncStatusCode
WriteToDatabase();
376 bool HasNewerFileMetadata(const std::string
& file_id
, int64 change_id
);
378 scoped_ptr
<base::ListValue
> DumpTrackers();
379 scoped_ptr
<base::ListValue
> DumpMetadata();
381 void AttachSyncRoot(const google_apis::FileResource
& sync_root_folder
);
382 void AttachInitialAppRoot(const google_apis::FileResource
& app_root_folder
);
384 void ForceActivateTrackerByPath(int64 parent_tracker_id
,
385 const std::string
& title
,
386 const std::string
& file_id
);
388 bool CanClearDirty(const FileTracker
& tracker
);
390 base::FilePath database_path_
;
391 leveldb::Env
* env_override_
;
392 scoped_ptr
<LevelDBWrapper
> db_
;
394 bool enable_on_disk_index_
;
396 int64 largest_known_change_id_
;
398 scoped_ptr
<MetadataDatabaseIndexInterface
> index_
;
400 base::WeakPtrFactory
<MetadataDatabase
> weak_ptr_factory_
;
402 DISALLOW_COPY_AND_ASSIGN(MetadataDatabase
);
405 } // namespace drive_backend
406 } // namespace sync_file_system
408 #endif // CHROME_BROWSER_SYNC_FILE_SYSTEM_DRIVE_BACKEND_METADATA_DATABASE_H_