FSTLocalStore.mm 22 KB

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