FSTMemoryPersistence.mm 13 KB

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