FSTLocalStore.mm 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. [remoteEvent.targetChanges enumerateKeysAndObjectsUsingBlock:^(
  219. NSNumber *targetIDNumber, FSTTargetChange *change, BOOL *stop) {
  220. FSTTargetID targetID = targetIDNumber.intValue;
  221. // Do not ref/unref unassigned targetIDs - it may lead to leaks.
  222. FSTQueryData *queryData = self.targetIDs[targetIDNumber];
  223. if (!queryData) {
  224. return;
  225. }
  226. // Update the resume token if the change includes one. Don't clear any preexisting value.
  227. // Bump the sequence number as well, so that documents being removed now are ordered later
  228. // than documents that were previously removed from this target.
  229. NSData *resumeToken = change.resumeToken;
  230. if (resumeToken.length > 0) {
  231. queryData = [queryData queryDataByReplacingSnapshotVersion:change.snapshotVersion
  232. resumeToken:resumeToken
  233. sequenceNumber:sequenceNumber];
  234. self.targetIDs[targetIDNumber] = queryData;
  235. [self.queryCache updateQueryData:queryData];
  236. }
  237. FSTTargetMapping *mapping = change.mapping;
  238. if (mapping) {
  239. // First make sure that all references are deleted.
  240. if ([mapping isKindOfClass:[FSTResetMapping class]]) {
  241. FSTResetMapping *reset = (FSTResetMapping *)mapping;
  242. [queryCache removeMatchingKeysForTargetID:targetID];
  243. [queryCache addMatchingKeys:reset.documents forTargetID:targetID];
  244. } else if ([mapping isKindOfClass:[FSTUpdateMapping class]]) {
  245. FSTUpdateMapping *update = (FSTUpdateMapping *)mapping;
  246. [queryCache removeMatchingKeys:update.removedDocuments forTargetID:targetID];
  247. [queryCache addMatchingKeys:update.addedDocuments forTargetID:targetID];
  248. } else {
  249. HARD_FAIL("Unknown mapping type: %s", mapping);
  250. }
  251. }
  252. }];
  253. // TODO(klimt): This could probably be an NSMutableDictionary.
  254. DocumentKeySet changedDocKeys;
  255. const DocumentKeySet &limboDocuments = remoteEvent.limboDocumentChanges;
  256. for (const auto &kv : remoteEvent.documentUpdates) {
  257. const DocumentKey &key = kv.first;
  258. FSTMaybeDocument *doc = kv.second;
  259. changedDocKeys = changedDocKeys.insert(key);
  260. FSTMaybeDocument *existingDoc = [self.remoteDocumentCache entryForKey:key];
  261. // Make sure we don't apply an old document version to the remote cache, though we
  262. // make an exception for SnapshotVersion::None() which can happen for manufactured
  263. // events (e.g. in the case of a limbo document resolution failing).
  264. if (!existingDoc || SnapshotVersion{doc.version} == SnapshotVersion::None() ||
  265. SnapshotVersion{doc.version} >= SnapshotVersion{existingDoc.version}) {
  266. [self.remoteDocumentCache addEntry:doc];
  267. } else {
  268. LOG_DEBUG(
  269. "FSTLocalStore Ignoring outdated watch update for %s. "
  270. "Current version: %s Watch version: %s",
  271. key.ToString(), existingDoc.version.timestamp().ToString(),
  272. doc.version.timestamp().ToString());
  273. }
  274. // The document might be garbage because it was unreferenced by everything.
  275. // Make sure to mark it as garbage if it is...
  276. [self.garbageCollector addPotentialGarbageKey:key];
  277. if (limboDocuments.contains(key)) {
  278. [self.persistence.referenceDelegate limboDocumentUpdated:key];
  279. }
  280. }
  281. // HACK: The only reason we allow omitting snapshot version is so we can synthesize remote
  282. // events when we get permission denied errors while trying to resolve the state of a locally
  283. // cached document that is in limbo.
  284. const SnapshotVersion &lastRemoteVersion = [self.queryCache lastRemoteSnapshotVersion];
  285. const SnapshotVersion &remoteVersion = remoteEvent.snapshotVersion;
  286. if (remoteVersion != SnapshotVersion::None()) {
  287. HARD_ASSERT(remoteVersion >= lastRemoteVersion,
  288. "Watch stream reverted to previous snapshot?? (%s < %s)",
  289. remoteVersion.timestamp().ToString(), lastRemoteVersion.timestamp().ToString());
  290. [self.queryCache setLastRemoteSnapshotVersion:remoteVersion];
  291. }
  292. DocumentKeySet releasedWriteKeys = [self releaseHeldBatchResults];
  293. // Union the two key sets.
  294. DocumentKeySet keysToRecalc = changedDocKeys;
  295. for (const DocumentKey &key : releasedWriteKeys) {
  296. keysToRecalc = keysToRecalc.insert(key);
  297. }
  298. return [self.localDocuments documentsForKeys:keysToRecalc];
  299. });
  300. }
  301. - (void)notifyLocalViewChanges:(NSArray<FSTLocalViewChanges *> *)viewChanges {
  302. self.persistence.run("NotifyLocalViewChanges", [&]() {
  303. FSTReferenceSet *localViewReferences = self.localViewReferences;
  304. for (FSTLocalViewChanges *view in viewChanges) {
  305. FSTQueryData *queryData = [self.queryCache queryDataForQuery:view.query];
  306. HARD_ASSERT(queryData, "Local view changes contain unallocated query.");
  307. FSTTargetID targetID = queryData.targetID;
  308. for (const DocumentKey &key : view.removedKeys) {
  309. [self->_persistence.referenceDelegate removeReference:key target:targetID];
  310. }
  311. [localViewReferences addReferencesToKeys:view.addedKeys forID:targetID];
  312. [localViewReferences removeReferencesToKeys:view.removedKeys forID:targetID];
  313. }
  314. });
  315. }
  316. - (nullable FSTMutationBatch *)nextMutationBatchAfterBatchID:(FSTBatchID)batchID {
  317. FSTMutationBatch *result =
  318. self.persistence.run("NextMutationBatchAfterBatchID", [&]() -> FSTMutationBatch * {
  319. return [self.mutationQueue nextMutationBatchAfterBatchID:batchID];
  320. });
  321. return result;
  322. }
  323. - (nullable FSTMaybeDocument *)readDocument:(const DocumentKey &)key {
  324. return self.persistence.run("ReadDocument", [&]() -> FSTMaybeDocument *_Nullable {
  325. return [self.localDocuments documentForKey:key];
  326. });
  327. }
  328. - (FSTQueryData *)allocateQuery:(FSTQuery *)query {
  329. FSTQueryData *queryData = self.persistence.run("Allocate query", [&]() -> FSTQueryData * {
  330. FSTQueryData *cached = [self.queryCache queryDataForQuery:query];
  331. // TODO(mcg): freshen last accessed date if cached exists?
  332. if (!cached) {
  333. cached = [[FSTQueryData alloc] initWithQuery:query
  334. targetID:_targetIDGenerator.NextId()
  335. listenSequenceNumber:[self.listenSequence next]
  336. purpose:FSTQueryPurposeListen];
  337. [self.queryCache addQueryData:cached];
  338. }
  339. return cached;
  340. });
  341. // Sanity check to ensure that even when resuming a query it's not currently active.
  342. FSTBoxedTargetID *boxedTargetID = @(queryData.targetID);
  343. HARD_ASSERT(!self.targetIDs[boxedTargetID], "Tried to allocate an already allocated query: %s",
  344. query);
  345. self.targetIDs[boxedTargetID] = queryData;
  346. return queryData;
  347. }
  348. - (void)releaseQuery:(FSTQuery *)query {
  349. self.persistence.run("Release query", [&]() {
  350. FSTQueryData *queryData = [self.queryCache queryDataForQuery:query];
  351. HARD_ASSERT(queryData, "Tried to release nonexistent query: %s", query);
  352. [self.localViewReferences removeReferencesForID:queryData.targetID];
  353. if (self.garbageCollector.isEager) {
  354. [self.queryCache removeQueryData:queryData];
  355. }
  356. [self.persistence.referenceDelegate removeTarget:queryData];
  357. [self.targetIDs removeObjectForKey:@(queryData.targetID)];
  358. // If this was the last watch target, then we won't get any more watch snapshots, so we should
  359. // release any held batch results.
  360. if ([self.targetIDs count] == 0) {
  361. [self releaseHeldBatchResults];
  362. }
  363. });
  364. }
  365. - (FSTDocumentDictionary *)executeQuery:(FSTQuery *)query {
  366. return self.persistence.run("ExecuteQuery", [&]() -> FSTDocumentDictionary * {
  367. return [self.localDocuments documentsMatchingQuery:query];
  368. });
  369. }
  370. - (DocumentKeySet)remoteDocumentKeysForTarget:(FSTTargetID)targetID {
  371. return self.persistence.run("RemoteDocumentKeysForTarget", [&]() -> DocumentKeySet {
  372. return [self.queryCache matchingKeysForTargetID:targetID];
  373. });
  374. }
  375. - (void)collectGarbage {
  376. self.persistence.run("Garbage Collection", [&]() {
  377. // Call collectGarbage regardless of whether isGCEnabled so the referenceSet doesn't continue to
  378. // accumulate the garbage keys.
  379. std::set<DocumentKey> garbage = [self.garbageCollector collectGarbage];
  380. if (garbage.size() > 0) {
  381. for (const DocumentKey &key : garbage) {
  382. [self.remoteDocumentCache removeEntryForKey:key];
  383. }
  384. }
  385. });
  386. }
  387. /**
  388. * Releases all the held mutation batches up to the current remote version received, and
  389. * applies their mutations to the docs in the remote documents cache.
  390. *
  391. * @return the set of keys of docs that were modified by those writes.
  392. */
  393. - (DocumentKeySet)releaseHeldBatchResults {
  394. NSMutableArray<FSTMutationBatchResult *> *toRelease = [NSMutableArray array];
  395. for (FSTMutationBatchResult *batchResult in self.heldBatchResults) {
  396. if (![self isRemoteUpToVersion:batchResult.commitVersion]) {
  397. break;
  398. }
  399. [toRelease addObject:batchResult];
  400. }
  401. if (toRelease.count == 0) {
  402. return DocumentKeySet{};
  403. } else {
  404. [self.heldBatchResults removeObjectsInRange:NSMakeRange(0, toRelease.count)];
  405. return [self releaseBatchResults:toRelease];
  406. }
  407. }
  408. - (BOOL)isRemoteUpToVersion:(const SnapshotVersion &)version {
  409. // If there are no watch targets, then we won't get remote snapshots, and are always "up-to-date."
  410. return version <= self.queryCache.lastRemoteSnapshotVersion || self.targetIDs.count == 0;
  411. }
  412. - (BOOL)shouldHoldBatchResultWithVersion:(const SnapshotVersion &)version {
  413. // Check if watcher isn't up to date or prior results are already held.
  414. return ![self isRemoteUpToVersion:version] || self.heldBatchResults.count > 0;
  415. }
  416. - (DocumentKeySet)releaseBatchResults:(NSArray<FSTMutationBatchResult *> *)batchResults {
  417. NSMutableArray<FSTMutationBatch *> *batches = [NSMutableArray array];
  418. for (FSTMutationBatchResult *batchResult in batchResults) {
  419. [self applyBatchResult:batchResult];
  420. [batches addObject:batchResult.batch];
  421. }
  422. return [self removeMutationBatches:batches];
  423. }
  424. - (DocumentKeySet)removeMutationBatch:(FSTMutationBatch *)batch {
  425. return [self removeMutationBatches:@[ batch ]];
  426. }
  427. /** Removes all the mutation batches named in the given array. */
  428. - (DocumentKeySet)removeMutationBatches:(NSArray<FSTMutationBatch *> *)batches {
  429. DocumentKeySet affectedDocs;
  430. for (FSTMutationBatch *batch in batches) {
  431. for (FSTMutation *mutation in batch.mutations) {
  432. const DocumentKey &key = mutation.key;
  433. affectedDocs = affectedDocs.insert(key);
  434. }
  435. }
  436. [self.mutationQueue removeMutationBatches:batches];
  437. return affectedDocs;
  438. }
  439. - (void)applyBatchResult:(FSTMutationBatchResult *)batchResult {
  440. FSTMutationBatch *batch = batchResult.batch;
  441. DocumentKeySet docKeys = batch.keys;
  442. const DocumentVersionMap &versions = batchResult.docVersions;
  443. for (const DocumentKey &docKey : docKeys) {
  444. FSTMaybeDocument *_Nullable remoteDoc = [self.remoteDocumentCache entryForKey:docKey];
  445. FSTMaybeDocument *_Nullable doc = remoteDoc;
  446. auto ackVersionIter = versions.find(docKey);
  447. HARD_ASSERT(ackVersionIter != versions.end(),
  448. "docVersions should contain every doc in the write.");
  449. const SnapshotVersion &ackVersion = ackVersionIter->second;
  450. if (!doc || doc.version < ackVersion) {
  451. doc = [batch applyTo:doc documentKey:docKey mutationBatchResult:batchResult];
  452. if (!doc) {
  453. HARD_ASSERT(!remoteDoc, "Mutation batch %s applied to document %s resulted in nil.", batch,
  454. remoteDoc);
  455. } else {
  456. [self.remoteDocumentCache addEntry:doc];
  457. }
  458. }
  459. }
  460. }
  461. @end
  462. NS_ASSUME_NONNULL_END