FSTLocalStore.mm 23 KB

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