FSTMemoryPersistence.mm 13 KB

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