FSTLocalStore.mm 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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/FSTGarbageCollector.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::model::DocumentKey;
  45. using firebase::firestore::model::SnapshotVersion;
  46. using firebase::firestore::model::DocumentKeySet;
  47. using firebase::firestore::model::DocumentVersionMap;
  48. NS_ASSUME_NONNULL_BEGIN
  49. @interface FSTLocalStore ()
  50. /** Manages our in-memory or durable persistence. */
  51. @property(nonatomic, strong, readonly) id<FSTPersistence> persistence;
  52. /** The set of all mutations that have been sent but not yet been applied to the backend. */
  53. @property(nonatomic, strong) id<FSTMutationQueue> mutationQueue;
  54. /** The set of all cached remote documents. */
  55. @property(nonatomic, strong) id<FSTRemoteDocumentCache> remoteDocumentCache;
  56. /** The "local" view of all documents (layering mutationQueue on top of remoteDocumentCache). */
  57. @property(nonatomic, strong) FSTLocalDocumentsView *localDocuments;
  58. /** The set of document references maintained by any local views. */
  59. @property(nonatomic, strong) FSTReferenceSet *localViewReferences;
  60. /**
  61. * The garbage collector collects documents that should no longer be cached (e.g. if they are no
  62. * longer retained by the above reference sets and the garbage collector is performing eager
  63. * collection).
  64. */
  65. @property(nonatomic, strong) id<FSTGarbageCollector> garbageCollector;
  66. /** Maps a query to the data about that query. */
  67. @property(nonatomic, strong) id<FSTQueryCache> queryCache;
  68. /** Maps a targetID to data about its query. */
  69. @property(nonatomic, strong) NSMutableDictionary<NSNumber *, FSTQueryData *> *targetIDs;
  70. @property(nonatomic, strong) FSTListenSequence *listenSequence;
  71. /**
  72. * A heldBatchResult is a mutation batch result (from a write acknowledgement) that arrived before
  73. * the watch stream got notified of a snapshot that includes the write.  So we "hold" it until
  74. * the watch stream catches up. It ensures that the local write remains visible (latency
  75. * compensation) and doesn't temporarily appear reverted because the watch stream is slower than
  76. * the write stream and so wasn't reflecting it.
  77. *
  78. * NOTE: Eventually we want to move this functionality into the remote store.
  79. */
  80. @property(nonatomic, strong) NSMutableArray<FSTMutationBatchResult *> *heldBatchResults;
  81. @end
  82. @implementation FSTLocalStore {
  83. /** Used to generate targetIDs for queries tracked locally. */
  84. TargetIdGenerator _targetIDGenerator;
  85. }
  86. - (instancetype)initWithPersistence:(id<FSTPersistence>)persistence
  87. garbageCollector:(id<FSTGarbageCollector>)garbageCollector
  88. initialUser:(const User &)initialUser {
  89. if (self = [super init]) {
  90. _persistence = persistence;
  91. _mutationQueue = [persistence mutationQueueForUser:initialUser];
  92. _remoteDocumentCache = [persistence remoteDocumentCache];
  93. _queryCache = [persistence queryCache];
  94. _localDocuments = [FSTLocalDocumentsView viewWithRemoteDocumentCache:_remoteDocumentCache
  95. mutationQueue:_mutationQueue];
  96. _localViewReferences = [[FSTReferenceSet alloc] init];
  97. [_persistence.referenceDelegate addInMemoryPins:_localViewReferences];
  98. _garbageCollector = garbageCollector;
  99. [_garbageCollector addGarbageSource:_queryCache];
  100. [_garbageCollector addGarbageSource:_localViewReferences];
  101. [_garbageCollector addGarbageSource:_mutationQueue];
  102. _targetIDs = [NSMutableDictionary dictionary];
  103. _heldBatchResults = [NSMutableArray array];
  104. _targetIDGenerator = TargetIdGenerator::LocalStoreTargetIdGenerator(0);
  105. }
  106. return self;
  107. }
  108. - (void)start {
  109. [self startMutationQueue];
  110. [self startQueryCache];
  111. }
  112. - (void)startMutationQueue {
  113. self.persistence.run("Start MutationQueue", [&]() {
  114. [self.mutationQueue start];
  115. // If we have any leftover mutation batch results from a prior run, just drop them.
  116. // TODO(http://b/33446471): We probably need to repopulate heldBatchResults or similar instead,
  117. // but that is not straightforward since we're not persisting the write ack versions.
  118. [self.heldBatchResults removeAllObjects];
  119. // TODO(mikelehen): This is the only usage of getAllMutationBatchesThroughBatchId:. Consider
  120. // removing it in favor of a getAcknowledgedBatches method.
  121. FSTBatchID highestAck = [self.mutationQueue highestAcknowledgedBatchID];
  122. if (highestAck != kFSTBatchIDUnknown) {
  123. NSArray<FSTMutationBatch *> *batches =
  124. [self.mutationQueue allMutationBatchesThroughBatchID:highestAck];
  125. if (batches.count > 0) {
  126. // NOTE: This could be more efficient if we had a removeBatchesThroughBatchID, but this set
  127. // should be very small and this code should go away eventually.
  128. [self.mutationQueue removeMutationBatches:batches];
  129. }
  130. }
  131. });
  132. }
  133. - (void)startQueryCache {
  134. [self.queryCache start];
  135. FSTTargetID targetID = [self.queryCache highestTargetID];
  136. _targetIDGenerator = TargetIdGenerator::LocalStoreTargetIdGenerator(targetID);
  137. FSTListenSequenceNumber sequenceNumber = [self.queryCache highestListenSequenceNumber];
  138. self.listenSequence = [[FSTListenSequence alloc] initStartingAfter:sequenceNumber];
  139. }
  140. - (FSTMaybeDocumentDictionary *)userDidChange:(const User &)user {
  141. // Swap out the mutation queue, grabbing the pending mutation batches before and after.
  142. NSArray<FSTMutationBatch *> *oldBatches = self.persistence.run(
  143. "OldBatches",
  144. [&]() -> NSArray<FSTMutationBatch *> * { return [self.mutationQueue allMutationBatches]; });
  145. [self.garbageCollector removeGarbageSource:self.mutationQueue];
  146. self.mutationQueue = [self.persistence mutationQueueForUser:user];
  147. [self.garbageCollector addGarbageSource:self.mutationQueue];
  148. [self startMutationQueue];
  149. return self.persistence.run("NewBatches", [&]() -> FSTMaybeDocumentDictionary * {
  150. NSArray<FSTMutationBatch *> *newBatches = [self.mutationQueue allMutationBatches];
  151. // Recreate our LocalDocumentsView using the new MutationQueue.
  152. self.localDocuments =
  153. [FSTLocalDocumentsView viewWithRemoteDocumentCache:self.remoteDocumentCache
  154. mutationQueue:self.mutationQueue];
  155. // Union the old/new changed keys.
  156. DocumentKeySet changedKeys;
  157. for (NSArray<FSTMutationBatch *> *batches in @[ oldBatches, newBatches ]) {
  158. for (FSTMutationBatch *batch in batches) {
  159. for (FSTMutation *mutation in batch.mutations) {
  160. changedKeys = changedKeys.insert(mutation.key);
  161. }
  162. }
  163. }
  164. // Return the set of all (potentially) changed documents as the result of the user change.
  165. return [self.localDocuments documentsForKeys:changedKeys];
  166. });
  167. }
  168. - (FSTLocalWriteResult *)locallyWriteMutations:(NSArray<FSTMutation *> *)mutations {
  169. return self.persistence.run("Locally write mutations", [&]() -> FSTLocalWriteResult * {
  170. FIRTimestamp *localWriteTime = [FIRTimestamp timestamp];
  171. FSTMutationBatch *batch =
  172. [self.mutationQueue addMutationBatchWithWriteTime:localWriteTime mutations:mutations];
  173. DocumentKeySet keys = [batch keys];
  174. FSTMaybeDocumentDictionary *changedDocuments = [self.localDocuments documentsForKeys:keys];
  175. return [FSTLocalWriteResult resultForBatchID:batch.batchID changes:changedDocuments];
  176. });
  177. }
  178. - (FSTMaybeDocumentDictionary *)acknowledgeBatchWithResult:(FSTMutationBatchResult *)batchResult {
  179. return self.persistence.run("Acknowledge batch", [&]() -> FSTMaybeDocumentDictionary * {
  180. id<FSTMutationQueue> mutationQueue = self.mutationQueue;
  181. [mutationQueue acknowledgeBatch:batchResult.batch streamToken:batchResult.streamToken];
  182. DocumentKeySet affected;
  183. if ([self shouldHoldBatchResultWithVersion:batchResult.commitVersion]) {
  184. [self.heldBatchResults addObject:batchResult];
  185. } else {
  186. affected = [self releaseBatchResults:@[ batchResult ]];
  187. }
  188. [self.mutationQueue performConsistencyCheck];
  189. return [self.localDocuments documentsForKeys:affected];
  190. });
  191. }
  192. - (FSTMaybeDocumentDictionary *)rejectBatchID:(FSTBatchID)batchID {
  193. return self.persistence.run("Reject batch", [&]() -> FSTMaybeDocumentDictionary * {
  194. FSTMutationBatch *toReject = [self.mutationQueue lookupMutationBatch:batchID];
  195. HARD_ASSERT(toReject, "Attempt to reject nonexistent batch!");
  196. FSTBatchID lastAcked = [self.mutationQueue highestAcknowledgedBatchID];
  197. HARD_ASSERT(batchID > lastAcked, "Acknowledged batches can't be rejected.");
  198. DocumentKeySet affected = [self removeMutationBatch:toReject];
  199. [self.mutationQueue performConsistencyCheck];
  200. return [self.localDocuments documentsForKeys:affected];
  201. });
  202. }
  203. - (nullable NSData *)lastStreamToken {
  204. return [self.mutationQueue lastStreamToken];
  205. }
  206. - (void)setLastStreamToken:(nullable NSData *)streamToken {
  207. self.persistence.run("Set stream token",
  208. [&]() { [self.mutationQueue setLastStreamToken:streamToken]; });
  209. }
  210. - (const SnapshotVersion &)lastRemoteSnapshotVersion {
  211. return [self.queryCache lastRemoteSnapshotVersion];
  212. }
  213. - (FSTMaybeDocumentDictionary *)applyRemoteEvent:(FSTRemoteEvent *)remoteEvent {
  214. return self.persistence.run("Apply remote event", [&]() -> FSTMaybeDocumentDictionary * {
  215. // TODO(gsoltis): move the sequence number into the reference delegate.
  216. FSTListenSequenceNumber sequenceNumber = [self.listenSequence next];
  217. id<FSTQueryCache> queryCache = self.queryCache;
  218. DocumentKeySet authoritativeUpdates;
  219. for (const auto &entry : remoteEvent.targetChanges) {
  220. FSTTargetID targetID = entry.first;
  221. FSTBoxedTargetID *boxedTargetID = @(targetID);
  222. FSTTargetChange *change = entry.second;
  223. // Do not ref/unref unassigned targetIDs - it may lead to leaks.
  224. FSTQueryData *queryData = self.targetIDs[boxedTargetID];
  225. if (!queryData) {
  226. continue;
  227. }
  228. // When a global snapshot contains updates (either add or modify) we can completely trust
  229. // these updates as authoritative and blindly apply them to our cache (as a defensive measure
  230. // to promote self-healing in the unfortunate case that our cache is ever somehow corrupted /
  231. // out-of-sync).
  232. //
  233. // If the document is only updated while removing it from a target then watch isn't obligated
  234. // to send the absolute latest version: it can send the first version that caused the document
  235. // not to match.
  236. for (const DocumentKey &key : change.addedDocuments) {
  237. authoritativeUpdates = authoritativeUpdates.insert(key);
  238. }
  239. for (const DocumentKey &key : change.modifiedDocuments) {
  240. authoritativeUpdates = authoritativeUpdates.insert(key);
  241. }
  242. [queryCache removeMatchingKeys:change.removedDocuments forTargetID:targetID];
  243. [queryCache addMatchingKeys:change.addedDocuments forTargetID:targetID];
  244. // Update the resume token if the change includes one. Don't clear any preexisting value.
  245. // Bump the sequence number as well, so that documents being removed now are ordered later
  246. // than documents that were previously removed from this target.
  247. NSData *resumeToken = change.resumeToken;
  248. if (resumeToken.length > 0) {
  249. queryData = [queryData queryDataByReplacingSnapshotVersion:remoteEvent.snapshotVersion
  250. resumeToken:resumeToken
  251. sequenceNumber:sequenceNumber];
  252. self.targetIDs[boxedTargetID] = queryData;
  253. [self.queryCache updateQueryData:queryData];
  254. }
  255. }
  256. // TODO(klimt): This could probably be an NSMutableDictionary.
  257. DocumentKeySet changedDocKeys;
  258. const DocumentKeySet &limboDocuments = remoteEvent.limboDocumentChanges;
  259. for (const auto &kv : remoteEvent.documentUpdates) {
  260. const DocumentKey &key = kv.first;
  261. FSTMaybeDocument *doc = kv.second;
  262. changedDocKeys = changedDocKeys.insert(key);
  263. FSTMaybeDocument *existingDoc = [self.remoteDocumentCache entryForKey:key];
  264. // If a document update isn't authoritative, make sure we don't apply an old document version
  265. // to the remote cache. We make an exception for SnapshotVersion.MIN which can happen for
  266. // manufactured events (e.g. in the case of a limbo document resolution failing).
  267. if (!existingDoc || doc.version == SnapshotVersion::None() ||
  268. authoritativeUpdates.contains(doc.key) || doc.version >= existingDoc.version) {
  269. [self.remoteDocumentCache addEntry:doc];
  270. } else {
  271. LOG_DEBUG(
  272. "FSTLocalStore Ignoring outdated watch update for %s. "
  273. "Current version: %s Watch version: %s",
  274. key.ToString(), existingDoc.version.timestamp().ToString(),
  275. doc.version.timestamp().ToString());
  276. }
  277. // The document might be garbage because it was unreferenced by everything.
  278. // Make sure to mark it as garbage if it is...
  279. [self.garbageCollector addPotentialGarbageKey:key];
  280. if (limboDocuments.contains(key)) {
  281. [self.persistence.referenceDelegate limboDocumentUpdated:key];
  282. }
  283. }
  284. // HACK: The only reason we allow omitting snapshot version is so we can synthesize remote
  285. // events when we get permission denied errors while trying to resolve the state of a locally
  286. // cached document that is in limbo.
  287. const SnapshotVersion &lastRemoteVersion = [self.queryCache lastRemoteSnapshotVersion];
  288. const SnapshotVersion &remoteVersion = remoteEvent.snapshotVersion;
  289. if (remoteVersion != SnapshotVersion::None()) {
  290. HARD_ASSERT(remoteVersion >= lastRemoteVersion,
  291. "Watch stream reverted to previous snapshot?? (%s < %s)",
  292. remoteVersion.timestamp().ToString(), lastRemoteVersion.timestamp().ToString());
  293. [self.queryCache setLastRemoteSnapshotVersion:remoteVersion];
  294. }
  295. DocumentKeySet releasedWriteKeys = [self releaseHeldBatchResults];
  296. // Union the two key sets.
  297. DocumentKeySet keysToRecalc = changedDocKeys;
  298. for (const DocumentKey &key : releasedWriteKeys) {
  299. keysToRecalc = keysToRecalc.insert(key);
  300. }
  301. return [self.localDocuments documentsForKeys:keysToRecalc];
  302. });
  303. }
  304. - (void)notifyLocalViewChanges:(NSArray<FSTLocalViewChanges *> *)viewChanges {
  305. self.persistence.run("NotifyLocalViewChanges", [&]() {
  306. FSTReferenceSet *localViewReferences = self.localViewReferences;
  307. for (FSTLocalViewChanges *view in viewChanges) {
  308. FSTQueryData *queryData = [self.queryCache queryDataForQuery:view.query];
  309. HARD_ASSERT(queryData, "Local view changes contain unallocated query.");
  310. FSTTargetID targetID = queryData.targetID;
  311. for (const DocumentKey &key : view.removedKeys) {
  312. [self->_persistence.referenceDelegate removeReference:key target:targetID];
  313. }
  314. [localViewReferences addReferencesToKeys:view.addedKeys forID:targetID];
  315. [localViewReferences removeReferencesToKeys:view.removedKeys forID:targetID];
  316. }
  317. });
  318. }
  319. - (nullable FSTMutationBatch *)nextMutationBatchAfterBatchID:(FSTBatchID)batchID {
  320. FSTMutationBatch *result =
  321. self.persistence.run("NextMutationBatchAfterBatchID", [&]() -> FSTMutationBatch * {
  322. return [self.mutationQueue nextMutationBatchAfterBatchID:batchID];
  323. });
  324. return result;
  325. }
  326. - (nullable FSTMaybeDocument *)readDocument:(const DocumentKey &)key {
  327. return self.persistence.run("ReadDocument", [&]() -> FSTMaybeDocument *_Nullable {
  328. return [self.localDocuments documentForKey:key];
  329. });
  330. }
  331. - (FSTQueryData *)allocateQuery:(FSTQuery *)query {
  332. FSTQueryData *queryData = self.persistence.run("Allocate query", [&]() -> FSTQueryData * {
  333. FSTQueryData *cached = [self.queryCache queryDataForQuery:query];
  334. // TODO(mcg): freshen last accessed date if cached exists?
  335. if (!cached) {
  336. cached = [[FSTQueryData alloc] initWithQuery:query
  337. targetID:_targetIDGenerator.NextId()
  338. listenSequenceNumber:[self.listenSequence next]
  339. purpose:FSTQueryPurposeListen];
  340. [self.queryCache addQueryData:cached];
  341. }
  342. return cached;
  343. });
  344. // Sanity check to ensure that even when resuming a query it's not currently active.
  345. FSTBoxedTargetID *boxedTargetID = @(queryData.targetID);
  346. HARD_ASSERT(!self.targetIDs[boxedTargetID], "Tried to allocate an already allocated query: %s",
  347. query);
  348. self.targetIDs[boxedTargetID] = queryData;
  349. return queryData;
  350. }
  351. - (void)releaseQuery:(FSTQuery *)query {
  352. self.persistence.run("Release query", [&]() {
  353. FSTQueryData *queryData = [self.queryCache queryDataForQuery:query];
  354. HARD_ASSERT(queryData, "Tried to release nonexistent query: %s", query);
  355. [self.localViewReferences removeReferencesForID:queryData.targetID];
  356. if (self.garbageCollector.isEager) {
  357. [self.queryCache removeQueryData:queryData];
  358. }
  359. [self.persistence.referenceDelegate removeTarget:queryData];
  360. [self.targetIDs removeObjectForKey:@(queryData.targetID)];
  361. // If this was the last watch target, then we won't get any more watch snapshots, so we should
  362. // release any held batch results.
  363. if ([self.targetIDs count] == 0) {
  364. [self releaseHeldBatchResults];
  365. }
  366. });
  367. }
  368. - (FSTDocumentDictionary *)executeQuery:(FSTQuery *)query {
  369. return self.persistence.run("ExecuteQuery", [&]() -> FSTDocumentDictionary * {
  370. return [self.localDocuments documentsMatchingQuery:query];
  371. });
  372. }
  373. - (DocumentKeySet)remoteDocumentKeysForTarget:(FSTTargetID)targetID {
  374. return self.persistence.run("RemoteDocumentKeysForTarget", [&]() -> DocumentKeySet {
  375. return [self.queryCache matchingKeysForTargetID:targetID];
  376. });
  377. }
  378. - (void)collectGarbage {
  379. self.persistence.run("Garbage Collection", [&]() {
  380. // Call collectGarbage regardless of whether isGCEnabled so the referenceSet doesn't continue to
  381. // accumulate the garbage keys.
  382. std::set<DocumentKey> garbage = [self.garbageCollector collectGarbage];
  383. if (garbage.size() > 0) {
  384. for (const DocumentKey &key : garbage) {
  385. [self.remoteDocumentCache removeEntryForKey:key];
  386. }
  387. }
  388. });
  389. }
  390. /**
  391. * Releases all the held mutation batches up to the current remote version received, and
  392. * applies their mutations to the docs in the remote documents cache.
  393. *
  394. * @return the set of keys of docs that were modified by those writes.
  395. */
  396. - (DocumentKeySet)releaseHeldBatchResults {
  397. NSMutableArray<FSTMutationBatchResult *> *toRelease = [NSMutableArray array];
  398. for (FSTMutationBatchResult *batchResult in self.heldBatchResults) {
  399. if (![self isRemoteUpToVersion:batchResult.commitVersion]) {
  400. break;
  401. }
  402. [toRelease addObject:batchResult];
  403. }
  404. if (toRelease.count == 0) {
  405. return DocumentKeySet{};
  406. } else {
  407. [self.heldBatchResults removeObjectsInRange:NSMakeRange(0, toRelease.count)];
  408. return [self releaseBatchResults:toRelease];
  409. }
  410. }
  411. - (BOOL)isRemoteUpToVersion:(const SnapshotVersion &)version {
  412. // If there are no watch targets, then we won't get remote snapshots, and are always "up-to-date."
  413. return version <= self.queryCache.lastRemoteSnapshotVersion || self.targetIDs.count == 0;
  414. }
  415. - (BOOL)shouldHoldBatchResultWithVersion:(const SnapshotVersion &)version {
  416. // Check if watcher isn't up to date or prior results are already held.
  417. return ![self isRemoteUpToVersion:version] || self.heldBatchResults.count > 0;
  418. }
  419. - (DocumentKeySet)releaseBatchResults:(NSArray<FSTMutationBatchResult *> *)batchResults {
  420. NSMutableArray<FSTMutationBatch *> *batches = [NSMutableArray array];
  421. for (FSTMutationBatchResult *batchResult in batchResults) {
  422. [self applyBatchResult:batchResult];
  423. [batches addObject:batchResult.batch];
  424. }
  425. return [self removeMutationBatches:batches];
  426. }
  427. - (DocumentKeySet)removeMutationBatch:(FSTMutationBatch *)batch {
  428. return [self removeMutationBatches:@[ batch ]];
  429. }
  430. /** Removes all the mutation batches named in the given array. */
  431. - (DocumentKeySet)removeMutationBatches:(NSArray<FSTMutationBatch *> *)batches {
  432. DocumentKeySet affectedDocs;
  433. for (FSTMutationBatch *batch in batches) {
  434. for (FSTMutation *mutation in batch.mutations) {
  435. const DocumentKey &key = mutation.key;
  436. affectedDocs = affectedDocs.insert(key);
  437. }
  438. }
  439. [self.mutationQueue removeMutationBatches:batches];
  440. return affectedDocs;
  441. }
  442. - (void)applyBatchResult:(FSTMutationBatchResult *)batchResult {
  443. FSTMutationBatch *batch = batchResult.batch;
  444. DocumentKeySet docKeys = batch.keys;
  445. const DocumentVersionMap &versions = batchResult.docVersions;
  446. for (const DocumentKey &docKey : docKeys) {
  447. FSTMaybeDocument *_Nullable remoteDoc = [self.remoteDocumentCache entryForKey:docKey];
  448. FSTMaybeDocument *_Nullable doc = remoteDoc;
  449. auto ackVersionIter = versions.find(docKey);
  450. HARD_ASSERT(ackVersionIter != versions.end(),
  451. "docVersions should contain every doc in the write.");
  452. const SnapshotVersion &ackVersion = ackVersionIter->second;
  453. if (!doc || doc.version < ackVersion) {
  454. doc = [batch applyTo:doc documentKey:docKey mutationBatchResult:batchResult];
  455. if (!doc) {
  456. HARD_ASSERT(!remoteDoc, "Mutation batch %s applied to document %s resulted in nil.", batch,
  457. remoteDoc);
  458. } else {
  459. [self.remoteDocumentCache addEntry:doc];
  460. }
  461. }
  462. }
  463. }
  464. @end
  465. NS_ASSUME_NONNULL_END