FSTLocalStore.mm 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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 <memory>
  18. #include <set>
  19. #include <unordered_map>
  20. #include <utility>
  21. #include <vector>
  22. #import "FIRTimestamp.h"
  23. #import "Firestore/Source/Core/FSTQuery.h"
  24. #import "Firestore/Source/Local/FSTLRUGarbageCollector.h"
  25. #import "Firestore/Source/Local/FSTLocalViewChanges.h"
  26. #import "Firestore/Source/Local/FSTLocalWriteResult.h"
  27. #import "Firestore/Source/Local/FSTPersistence.h"
  28. #import "Firestore/Source/Local/FSTQueryData.h"
  29. #import "Firestore/Source/Model/FSTDocument.h"
  30. #import "Firestore/Source/Model/FSTMutation.h"
  31. #import "Firestore/Source/Model/FSTMutationBatch.h"
  32. #include "Firestore/core/include/firebase/firestore/timestamp.h"
  33. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  34. #include "Firestore/core/src/firebase/firestore/core/target_id_generator.h"
  35. #include "Firestore/core/src/firebase/firestore/immutable/sorted_set.h"
  36. #include "Firestore/core/src/firebase/firestore/local/local_documents_view.h"
  37. #include "Firestore/core/src/firebase/firestore/local/mutation_queue.h"
  38. #include "Firestore/core/src/firebase/firestore/local/query_cache.h"
  39. #include "Firestore/core/src/firebase/firestore/local/reference_set.h"
  40. #include "Firestore/core/src/firebase/firestore/local/remote_document_cache.h"
  41. #include "Firestore/core/src/firebase/firestore/model/document_key_set.h"
  42. #include "Firestore/core/src/firebase/firestore/model/document_map.h"
  43. #include "Firestore/core/src/firebase/firestore/model/snapshot_version.h"
  44. #include "Firestore/core/src/firebase/firestore/remote/remote_event.h"
  45. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  46. #include "Firestore/core/src/firebase/firestore/util/log.h"
  47. #include "absl/memory/memory.h"
  48. #include "absl/types/optional.h"
  49. using firebase::Timestamp;
  50. using firebase::firestore::auth::User;
  51. using firebase::firestore::core::TargetIdGenerator;
  52. using firebase::firestore::local::LocalDocumentsView;
  53. using firebase::firestore::local::LruResults;
  54. using firebase::firestore::local::MutationQueue;
  55. using firebase::firestore::local::QueryCache;
  56. using firebase::firestore::local::ReferenceSet;
  57. using firebase::firestore::local::RemoteDocumentCache;
  58. using firebase::firestore::model::BatchId;
  59. using firebase::firestore::model::DocumentKey;
  60. using firebase::firestore::model::DocumentKeySet;
  61. using firebase::firestore::model::DocumentMap;
  62. using firebase::firestore::model::DocumentVersionMap;
  63. using firebase::firestore::model::FieldMask;
  64. using firebase::firestore::model::FieldPath;
  65. using firebase::firestore::model::ListenSequenceNumber;
  66. using firebase::firestore::model::MaybeDocumentMap;
  67. using firebase::firestore::model::ObjectValue;
  68. using firebase::firestore::model::Precondition;
  69. using firebase::firestore::model::SnapshotVersion;
  70. using firebase::firestore::model::TargetId;
  71. using firebase::firestore::remote::RemoteEvent;
  72. using firebase::firestore::remote::TargetChange;
  73. NS_ASSUME_NONNULL_BEGIN
  74. /**
  75. * The maximum time to leave a resume token buffered without writing it out. This value is
  76. * arbitrary: it's long enough to avoid several writes (possibly indefinitely if updates come more
  77. * frequently than this) but short enough that restarting after crashing will still have a pretty
  78. * recent resume token.
  79. */
  80. static const int64_t kResumeTokenMaxAgeSeconds = 5 * 60; // 5 minutes
  81. @interface FSTLocalStore ()
  82. /** Manages our in-memory or durable persistence. */
  83. @property(nonatomic, strong, readonly) id<FSTPersistence> persistence;
  84. /** Maps a query to the data about that query. */
  85. @property(nonatomic) QueryCache *queryCache;
  86. @end
  87. @implementation FSTLocalStore {
  88. /** Used to generate targetIDs for queries tracked locally. */
  89. TargetIdGenerator _targetIDGenerator;
  90. /** The set of all cached remote documents. */
  91. RemoteDocumentCache *_remoteDocumentCache;
  92. QueryCache *_queryCache;
  93. /** The set of all mutations that have been sent but not yet been applied to the backend. */
  94. MutationQueue *_mutationQueue;
  95. /** The "local" view of all documents (layering mutationQueue on top of remoteDocumentCache). */
  96. std::unique_ptr<LocalDocumentsView> _localDocuments;
  97. /** The set of document references maintained by any local views. */
  98. ReferenceSet _localViewReferences;
  99. /** Maps a targetID to data about its query. */
  100. std::unordered_map<TargetId, FSTQueryData *> _targetIDs;
  101. }
  102. - (instancetype)initWithPersistence:(id<FSTPersistence>)persistence
  103. initialUser:(const User &)initialUser {
  104. if (self = [super init]) {
  105. _persistence = persistence;
  106. _mutationQueue = [persistence mutationQueueForUser:initialUser];
  107. _remoteDocumentCache = [persistence remoteDocumentCache];
  108. _queryCache = [persistence queryCache];
  109. _localDocuments = absl::make_unique<LocalDocumentsView>(_remoteDocumentCache, _mutationQueue,
  110. [_persistence indexManager]);
  111. [_persistence.referenceDelegate addInMemoryPins:&_localViewReferences];
  112. _targetIDGenerator = TargetIdGenerator::QueryCacheTargetIdGenerator(0);
  113. }
  114. return self;
  115. }
  116. - (void)start {
  117. [self startMutationQueue];
  118. TargetId targetID = _queryCache->highest_target_id();
  119. _targetIDGenerator = TargetIdGenerator::QueryCacheTargetIdGenerator(targetID);
  120. }
  121. - (void)startMutationQueue {
  122. self.persistence.run("Start MutationQueue", [&]() { _mutationQueue->Start(); });
  123. }
  124. - (MaybeDocumentMap)userDidChange:(const User &)user {
  125. // Swap out the mutation queue, grabbing the pending mutation batches before and after.
  126. std::vector<FSTMutationBatch *> oldBatches = self.persistence.run(
  127. "OldBatches",
  128. [&]() -> std::vector<FSTMutationBatch *> { return _mutationQueue->AllMutationBatches(); });
  129. // The old one has a reference to the mutation queue, so nil it out first.
  130. _localDocuments.reset();
  131. _mutationQueue = [self.persistence mutationQueueForUser:user];
  132. [self startMutationQueue];
  133. return self.persistence.run("NewBatches", [&]() -> MaybeDocumentMap {
  134. std::vector<FSTMutationBatch *> newBatches = _mutationQueue->AllMutationBatches();
  135. // Recreate our LocalDocumentsView using the new MutationQueue.
  136. _localDocuments = absl::make_unique<LocalDocumentsView>(_remoteDocumentCache, _mutationQueue,
  137. [_persistence indexManager]);
  138. // Union the old/new changed keys.
  139. DocumentKeySet changedKeys;
  140. for (const std::vector<FSTMutationBatch *> &batches : {oldBatches, newBatches}) {
  141. for (FSTMutationBatch *batch : batches) {
  142. for (FSTMutation *mutation : [batch mutations]) {
  143. changedKeys = changedKeys.insert(mutation.key);
  144. }
  145. }
  146. }
  147. // Return the set of all (potentially) changed documents as the result of the user change.
  148. return _localDocuments->GetDocuments(changedKeys);
  149. });
  150. }
  151. - (FSTLocalWriteResult *)locallyWriteMutations:(std::vector<FSTMutation *> &&)mutations {
  152. Timestamp localWriteTime = Timestamp::Now();
  153. DocumentKeySet keys;
  154. for (FSTMutation *mutation : mutations) {
  155. keys = keys.insert(mutation.key);
  156. }
  157. return self.persistence.run("Locally write mutations", [&]() -> FSTLocalWriteResult * {
  158. // Load and apply all existing mutations. This lets us compute the current base state for
  159. // all non-idempotent transforms before applying any additional user-provided writes.
  160. MaybeDocumentMap existingDocuments = _localDocuments->GetDocuments(keys);
  161. // For non-idempotent mutations (such as `FieldValue.increment()`), we record the base
  162. // state in a separate patch mutation. This is later used to guarantee consistent values
  163. // and prevents flicker even if the backend sends us an update that already includes our
  164. // transform.
  165. std::vector<FSTMutation *> baseMutations;
  166. for (FSTMutation *mutation : mutations) {
  167. auto base_document_it = existingDocuments.find(mutation.key);
  168. FSTMaybeDocument *base_document =
  169. base_document_it != existingDocuments.end() ? base_document_it->second : nil;
  170. absl::optional<ObjectValue> base_value = [mutation extractBaseValue:base_document];
  171. if (base_value) {
  172. // NOTE: The base state should only be applied if there's some existing document to
  173. // override, so use a Precondition of exists=true
  174. baseMutations.push_back([[FSTPatchMutation alloc] initWithKey:mutation.key
  175. fieldMask:base_value->ToFieldMask()
  176. value:*base_value
  177. precondition:Precondition::Exists(true)]);
  178. }
  179. }
  180. FSTMutationBatch *batch = _mutationQueue->AddMutationBatch(
  181. localWriteTime, std::move(baseMutations), std::move(mutations));
  182. MaybeDocumentMap changedDocuments = [batch applyToLocalDocumentSet:existingDocuments];
  183. return [FSTLocalWriteResult resultForBatchID:batch.batchID changes:std::move(changedDocuments)];
  184. });
  185. }
  186. - (MaybeDocumentMap)acknowledgeBatchWithResult:(FSTMutationBatchResult *)batchResult {
  187. return self.persistence.run("Acknowledge batch", [&]() -> MaybeDocumentMap {
  188. FSTMutationBatch *batch = batchResult.batch;
  189. _mutationQueue->AcknowledgeBatch(batch, batchResult.streamToken);
  190. [self applyBatchResult:batchResult];
  191. _mutationQueue->PerformConsistencyCheck();
  192. return _localDocuments->GetDocuments(batch.keys);
  193. });
  194. }
  195. - (MaybeDocumentMap)rejectBatchID:(BatchId)batchID {
  196. return self.persistence.run("Reject batch", [&]() -> MaybeDocumentMap {
  197. FSTMutationBatch *toReject = _mutationQueue->LookupMutationBatch(batchID);
  198. HARD_ASSERT(toReject, "Attempt to reject nonexistent batch!");
  199. _mutationQueue->RemoveMutationBatch(toReject);
  200. _mutationQueue->PerformConsistencyCheck();
  201. return _localDocuments->GetDocuments(toReject.keys);
  202. });
  203. }
  204. - (nullable NSData *)lastStreamToken {
  205. return _mutationQueue->GetLastStreamToken();
  206. }
  207. - (void)setLastStreamToken:(nullable NSData *)streamToken {
  208. self.persistence.run("Set stream token",
  209. [&]() { _mutationQueue->SetLastStreamToken(streamToken); });
  210. }
  211. - (const SnapshotVersion &)lastRemoteSnapshotVersion {
  212. return self.queryCache->GetLastRemoteSnapshotVersion();
  213. }
  214. - (MaybeDocumentMap)applyRemoteEvent:(const RemoteEvent &)remoteEvent {
  215. return self.persistence.run("Apply remote event", [&]() -> MaybeDocumentMap {
  216. // TODO(gsoltis): move the sequence number into the reference delegate.
  217. ListenSequenceNumber sequenceNumber = self.persistence.currentSequenceNumber;
  218. DocumentKeySet authoritativeUpdates;
  219. for (const auto &entry : remoteEvent.target_changes()) {
  220. TargetId targetID = entry.first;
  221. const TargetChange &change = entry.second;
  222. // Do not ref/unref unassigned targetIDs - it may lead to leaks.
  223. auto found = _targetIDs.find(targetID);
  224. if (found == _targetIDs.end()) {
  225. continue;
  226. }
  227. FSTQueryData *queryData = found->second;
  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.added_documents()) {
  237. authoritativeUpdates = authoritativeUpdates.insert(key);
  238. }
  239. for (const DocumentKey &key : change.modified_documents()) {
  240. authoritativeUpdates = authoritativeUpdates.insert(key);
  241. }
  242. _queryCache->RemoveMatchingKeys(change.removed_documents(), targetID);
  243. _queryCache->AddMatchingKeys(change.added_documents(), 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.resume_token();
  248. if (resumeToken.length > 0) {
  249. FSTQueryData *oldQueryData = queryData;
  250. queryData = [queryData queryDataByReplacingSnapshotVersion:remoteEvent.snapshot_version()
  251. resumeToken:resumeToken
  252. sequenceNumber:sequenceNumber];
  253. _targetIDs[targetID] = queryData;
  254. if ([self shouldPersistQueryData:queryData oldQueryData:oldQueryData change:change]) {
  255. _queryCache->UpdateTarget(queryData);
  256. }
  257. }
  258. }
  259. MaybeDocumentMap changedDocs;
  260. const DocumentKeySet &limboDocuments = remoteEvent.limbo_document_changes();
  261. DocumentKeySet updatedKeys;
  262. for (const auto &kv : remoteEvent.document_updates()) {
  263. updatedKeys = updatedKeys.insert(kv.first);
  264. }
  265. // Each loop iteration only affects its "own" doc, so it's safe to get all the remote
  266. // documents in advance in a single call.
  267. MaybeDocumentMap existingDocs = _remoteDocumentCache->GetAll(updatedKeys);
  268. for (const auto &kv : remoteEvent.document_updates()) {
  269. const DocumentKey &key = kv.first;
  270. FSTMaybeDocument *doc = kv.second;
  271. FSTMaybeDocument *existingDoc = nil;
  272. auto foundExisting = existingDocs.find(key);
  273. if (foundExisting != existingDocs.end()) {
  274. existingDoc = foundExisting->second;
  275. }
  276. // If a document update isn't authoritative, make sure we don't apply an old document version
  277. // to the remote cache. We make an exception for SnapshotVersion.MIN which can happen for
  278. // manufactured events (e.g. in the case of a limbo document resolution failing).
  279. if (!existingDoc || doc.version == SnapshotVersion::None() ||
  280. (authoritativeUpdates.contains(doc.key) && !existingDoc.hasPendingWrites) ||
  281. doc.version >= existingDoc.version) {
  282. _remoteDocumentCache->Add(doc);
  283. changedDocs = changedDocs.insert(key, doc);
  284. } else {
  285. LOG_DEBUG("FSTLocalStore Ignoring outdated watch update for %s. "
  286. "Current version: %s Watch version: %s",
  287. key.ToString(), existingDoc.version.timestamp().ToString(),
  288. doc.version.timestamp().ToString());
  289. }
  290. // If this was a limbo resolution, make sure we mark when it was accessed.
  291. if (limboDocuments.contains(key)) {
  292. [self.persistence.referenceDelegate limboDocumentUpdated:key];
  293. }
  294. }
  295. // HACK: The only reason we allow omitting snapshot version is so we can synthesize remote
  296. // events when we get permission denied errors while trying to resolve the state of a locally
  297. // cached document that is in limbo.
  298. const SnapshotVersion &lastRemoteVersion = _queryCache->GetLastRemoteSnapshotVersion();
  299. const SnapshotVersion &remoteVersion = remoteEvent.snapshot_version();
  300. if (remoteVersion != SnapshotVersion::None()) {
  301. HARD_ASSERT(remoteVersion >= lastRemoteVersion,
  302. "Watch stream reverted to previous snapshot?? (%s < %s)",
  303. remoteVersion.timestamp().ToString(), lastRemoteVersion.timestamp().ToString());
  304. _queryCache->SetLastRemoteSnapshotVersion(remoteVersion);
  305. }
  306. return _localDocuments->GetLocalViewOfDocuments(changedDocs);
  307. });
  308. }
  309. /**
  310. * Returns YES if the newQueryData should be persisted during an update of an active target.
  311. * QueryData should always be persisted when a target is being released and should not call this
  312. * function.
  313. *
  314. * While the target is active, QueryData updates can be omitted when nothing about the target has
  315. * changed except metadata like the resume token or snapshot version. Occasionally it's worth the
  316. * extra write to prevent these values from getting too stale after a crash, but this doesn't have
  317. * to be too frequent.
  318. */
  319. - (BOOL)shouldPersistQueryData:(FSTQueryData *)newQueryData
  320. oldQueryData:(FSTQueryData *)oldQueryData
  321. change:(const TargetChange &)change {
  322. // Avoid clearing any existing value
  323. if (newQueryData.resumeToken.length == 0) return NO;
  324. // Any resume token is interesting if there isn't one already.
  325. if (oldQueryData.resumeToken.length == 0) return YES;
  326. // Don't allow resume token changes to be buffered indefinitely. This allows us to be reasonably
  327. // up-to-date after a crash and avoids needing to loop over all active queries on shutdown.
  328. // Especially in the browser we may not get time to do anything interesting while the current
  329. // tab is closing.
  330. int64_t newSeconds = newQueryData.snapshotVersion.timestamp().seconds();
  331. int64_t oldSeconds = oldQueryData.snapshotVersion.timestamp().seconds();
  332. int64_t timeDelta = newSeconds - oldSeconds;
  333. if (timeDelta >= kResumeTokenMaxAgeSeconds) return YES;
  334. // Otherwise if the only thing that has changed about a target is its resume token then it's not
  335. // worth persisting. Note that the RemoteStore keeps an in-memory view of the currently active
  336. // targets which includes the current resume token, so stream failure or user changes will still
  337. // use an up-to-date resume token regardless of what we do here.
  338. size_t changes = change.added_documents().size() + change.modified_documents().size() +
  339. change.removed_documents().size();
  340. return changes > 0;
  341. }
  342. - (void)notifyLocalViewChanges:(NSArray<FSTLocalViewChanges *> *)viewChanges {
  343. self.persistence.run("NotifyLocalViewChanges", [&]() {
  344. for (FSTLocalViewChanges *viewChange in viewChanges) {
  345. for (const DocumentKey &key : viewChange.removedKeys) {
  346. [self->_persistence.referenceDelegate removeReference:key];
  347. }
  348. _localViewReferences.AddReferences(viewChange.addedKeys, viewChange.targetID);
  349. _localViewReferences.AddReferences(viewChange.removedKeys, viewChange.targetID);
  350. }
  351. });
  352. }
  353. - (nullable FSTMutationBatch *)nextMutationBatchAfterBatchID:(BatchId)batchID {
  354. FSTMutationBatch *result =
  355. self.persistence.run("NextMutationBatchAfterBatchID", [&]() -> FSTMutationBatch * {
  356. return _mutationQueue->NextMutationBatchAfterBatchId(batchID);
  357. });
  358. return result;
  359. }
  360. - (nullable FSTMaybeDocument *)readDocument:(const DocumentKey &)key {
  361. return self.persistence.run("ReadDocument", [&]() -> FSTMaybeDocument *_Nullable {
  362. return _localDocuments->GetDocument(key);
  363. });
  364. }
  365. - (FSTQueryData *)allocateQuery:(FSTQuery *)query {
  366. FSTQueryData *queryData = self.persistence.run("Allocate query", [&]() -> FSTQueryData * {
  367. FSTQueryData *cached = _queryCache->GetTarget(query);
  368. // TODO(mcg): freshen last accessed date if cached exists?
  369. if (!cached) {
  370. cached = [[FSTQueryData alloc] initWithQuery:query
  371. targetID:_targetIDGenerator.NextId()
  372. listenSequenceNumber:self.persistence.currentSequenceNumber
  373. purpose:FSTQueryPurposeListen];
  374. _queryCache->AddTarget(cached);
  375. }
  376. return cached;
  377. });
  378. // Sanity check to ensure that even when resuming a query it's not currently active.
  379. TargetId targetID = queryData.targetID;
  380. HARD_ASSERT(_targetIDs.find(targetID) == _targetIDs.end(),
  381. "Tried to allocate an already allocated query: %s", query);
  382. _targetIDs[targetID] = queryData;
  383. return queryData;
  384. }
  385. - (void)releaseQuery:(FSTQuery *)query {
  386. self.persistence.run("Release query", [&]() {
  387. FSTQueryData *queryData = _queryCache->GetTarget(query);
  388. HARD_ASSERT(queryData, "Tried to release nonexistent query: %s", query);
  389. TargetId targetID = queryData.targetID;
  390. auto found = _targetIDs.find(targetID);
  391. if (found != _targetIDs.end()) {
  392. FSTQueryData *cachedQueryData = found->second;
  393. if (cachedQueryData.snapshotVersion > queryData.snapshotVersion) {
  394. // If we've been avoiding persisting the resumeToken (see shouldPersistQueryData for
  395. // conditions and rationale) we need to persist the token now because there will no
  396. // longer be an in-memory version to fall back on.
  397. queryData = cachedQueryData;
  398. _queryCache->UpdateTarget(queryData);
  399. }
  400. }
  401. // References for documents sent via Watch are automatically removed when we delete a
  402. // query's target data from the reference delegate. Since this does not remove references
  403. // for locally mutated documents, we have to remove the target associations for these
  404. // documents manually.
  405. DocumentKeySet removed = _localViewReferences.RemoveReferences(targetID);
  406. for (const DocumentKey &key : removed) {
  407. [self.persistence.referenceDelegate removeReference:key];
  408. }
  409. _targetIDs.erase(targetID);
  410. [self.persistence.referenceDelegate removeTarget:queryData];
  411. });
  412. }
  413. - (DocumentMap)executeQuery:(FSTQuery *)query {
  414. return self.persistence.run("ExecuteQuery", [&]() -> DocumentMap {
  415. return _localDocuments->GetDocumentsMatchingQuery(query);
  416. });
  417. }
  418. - (DocumentKeySet)remoteDocumentKeysForTarget:(TargetId)targetID {
  419. return self.persistence.run("RemoteDocumentKeysForTarget", [&]() -> DocumentKeySet {
  420. return _queryCache->GetMatchingKeys(targetID);
  421. });
  422. }
  423. - (void)applyBatchResult:(FSTMutationBatchResult *)batchResult {
  424. FSTMutationBatch *batch = batchResult.batch;
  425. DocumentKeySet docKeys = batch.keys;
  426. const DocumentVersionMap &versions = batchResult.docVersions;
  427. for (const DocumentKey &docKey : docKeys) {
  428. FSTMaybeDocument *_Nullable remoteDoc = _remoteDocumentCache->Get(docKey);
  429. FSTMaybeDocument *_Nullable doc = remoteDoc;
  430. auto ackVersionIter = versions.find(docKey);
  431. HARD_ASSERT(ackVersionIter != versions.end(),
  432. "docVersions should contain every doc in the write.");
  433. const SnapshotVersion &ackVersion = ackVersionIter->second;
  434. if (!doc || doc.version < ackVersion) {
  435. doc = [batch applyToRemoteDocument:doc documentKey:docKey mutationBatchResult:batchResult];
  436. if (!doc) {
  437. HARD_ASSERT(!remoteDoc, "Mutation batch %s applied to document %s resulted in nil.", batch,
  438. remoteDoc);
  439. } else {
  440. _remoteDocumentCache->Add(doc);
  441. }
  442. }
  443. }
  444. _mutationQueue->RemoveMutationBatch(batch);
  445. }
  446. - (LruResults)collectGarbage:(FSTLRUGarbageCollector *)garbageCollector {
  447. return self.persistence.run("Collect garbage", [&]() -> LruResults {
  448. return [garbageCollector collectWithLiveTargets:_targetIDs];
  449. });
  450. }
  451. @end
  452. NS_ASSUME_NONNULL_END