FSTLocalStore.h 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import <Foundation/Foundation.h>
  17. #include <vector>
  18. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  19. #include "Firestore/core/src/firebase/firestore/local/local_view_changes.h"
  20. #include "Firestore/core/src/firebase/firestore/local/local_write_result.h"
  21. #include "Firestore/core/src/firebase/firestore/local/lru_garbage_collector.h"
  22. #include "Firestore/core/src/firebase/firestore/local/query_data.h"
  23. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  24. #include "Firestore/core/src/firebase/firestore/model/document_key_set.h"
  25. #include "Firestore/core/src/firebase/firestore/model/document_map.h"
  26. #include "Firestore/core/src/firebase/firestore/model/mutation.h"
  27. #include "Firestore/core/src/firebase/firestore/model/mutation_batch.h"
  28. #include "Firestore/core/src/firebase/firestore/model/snapshot_version.h"
  29. #include "Firestore/core/src/firebase/firestore/model/types.h"
  30. #include "Firestore/core/src/firebase/firestore/nanopb/byte_string.h"
  31. namespace firebase {
  32. namespace firestore {
  33. namespace remote {
  34. class RemoteEvent;
  35. } // namespace remote
  36. } // namespace firestore
  37. } // namespace firebase
  38. @class FSTLocalViewChanges;
  39. @class FSTLocalWriteResult;
  40. @protocol FSTPersistence;
  41. namespace auth = firebase::firestore::auth;
  42. namespace core = firebase::firestore::core;
  43. namespace local = firebase::firestore::local;
  44. namespace model = firebase::firestore::model;
  45. namespace nanopb = firebase::firestore::nanopb;
  46. namespace remote = firebase::firestore::remote;
  47. NS_ASSUME_NONNULL_BEGIN
  48. /**
  49. * Local storage in the Firestore client. Coordinates persistence components like the mutation
  50. * queue and remote document cache to present a latency compensated view of stored data.
  51. *
  52. * The LocalStore is responsible for accepting mutations from the Sync Engine. Writes from the
  53. * client are put into a queue as provisional Mutations until they are processed by the RemoteStore
  54. * and confirmed as having been written to the server.
  55. *
  56. * The local store provides the local version of documents that have been modified locally. It
  57. * maintains the constraint:
  58. *
  59. * LocalDocument = RemoteDocument + Active(LocalMutations)
  60. *
  61. * (Active mutations are those that are enqueued and have not been previously acknowledged or
  62. * rejected).
  63. *
  64. * The RemoteDocument ("ground truth") state is provided via the applyChangeBatch method. It will
  65. * be some version of a server-provided document OR will be a server-provided document PLUS
  66. * acknowledged mutations:
  67. *
  68. * RemoteDocument' = RemoteDocument + Acknowledged(LocalMutations)
  69. *
  70. * Note that this "dirty" version of a RemoteDocument will not be identical to a server base
  71. * version, since it has LocalMutations added to it pending getting an authoritative copy from the
  72. * server.
  73. *
  74. * Since LocalMutations can be rejected by the server, we have to be able to revert a LocalMutation
  75. * that has already been applied to the LocalDocument (typically done by replaying all remaining
  76. * LocalMutations to the RemoteDocument to re-apply).
  77. *
  78. * It also maintains the persistence of mapping queries to resume tokens and target ids.
  79. *
  80. * The LocalStore must be able to efficiently execute queries against its local cache of the
  81. * documents, to provide the initial set of results before any remote changes have been received.
  82. */
  83. @interface FSTLocalStore : NSObject
  84. /** Creates a new instance of the FSTLocalStore with its required dependencies as parameters. */
  85. - (instancetype)initWithPersistence:(id<FSTPersistence>)persistence
  86. initialUser:(const auth::User &)initialUser NS_DESIGNATED_INITIALIZER;
  87. - (instancetype)init NS_UNAVAILABLE;
  88. /** Performs any initial startup actions required by the local store. */
  89. - (void)start;
  90. /**
  91. * Tells the FSTLocalStore that the currently authenticated user has changed.
  92. *
  93. * In response the local store switches the mutation queue to the new user and returns any
  94. * resulting document changes.
  95. */
  96. - (model::MaybeDocumentMap)userDidChange:(const auth::User &)user;
  97. /** Accepts locally generated Mutations and commits them to storage. */
  98. - (local::LocalWriteResult)locallyWriteMutations:(std::vector<model::Mutation> &&)mutations;
  99. /** Returns the current value of a document with a given key, or nil if not found. */
  100. - (absl::optional<model::MaybeDocument>)readDocument:(const model::DocumentKey &)key;
  101. /**
  102. * Acknowledges the given batch.
  103. *
  104. * On the happy path when a batch is acknowledged, the local store will
  105. *
  106. * + remove the batch from the mutation queue;
  107. * + apply the changes to the remote document cache;
  108. * + recalculate the latency compensated view implied by those changes (there may be mutations in
  109. * the queue that affect the documents but haven't been acknowledged yet); and
  110. * + give the changed documents back the sync engine
  111. *
  112. * @return The resulting (modified) documents.
  113. */
  114. - (model::MaybeDocumentMap)acknowledgeBatchWithResult:
  115. (const model::MutationBatchResult &)batchResult;
  116. /**
  117. * Removes mutations from the MutationQueue for the specified batch. LocalDocuments will be
  118. * recalculated.
  119. *
  120. * @return The resulting (modified) documents.
  121. */
  122. - (model::MaybeDocumentMap)rejectBatchID:(model::BatchId)batchID;
  123. /** Returns the last recorded stream token for the current user. */
  124. - (nanopb::ByteString)lastStreamToken;
  125. /**
  126. * Sets the stream token for the current user without acknowledging any mutation batch. This is
  127. * usually only useful after a stream handshake or in response to an error that requires clearing
  128. * the stream token.
  129. */
  130. - (void)setLastStreamToken:(const nanopb::ByteString &)streamToken;
  131. /**
  132. * Returns the last consistent snapshot processed (used by the RemoteStore to determine whether to
  133. * buffer incoming snapshots from the backend).
  134. */
  135. - (const model::SnapshotVersion &)lastRemoteSnapshotVersion;
  136. /**
  137. * Updates the "ground-state" (remote) documents. We assume that the remote event reflects any
  138. * write batches that have been acknowledged or rejected (i.e. we do not re-apply local mutations
  139. * to updates from this event).
  140. *
  141. * LocalDocuments are re-calculated if there are remaining mutations in the queue.
  142. */
  143. - (model::MaybeDocumentMap)applyRemoteEvent:(const remote::RemoteEvent &)remoteEvent;
  144. /**
  145. * Returns the keys of the documents that are associated with the given targetID in the remote
  146. * table.
  147. */
  148. - (model::DocumentKeySet)remoteDocumentKeysForTarget:(model::TargetId)targetID;
  149. /**
  150. * Assigns @a query an internal ID so that its results can be pinned so they don't get GC'd.
  151. * A query must be allocated in the local store before the store can be used to manage its view.
  152. */
  153. - (local::QueryData)allocateQuery:(core::Query)query;
  154. /** Unpin all the documents associated with @a query. */
  155. - (void)releaseQuery:(const core::Query &)query;
  156. /** Runs @a query against all the documents in the local store and returns the results. */
  157. - (model::DocumentMap)executeQuery:(const core::Query &)query;
  158. /** Notify the local store of the changed views to locally pin / unpin documents. */
  159. - (void)notifyLocalViewChanges:(const std::vector<local::LocalViewChanges> &)viewChanges;
  160. /**
  161. * Gets the mutation batch after the passed in batchId in the mutation queue or nil if empty.
  162. *
  163. * @param batchID The batch to search after, or -1 for the first mutation in the queue.
  164. * @return the next mutation or nil if there wasn't one.
  165. */
  166. - (absl::optional<model::MutationBatch>)nextMutationBatchAfterBatchID:(model::BatchId)batchID;
  167. /**
  168. * Returns the largest (latest) batch id in mutation queue that is pending server response.
  169. * Returns `kBatchIdUnknown` if the queue is empty.
  170. */
  171. - (model::BatchId)getHighestUnacknowledgedBatchId;
  172. - (local::LruResults)collectGarbage:(local::LruGarbageCollector *)garbageCollector;
  173. @end
  174. NS_ASSUME_NONNULL_END