FSTLocalStore.mm 20 KB

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