FSTMemoryPersistence.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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 "Firestore/Source/Local/FSTMemoryPersistence.h"
  17. #include <memory>
  18. #include <unordered_map>
  19. #include <unordered_set>
  20. #import "Firestore/Source/Core/FSTListenSequence.h"
  21. #import "Firestore/Source/Local/FSTMemoryMutationQueue.h"
  22. #import "Firestore/Source/Local/FSTMemoryQueryCache.h"
  23. #import "Firestore/Source/Local/FSTMemoryRemoteDocumentCache.h"
  24. #import "Firestore/Source/Local/FSTReferenceSet.h"
  25. #include "absl/memory/memory.h"
  26. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  27. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  28. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  29. using firebase::firestore::auth::HashUser;
  30. using firebase::firestore::auth::User;
  31. using firebase::firestore::model::DocumentKey;
  32. using firebase::firestore::model::DocumentKeyHash;
  33. using firebase::firestore::model::ListenSequenceNumber;
  34. using firebase::firestore::util::Status;
  35. using MutationQueues = std::unordered_map<User, FSTMemoryMutationQueue *, HashUser>;
  36. NS_ASSUME_NONNULL_BEGIN
  37. @interface FSTMemoryPersistence ()
  38. @property(nonatomic, readonly) MutationQueues &mutationQueues;
  39. @property(nonatomic, assign, getter=isStarted) BOOL started;
  40. // Make this property writable so we can wire up a delegate.
  41. @property(nonatomic, strong) id<FSTReferenceDelegate> referenceDelegate;
  42. @end
  43. @implementation FSTMemoryPersistence {
  44. /**
  45. * The FSTQueryCache representing the persisted cache of queries.
  46. *
  47. * Note that this is retained here to make it easier to write tests affecting both the in-memory
  48. * and LevelDB-backed persistence layers. Tests can create a new FSTLocalStore wrapping this
  49. * FSTPersistence instance and this will make the in-memory persistence layer behave as if it
  50. * were actually persisting values.
  51. */
  52. FSTMemoryQueryCache *_queryCache;
  53. /** The FSTRemoteDocumentCache representing the persisted cache of remote documents. */
  54. FSTMemoryRemoteDocumentCache *_remoteDocumentCache;
  55. FSTTransactionRunner _transactionRunner;
  56. id<FSTReferenceDelegate> _referenceDelegate;
  57. }
  58. + (instancetype)persistenceWithEagerGC {
  59. FSTMemoryPersistence *persistence = [[FSTMemoryPersistence alloc] init];
  60. persistence.referenceDelegate =
  61. [[FSTMemoryEagerReferenceDelegate alloc] initWithPersistence:persistence];
  62. return persistence;
  63. }
  64. + (instancetype)persistenceWithLRUGC {
  65. FSTMemoryPersistence *persistence = [[FSTMemoryPersistence alloc] init];
  66. persistence.referenceDelegate =
  67. [[FSTMemoryLRUReferenceDelegate alloc] initWithPersistence:persistence];
  68. return persistence;
  69. }
  70. - (instancetype)init {
  71. if (self = [super init]) {
  72. _queryCache = [[FSTMemoryQueryCache alloc] initWithPersistence:self];
  73. _remoteDocumentCache = [[FSTMemoryRemoteDocumentCache alloc] init];
  74. }
  75. return self;
  76. }
  77. - (void)setReferenceDelegate:(id<FSTReferenceDelegate>)referenceDelegate {
  78. _referenceDelegate = referenceDelegate;
  79. id delegate = _referenceDelegate;
  80. if ([delegate conformsToProtocol:@protocol(FSTTransactional)]) {
  81. _transactionRunner.SetBackingPersistence((id<FSTTransactional>)_referenceDelegate);
  82. }
  83. }
  84. - (Status)start {
  85. // No durable state to read on startup.
  86. HARD_ASSERT(!self.isStarted, "FSTMemoryPersistence double-started!");
  87. self.started = YES;
  88. return Status::OK();
  89. }
  90. - (void)shutdown {
  91. // No durable state to ensure is closed on shutdown.
  92. HARD_ASSERT(self.isStarted, "FSTMemoryPersistence shutdown without start!");
  93. self.started = NO;
  94. }
  95. - (id<FSTReferenceDelegate>)referenceDelegate {
  96. return _referenceDelegate;
  97. }
  98. - (ListenSequenceNumber)currentSequenceNumber {
  99. return [_referenceDelegate currentSequenceNumber];
  100. }
  101. - (const FSTTransactionRunner &)run {
  102. return _transactionRunner;
  103. }
  104. - (id<FSTMutationQueue>)mutationQueueForUser:(const User &)user {
  105. id<FSTMutationQueue> queue = _mutationQueues[user];
  106. if (!queue) {
  107. queue = [[FSTMemoryMutationQueue alloc] initWithPersistence:self];
  108. _mutationQueues[user] = queue;
  109. }
  110. return queue;
  111. }
  112. - (id<FSTQueryCache>)queryCache {
  113. return _queryCache;
  114. }
  115. - (id<FSTRemoteDocumentCache>)remoteDocumentCache {
  116. return _remoteDocumentCache;
  117. }
  118. @end
  119. @implementation FSTMemoryLRUReferenceDelegate {
  120. // This delegate should have the same lifetime as the persistence layer, but mark as
  121. // weak to avoid retain cycle.
  122. __weak FSTMemoryPersistence *_persistence;
  123. std::unordered_map<DocumentKey, ListenSequenceNumber, DocumentKeyHash> _sequenceNumbers;
  124. FSTReferenceSet *_additionalReferences;
  125. FSTLRUGarbageCollector *_gc;
  126. FSTListenSequence *_listenSequence;
  127. ListenSequenceNumber _currentSequenceNumber;
  128. }
  129. - (instancetype)initWithPersistence:(FSTMemoryPersistence *)persistence {
  130. if (self = [super init]) {
  131. _persistence = persistence;
  132. _gc =
  133. [[FSTLRUGarbageCollector alloc] initWithQueryCache:[_persistence queryCache] delegate:self];
  134. _currentSequenceNumber = kFSTListenSequenceNumberInvalid;
  135. // Theoretically this is always 0, since this is all in-memory...
  136. ListenSequenceNumber highestSequenceNumber =
  137. _persistence.queryCache.highestListenSequenceNumber;
  138. _listenSequence = [[FSTListenSequence alloc] initStartingAfter:highestSequenceNumber];
  139. }
  140. return self;
  141. }
  142. - (FSTLRUGarbageCollector *)gc {
  143. return _gc;
  144. }
  145. - (ListenSequenceNumber)currentSequenceNumber {
  146. HARD_ASSERT(_currentSequenceNumber != kFSTListenSequenceNumberInvalid,
  147. "Asking for a sequence number outside of a transaction");
  148. return _currentSequenceNumber;
  149. }
  150. - (void)addInMemoryPins:(FSTReferenceSet *)set {
  151. // Technically can't assert this, due to restartWithNoopGarbageCollector (for now...)
  152. // FSTAssert(_additionalReferences == nil, @"Overwriting additional references");
  153. _additionalReferences = set;
  154. }
  155. - (void)removeTarget:(FSTQueryData *)queryData {
  156. FSTQueryData *updated = [queryData queryDataByReplacingSnapshotVersion:queryData.snapshotVersion
  157. resumeToken:queryData.resumeToken
  158. sequenceNumber:_currentSequenceNumber];
  159. [_persistence.queryCache updateQueryData:updated];
  160. }
  161. - (void)limboDocumentUpdated:(const DocumentKey &)key {
  162. _sequenceNumbers[key] = self.currentSequenceNumber;
  163. }
  164. - (void)startTransaction:(absl::string_view)label {
  165. _currentSequenceNumber = [_listenSequence next];
  166. }
  167. - (void)commitTransaction {
  168. _currentSequenceNumber = kFSTListenSequenceNumberInvalid;
  169. }
  170. - (void)enumerateTargetsUsingBlock:(void (^)(FSTQueryData *queryData, BOOL *stop))block {
  171. return [_persistence.queryCache enumerateTargetsUsingBlock:block];
  172. }
  173. - (void)enumerateMutationsUsingBlock:
  174. (void (^)(const DocumentKey &key, ListenSequenceNumber sequenceNumber, BOOL *stop))block {
  175. BOOL stop = NO;
  176. for (auto it = _sequenceNumbers.begin(); !stop && it != _sequenceNumbers.end(); ++it) {
  177. ListenSequenceNumber sequenceNumber = it->second;
  178. const DocumentKey &key = it->first;
  179. if (![_persistence.queryCache containsKey:key]) {
  180. block(key, sequenceNumber, &stop);
  181. }
  182. }
  183. }
  184. - (int)removeTargetsThroughSequenceNumber:(ListenSequenceNumber)sequenceNumber
  185. liveQueries:(NSDictionary<NSNumber *, FSTQueryData *> *)liveQueries {
  186. return [_persistence.queryCache removeQueriesThroughSequenceNumber:sequenceNumber
  187. liveQueries:liveQueries];
  188. }
  189. - (int)removeOrphanedDocumentsThroughSequenceNumber:(ListenSequenceNumber)upperBound {
  190. return [(FSTMemoryRemoteDocumentCache *)_persistence.remoteDocumentCache
  191. removeOrphanedDocuments:self
  192. throughSequenceNumber:upperBound];
  193. }
  194. - (void)addReference:(const DocumentKey &)key {
  195. _sequenceNumbers[key] = self.currentSequenceNumber;
  196. }
  197. - (void)removeReference:(const DocumentKey &)key {
  198. _sequenceNumbers[key] = self.currentSequenceNumber;
  199. }
  200. - (BOOL)mutationQueuesContainKey:(const DocumentKey &)key {
  201. const MutationQueues &queues = [_persistence mutationQueues];
  202. for (auto it = queues.begin(); it != queues.end(); ++it) {
  203. if ([it->second containsKey:key]) {
  204. return YES;
  205. }
  206. }
  207. return NO;
  208. }
  209. - (void)removeMutationReference:(const DocumentKey &)key {
  210. _sequenceNumbers[key] = self.currentSequenceNumber;
  211. }
  212. - (BOOL)isPinnedAtSequenceNumber:(ListenSequenceNumber)upperBound
  213. document:(const DocumentKey &)key {
  214. if ([self mutationQueuesContainKey:key]) {
  215. return YES;
  216. }
  217. if ([_additionalReferences containsKey:key]) {
  218. return YES;
  219. }
  220. if ([_persistence.queryCache containsKey:key]) {
  221. return YES;
  222. }
  223. auto it = _sequenceNumbers.find(key);
  224. if (it != _sequenceNumbers.end() && it->second > upperBound) {
  225. return YES;
  226. }
  227. return NO;
  228. }
  229. @end
  230. @implementation FSTMemoryEagerReferenceDelegate {
  231. std::unique_ptr<std::unordered_set<DocumentKey, DocumentKeyHash>> _orphaned;
  232. // This delegate should have the same lifetime as the persistence layer, but mark as
  233. // weak to avoid retain cycle.
  234. __weak FSTMemoryPersistence *_persistence;
  235. FSTReferenceSet *_additionalReferences;
  236. }
  237. - (instancetype)initWithPersistence:(FSTMemoryPersistence *)persistence {
  238. if (self = [super init]) {
  239. _persistence = persistence;
  240. }
  241. return self;
  242. }
  243. - (ListenSequenceNumber)currentSequenceNumber {
  244. return kFSTListenSequenceNumberInvalid;
  245. }
  246. - (void)addInMemoryPins:(FSTReferenceSet *)set {
  247. // We should be able to assert that _additionalReferences is nil, but due to restarts in spec
  248. // tests it would fail.
  249. _additionalReferences = set;
  250. }
  251. - (void)removeTarget:(FSTQueryData *)queryData {
  252. for (const DocumentKey &docKey :
  253. [_persistence.queryCache matchingKeysForTargetID:queryData.targetID]) {
  254. _orphaned->insert(docKey);
  255. }
  256. [_persistence.queryCache removeQueryData:queryData];
  257. }
  258. - (void)addReference:(const DocumentKey &)key {
  259. _orphaned->erase(key);
  260. }
  261. - (void)removeReference:(const DocumentKey &)key {
  262. _orphaned->insert(key);
  263. }
  264. - (void)removeMutationReference:(const DocumentKey &)key {
  265. _orphaned->insert(key);
  266. }
  267. - (BOOL)isReferenced:(const DocumentKey &)key {
  268. if ([[_persistence queryCache] containsKey:key]) {
  269. return YES;
  270. }
  271. if ([self mutationQueuesContainKey:key]) {
  272. return YES;
  273. }
  274. if ([_additionalReferences containsKey:key]) {
  275. return YES;
  276. }
  277. return NO;
  278. }
  279. - (void)limboDocumentUpdated:(const DocumentKey &)key {
  280. if ([self isReferenced:key]) {
  281. _orphaned->erase(key);
  282. } else {
  283. _orphaned->insert(key);
  284. }
  285. }
  286. - (void)startTransaction:(__unused absl::string_view)label {
  287. _orphaned = absl::make_unique<std::unordered_set<DocumentKey, DocumentKeyHash>>();
  288. }
  289. - (BOOL)mutationQueuesContainKey:(const DocumentKey &)key {
  290. const MutationQueues &queues = [_persistence mutationQueues];
  291. for (auto it = queues.begin(); it != queues.end(); ++it) {
  292. if ([it->second containsKey:key]) {
  293. return YES;
  294. }
  295. }
  296. return NO;
  297. }
  298. - (void)commitTransaction {
  299. for (auto it = _orphaned->begin(); it != _orphaned->end(); ++it) {
  300. const DocumentKey key = *it;
  301. if (![self isReferenced:key]) {
  302. [[_persistence remoteDocumentCache] removeEntryForKey:key];
  303. }
  304. }
  305. _orphaned.reset();
  306. }
  307. @end
  308. NS_ASSUME_NONNULL_END