FSTPersistence.h 8.4 KB

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