FSTPersistence.h 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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/Util/FSTAssert.h"
  18. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  19. @protocol FSTMutationQueue;
  20. @protocol FSTQueryCache;
  21. @protocol FSTRemoteDocumentCache;
  22. NS_ASSUME_NONNULL_BEGIN
  23. /**
  24. * FSTPersistence is the lowest-level shared interface to persistent storage in Firestore.
  25. *
  26. * FSTPersistence is used to create FSTMutationQueue and FSTRemoteDocumentCache instances backed
  27. * by persistence (which might be in-memory or LevelDB).
  28. *
  29. * FSTPersistence also exposes an API to create and commit FSTWriteGroup instances.
  30. * Implementations of FSTWriteGroup/FSTPersistence only need to guarantee that writes made
  31. * against the FSTWriteGroup are not made to durable storage until commitGroup:action: is called
  32. * here. Since memory-only storage components do not alter durable storage, they are free to ignore
  33. * the group.
  34. *
  35. * This contract is enough to allow the FSTLocalStore be be written independently of whether or not
  36. * the stored state actually is durably persisted. If persistent storage is enabled, writes are
  37. * grouped together to avoid inconsistent state that could cause crashes.
  38. *
  39. * Concretely, when persistent storage is enabled, the persistent versions of FSTMutationQueue,
  40. * FSTRemoteDocumentCache, and others (the mutators) will defer their writes into an FSTWriteGroup.
  41. * Once the local store has completed one logical operation, it commits the write group using
  42. * [FSTPersistence commitGroup:action:].
  43. *
  44. * When persistent storage is disabled, the non-persistent versions of the mutators ignore the
  45. * FSTWriteGroup and [FSTPersistence commitGroup:action:] is a no-op. This short-cut is allowed
  46. * because memory-only storage leaves no state so it cannot be inconsistent.
  47. *
  48. * This simplifies the implementations of the mutators and allows memory-only implementations to
  49. * supplement the persistent ones without requiring any special dual-store implementation of
  50. * FSTPersistence. The cost is that the FSTLocalStore needs to be slightly careful about the order
  51. * of its reads and writes in order to avoid relying on being able to read back uncommitted writes.
  52. */
  53. struct FSTTransactionRunner;
  54. @protocol FSTPersistence <NSObject>
  55. /**
  56. * Starts persistent storage, opening the database or similar.
  57. *
  58. * @param error An error object that will be populated if startup fails.
  59. * @return YES if persistent storage started successfully, NO otherwise.
  60. */
  61. - (BOOL)start:(NSError **)error;
  62. /** Releases any resources held during eager shutdown. */
  63. - (void)shutdown;
  64. /**
  65. * Returns an FSTMutationQueue representing the persisted mutations for the given user.
  66. *
  67. * <p>Note: The implementation is free to return the same instance every time this is called for a
  68. * given user. In particular, the memory-backed implementation does this to emulate the persisted
  69. * implementation to the extent possible (e.g. in the case of uid switching from
  70. * sally=>jack=>sally, sally's mutation queue will be preserved).
  71. */
  72. - (id<FSTMutationQueue>)mutationQueueForUser:(const firebase::firestore::auth::User &)user;
  73. /** Creates an FSTQueryCache representing the persisted cache of queries. */
  74. - (id<FSTQueryCache>)queryCache;
  75. /** Creates an FSTRemoteDocumentCache representing the persisted cache of remote documents. */
  76. - (id<FSTRemoteDocumentCache>)remoteDocumentCache;
  77. @property(nonatomic, readonly, assign) const FSTTransactionRunner &run;
  78. @end
  79. @protocol FSTTransactional
  80. - (void)startTransaction:(absl::string_view)label;
  81. - (void)commitTransaction;
  82. @end
  83. struct FSTTransactionRunner {
  84. // Intentionally disable nullability checking for this function. We cannot properly annotate
  85. // the function because this function can handle both pointer and non-pointer types. It is an error
  86. // to annotate non-pointer types with a nullability annotation.
  87. #pragma clang diagnostic push
  88. #pragma clang diagnostic ignored "-Wnullability-completeness"
  89. /**
  90. * The following two functions handle accepting callables and optionally running them within a
  91. * transaction. Persistence layers that conform to the FSTTransactional protocol can set
  92. * themselves as the backing persistence for a transaction runner, in which case a transaction
  93. * will be started before a block is run, and committed after the block has executed. If there is
  94. * no backing instance of FSTTransactional, the block will be run directly.
  95. *
  96. * There are two instances of operator() to handle the case where the block returns void, rather
  97. * than a type.
  98. *
  99. * The transaction runner keeps a weak reference to the backing persistence so as not to cause a
  100. * retain cycle. The reference is upgraded to strong (with a fatal error if it has disappeared)
  101. * for the duration of running a transaction.
  102. */
  103. template <typename F>
  104. auto operator()(absl::string_view label, F block) const ->
  105. typename std::enable_if<std::is_void<decltype(block())>::value, void>::type {
  106. __strong id<FSTTransactional> strongDb = _db;
  107. if (!strongDb && _expect_db) {
  108. FSTCFail(@"Transaction runner accessed without underlying db when it expected one");
  109. }
  110. if (strongDb) {
  111. [strongDb startTransaction:label];
  112. }
  113. block();
  114. if (strongDb) {
  115. [strongDb commitTransaction];
  116. }
  117. }
  118. template <typename F>
  119. auto operator()(absl::string_view label, F block) const ->
  120. typename std::enable_if<!std::is_void<decltype(block())>::value, decltype(block())>::type {
  121. using ReturnT = decltype(block());
  122. __strong id<FSTTransactional> strongDb = _db;
  123. if (!strongDb && _expect_db) {
  124. FSTCFail(@"Transaction runner accessed without underlying db when it expected one");
  125. }
  126. if (strongDb) {
  127. [strongDb startTransaction:label];
  128. }
  129. ReturnT result = block();
  130. if (strongDb) {
  131. [strongDb commitTransaction];
  132. }
  133. return result;
  134. }
  135. #pragma clang diagnostic pop
  136. void SetBackingPersistence(id<FSTTransactional> db) {
  137. _db = db;
  138. _expect_db = true;
  139. }
  140. private:
  141. __weak id<FSTTransactional> _db;
  142. bool _expect_db = false;
  143. };
  144. NS_ASSUME_NONNULL_END