FSTLocalStore.mm 21 KB

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