FSTPersistence.h 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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 "Firestore/core/src/firebase/firestore/auth/user.h"
  18. #include "Firestore/core/src/firebase/firestore/local/index_manager.h"
  19. #include "Firestore/core/src/firebase/firestore/local/mutation_queue.h"
  20. #include "Firestore/core/src/firebase/firestore/local/query_cache.h"
  21. #include "Firestore/core/src/firebase/firestore/local/reference_set.h"
  22. #include "Firestore/core/src/firebase/firestore/local/remote_document_cache.h"
  23. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  24. #include "Firestore/core/src/firebase/firestore/model/types.h"
  25. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  26. #include "Firestore/core/src/firebase/firestore/util/status.h"
  27. @class FSTQueryData;
  28. @protocol FSTReferenceDelegate;
  29. namespace auth = firebase::firestore::auth;
  30. namespace local = firebase::firestore::local;
  31. namespace model = firebase::firestore::model;
  32. struct FSTTransactionRunner;
  33. NS_ASSUME_NONNULL_BEGIN
  34. /**
  35. * FSTPersistence is the lowest-level shared interface to persistent storage in Firestore.
  36. *
  37. * FSTPersistence is used to create FSTMutationQueue and FSTRemoteDocumentCache instances backed
  38. * by persistence (which might be in-memory or LevelDB).
  39. *
  40. * FSTPersistence also exposes an API to create and commit FSTWriteGroup instances.
  41. * Implementations of FSTWriteGroup/FSTPersistence only need to guarantee that writes made
  42. * against the FSTWriteGroup are not made to durable storage until commitGroup:action: is called
  43. * here. Since memory-only storage components do not alter durable storage, they are free to ignore
  44. * the group.
  45. *
  46. * This contract is enough to allow the FSTLocalStore be be written independently of whether or not
  47. * the stored state actually is durably persisted. If persistent storage is enabled, writes are
  48. * grouped together to avoid inconsistent state that could cause crashes.
  49. *
  50. * Concretely, when persistent storage is enabled, the persistent versions of FSTMutationQueue,
  51. * FSTRemoteDocumentCache, and others (the mutators) will defer their writes into an FSTWriteGroup.
  52. * Once the local store has completed one logical operation, it commits the write group using
  53. * [FSTPersistence commitGroup:action:].
  54. *
  55. * When persistent storage is disabled, the non-persistent versions of the mutators ignore the
  56. * FSTWriteGroup and [FSTPersistence commitGroup:action:] is a no-op. This short-cut is allowed
  57. * because memory-only storage leaves no state so it cannot be inconsistent.
  58. *
  59. * This simplifies the implementations of the mutators and allows memory-only implementations to
  60. * supplement the persistent ones without requiring any special dual-store implementation of
  61. * FSTPersistence. The cost is that the FSTLocalStore needs to be slightly careful about the order
  62. * of its reads and writes in order to avoid relying on being able to read back uncommitted writes.
  63. */
  64. @protocol FSTPersistence <NSObject>
  65. /** Releases any resources held during eager shutdown. */
  66. - (void)shutdown;
  67. /**
  68. * Returns a MutationQueue representing the persisted mutations for the given user.
  69. *
  70. * <p>Note: The implementation is free to return the same instance every time this is called for a
  71. * given user. In particular, the memory-backed implementation does this to emulate the persisted
  72. * implementation to the extent possible (e.g. in the case of uid switching from
  73. * sally=>jack=>sally, sally's mutation queue will be preserved).
  74. */
  75. - (local::MutationQueue *)mutationQueueForUser:(const auth::User &)user;
  76. /** Creates an FSTQueryCache representing the persisted cache of queries. */
  77. - (local::QueryCache *)queryCache;
  78. /** Creates a RemoteDocumentCache representing the persisted cache of remote documents. */
  79. - (local::RemoteDocumentCache *)remoteDocumentCache;
  80. /** Creates an IndexManager that manages our persisted query indexes. */
  81. - (local::IndexManager *)indexManager;
  82. @property(nonatomic, readonly, assign) const FSTTransactionRunner &run;
  83. /**
  84. * This property provides access to hooks around the document reference lifecycle. It is initially
  85. * nullable while being implemented, but the goal is to eventually have it be non-nil.
  86. */
  87. @property(nonatomic, readonly, strong) id<FSTReferenceDelegate> referenceDelegate;
  88. @property(nonatomic, readonly) model::ListenSequenceNumber currentSequenceNumber;
  89. @end
  90. @protocol FSTTransactional
  91. - (void)startTransaction:(absl::string_view)label;
  92. - (void)commitTransaction;
  93. @end
  94. /**
  95. * An FSTReferenceDelegate instance handles all of the hooks into the document-reference lifecycle.
  96. * This includes being added to a target, being removed from a target, being subject to mutation,
  97. * and being mutated by the user.
  98. *
  99. * Different implementations may do different things with each of these events. Not every
  100. * implementation needs to do something with every lifecycle hook.
  101. *
  102. * Implementations that care about sequence numbers are responsible for generating them and making
  103. * them available.
  104. */
  105. @protocol FSTReferenceDelegate <NSObject>
  106. /**
  107. * Registers an FSTReferenceSet of documents that should be considered 'referenced' and not eligible
  108. * for removal during garbage collection.
  109. */
  110. - (void)addInMemoryPins:(local::ReferenceSet *)set;
  111. /**
  112. * Notify the delegate that a target was removed.
  113. */
  114. - (void)removeTarget:(FSTQueryData *)queryData;
  115. /**
  116. * Notify the delegate that the given document was added to a target.
  117. */
  118. - (void)addReference:(const model::DocumentKey &)key;
  119. /**
  120. * Notify the delegate that the given document was removed from a target.
  121. */
  122. - (void)removeReference:(const model::DocumentKey &)key;
  123. /**
  124. * Notify the delegate that a document is no longer being mutated by the user.
  125. */
  126. - (void)removeMutationReference:(const model::DocumentKey &)key;
  127. /**
  128. * Notify the delegate that a limbo document was updated.
  129. */
  130. - (void)limboDocumentUpdated:(const model::DocumentKey &)key;
  131. @property(nonatomic, readonly) model::ListenSequenceNumber currentSequenceNumber;
  132. @end
  133. struct FSTTransactionRunner {
  134. // Intentionally disable nullability checking for this function. We cannot properly annotate
  135. // the function because this function can handle both pointer and non-pointer types. It is an error
  136. // to annotate non-pointer types with a nullability annotation.
  137. #pragma clang diagnostic push
  138. #pragma clang diagnostic ignored "-Wnullability-completeness"
  139. /**
  140. * The following two functions handle accepting callables and optionally running them within a
  141. * transaction. Persistence layers that conform to the FSTTransactional protocol can set
  142. * themselves as the backing persistence for a transaction runner, in which case a transaction
  143. * will be started before a block is run, and committed after the block has executed. If there is
  144. * no backing instance of FSTTransactional, the block will be run directly.
  145. *
  146. * There are two instances of operator() to handle the case where the block returns void, rather
  147. * than a type.
  148. *
  149. * The transaction runner keeps a weak reference to the backing persistence so as not to cause a
  150. * retain cycle. The reference is upgraded to strong (with a fatal error if it has disappeared)
  151. * for the duration of running a transaction.
  152. */
  153. template <typename F>
  154. auto operator()(absl::string_view label, F block) const ->
  155. typename std::enable_if<std::is_void<decltype(block())>::value, void>::type {
  156. __strong id<FSTTransactional> strongDb = _db;
  157. if (!strongDb && _expect_db) {
  158. HARD_FAIL("Transaction runner accessed without underlying db when it expected one");
  159. }
  160. if (strongDb) {
  161. [strongDb startTransaction:label];
  162. }
  163. block();
  164. if (strongDb) {
  165. [strongDb commitTransaction];
  166. }
  167. }
  168. template <typename F>
  169. auto operator()(absl::string_view label, F block) const ->
  170. typename std::enable_if<!std::is_void<decltype(block())>::value, decltype(block())>::type {
  171. using ReturnT = decltype(block());
  172. __strong id<FSTTransactional> strongDb = _db;
  173. if (!strongDb && _expect_db) {
  174. HARD_FAIL("Transaction runner accessed without underlying db when it expected one");
  175. }
  176. if (strongDb) {
  177. [strongDb startTransaction:label];
  178. }
  179. ReturnT result = block();
  180. if (strongDb) {
  181. [strongDb commitTransaction];
  182. }
  183. return result;
  184. }
  185. #pragma clang diagnostic pop
  186. void SetBackingPersistence(id<FSTTransactional> db) {
  187. _db = db;
  188. _expect_db = true;
  189. }
  190. private:
  191. __weak id<FSTTransactional> _db;
  192. bool _expect_db = false;
  193. };
  194. NS_ASSUME_NONNULL_END