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::local::TargetCallback;
  42. using firebase::firestore::model::DocumentKey;
  43. using firebase::firestore::model::DocumentKeyHash;
  44. using firebase::firestore::model::ListenSequenceNumber;
  45. using firebase::firestore::model::TargetId;
  46. using firebase::firestore::util::Status;
  47. using MutationQueues = std::unordered_map<User, std::unique_ptr<MemoryMutationQueue>, HashUser>;
  48. NS_ASSUME_NONNULL_BEGIN
  49. @interface FSTMemoryPersistence ()
  50. - (MemoryQueryCache *)queryCache;
  51. - (MemoryRemoteDocumentCache *)remoteDocumentCache;
  52. - (MemoryIndexManager *)indexManager;
  53. - (MemoryMutationQueue *)mutationQueueForUser:(const User &)user;
  54. @property(nonatomic, readonly) MutationQueues &mutationQueues;
  55. @property(nonatomic, assign, getter=isStarted) BOOL started;
  56. // Make this property writable so we can wire up a delegate.
  57. @property(nonatomic, strong) id<FSTReferenceDelegate> referenceDelegate;
  58. @end
  59. @implementation FSTMemoryPersistence {
  60. /**
  61. * The QueryCache representing the persisted cache of queries.
  62. *
  63. * Note that this is retained here to make it easier to write tests affecting both the in-memory
  64. * and LevelDB-backed persistence layers. Tests can create a new FSTLocalStore wrapping this
  65. * FSTPersistence instance and this will make the in-memory persistence layer behave as if it
  66. * were actually persisting values.
  67. */
  68. std::unique_ptr<MemoryQueryCache> _queryCache;
  69. /** The RemoteDocumentCache representing the persisted cache of remote documents. */
  70. std::unique_ptr<MemoryRemoteDocumentCache> _remoteDocumentCache;
  71. MemoryIndexManager _indexManager;
  72. FSTTransactionRunner _transactionRunner;
  73. id<FSTReferenceDelegate> _referenceDelegate;
  74. }
  75. + (instancetype)persistenceWithEagerGC {
  76. FSTMemoryPersistence *persistence = [[FSTMemoryPersistence alloc] init];
  77. persistence.referenceDelegate =
  78. [[FSTMemoryEagerReferenceDelegate alloc] initWithPersistence:persistence];
  79. return persistence;
  80. }
  81. + (instancetype)persistenceWithLruParams:(firebase::firestore::local::LruParams)lruParams
  82. serializer:(FSTLocalSerializer *)serializer {
  83. FSTMemoryPersistence *persistence = [[FSTMemoryPersistence alloc] init];
  84. persistence.referenceDelegate =
  85. [[FSTMemoryLRUReferenceDelegate alloc] initWithPersistence:persistence
  86. serializer:serializer
  87. lruParams:lruParams];
  88. return persistence;
  89. }
  90. - (instancetype)init {
  91. if (self = [super init]) {
  92. _queryCache = absl::make_unique<MemoryQueryCache>(self);
  93. _remoteDocumentCache = absl::make_unique<MemoryRemoteDocumentCache>(self);
  94. self.started = YES;
  95. }
  96. return self;
  97. }
  98. - (void)setReferenceDelegate:(id<FSTReferenceDelegate>)referenceDelegate {
  99. _referenceDelegate = referenceDelegate;
  100. id delegate = _referenceDelegate;
  101. if ([delegate conformsToProtocol:@protocol(FSTTransactional)]) {
  102. _transactionRunner.SetBackingPersistence((id<FSTTransactional>)_referenceDelegate);
  103. }
  104. }
  105. - (void)shutdown {
  106. // No durable state to ensure is closed on shutdown.
  107. HARD_ASSERT(self.isStarted, "FSTMemoryPersistence shutdown without start!");
  108. self.started = NO;
  109. }
  110. - (id<FSTReferenceDelegate>)referenceDelegate {
  111. return _referenceDelegate;
  112. }
  113. - (ListenSequenceNumber)currentSequenceNumber {
  114. return [_referenceDelegate currentSequenceNumber];
  115. }
  116. - (const FSTTransactionRunner &)run {
  117. return _transactionRunner;
  118. }
  119. - (MemoryMutationQueue *)mutationQueueForUser:(const User &)user {
  120. const std::unique_ptr<MemoryMutationQueue> &existing = _mutationQueues[user];
  121. if (!existing) {
  122. _mutationQueues[user] = absl::make_unique<MemoryMutationQueue>(self);
  123. return _mutationQueues[user].get();
  124. } else {
  125. return existing.get();
  126. }
  127. }
  128. - (MemoryQueryCache *)queryCache {
  129. return _queryCache.get();
  130. }
  131. - (MemoryRemoteDocumentCache *)remoteDocumentCache {
  132. return _remoteDocumentCache.get();
  133. }
  134. - (MemoryIndexManager *)indexManager {
  135. return &_indexManager;
  136. }
  137. @end
  138. @implementation FSTMemoryLRUReferenceDelegate {
  139. // This delegate should have the same lifetime as the persistence layer, but mark as
  140. // weak to avoid retain cycle.
  141. __weak FSTMemoryPersistence *_persistence;
  142. // Tracks sequence numbers of when documents are used. Equivalent to sentinel rows in
  143. // the leveldb implementation.
  144. std::unordered_map<DocumentKey, ListenSequenceNumber, DocumentKeyHash> _sequenceNumbers;
  145. ReferenceSet *_additionalReferences;
  146. FSTLRUGarbageCollector *_gc;
  147. // PORTING NOTE: when this class is ported to C++, this does not need to be a pointer
  148. std::unique_ptr<ListenSequence> _listenSequence;
  149. ListenSequenceNumber _currentSequenceNumber;
  150. FSTLocalSerializer *_serializer;
  151. }
  152. - (instancetype)initWithPersistence:(FSTMemoryPersistence *)persistence
  153. serializer:(FSTLocalSerializer *)serializer
  154. lruParams:(firebase::firestore::local::LruParams)lruParams {
  155. if (self = [super init]) {
  156. _persistence = persistence;
  157. _gc = [[FSTLRUGarbageCollector alloc] initWithDelegate:self params:lruParams];
  158. _currentSequenceNumber = kFSTListenSequenceNumberInvalid;
  159. // Theoretically this is always 0, since this is all in-memory...
  160. ListenSequenceNumber highestSequenceNumber =
  161. _persistence.queryCache->highest_listen_sequence_number();
  162. _listenSequence = absl::make_unique<ListenSequence>(highestSequenceNumber);
  163. _serializer = serializer;
  164. }
  165. return self;
  166. }
  167. - (FSTLRUGarbageCollector *)gc {
  168. return _gc;
  169. }
  170. - (ListenSequenceNumber)currentSequenceNumber {
  171. HARD_ASSERT(_currentSequenceNumber != kFSTListenSequenceNumberInvalid,
  172. "Asking for a sequence number outside of a transaction");
  173. return _currentSequenceNumber;
  174. }
  175. - (void)addInMemoryPins:(ReferenceSet *)set {
  176. // Technically can't assert this, due to restartWithNoopGarbageCollector (for now...)
  177. // FSTAssert(_additionalReferences == nil, @"Overwriting additional references");
  178. _additionalReferences = set;
  179. }
  180. - (void)removeTarget:(FSTQueryData *)queryData {
  181. FSTQueryData *updated = [queryData queryDataByReplacingSnapshotVersion:queryData.snapshotVersion
  182. resumeToken:queryData.resumeToken
  183. sequenceNumber:_currentSequenceNumber];
  184. _persistence.queryCache->UpdateTarget(updated);
  185. }
  186. - (void)limboDocumentUpdated:(const DocumentKey &)key {
  187. _sequenceNumbers[key] = self.currentSequenceNumber;
  188. }
  189. - (void)startTransaction:(absl::string_view)label {
  190. _currentSequenceNumber = _listenSequence->Next();
  191. }
  192. - (void)commitTransaction {
  193. _currentSequenceNumber = kFSTListenSequenceNumberInvalid;
  194. }
  195. - (void)enumerateTargetsUsingCallback:(const TargetCallback &)callback {
  196. return _persistence.queryCache->EnumerateTargets(callback);
  197. }
  198. - (void)enumerateMutationsUsingCallback:
  199. (const firebase::firestore::local::OrphanedDocumentCallback &)callback {
  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. callback(key, sequenceNumber);
  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. size_t totalCount = _persistence.queryCache->size();
  217. [self enumerateMutationsUsingCallback:[&totalCount](const DocumentKey &key,
  218. ListenSequenceNumber sequenceNumber) {
  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