FSTLocalStore.mm 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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/FSTLocalStore.h"
  17. #include <set>
  18. #import "FIRTimestamp.h"
  19. #import "Firestore/Source/Core/FSTListenSequence.h"
  20. #import "Firestore/Source/Core/FSTQuery.h"
  21. #import "Firestore/Source/Local/FSTLRUGarbageCollector.h"
  22. #import "Firestore/Source/Local/FSTLocalDocumentsView.h"
  23. #import "Firestore/Source/Local/FSTLocalViewChanges.h"
  24. #import "Firestore/Source/Local/FSTLocalWriteResult.h"
  25. #import "Firestore/Source/Local/FSTMutationQueue.h"
  26. #import "Firestore/Source/Local/FSTPersistence.h"
  27. #import "Firestore/Source/Local/FSTQueryCache.h"
  28. #import "Firestore/Source/Local/FSTQueryData.h"
  29. #import "Firestore/Source/Local/FSTReferenceSet.h"
  30. #import "Firestore/Source/Local/FSTRemoteDocumentCache.h"
  31. #import "Firestore/Source/Model/FSTDocument.h"
  32. #import "Firestore/Source/Model/FSTDocumentDictionary.h"
  33. #import "Firestore/Source/Model/FSTMutation.h"
  34. #import "Firestore/Source/Model/FSTMutationBatch.h"
  35. #import "Firestore/Source/Remote/FSTRemoteEvent.h"
  36. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  37. #include "Firestore/core/src/firebase/firestore/core/target_id_generator.h"
  38. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  39. #include "Firestore/core/src/firebase/firestore/model/snapshot_version.h"
  40. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  41. #include "Firestore/core/src/firebase/firestore/util/log.h"
  42. using firebase::firestore::auth::User;
  43. using firebase::firestore::core::TargetIdGenerator;
  44. using firebase::firestore::local::LruResults;
  45. using firebase::firestore::model::BatchId;
  46. using firebase::firestore::model::DocumentKey;
  47. using firebase::firestore::model::DocumentKeySet;
  48. using firebase::firestore::model::DocumentVersionMap;
  49. using firebase::firestore::model::ListenSequenceNumber;
  50. using firebase::firestore::model::SnapshotVersion;
  51. using firebase::firestore::model::TargetId;
  52. NS_ASSUME_NONNULL_BEGIN
  53. /**
  54. * The maximum time to leave a resume token buffered without writing it out. This value is
  55. * arbitrary: it's long enough to avoid several writes (possibly indefinitely if updates come more
  56. * frequently than this) but short enough that restarting after crashing will still have a pretty
  57. * recent resume token.
  58. */
  59. static const int64_t kResumeTokenMaxAgeSeconds = 5 * 60; // 5 minutes
  60. @interface FSTLocalStore ()
  61. /** Manages our in-memory or durable persistence. */
  62. @property(nonatomic, strong, readonly) id<FSTPersistence> persistence;
  63. /** The set of all mutations that have been sent but not yet been applied to the backend. */
  64. @property(nonatomic, strong) id<FSTMutationQueue> mutationQueue;
  65. /** The set of all cached remote documents. */
  66. @property(nonatomic, strong) id<FSTRemoteDocumentCache> remoteDocumentCache;
  67. /** The "local" view of all documents (layering mutationQueue on top of remoteDocumentCache). */
  68. @property(nonatomic, strong) FSTLocalDocumentsView *localDocuments;
  69. /** The set of document references maintained by any local views. */
  70. @property(nonatomic, strong) FSTReferenceSet *localViewReferences;
  71. /** Maps a query to the data about that query. */
  72. @property(nonatomic, strong) id<FSTQueryCache> queryCache;
  73. /** Maps a targetID to data about its query. */
  74. @property(nonatomic, strong) NSMutableDictionary<NSNumber *, FSTQueryData *> *targetIDs;
  75. @end
  76. @implementation FSTLocalStore {
  77. /** Used to generate targetIDs for queries tracked locally. */
  78. TargetIdGenerator _targetIDGenerator;
  79. }
  80. - (instancetype)initWithPersistence:(id<FSTPersistence>)persistence
  81. initialUser:(const User &)initialUser {
  82. if (self = [super init]) {
  83. _persistence = persistence;
  84. _mutationQueue = [persistence mutationQueueForUser:initialUser];
  85. _remoteDocumentCache = [persistence remoteDocumentCache];
  86. _queryCache = [persistence queryCache];
  87. _localDocuments = [FSTLocalDocumentsView viewWithRemoteDocumentCache:_remoteDocumentCache
  88. mutationQueue:_mutationQueue];
  89. _localViewReferences = [[FSTReferenceSet alloc] init];
  90. [_persistence.referenceDelegate addInMemoryPins:_localViewReferences];
  91. _targetIDs = [NSMutableDictionary dictionary];
  92. _targetIDGenerator = TargetIdGenerator::QueryCacheTargetIdGenerator(0);
  93. }
  94. return self;
  95. }
  96. - (void)start {
  97. [self startMutationQueue];
  98. TargetId targetID = [self.queryCache highestTargetID];
  99. _targetIDGenerator = TargetIdGenerator::QueryCacheTargetIdGenerator(targetID);
  100. }
  101. - (void)startMutationQueue {
  102. self.persistence.run("Start MutationQueue", [&]() { [self.mutationQueue start]; });
  103. }
  104. - (FSTMaybeDocumentDictionary *)userDidChange:(const User &)user {
  105. // Swap out the mutation queue, grabbing the pending mutation batches before and after.
  106. NSArray<FSTMutationBatch *> *oldBatches = self.persistence.run(
  107. "OldBatches",
  108. [&]() -> NSArray<FSTMutationBatch *> * { return [self.mutationQueue allMutationBatches]; });
  109. self.mutationQueue = [self.persistence mutationQueueForUser:user];
  110. [self startMutationQueue];
  111. return self.persistence.run("NewBatches", [&]() -> FSTMaybeDocumentDictionary * {
  112. NSArray<FSTMutationBatch *> *newBatches = [self.mutationQueue allMutationBatches];
  113. // Recreate our LocalDocumentsView using the new MutationQueue.
  114. self.localDocuments =
  115. [FSTLocalDocumentsView viewWithRemoteDocumentCache:self.remoteDocumentCache
  116. mutationQueue:self.mutationQueue];
  117. // Union the old/new changed keys.
  118. DocumentKeySet changedKeys;
  119. for (NSArray<FSTMutationBatch *> *batches in @[ oldBatches, newBatches ]) {
  120. for (FSTMutationBatch *batch in batches) {
  121. for (FSTMutation *mutation in batch.mutations) {
  122. changedKeys = changedKeys.insert(mutation.key);
  123. }
  124. }
  125. }
  126. // Return the set of all (potentially) changed documents as the result of the user change.
  127. return [self.localDocuments documentsForKeys:changedKeys];
  128. });
  129. }
  130. - (FSTLocalWriteResult *)locallyWriteMutations:(NSArray<FSTMutation *> *)mutations {
  131. return self.persistence.run("Locally write mutations", [&]() -> FSTLocalWriteResult * {
  132. FIRTimestamp *localWriteTime = [FIRTimestamp timestamp];
  133. FSTMutationBatch *batch =
  134. [self.mutationQueue addMutationBatchWithWriteTime:localWriteTime mutations:mutations];
  135. DocumentKeySet keys = [batch keys];
  136. FSTMaybeDocumentDictionary *changedDocuments = [self.localDocuments documentsForKeys:keys];
  137. return [FSTLocalWriteResult resultForBatchID:batch.batchID changes:changedDocuments];
  138. });
  139. }
  140. - (FSTMaybeDocumentDictionary *)acknowledgeBatchWithResult:(FSTMutationBatchResult *)batchResult {
  141. return self.persistence.run("Acknowledge batch", [&]() -> FSTMaybeDocumentDictionary * {
  142. id<FSTMutationQueue> mutationQueue = self.mutationQueue;
  143. FSTMutationBatch *batch = batchResult.batch;
  144. [mutationQueue acknowledgeBatch:batch streamToken:batchResult.streamToken];
  145. [self applyBatchResult:batchResult];
  146. [self.mutationQueue performConsistencyCheck];
  147. return [self.localDocuments documentsForKeys:batch.keys];
  148. });
  149. }
  150. - (FSTMaybeDocumentDictionary *)rejectBatchID:(BatchId)batchID {
  151. return self.persistence.run("Reject batch", [&]() -> FSTMaybeDocumentDictionary * {
  152. FSTMutationBatch *toReject = [self.mutationQueue lookupMutationBatch:batchID];
  153. HARD_ASSERT(toReject, "Attempt to reject nonexistent batch!");
  154. BatchId lastAcked = [self.mutationQueue highestAcknowledgedBatchID];
  155. HARD_ASSERT(batchID > lastAcked, "Acknowledged batches can't be rejected.");
  156. [self.mutationQueue removeMutationBatch:toReject];
  157. [self.mutationQueue performConsistencyCheck];
  158. return [self.localDocuments documentsForKeys:toReject.keys];
  159. });
  160. }
  161. - (nullable NSData *)lastStreamToken {
  162. return [self.mutationQueue lastStreamToken];
  163. }
  164. - (void)setLastStreamToken:(nullable NSData *)streamToken {
  165. self.persistence.run("Set stream token",
  166. [&]() { [self.mutationQueue setLastStreamToken:streamToken]; });
  167. }
  168. - (const SnapshotVersion &)lastRemoteSnapshotVersion {
  169. return [self.queryCache lastRemoteSnapshotVersion];
  170. }
  171. - (FSTMaybeDocumentDictionary *)applyRemoteEvent:(FSTRemoteEvent *)remoteEvent {
  172. return self.persistence.run("Apply remote event", [&]() -> FSTMaybeDocumentDictionary * {
  173. // TODO(gsoltis): move the sequence number into the reference delegate.
  174. ListenSequenceNumber sequenceNumber = self.persistence.currentSequenceNumber;
  175. id<FSTQueryCache> queryCache = self.queryCache;
  176. DocumentKeySet authoritativeUpdates;
  177. for (const auto &entry : remoteEvent.targetChanges) {
  178. TargetId targetID = entry.first;
  179. FSTBoxedTargetID *boxedTargetID = @(targetID);
  180. FSTTargetChange *change = entry.second;
  181. // Do not ref/unref unassigned targetIDs - it may lead to leaks.
  182. FSTQueryData *queryData = self.targetIDs[boxedTargetID];
  183. if (!queryData) {
  184. continue;
  185. }
  186. // When a global snapshot contains updates (either add or modify) we can completely trust
  187. // these updates as authoritative and blindly apply them to our cache (as a defensive measure
  188. // to promote self-healing in the unfortunate case that our cache is ever somehow corrupted /
  189. // out-of-sync).
  190. //
  191. // If the document is only updated while removing it from a target then watch isn't obligated
  192. // to send the absolute latest version: it can send the first version that caused the document
  193. // not to match.
  194. for (const DocumentKey &key : change.addedDocuments) {
  195. authoritativeUpdates = authoritativeUpdates.insert(key);
  196. }
  197. for (const DocumentKey &key : change.modifiedDocuments) {
  198. authoritativeUpdates = authoritativeUpdates.insert(key);
  199. }
  200. [queryCache removeMatchingKeys:change.removedDocuments forTargetID:targetID];
  201. [queryCache addMatchingKeys:change.addedDocuments forTargetID:targetID];
  202. // Update the resume token if the change includes one. Don't clear any preexisting value.
  203. // Bump the sequence number as well, so that documents being removed now are ordered later
  204. // than documents that were previously removed from this target.
  205. NSData *resumeToken = change.resumeToken;
  206. if (resumeToken.length > 0) {
  207. FSTQueryData *oldQueryData = queryData;
  208. queryData = [queryData queryDataByReplacingSnapshotVersion:remoteEvent.snapshotVersion
  209. resumeToken:resumeToken
  210. sequenceNumber:sequenceNumber];
  211. self.targetIDs[boxedTargetID] = queryData;
  212. if ([self shouldPersistQueryData:queryData oldQueryData:oldQueryData change:change]) {
  213. [self.queryCache updateQueryData:queryData];
  214. }
  215. }
  216. }
  217. // TODO(klimt): This could probably be an NSMutableDictionary.
  218. DocumentKeySet changedDocKeys;
  219. const DocumentKeySet &limboDocuments = remoteEvent.limboDocumentChanges;
  220. for (const auto &kv : remoteEvent.documentUpdates) {
  221. const DocumentKey &key = kv.first;
  222. FSTMaybeDocument *doc = kv.second;
  223. changedDocKeys = changedDocKeys.insert(key);
  224. FSTMaybeDocument *existingDoc = [self.remoteDocumentCache entryForKey:key];
  225. // If a document update isn't authoritative, make sure we don't apply an old document version
  226. // to the remote cache. We make an exception for SnapshotVersion.MIN which can happen for
  227. // manufactured events (e.g. in the case of a limbo document resolution failing).
  228. if (!existingDoc || doc.version == SnapshotVersion::None() ||
  229. (authoritativeUpdates.contains(doc.key) && !existingDoc.hasPendingWrites) ||
  230. doc.version >= existingDoc.version) {
  231. [self.remoteDocumentCache addEntry:doc];
  232. } else {
  233. LOG_DEBUG(
  234. "FSTLocalStore Ignoring outdated watch update for %s. "
  235. "Current version: %s Watch version: %s",
  236. key.ToString(), existingDoc.version.timestamp().ToString(),
  237. doc.version.timestamp().ToString());
  238. }
  239. // If this was a limbo resolution, make sure we mark when it was accessed.
  240. if (limboDocuments.contains(key)) {
  241. [self.persistence.referenceDelegate limboDocumentUpdated:key];
  242. }
  243. }
  244. // HACK: The only reason we allow omitting snapshot version is so we can synthesize remote
  245. // events when we get permission denied errors while trying to resolve the state of a locally
  246. // cached document that is in limbo.
  247. const SnapshotVersion &lastRemoteVersion = [self.queryCache lastRemoteSnapshotVersion];
  248. const SnapshotVersion &remoteVersion = remoteEvent.snapshotVersion;
  249. if (remoteVersion != SnapshotVersion::None()) {
  250. HARD_ASSERT(remoteVersion >= lastRemoteVersion,
  251. "Watch stream reverted to previous snapshot?? (%s < %s)",
  252. remoteVersion.timestamp().ToString(), lastRemoteVersion.timestamp().ToString());
  253. [self.queryCache setLastRemoteSnapshotVersion:remoteVersion];
  254. }
  255. return [self.localDocuments documentsForKeys:changedDocKeys];
  256. });
  257. }
  258. /**
  259. * Returns YES if the newQueryData should be persisted during an update of an active target.
  260. * QueryData should always be persisted when a target is being released and should not call this
  261. * function.
  262. *
  263. * While the target is active, QueryData updates can be omitted when nothing about the target has
  264. * changed except metadata like the resume token or snapshot version. Occasionally it's worth the
  265. * extra write to prevent these values from getting too stale after a crash, but this doesn't have
  266. * to be too frequent.
  267. */
  268. - (BOOL)shouldPersistQueryData:(FSTQueryData *)newQueryData
  269. oldQueryData:(FSTQueryData *)oldQueryData
  270. change:(FSTTargetChange *)change {
  271. // Avoid clearing any existing value
  272. if (newQueryData.resumeToken.length == 0) return NO;
  273. // Any resume token is interesting if there isn't one already.
  274. if (oldQueryData.resumeToken.length == 0) return YES;
  275. // Don't allow resume token changes to be buffered indefinitely. This allows us to be reasonably
  276. // up-to-date after a crash and avoids needing to loop over all active queries on shutdown.
  277. // Especially in the browser we may not get time to do anything interesting while the current
  278. // tab is closing.
  279. int64_t newSeconds = newQueryData.snapshotVersion.timestamp().seconds();
  280. int64_t oldSeconds = oldQueryData.snapshotVersion.timestamp().seconds();
  281. int64_t timeDelta = newSeconds - oldSeconds;
  282. if (timeDelta >= kResumeTokenMaxAgeSeconds) return YES;
  283. // Otherwise if the only thing that has changed about a target is its resume token then it's not
  284. // worth persisting. Note that the RemoteStore keeps an in-memory view of the currently active
  285. // targets which includes the current resume token, so stream failure or user changes will still
  286. // use an up-to-date resume token regardless of what we do here.
  287. size_t changes = change.addedDocuments.size() + change.modifiedDocuments.size() +
  288. change.removedDocuments.size();
  289. return changes > 0;
  290. }
  291. - (void)notifyLocalViewChanges:(NSArray<FSTLocalViewChanges *> *)viewChanges {
  292. self.persistence.run("NotifyLocalViewChanges", [&]() {
  293. FSTReferenceSet *localViewReferences = self.localViewReferences;
  294. for (FSTLocalViewChanges *viewChange in viewChanges) {
  295. for (const DocumentKey &key : viewChange.removedKeys) {
  296. [self->_persistence.referenceDelegate removeReference:key];
  297. }
  298. [localViewReferences addReferencesToKeys:viewChange.addedKeys forID:viewChange.targetID];
  299. [localViewReferences removeReferencesToKeys:viewChange.removedKeys forID:viewChange.targetID];
  300. }
  301. });
  302. }
  303. - (nullable FSTMutationBatch *)nextMutationBatchAfterBatchID:(BatchId)batchID {
  304. FSTMutationBatch *result =
  305. self.persistence.run("NextMutationBatchAfterBatchID", [&]() -> FSTMutationBatch * {
  306. return [self.mutationQueue nextMutationBatchAfterBatchID:batchID];
  307. });
  308. return result;
  309. }
  310. - (nullable FSTMaybeDocument *)readDocument:(const DocumentKey &)key {
  311. return self.persistence.run("ReadDocument", [&]() -> FSTMaybeDocument *_Nullable {
  312. return [self.localDocuments documentForKey:key];
  313. });
  314. }
  315. - (FSTQueryData *)allocateQuery:(FSTQuery *)query {
  316. FSTQueryData *queryData = self.persistence.run("Allocate query", [&]() -> FSTQueryData * {
  317. FSTQueryData *cached = [self.queryCache queryDataForQuery:query];
  318. // TODO(mcg): freshen last accessed date if cached exists?
  319. if (!cached) {
  320. cached = [[FSTQueryData alloc] initWithQuery:query
  321. targetID:_targetIDGenerator.NextId()
  322. listenSequenceNumber:self.persistence.currentSequenceNumber
  323. purpose:FSTQueryPurposeListen];
  324. [self.queryCache addQueryData:cached];
  325. }
  326. return cached;
  327. });
  328. // Sanity check to ensure that even when resuming a query it's not currently active.
  329. FSTBoxedTargetID *boxedTargetID = @(queryData.targetID);
  330. HARD_ASSERT(!self.targetIDs[boxedTargetID], "Tried to allocate an already allocated query: %s",
  331. query);
  332. self.targetIDs[boxedTargetID] = queryData;
  333. return queryData;
  334. }
  335. - (void)releaseQuery:(FSTQuery *)query {
  336. self.persistence.run("Release query", [&]() {
  337. FSTQueryData *queryData = [self.queryCache queryDataForQuery:query];
  338. HARD_ASSERT(queryData, "Tried to release nonexistent query: %s", query);
  339. TargetId targetID = queryData.targetID;
  340. FSTBoxedTargetID *boxedTargetID = @(targetID);
  341. FSTQueryData *cachedQueryData = self.targetIDs[boxedTargetID];
  342. if (cachedQueryData.snapshotVersion > queryData.snapshotVersion) {
  343. // If we've been avoiding persisting the resumeToken (see shouldPersistQueryData for
  344. // conditions and rationale) we need to persist the token now because there will no
  345. // longer be an in-memory version to fall back on.
  346. queryData = cachedQueryData;
  347. [self.queryCache updateQueryData:queryData];
  348. }
  349. // References for documents sent via Watch are automatically removed when we delete a
  350. // query's target data from the reference delegate. Since this does not remove references
  351. // for locally mutated documents, we have to remove the target associations for these
  352. // documents manually.
  353. DocumentKeySet removed = [self.localViewReferences removeReferencesForID:targetID];
  354. for (const DocumentKey &key : removed) {
  355. [self.persistence.referenceDelegate removeReference:key];
  356. }
  357. [self.targetIDs removeObjectForKey:boxedTargetID];
  358. [self.persistence.referenceDelegate removeTarget:queryData];
  359. });
  360. }
  361. - (FSTDocumentDictionary *)executeQuery:(FSTQuery *)query {
  362. return self.persistence.run("ExecuteQuery", [&]() -> FSTDocumentDictionary * {
  363. return [self.localDocuments documentsMatchingQuery:query];
  364. });
  365. }
  366. - (DocumentKeySet)remoteDocumentKeysForTarget:(TargetId)targetID {
  367. return self.persistence.run("RemoteDocumentKeysForTarget", [&]() -> DocumentKeySet {
  368. return [self.queryCache matchingKeysForTargetID:targetID];
  369. });
  370. }
  371. - (void)applyBatchResult:(FSTMutationBatchResult *)batchResult {
  372. FSTMutationBatch *batch = batchResult.batch;
  373. DocumentKeySet docKeys = batch.keys;
  374. const DocumentVersionMap &versions = batchResult.docVersions;
  375. for (const DocumentKey &docKey : docKeys) {
  376. FSTMaybeDocument *_Nullable remoteDoc = [self.remoteDocumentCache entryForKey:docKey];
  377. FSTMaybeDocument *_Nullable doc = remoteDoc;
  378. auto ackVersionIter = versions.find(docKey);
  379. HARD_ASSERT(ackVersionIter != versions.end(),
  380. "docVersions should contain every doc in the write.");
  381. const SnapshotVersion &ackVersion = ackVersionIter->second;
  382. if (!doc || doc.version < ackVersion) {
  383. doc = [batch applyToRemoteDocument:doc documentKey:docKey mutationBatchResult:batchResult];
  384. if (!doc) {
  385. HARD_ASSERT(!remoteDoc, "Mutation batch %s applied to document %s resulted in nil.", batch,
  386. remoteDoc);
  387. } else {
  388. [self.remoteDocumentCache addEntry:doc];
  389. }
  390. }
  391. }
  392. [self.mutationQueue removeMutationBatch:batch];
  393. }
  394. - (LruResults)collectGarbage:(FSTLRUGarbageCollector *)garbageCollector {
  395. return self.persistence.run("Collect garbage", [&]() -> LruResults {
  396. return [garbageCollector collectWithLiveTargets:_targetIDs];
  397. });
  398. }
  399. @end
  400. NS_ASSUME_NONNULL_END