FSTMemoryPersistence.mm 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. #include <vector>
  21. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  22. #include "Firestore/core/src/firebase/firestore/local/listen_sequence.h"
  23. #include "Firestore/core/src/firebase/firestore/local/memory_mutation_queue.h"
  24. #include "Firestore/core/src/firebase/firestore/local/memory_query_cache.h"
  25. #include "Firestore/core/src/firebase/firestore/local/memory_remote_document_cache.h"
  26. #include "Firestore/core/src/firebase/firestore/local/reference_set.h"
  27. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  28. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  29. #include "absl/memory/memory.h"
  30. using firebase::firestore::auth::HashUser;
  31. using firebase::firestore::auth::User;
  32. using firebase::firestore::local::ListenSequence;
  33. using firebase::firestore::local::LruParams;
  34. using firebase::firestore::local::MemoryMutationQueue;
  35. using firebase::firestore::local::MemoryQueryCache;
  36. using firebase::firestore::local::MemoryRemoteDocumentCache;
  37. using firebase::firestore::local::ReferenceSet;
  38. using firebase::firestore::model::DocumentKey;
  39. using firebase::firestore::model::DocumentKeyHash;
  40. using firebase::firestore::model::ListenSequenceNumber;
  41. using firebase::firestore::model::TargetId;
  42. using firebase::firestore::util::Status;
  43. using MutationQueues = std::unordered_map<User, std::unique_ptr<MemoryMutationQueue>, HashUser>;
  44. NS_ASSUME_NONNULL_BEGIN
  45. @interface FSTMemoryPersistence ()
  46. - (MemoryQueryCache *)queryCache;
  47. - (MemoryRemoteDocumentCache *)remoteDocumentCache;
  48. - (MemoryMutationQueue *)mutationQueueForUser:(const User &)user;
  49. @property(nonatomic, readonly) MutationQueues &mutationQueues;
  50. @property(nonatomic, assign, getter=isStarted) BOOL started;
  51. // Make this property writable so we can wire up a delegate.
  52. @property(nonatomic, strong) id<FSTReferenceDelegate> referenceDelegate;
  53. @end
  54. @implementation FSTMemoryPersistence {
  55. /**
  56. * The QueryCache representing the persisted cache of queries.
  57. *
  58. * Note that this is retained here to make it easier to write tests affecting both the in-memory
  59. * and LevelDB-backed persistence layers. Tests can create a new FSTLocalStore wrapping this
  60. * FSTPersistence instance and this will make the in-memory persistence layer behave as if it
  61. * were actually persisting values.
  62. */
  63. std::unique_ptr<MemoryQueryCache> _queryCache;
  64. /** The RemoteDocumentCache representing the persisted cache of remote documents. */
  65. MemoryRemoteDocumentCache _remoteDocumentCache;
  66. FSTTransactionRunner _transactionRunner;
  67. id<FSTReferenceDelegate> _referenceDelegate;
  68. }
  69. + (instancetype)persistenceWithEagerGC {
  70. FSTMemoryPersistence *persistence = [[FSTMemoryPersistence alloc] init];
  71. persistence.referenceDelegate =
  72. [[FSTMemoryEagerReferenceDelegate alloc] initWithPersistence:persistence];
  73. return persistence;
  74. }
  75. + (instancetype)persistenceWithLruParams:(firebase::firestore::local::LruParams)lruParams
  76. serializer:(FSTLocalSerializer *)serializer {
  77. FSTMemoryPersistence *persistence = [[FSTMemoryPersistence alloc] init];
  78. persistence.referenceDelegate =
  79. [[FSTMemoryLRUReferenceDelegate alloc] initWithPersistence:persistence
  80. serializer:serializer
  81. lruParams:lruParams];
  82. return persistence;
  83. }
  84. - (instancetype)init {
  85. if (self = [super init]) {
  86. _queryCache = absl::make_unique<MemoryQueryCache>(self);
  87. self.started = YES;
  88. }
  89. return self;
  90. }
  91. - (void)setReferenceDelegate:(id<FSTReferenceDelegate>)referenceDelegate {
  92. _referenceDelegate = referenceDelegate;
  93. id delegate = _referenceDelegate;
  94. if ([delegate conformsToProtocol:@protocol(FSTTransactional)]) {
  95. _transactionRunner.SetBackingPersistence((id<FSTTransactional>)_referenceDelegate);
  96. }
  97. }
  98. - (void)shutdown {
  99. // No durable state to ensure is closed on shutdown.
  100. HARD_ASSERT(self.isStarted, "FSTMemoryPersistence shutdown without start!");
  101. self.started = NO;
  102. }
  103. - (id<FSTReferenceDelegate>)referenceDelegate {
  104. return _referenceDelegate;
  105. }
  106. - (ListenSequenceNumber)currentSequenceNumber {
  107. return [_referenceDelegate currentSequenceNumber];
  108. }
  109. - (const FSTTransactionRunner &)run {
  110. return _transactionRunner;
  111. }
  112. - (MemoryMutationQueue *)mutationQueueForUser:(const User &)user {
  113. const std::unique_ptr<MemoryMutationQueue> &existing = _mutationQueues[user];
  114. if (!existing) {
  115. _mutationQueues[user] = absl::make_unique<MemoryMutationQueue>(self);
  116. return _mutationQueues[user].get();
  117. } else {
  118. return existing.get();
  119. }
  120. }
  121. - (MemoryQueryCache *)queryCache {
  122. return _queryCache.get();
  123. }
  124. - (MemoryRemoteDocumentCache *)remoteDocumentCache {
  125. return &_remoteDocumentCache;
  126. }
  127. @end
  128. @implementation FSTMemoryLRUReferenceDelegate {
  129. // This delegate should have the same lifetime as the persistence layer, but mark as
  130. // weak to avoid retain cycle.
  131. __weak FSTMemoryPersistence *_persistence;
  132. // Tracks sequence numbers of when documents are used. Equivalent to sentinel rows in
  133. // the leveldb implementation.
  134. std::unordered_map<DocumentKey, ListenSequenceNumber, DocumentKeyHash> _sequenceNumbers;
  135. ReferenceSet *_additionalReferences;
  136. FSTLRUGarbageCollector *_gc;
  137. // PORTING NOTE: when this class is ported to C++, this does not need to be a pointer
  138. std::unique_ptr<ListenSequence> _listenSequence;
  139. ListenSequenceNumber _currentSequenceNumber;
  140. FSTLocalSerializer *_serializer;
  141. }
  142. - (instancetype)initWithPersistence:(FSTMemoryPersistence *)persistence
  143. serializer:(FSTLocalSerializer *)serializer
  144. lruParams:(firebase::firestore::local::LruParams)lruParams {
  145. if (self = [super init]) {
  146. _persistence = persistence;
  147. _gc = [[FSTLRUGarbageCollector alloc] initWithDelegate:self params:lruParams];
  148. _currentSequenceNumber = kFSTListenSequenceNumberInvalid;
  149. // Theoretically this is always 0, since this is all in-memory...
  150. ListenSequenceNumber highestSequenceNumber =
  151. _persistence.queryCache->highest_listen_sequence_number();
  152. _listenSequence = absl::make_unique<ListenSequence>(highestSequenceNumber);
  153. _serializer = serializer;
  154. }
  155. return self;
  156. }
  157. - (FSTLRUGarbageCollector *)gc {
  158. return _gc;
  159. }
  160. - (ListenSequenceNumber)currentSequenceNumber {
  161. HARD_ASSERT(_currentSequenceNumber != kFSTListenSequenceNumberInvalid,
  162. "Asking for a sequence number outside of a transaction");
  163. return _currentSequenceNumber;
  164. }
  165. - (void)addInMemoryPins:(ReferenceSet *)set {
  166. // Technically can't assert this, due to restartWithNoopGarbageCollector (for now...)
  167. // FSTAssert(_additionalReferences == nil, @"Overwriting additional references");
  168. _additionalReferences = set;
  169. }
  170. - (void)removeTarget:(FSTQueryData *)queryData {
  171. FSTQueryData *updated = [queryData queryDataByReplacingSnapshotVersion:queryData.snapshotVersion
  172. resumeToken:queryData.resumeToken
  173. sequenceNumber:_currentSequenceNumber];
  174. _persistence.queryCache->UpdateTarget(updated);
  175. }
  176. - (void)limboDocumentUpdated:(const DocumentKey &)key {
  177. _sequenceNumbers[key] = self.currentSequenceNumber;
  178. }
  179. - (void)startTransaction:(absl::string_view)label {
  180. _currentSequenceNumber = _listenSequence->Next();
  181. }
  182. - (void)commitTransaction {
  183. _currentSequenceNumber = kFSTListenSequenceNumberInvalid;
  184. }
  185. - (void)enumerateTargetsUsingBlock:(void (^)(FSTQueryData *queryData, BOOL *stop))block {
  186. return _persistence.queryCache->EnumerateTargets(block);
  187. }
  188. - (void)enumerateMutationsUsingBlock:
  189. (void (^)(const DocumentKey &key, ListenSequenceNumber sequenceNumber, BOOL *stop))block {
  190. BOOL stop = NO;
  191. for (const auto &entry : _sequenceNumbers) {
  192. ListenSequenceNumber sequenceNumber = entry.second;
  193. const DocumentKey &key = entry.first;
  194. // Pass in the exact sequence number as the upper bound so we know it won't be pinned by being
  195. // too recent.
  196. if (![self isPinnedAtSequenceNumber:sequenceNumber document:key]) {
  197. block(key, sequenceNumber, &stop);
  198. }
  199. }
  200. }
  201. - (int)removeTargetsThroughSequenceNumber:(ListenSequenceNumber)sequenceNumber
  202. liveQueries:(const std::unordered_map<TargetId, FSTQueryData *> &)
  203. liveQueries {
  204. return _persistence.queryCache->RemoveTargets(sequenceNumber, liveQueries);
  205. }
  206. - (size_t)sequenceNumberCount {
  207. __block size_t totalCount = _persistence.queryCache->size();
  208. [self enumerateMutationsUsingBlock:^(const DocumentKey &key, ListenSequenceNumber sequenceNumber,
  209. BOOL *stop) {
  210. totalCount++;
  211. }];
  212. return totalCount;
  213. }
  214. - (int)removeOrphanedDocumentsThroughSequenceNumber:(ListenSequenceNumber)upperBound {
  215. std::vector<DocumentKey> removed =
  216. _persistence.remoteDocumentCache->RemoveOrphanedDocuments(self, upperBound);
  217. for (const auto &key : removed) {
  218. _sequenceNumbers.erase(key);
  219. }
  220. return static_cast<int>(removed.size());
  221. }
  222. - (void)addReference:(const DocumentKey &)key {
  223. _sequenceNumbers[key] = self.currentSequenceNumber;
  224. }
  225. - (void)removeReference:(const DocumentKey &)key {
  226. _sequenceNumbers[key] = self.currentSequenceNumber;
  227. }
  228. - (BOOL)mutationQueuesContainKey:(const DocumentKey &)key {
  229. const MutationQueues &queues = [_persistence mutationQueues];
  230. for (const auto &entry : queues) {
  231. if (entry.second->ContainsKey(key)) {
  232. return YES;
  233. }
  234. }
  235. return NO;
  236. }
  237. - (void)removeMutationReference:(const DocumentKey &)key {
  238. _sequenceNumbers[key] = self.currentSequenceNumber;
  239. }
  240. - (BOOL)isPinnedAtSequenceNumber:(ListenSequenceNumber)upperBound
  241. document:(const DocumentKey &)key {
  242. if ([self mutationQueuesContainKey:key]) {
  243. return YES;
  244. }
  245. if (_additionalReferences->ContainsKey(key)) {
  246. return YES;
  247. }
  248. if (_persistence.queryCache->Contains(key)) {
  249. return YES;
  250. }
  251. auto it = _sequenceNumbers.find(key);
  252. if (it != _sequenceNumbers.end() && it->second > upperBound) {
  253. return YES;
  254. }
  255. return NO;
  256. }
  257. - (size_t)byteSize {
  258. // Note that this method is only used for testing because this delegate is only
  259. // used for testing. The algorithm here (loop through everything, serialize it
  260. // and count bytes) is inefficient and inexact, but won't run in production.
  261. size_t count = 0;
  262. count += _persistence.queryCache->CalculateByteSize(_serializer);
  263. count += _persistence.remoteDocumentCache->CalculateByteSize(_serializer);
  264. const MutationQueues &queues = [_persistence mutationQueues];
  265. for (const auto &entry : queues) {
  266. count += entry.second->CalculateByteSize(_serializer);
  267. }
  268. return count;
  269. }
  270. @end
  271. @implementation FSTMemoryEagerReferenceDelegate {
  272. std::unique_ptr<std::unordered_set<DocumentKey, DocumentKeyHash>> _orphaned;
  273. // This delegate should have the same lifetime as the persistence layer, but mark as
  274. // weak to avoid retain cycle.
  275. __weak FSTMemoryPersistence *_persistence;
  276. ReferenceSet *_additionalReferences;
  277. }
  278. - (instancetype)initWithPersistence:(FSTMemoryPersistence *)persistence {
  279. if (self = [super init]) {
  280. _persistence = persistence;
  281. }
  282. return self;
  283. }
  284. - (ListenSequenceNumber)currentSequenceNumber {
  285. return kFSTListenSequenceNumberInvalid;
  286. }
  287. - (void)addInMemoryPins:(ReferenceSet *)set {
  288. // We should be able to assert that _additionalReferences is nil, but due to restarts in spec
  289. // tests it would fail.
  290. _additionalReferences = set;
  291. }
  292. - (void)removeTarget:(FSTQueryData *)queryData {
  293. for (const DocumentKey &docKey : _persistence.queryCache->GetMatchingKeys(queryData.targetID)) {
  294. _orphaned->insert(docKey);
  295. }
  296. _persistence.queryCache->RemoveTarget(queryData);
  297. }
  298. - (void)addReference:(const DocumentKey &)key {
  299. _orphaned->erase(key);
  300. }
  301. - (void)removeReference:(const DocumentKey &)key {
  302. _orphaned->insert(key);
  303. }
  304. - (void)removeMutationReference:(const DocumentKey &)key {
  305. _orphaned->insert(key);
  306. }
  307. - (BOOL)isReferenced:(const DocumentKey &)key {
  308. if (_persistence.queryCache->Contains(key)) {
  309. return YES;
  310. }
  311. if ([self mutationQueuesContainKey:key]) {
  312. return YES;
  313. }
  314. if (_additionalReferences->ContainsKey(key)) {
  315. return YES;
  316. }
  317. return NO;
  318. }
  319. - (void)limboDocumentUpdated:(const DocumentKey &)key {
  320. if ([self isReferenced:key]) {
  321. _orphaned->erase(key);
  322. } else {
  323. _orphaned->insert(key);
  324. }
  325. }
  326. - (void)startTransaction:(__unused absl::string_view)label {
  327. _orphaned = absl::make_unique<std::unordered_set<DocumentKey, DocumentKeyHash>>();
  328. }
  329. - (BOOL)mutationQueuesContainKey:(const DocumentKey &)key {
  330. const MutationQueues &queues = [_persistence mutationQueues];
  331. for (const auto &entry : queues) {
  332. if (entry.second->ContainsKey(key)) {
  333. return YES;
  334. }
  335. }
  336. return NO;
  337. }
  338. - (void)commitTransaction {
  339. for (const auto &key : *_orphaned) {
  340. if (![self isReferenced:key]) {
  341. _persistence.remoteDocumentCache->Remove(key);
  342. }
  343. }
  344. _orphaned.reset();
  345. }
  346. @end
  347. NS_ASSUME_NONNULL_END