FSTLocalStore.mm 23 KB

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