f7dd44ebb8377d746914e2bc9a6568a4cfc41cd0
[platform/framework/web/crosswalk.git] / src / sync / syncable / directory.h
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.
4
5 #ifndef SYNC_SYNCABLE_DIRECTORY_H_
6 #define SYNC_SYNCABLE_DIRECTORY_H_
7
8 #include <deque>
9 #include <set>
10 #include <string>
11 #include <vector>
12
13 #include "base/basictypes.h"
14 #include "base/containers/hash_tables.h"
15 #include "base/file_util.h"
16 #include "base/gtest_prod_util.h"
17 #include "base/values.h"
18 #include "sync/base/sync_export.h"
19 #include "sync/internal_api/public/util/report_unrecoverable_error_function.h"
20 #include "sync/internal_api/public/util/weak_handle.h"
21 #include "sync/syncable/dir_open_result.h"
22 #include "sync/syncable/entry_kernel.h"
23 #include "sync/syncable/metahandle_set.h"
24 #include "sync/syncable/parent_child_index.h"
25 #include "sync/syncable/syncable_delete_journal.h"
26
27 namespace syncer {
28
29 class Cryptographer;
30 class TestUserShare;
31 class UnrecoverableErrorHandler;
32
33 namespace syncable {
34
35 class BaseTransaction;
36 class BaseWriteTransaction;
37 class DirectoryChangeDelegate;
38 class DirectoryBackingStore;
39 class NigoriHandler;
40 class ScopedKernelLock;
41 class TransactionObserver;
42 class WriteTransaction;
43
44 enum InvariantCheckLevel {
45   OFF = 0,            // No checking.
46   VERIFY_CHANGES = 1, // Checks only mutated entries.  Does not check hierarchy.
47   FULL_DB_VERIFICATION = 2 // Check every entry.  This can be expensive.
48 };
49
50 // Directory stores and manages EntryKernels.
51 //
52 // This class is tightly coupled to several other classes (see friends).
53 class SYNC_EXPORT Directory {
54   friend class BaseTransaction;
55   friend class Entry;
56   friend class ModelNeutralMutableEntry;
57   friend class MutableEntry;
58   friend class ReadTransaction;
59   friend class ScopedKernelLock;
60   friend class WriteTransaction;
61   friend class SyncableDirectoryTest;
62   friend class syncer::TestUserShare;
63   FRIEND_TEST_ALL_PREFIXES(SyncableDirectoryTest, ManageDeleteJournals);
64   FRIEND_TEST_ALL_PREFIXES(SyncableDirectoryTest,
65                            TakeSnapshotGetsAllDirtyHandlesTest);
66   FRIEND_TEST_ALL_PREFIXES(SyncableDirectoryTest,
67                            TakeSnapshotGetsOnlyDirtyHandlesTest);
68   FRIEND_TEST_ALL_PREFIXES(SyncableDirectoryTest,
69                            TakeSnapshotGetsMetahandlesToPurge);
70
71  public:
72   typedef std::vector<int64> Metahandles;
73
74   // Be careful when using these hash_map containers.  According to the spec,
75   // inserting into them may invalidate all iterators.
76   //
77   // It gets worse, though.  The Anroid STL library has a bug that means it may
78   // invalidate all iterators when you erase from the map, too.  That means that
79   // you can't iterate while erasing.  STLDeleteElements(), std::remove_if(),
80   // and other similar functions are off-limits too, until this bug is fixed.
81   //
82   // See http://sourceforge.net/p/stlport/bugs/239/.
83   typedef base::hash_map<int64, EntryKernel*> MetahandlesMap;
84   typedef base::hash_map<std::string, EntryKernel*> IdsMap;
85   typedef base::hash_map<std::string, EntryKernel*> TagsMap;
86   typedef std::string AttachmentIdUniqueId;
87   typedef base::hash_map<AttachmentIdUniqueId, MetahandleSet>
88       IndexByAttachmentId;
89
90   static const base::FilePath::CharType kSyncDatabaseFilename[];
91
92   // The dirty/clean state of kernel fields backed by the share_info table.
93   // This is public so it can be used in SaveChangesSnapshot for persistence.
94   enum KernelShareInfoStatus {
95     KERNEL_SHARE_INFO_INVALID,
96     KERNEL_SHARE_INFO_VALID,
97     KERNEL_SHARE_INFO_DIRTY
98   };
99
100   // Various data that the Directory::Kernel we are backing (persisting data
101   // for) needs saved across runs of the application.
102   struct SYNC_EXPORT_PRIVATE PersistedKernelInfo {
103     PersistedKernelInfo();
104     ~PersistedKernelInfo();
105
106     // Set the |download_progress| entry for the given model to a
107     // "first sync" start point.  When such a value is sent to the server,
108     // a full download of all objects of the model will be initiated.
109     void ResetDownloadProgress(ModelType model_type);
110
111     // Last sync timestamp fetched from the server.
112     sync_pb::DataTypeProgressMarker download_progress[MODEL_TYPE_COUNT];
113     // Sync-side transaction version per data type. Monotonically incremented
114     // when updating native model. A copy is also saved in native model.
115     // Later out-of-sync models can be detected and fixed by comparing
116     // transaction versions of sync model and native model.
117     // TODO(hatiaol): implement detection and fixing of out-of-sync models.
118     //                Bug 154858.
119     int64 transaction_version[MODEL_TYPE_COUNT];
120     // The store birthday we were given by the server. Contents are opaque to
121     // the client.
122     std::string store_birthday;
123     // The next local ID that has not been used with this cache-GUID.
124     int64 next_id;
125     // The serialized bag of chips we were given by the server. Contents are
126     // opaque to the client. This is the serialization of a message of type
127     // ChipBag defined in sync.proto. It can contains NULL characters.
128     std::string bag_of_chips;
129     // The per-datatype context.
130     sync_pb::DataTypeContext datatype_context[MODEL_TYPE_COUNT];
131   };
132
133   // What the Directory needs on initialization to create itself and its Kernel.
134   // Filled by DirectoryBackingStore::Load.
135   struct KernelLoadInfo {
136     PersistedKernelInfo kernel_info;
137     std::string cache_guid;  // Created on first initialization, never changes.
138     int64 max_metahandle;    // Computed (using sql MAX aggregate) on init.
139     KernelLoadInfo() : max_metahandle(0) {
140     }
141   };
142
143   // When the Directory is told to SaveChanges, a SaveChangesSnapshot is
144   // constructed and forms a consistent snapshot of what needs to be sent to
145   // the backing store.
146   struct SYNC_EXPORT_PRIVATE SaveChangesSnapshot {
147     SaveChangesSnapshot();
148     ~SaveChangesSnapshot();
149
150     KernelShareInfoStatus kernel_info_status;
151     PersistedKernelInfo kernel_info;
152     EntryKernelSet dirty_metas;
153     MetahandleSet metahandles_to_purge;
154     EntryKernelSet delete_journals;
155     MetahandleSet delete_journals_to_purge;
156   };
157
158   // Does not take ownership of |encryptor|.
159   // |report_unrecoverable_error_function| may be NULL.
160   // Takes ownership of |store|.
161   Directory(
162       DirectoryBackingStore* store,
163       UnrecoverableErrorHandler* unrecoverable_error_handler,
164       ReportUnrecoverableErrorFunction
165           report_unrecoverable_error_function,
166       NigoriHandler* nigori_handler,
167       Cryptographer* cryptographer);
168   virtual ~Directory();
169
170   // Does not take ownership of |delegate|, which must not be NULL.
171   // Starts sending events to |delegate| if the returned result is
172   // OPENED.  Note that events to |delegate| may be sent from *any*
173   // thread.  |transaction_observer| must be initialized.
174   DirOpenResult Open(const std::string& name,
175                      DirectoryChangeDelegate* delegate,
176                      const WeakHandle<TransactionObserver>&
177                          transaction_observer);
178
179   // Stops sending events to the delegate and the transaction
180   // observer.
181   void Close();
182
183   int64 NextMetahandle();
184   // Returns a negative integer unique to this client.
185   syncable::Id NextId();
186
187   bool good() const { return NULL != kernel_; }
188
189   // The download progress is an opaque token provided by the sync server
190   // to indicate the continuation state of the next GetUpdates operation.
191   void GetDownloadProgress(
192       ModelType type,
193       sync_pb::DataTypeProgressMarker* value_out) const;
194   void GetDownloadProgressAsString(
195       ModelType type,
196       std::string* value_out) const;
197   size_t GetEntriesCount() const;
198   void SetDownloadProgress(
199       ModelType type,
200       const sync_pb::DataTypeProgressMarker& value);
201
202   // Gets/Increments transaction version of a model type. Must be called when
203   // holding kernel mutex.
204   int64 GetTransactionVersion(ModelType type) const;
205   void IncrementTransactionVersion(ModelType type);
206
207   // Getter/setters for the per datatype context.
208   void GetDataTypeContext(BaseTransaction* trans,
209                           ModelType type,
210                           sync_pb::DataTypeContext* context) const;
211   void SetDataTypeContext(BaseWriteTransaction* trans,
212                           ModelType type,
213                           const sync_pb::DataTypeContext& context);
214
215   ModelTypeSet InitialSyncEndedTypes();
216   bool InitialSyncEndedForType(ModelType type);
217   bool InitialSyncEndedForType(BaseTransaction* trans, ModelType type);
218
219   const std::string& name() const { return kernel_->name; }
220
221   // (Account) Store birthday is opaque to the client, so we keep it in the
222   // format it is in the proto buffer in case we switch to a binary birthday
223   // later.
224   std::string store_birthday() const;
225   void set_store_birthday(const std::string& store_birthday);
226
227   // (Account) Bag of chip is an opaque state used by the server to track the
228   // client.
229   std::string bag_of_chips() const;
230   void set_bag_of_chips(const std::string& bag_of_chips);
231
232   // Unique to each account / client pair.
233   std::string cache_guid() const;
234
235   // Returns a pointer to our Nigori node handler.
236   NigoriHandler* GetNigoriHandler();
237
238   // Returns a pointer to our cryptographer. Does not transfer ownership.
239   // Not thread safe, so should only be accessed while holding a transaction.
240   Cryptographer* GetCryptographer(const BaseTransaction* trans);
241
242   // Returns true if the directory had encountered an unrecoverable error.
243   // Note: Any function in |Directory| that can be called without holding a
244   // transaction need to check if the Directory already has an unrecoverable
245   // error on it.
246   bool unrecoverable_error_set(const BaseTransaction* trans) const;
247
248   // Called to immediately report an unrecoverable error (but don't
249   // propagate it up).
250   void ReportUnrecoverableError() {
251     if (report_unrecoverable_error_function_) {
252       report_unrecoverable_error_function_();
253     }
254   }
255
256   // Called to set the unrecoverable error on the directory and to propagate
257   // the error to upper layers.
258   void OnUnrecoverableError(const BaseTransaction* trans,
259                             const tracked_objects::Location& location,
260                             const std::string & message);
261
262   DeleteJournal* delete_journal();
263
264   // Returns the child meta handles (even those for deleted/unlinked
265   // nodes) for given parent id.  Clears |result| if there are no
266   // children.
267   bool GetChildHandlesById(BaseTransaction*, const Id& parent_id,
268       Metahandles* result);
269
270   // Counts all items under the given node, including the node itself.
271   int GetTotalNodeCount(BaseTransaction*, EntryKernel* kernel_) const;
272
273   // Returns this item's position within its parent folder.
274   // The left-most item is 0, second left-most is 1, etc.
275   int GetPositionIndex(BaseTransaction*, EntryKernel* kernel_) const;
276
277   // Returns true iff |id| has children.
278   bool HasChildren(BaseTransaction* trans, const Id& id);
279
280   // Find the first child in the positional ordering under a parent,
281   // and fill in |*first_child_id| with its id.  Fills in a root Id if
282   // parent has no children.  Returns true if the first child was
283   // successfully found, or false if an error was encountered.
284   Id GetFirstChildId(BaseTransaction* trans, const EntryKernel* parent);
285
286   // These functions allow one to fetch the next or previous item under
287   // the same folder.  Returns the "root" ID if there is no predecessor
288   // or successor.
289   //
290   // TODO(rlarocque): These functions are used mainly for tree traversal.  We
291   // should replace these with an iterator API.  See crbug.com/178275.
292   syncable::Id GetPredecessorId(EntryKernel*);
293   syncable::Id GetSuccessorId(EntryKernel*);
294
295   // Places |e| as a successor to |predecessor|.  If |predecessor| is NULL,
296   // |e| will be placed as the left-most item in its folder.
297   //
298   // Both |e| and |predecessor| must be valid entries under the same parent.
299   //
300   // TODO(rlarocque): This function includes limited support for placing items
301   // with valid positions (ie. Bookmarks) as siblings of items that have no set
302   // ordering (ie. Autofill items).  This support is required only for tests,
303   // and should be removed.  See crbug.com/178282.
304   void PutPredecessor(EntryKernel* e, EntryKernel* predecessor);
305
306   // SaveChanges works by taking a consistent snapshot of the current Directory
307   // state and indices (by deep copy) under a ReadTransaction, passing this
308   // snapshot to the backing store under no transaction, and finally cleaning
309   // up by either purging entries no longer needed (this part done under a
310   // WriteTransaction) or rolling back the dirty bits.  It also uses
311   // internal locking to enforce SaveChanges operations are mutually exclusive.
312   //
313   // WARNING: THIS METHOD PERFORMS SYNCHRONOUS I/O VIA SQLITE.
314   bool SaveChanges();
315
316   // Returns the number of entities with the unsynced bit set.
317   int64 unsynced_entity_count() const;
318
319   // Get GetUnsyncedMetaHandles should only be called after SaveChanges and
320   // before any new entries have been created. The intention is that the
321   // syncer should call it from its PerformSyncQueries member.
322   void GetUnsyncedMetaHandles(BaseTransaction* trans,
323                               Metahandles* result);
324
325   // Returns whether or not this |type| has unapplied updates.
326   bool TypeHasUnappliedUpdates(ModelType type);
327
328   // Get all the metahandles for unapplied updates for a given set of
329   // server types.
330   void GetUnappliedUpdateMetaHandles(BaseTransaction* trans,
331                                      FullModelTypeSet server_types,
332                                      std::vector<int64>* result);
333
334   // Get all the metahandles of entries of |type|.
335   void GetMetaHandlesOfType(BaseTransaction* trans,
336                             ModelType type,
337                             Metahandles* result);
338
339   // Get metahandle counts for various criteria to show on the
340   // about:sync page. The information is computed on the fly
341   // each time. If this results in a significant performance hit,
342   // additional data structures can be added to cache results.
343   void CollectMetaHandleCounts(std::vector<int>* num_entries_by_type,
344                                std::vector<int>* num_to_delete_entries_by_type);
345
346   // Returns a ListValue serialization of all nodes for the given type.
347   scoped_ptr<base::ListValue> GetNodeDetailsForType(
348       BaseTransaction* trans,
349       ModelType type);
350
351   // Sets the level of invariant checking performed after transactions.
352   void SetInvariantCheckLevel(InvariantCheckLevel check_level);
353
354   // Checks tree metadata consistency following a transaction.  It is intended
355   // to provide a reasonable tradeoff between performance and comprehensiveness
356   // and may be used in release code.
357   bool CheckInvariantsOnTransactionClose(
358       syncable::BaseTransaction* trans,
359       const MetahandleSet& modified_handles);
360
361   // Forces a full check of the directory.  This operation may be slow and
362   // should not be invoked outside of tests.
363   bool FullyCheckTreeInvariants(BaseTransaction *trans);
364
365   // Purges data associated with any entries whose ModelType or ServerModelType
366   // is found in |disabled_types|, from sync directory _both_ in memory and on
367   // disk. Only valid, "real" model types are allowed in |disabled_types| (see
368   // model_type.h for definitions).
369   // 1. Data associated with |types_to_journal| is saved in the delete journal
370   // to help prevent back-from-dead problem due to offline delete in the next
371   // sync session. |types_to_journal| must be a subset of |disabled_types|.
372   // 2. Data associated with |types_to_unapply| is reset to an "unapplied"
373   // state, wherein all local data is deleted and IS_UNAPPLIED is set to true.
374   // This is useful when there's no benefit in discarding the currently
375   // downloaded state, such as when there are cryptographer errors.
376   // |types_to_unapply| must be a subset of |disabled_types|.
377   // 3. All other data is purged entirely.
378   // Note: "Purge" is just meant to distinguish from "deleting" entries, which
379   // means something different in the syncable namespace.
380   // WARNING! This can be real slow, as it iterates over all entries.
381   // WARNING! Performs synchronous I/O.
382   // Returns: true on success, false if an error was encountered.
383   virtual bool PurgeEntriesWithTypeIn(ModelTypeSet disabled_types,
384                                       ModelTypeSet types_to_journal,
385                                       ModelTypeSet types_to_unapply);
386
387   // Resets the base_versions and server_versions of all synced entities
388   // associated with |type| to 1.
389   // WARNING! This can be slow, as it iterates over all entries for a type.
390   bool ResetVersionsForType(BaseWriteTransaction* trans, ModelType type);
391
392   // Returns true iff the attachment identified by |attachment_id_proto| is
393   // linked to an entry.
394   //
395   // An attachment linked to a deleted entry is still considered linked if the
396   // entry hasn't yet been purged.
397   bool IsAttachmentLinked(
398       const sync_pb::AttachmentIdProto& attachment_id_proto) const;
399
400   // Given attachment id return metahandles to all entries that reference this
401   // attachment.
402   void GetMetahandlesByAttachmentId(
403       BaseTransaction* trans,
404       const sync_pb::AttachmentIdProto& attachment_id_proto,
405       Metahandles* result);
406
407  protected:  // for friends, mainly used by Entry constructors
408   virtual EntryKernel* GetEntryByHandle(int64 handle);
409   virtual EntryKernel* GetEntryByHandle(int64 metahandle,
410       ScopedKernelLock* lock);
411   virtual EntryKernel* GetEntryById(const Id& id);
412   EntryKernel* GetEntryByServerTag(const std::string& tag);
413   virtual EntryKernel* GetEntryByClientTag(const std::string& tag);
414   bool ReindexId(BaseWriteTransaction* trans, EntryKernel* const entry,
415                  const Id& new_id);
416   bool ReindexParentId(BaseWriteTransaction* trans, EntryKernel* const entry,
417                        const Id& new_parent_id);
418   // Update the attachment index for |metahandle| removing it from the index
419   // under |old_metadata| entries and add it under |new_metadata| entries.
420   void UpdateAttachmentIndex(const int64 metahandle,
421                              const sync_pb::AttachmentMetadata& old_metadata,
422                              const sync_pb::AttachmentMetadata& new_metadata);
423   void ClearDirtyMetahandles();
424
425   DirOpenResult OpenImpl(
426       const std::string& name,
427       DirectoryChangeDelegate* delegate,
428       const WeakHandle<TransactionObserver>& transaction_observer);
429
430  private:
431   struct Kernel {
432     // |delegate| must not be NULL.  |transaction_observer| must be
433     // initialized.
434     Kernel(const std::string& name, const KernelLoadInfo& info,
435            DirectoryChangeDelegate* delegate,
436            const WeakHandle<TransactionObserver>& transaction_observer);
437
438     ~Kernel();
439
440     // Implements ReadTransaction / WriteTransaction using a simple lock.
441     base::Lock transaction_mutex;
442
443     // Protected by transaction_mutex.  Used by WriteTransactions.
444     int64 next_write_transaction_id;
445
446     // The name of this directory.
447     std::string const name;
448
449     // Protects all members below.
450     // The mutex effectively protects all the indices, but not the
451     // entries themselves.  So once a pointer to an entry is pulled
452     // from the index, the mutex can be unlocked and entry read or written.
453     //
454     // Never hold the mutex and do anything with the database or any
455     // other buffered IO.  Violating this rule will result in deadlock.
456     base::Lock mutex;
457
458     // Entries indexed by metahandle.  This container is considered to be the
459     // owner of all EntryKernels, which may be referened by the other
460     // containers.  If you remove an EntryKernel from this map, you probably
461     // want to remove it from all other containers and delete it, too.
462     MetahandlesMap metahandles_map;
463
464     // Entries indexed by id
465     IdsMap ids_map;
466
467     // Entries indexed by server tag.
468     // This map does not include any entries with non-existent server tags.
469     TagsMap server_tags_map;
470
471     // Entries indexed by client tag.
472     // This map does not include any entries with non-existent client tags.
473     // IS_DEL items are included.
474     TagsMap client_tags_map;
475
476     // Contains non-deleted items, indexed according to parent and position
477     // within parent.  Protected by the ScopedKernelLock.
478     ParentChildIndex parent_child_index;
479
480     // This index keeps track of which metahandles refer to a given attachment.
481     // Think of it as the inverse of EntryKernel's AttachmentMetadata Records.
482     //
483     // Because entries can be undeleted (e.g. PutIsDel(false)), entries should
484     // not removed from the index until they are actually deleted from memory.
485     //
486     // All access should go through IsAttachmentLinked,
487     // RemoveFromAttachmentIndex, AddToAttachmentIndex, and
488     // UpdateAttachmentIndex methods to avoid iterator invalidation errors.
489     IndexByAttachmentId index_by_attachment_id;
490
491     // 3 in-memory indices on bits used extremely frequently by the syncer.
492     // |unapplied_update_metahandles| is keyed by the server model type.
493     MetahandleSet unapplied_update_metahandles[MODEL_TYPE_COUNT];
494     MetahandleSet unsynced_metahandles;
495     // Contains metahandles that are most likely dirty (though not
496     // necessarily).  Dirtyness is confirmed in TakeSnapshotForSaveChanges().
497     MetahandleSet dirty_metahandles;
498
499     // When a purge takes place, we remove items from all our indices and stash
500     // them in here so that SaveChanges can persist their permanent deletion.
501     MetahandleSet metahandles_to_purge;
502
503     KernelShareInfoStatus info_status;
504
505     // These 3 members are backed in the share_info table, and
506     // their state is marked by the flag above.
507
508     // A structure containing the Directory state that is written back into the
509     // database on SaveChanges.
510     PersistedKernelInfo persisted_info;
511
512     // A unique identifier for this account's cache db, used to generate
513     // unique server IDs. No need to lock, only written at init time.
514     const std::string cache_guid;
515
516     // It doesn't make sense for two threads to run SaveChanges at the same
517     // time; this mutex protects that activity.
518     base::Lock save_changes_mutex;
519
520     // The next metahandle is protected by kernel mutex.
521     int64 next_metahandle;
522
523     // The delegate for directory change events.  Must not be NULL.
524     DirectoryChangeDelegate* const delegate;
525
526     // The transaction observer.
527     const WeakHandle<TransactionObserver> transaction_observer;
528   };
529
530   // These private versions expect the kernel lock to already be held
531   // before calling.
532   EntryKernel* GetEntryById(const Id& id, ScopedKernelLock* const lock);
533
534   // A helper that implements the logic of checking tree invariants.
535   bool CheckTreeInvariants(syncable::BaseTransaction* trans,
536                            const MetahandleSet& handles);
537
538   // Helper to prime metahandles_map, ids_map, parent_child_index,
539   // unsynced_metahandles, unapplied_update_metahandles, server_tags_map and
540   // client_tags_map from metahandles_index.  The input |handles_map| will be
541   // cleared during the initialization process.
542   void InitializeIndices(MetahandlesMap* handles_map);
543
544   // Constructs a consistent snapshot of the current Directory state and
545   // indices (by deep copy) under a ReadTransaction for use in |snapshot|.
546   // See SaveChanges() for more information.
547   void TakeSnapshotForSaveChanges(SaveChangesSnapshot* snapshot);
548
549   // Purges from memory any unused, safe to remove entries that were
550   // successfully deleted on disk as a result of the SaveChanges that processed
551   // |snapshot|.  See SaveChanges() for more information.
552   bool VacuumAfterSaveChanges(const SaveChangesSnapshot& snapshot);
553
554   // Rolls back dirty bits in the event that the SaveChanges that
555   // processed |snapshot| failed, for example, due to no disk space.
556   void HandleSaveChangesFailure(const SaveChangesSnapshot& snapshot);
557
558   // For new entry creation only
559   bool InsertEntry(BaseWriteTransaction* trans,
560                    EntryKernel* entry, ScopedKernelLock* lock);
561   bool InsertEntry(BaseWriteTransaction* trans, EntryKernel* entry);
562
563   // Used by CheckTreeInvariants
564   void GetAllMetaHandles(BaseTransaction* trans, MetahandleSet* result);
565   bool SafeToPurgeFromMemory(WriteTransaction* trans,
566                              const EntryKernel* const entry) const;
567
568   // A helper used by GetTotalNodeCount.
569   void GetChildSetForKernel(
570       BaseTransaction*,
571       EntryKernel* kernel_,
572       std::deque<const OrderedChildSet*>* child_sets) const;
573
574   // Append the handles of the children of |parent_id| to |result|.
575   void AppendChildHandles(
576       const ScopedKernelLock& lock,
577       const Id& parent_id, Directory::Metahandles* result);
578
579   // Helper methods used by PurgeDisabledTypes.
580   void UnapplyEntry(EntryKernel* entry);
581   void DeleteEntry(bool save_to_journal,
582                    EntryKernel* entry,
583                    EntryKernelSet* entries_to_journal,
584                    const ScopedKernelLock& lock);
585
586   // Remove each of |metahandle|'s attachment ids from index_by_attachment_id.
587   void RemoveFromAttachmentIndex(
588       const int64 metahandle,
589       const sync_pb::AttachmentMetadata& attachment_metadata,
590       const ScopedKernelLock& lock);
591   // Add each of |metahandle|'s attachment ids to the index_by_attachment_id.
592   void AddToAttachmentIndex(
593       const int64 metahandle,
594       const sync_pb::AttachmentMetadata& attachment_metadata,
595       const ScopedKernelLock& lock);
596
597   Kernel* kernel_;
598
599   scoped_ptr<DirectoryBackingStore> store_;
600
601   UnrecoverableErrorHandler* const unrecoverable_error_handler_;
602   const ReportUnrecoverableErrorFunction report_unrecoverable_error_function_;
603   bool unrecoverable_error_set_;
604
605   // Not owned.
606   NigoriHandler* const nigori_handler_;
607   Cryptographer* const cryptographer_;
608
609   InvariantCheckLevel invariant_check_level_;
610
611   // Maintain deleted entries not in |kernel_| until it's verified that they
612   // are deleted in native models as well.
613   scoped_ptr<DeleteJournal> delete_journal_;
614
615   DISALLOW_COPY_AND_ASSIGN(Directory);
616 };
617
618 }  // namespace syncable
619 }  // namespace syncer
620
621 #endif // SYNC_SYNCABLE_DIRECTORY_H_