model_type_sync_bridge.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. // Copyright 2015 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. #ifndef COMPONENTS_SYNC_MODEL_MODEL_TYPE_SYNC_BRIDGE_H_
  5. #define COMPONENTS_SYNC_MODEL_MODEL_TYPE_SYNC_BRIDGE_H_
  6. #include <memory>
  7. #include <string>
  8. #include <vector>
  9. #include "base/callback.h"
  10. #include "components/sync/engine/commit_and_get_updates_types.h"
  11. #include "components/sync/model/entity_change.h"
  12. #include "components/sync/model/model_type_change_processor.h"
  13. #include "third_party/abseil-cpp/absl/types/optional.h"
  14. namespace syncer {
  15. enum class ConflictResolution;
  16. class DataBatch;
  17. struct DataTypeActivationRequest;
  18. struct EntityData;
  19. class MetadataChangeList;
  20. class ModelError;
  21. // Interface implemented by model types to receive updates from sync via a
  22. // ModelTypeChangeProcessor. Provides a way for sync to update the data and
  23. // metadata for entities, as well as the model type state. Sync bridge
  24. // implementations must provide their change_processor() with metadata through
  25. // ModelReadyToSync() as soon as possible. Once this is called, sync will
  26. // immediately begin locally tracking changes and can start syncing with the
  27. // server soon afterward. If an error occurs during startup, the processor's
  28. // ReportError() method should be called instead of ModelReadyToSync().
  29. class ModelTypeSyncBridge {
  30. public:
  31. using DataCallback = base::OnceCallback<void(std::unique_ptr<DataBatch>)>;
  32. using StorageKeyList = std::vector<std::string>;
  33. // When commit fails, all entities from the commit request are in transient
  34. // state. This state is normally (by default) kept until the next successful
  35. // commit of the data type or until the change processor is disconnected.
  36. // However, the bridge can return the preferred option to reset state of all
  37. // entities from the last failed commit.
  38. enum class CommitAttemptFailedBehavior {
  39. // Keep transient state of entities from the last commit request.
  40. kDontRetryOnNextCycle,
  41. // The processor should reset the transient state and include all entities
  42. // into the next sync cycle.
  43. kShouldRetryOnNextCycle,
  44. };
  45. explicit ModelTypeSyncBridge(
  46. std::unique_ptr<ModelTypeChangeProcessor> change_processor);
  47. virtual ~ModelTypeSyncBridge();
  48. // Called by the processor as a notification that sync has been started by the
  49. // ModelTypeController.
  50. virtual void OnSyncStarting(const DataTypeActivationRequest& request);
  51. // Creates an object used to communicate changes in the sync metadata to the
  52. // model type store.
  53. virtual std::unique_ptr<MetadataChangeList> CreateMetadataChangeList() = 0;
  54. // Perform the initial merge between local and sync data.
  55. //
  56. // If the bridge supports incremental updates, this is only called when a data
  57. // type is first enabled to start syncing, and there is no sync metadata.
  58. // In this case, best effort should be made to match local and sync data.
  59. //
  60. // For datatypes that do not support incremental updates, the processor will
  61. // call this method every time it gets new sync data from the server. It is
  62. // then the responsibility of the bridge to clear all existing sync data, and
  63. // replace it with the passed in |entity_data|.
  64. //
  65. // Storage key in entity_data elements will be set to result of
  66. // GetStorageKey() call if the bridge supports it. Otherwise it will be left
  67. // empty, bridge is responsible for updating storage keys of new entities with
  68. // change_processor()->UpdateStorageKey() in this case.
  69. //
  70. // If a local and sync data should match/merge but disagree on storage key,
  71. // the bridge should delete one of the records (preferably local). Any local
  72. // pieces of data that are not present in sync should immediately be Put(...)
  73. // to the processor before returning. The same MetadataChangeList that was
  74. // passed into this function can be passed to Put(...) calls. Delete(...) can
  75. // also be called but should not be needed for most model types. Durable
  76. // storage writes, if not able to combine all change atomically, should save
  77. // the metadata after the data changes, so that this merge will be re-driven
  78. // by sync if is not completely saved during the current run.
  79. virtual absl::optional<ModelError> MergeSyncData(
  80. std::unique_ptr<MetadataChangeList> metadata_change_list,
  81. EntityChangeList entity_data) = 0;
  82. // Apply changes from the sync server locally.
  83. // Please note that |entity_changes| might have fewer entries than
  84. // |metadata_change_list| in case when some of the data changes are filtered
  85. // out, or even be empty in case when a commit confirmation is processed and
  86. // only the metadata needs to persisted.
  87. virtual absl::optional<ModelError> ApplySyncChanges(
  88. std::unique_ptr<MetadataChangeList> metadata_change_list,
  89. EntityChangeList entity_changes) = 0;
  90. // Asynchronously retrieve the corresponding sync data for |storage_keys|.
  91. // |callback| should be invoked if the operation is successful, otherwise
  92. // the processor's ReportError method should be called.
  93. virtual void GetData(StorageKeyList storage_keys, DataCallback callback) = 0;
  94. // Asynchronously retrieve all of the local sync data. |callback| should be
  95. // invoked if the operation is successful, otherwise the processor's
  96. // ReportError method should be called.
  97. // Used for getting all data in Sync Node Browser of chrome://sync-internals.
  98. virtual void GetAllDataForDebugging(DataCallback callback) = 0;
  99. // Must not be called unless SupportsGetClientTag() returns true.
  100. //
  101. // Get or generate a client tag for |entity_data|. This must be the same tag
  102. // that was/would have been generated in the SyncableService/Directory world
  103. // for backward compatibility with pre-USS clients. The only time this
  104. // theoretically needs to be called is on the creation of local data.
  105. //
  106. // If a model type was never launched pre-USS, then method does not need to be
  107. // different from GetStorageKey(). Only the hash of this value is kept.
  108. virtual std::string GetClientTag(const EntityData& entity_data) = 0;
  109. // Must not be called unless SupportsGetStorageKey() returns true.
  110. //
  111. // Get or generate a storage key for |entity_data|. This will only ever be
  112. // called once when first encountering a remote entity. Local changes will
  113. // provide their storage keys directly to Put instead of using this method.
  114. // Theoretically this function doesn't need to be stable across multiple calls
  115. // on the same or different clients, but to keep things simple, it probably
  116. // should be. Storage keys are kept in memory at steady state, so each model
  117. // type should strive to keep these keys as small as possible.
  118. // Returning an empty string means the remote creation should be ignored (i.e.
  119. // it contains invalid data).
  120. // TODO(crbug.com/1057947): introduce a dedicated method to validate data from
  121. // the server to solve the inconsistency with bridges that don't support
  122. // GetStorageKey() and with remote updates which are not creations.
  123. virtual std::string GetStorageKey(const EntityData& entity_data) = 0;
  124. // Whether or not the bridge is capable of producing a client tag from
  125. // |EntityData| (usually remote changes), via GetClientTag(). Most bridges do,
  126. // but in rare cases including commit-only types and read-only types, it may
  127. // not.
  128. virtual bool SupportsGetClientTag() const;
  129. // By returning true in this function datatype indicates that it can generate
  130. // storage key from EntityData. In this case for all new entities received
  131. // from server, change processor will call GetStorageKey and update
  132. // EntityChange structures before passing them to MergeSyncData and
  133. // ApplySyncChanges.
  134. //
  135. // This function should return false when datatype's native storage is not
  136. // indexed by some combination of values from EntityData, when key into the
  137. // storage is obtained at the time the record is inserted into it (e.g. ROWID
  138. // in SQLite). In this case entity changes for new entities passed to
  139. // MergeSyncData and ApplySyncChanges will have empty storage_key. It is
  140. // datatype's responsibility to call UpdateStorageKey for such entities.
  141. virtual bool SupportsGetStorageKey() const;
  142. // By returning true in this function, the datatype indicates that it supports
  143. // receiving partial (incremental) updates. If it returns false, the type
  144. // indicates that it requires the full data set to be sent to it through
  145. // MergeSyncData for any change to the data set.
  146. virtual bool SupportsIncrementalUpdates() const;
  147. // Resolve a conflict between the client and server versions of data. They are
  148. // guaranteed not to match (both be deleted or have identical specifics). A
  149. // default implementation chooses the server data unless it is a deletion.
  150. virtual ConflictResolution ResolveConflict(
  151. const std::string& storage_key,
  152. const EntityData& remote_data) const;
  153. // Similar to ApplySyncChanges() but called by the processor when sync
  154. // is in the process of being stopped. If |delete_metadata_change_list| is not
  155. // null, it indicates that sync metadata must be deleted (i.e. the datatype
  156. // was disabled), and |*delete_metadata_change_list| contains a change list to
  157. // remove all metadata that the processor knows about (the bridge may decide
  158. // to implement deletion by other means).
  159. virtual void ApplyStopSyncChanges(
  160. std::unique_ptr<MetadataChangeList> delete_metadata_change_list);
  161. // Called only when some items in a commit haven't been committed due to an
  162. // error.
  163. virtual void OnCommitAttemptErrors(
  164. const syncer::FailedCommitResponseDataList& error_response_list);
  165. // Called only when a commit failed due to server error.
  166. virtual CommitAttemptFailedBehavior OnCommitAttemptFailed(
  167. SyncCommitError commit_error);
  168. // Returns an estimate of memory usage attributed to sync (that is, excludes
  169. // the actual model). Because the resulting UMA metrics are often used to
  170. // compare with the non-USS equivalent implementations (SyncableService), it's
  171. // a good idea to account for overhead that would also get accounted for the
  172. // SyncableService by other means.
  173. virtual size_t EstimateSyncOverheadMemoryUsage() const;
  174. // Returns a copy of |entity_specifics| where fields that do not need to be
  175. // preserved in EntityMetadata cache are cleared. This allows each data type
  176. // to specify which fields are supported in the current version. This usually
  177. // means all known proto fields (i.e. all except unknown proto fields synced
  178. // from more recent versions of the browser) but not always, since there are
  179. // cases where a proto field is defined, but its implementation is not
  180. // complete yet or exists behind a feature flag.
  181. // By default, empty EntitySpecifics is returned.
  182. virtual sync_pb::EntitySpecifics TrimRemoteSpecificsForCaching(
  183. const sync_pb::EntitySpecifics& entity_specifics) const;
  184. // Needs to be informed about any model change occurring via Delete() and
  185. // Put(). The changing metadata should be stored to persistent storage
  186. // before or atomically with the model changes.
  187. ModelTypeChangeProcessor* change_processor();
  188. const ModelTypeChangeProcessor* change_processor() const;
  189. private:
  190. std::unique_ptr<ModelTypeChangeProcessor> change_processor_;
  191. };
  192. } // namespace syncer
  193. #endif // COMPONENTS_SYNC_MODEL_MODEL_TYPE_SYNC_BRIDGE_H_