FSTMemoryPersistence.mm 14 KB

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