FSTSyncEngineTestDriver.mm 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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/Example/Tests/SpecTests/FSTSyncEngineTestDriver.h"
  17. #import <FirebaseFirestore/FIRFirestoreErrors.h>
  18. #include <cstddef>
  19. #include <map>
  20. #include <memory>
  21. #include <string>
  22. #include <unordered_map>
  23. #include <utility>
  24. #include <vector>
  25. #import "Firestore/Example/Tests/SpecTests/FSTMockDatastore.h"
  26. #include "Firestore/core/include/firebase/firestore/firestore_errors.h"
  27. #include "Firestore/core/src/api/load_bundle_task.h"
  28. #include "Firestore/core/src/bundle/bundle_reader.h"
  29. #include "Firestore/core/src/core/database_info.h"
  30. #include "Firestore/core/src/core/event_manager.h"
  31. #include "Firestore/core/src/core/listen_options.h"
  32. #include "Firestore/core/src/core/query_listener.h"
  33. #include "Firestore/core/src/core/sync_engine.h"
  34. #include "Firestore/core/src/credentials/empty_credentials_provider.h"
  35. #include "Firestore/core/src/credentials/user.h"
  36. #include "Firestore/core/src/local/local_store.h"
  37. #include "Firestore/core/src/local/lru_garbage_collector.h"
  38. #include "Firestore/core/src/local/memory_lru_reference_delegate.h"
  39. #include "Firestore/core/src/local/persistence.h"
  40. #include "Firestore/core/src/local/query_engine.h"
  41. #include "Firestore/core/src/model/database_id.h"
  42. #include "Firestore/core/src/model/document_key.h"
  43. #include "Firestore/core/src/remote/firebase_metadata_provider.h"
  44. #include "Firestore/core/src/remote/firebase_metadata_provider_noop.h"
  45. #include "Firestore/core/src/remote/remote_store.h"
  46. #include "Firestore/core/src/util/async_queue.h"
  47. #include "Firestore/core/src/util/delayed_constructor.h"
  48. #include "Firestore/core/src/util/error_apple.h"
  49. #include "Firestore/core/src/util/executor.h"
  50. #include "Firestore/core/src/util/hard_assert.h"
  51. #include "Firestore/core/src/util/log.h"
  52. #include "Firestore/core/src/util/status.h"
  53. #include "Firestore/core/src/util/statusor.h"
  54. #include "Firestore/core/src/util/string_format.h"
  55. #include "Firestore/core/src/util/to_string.h"
  56. #include "Firestore/core/test/unit/remote/create_noop_connectivity_monitor.h"
  57. #include "Firestore/core/test/unit/testutil/async_testing.h"
  58. #include "absl/memory/memory.h"
  59. using firebase::firestore::Error;
  60. using firebase::firestore::api::LoadBundleTask;
  61. using firebase::firestore::bundle::BundleReader;
  62. using firebase::firestore::core::DatabaseInfo;
  63. using firebase::firestore::core::EventListener;
  64. using firebase::firestore::core::EventManager;
  65. using firebase::firestore::core::ListenOptions;
  66. using firebase::firestore::core::Query;
  67. using firebase::firestore::core::QueryListener;
  68. using firebase::firestore::core::SyncEngine;
  69. using firebase::firestore::core::ViewSnapshot;
  70. using firebase::firestore::credentials::EmptyAppCheckCredentialsProvider;
  71. using firebase::firestore::credentials::EmptyAuthCredentialsProvider;
  72. using firebase::firestore::credentials::HashUser;
  73. using firebase::firestore::credentials::User;
  74. using firebase::firestore::local::LocalStore;
  75. using firebase::firestore::local::LruDelegate;
  76. using firebase::firestore::local::LruParams;
  77. using firebase::firestore::local::Persistence;
  78. using firebase::firestore::local::QueryEngine;
  79. using firebase::firestore::local::TargetData;
  80. using firebase::firestore::model::DatabaseId;
  81. using firebase::firestore::model::DocumentKey;
  82. using firebase::firestore::model::DocumentKeySet;
  83. using firebase::firestore::model::Mutation;
  84. using firebase::firestore::model::MutationResult;
  85. using firebase::firestore::model::OnlineState;
  86. using firebase::firestore::model::SnapshotVersion;
  87. using firebase::firestore::model::TargetId;
  88. using firebase::firestore::remote::ConnectivityMonitor;
  89. using firebase::firestore::remote::CreateFirebaseMetadataProviderNoOp;
  90. using firebase::firestore::remote::CreateNoOpConnectivityMonitor;
  91. using firebase::firestore::remote::FirebaseMetadataProvider;
  92. using firebase::firestore::remote::MockDatastore;
  93. using firebase::firestore::remote::RemoteStore;
  94. using firebase::firestore::remote::WatchChange;
  95. using firebase::firestore::testutil::AsyncQueueForTesting;
  96. using firebase::firestore::util::AsyncQueue;
  97. using firebase::firestore::util::DelayedConstructor;
  98. using firebase::firestore::util::Empty;
  99. using firebase::firestore::util::Executor;
  100. using firebase::firestore::util::MakeNSError;
  101. using firebase::firestore::util::MakeNSString;
  102. using firebase::firestore::util::MakeString;
  103. using firebase::firestore::util::Status;
  104. using firebase::firestore::util::StatusOr;
  105. using firebase::firestore::util::StringFormat;
  106. using firebase::firestore::util::TimerId;
  107. using firebase::firestore::util::ToString;
  108. NS_ASSUME_NONNULL_BEGIN
  109. @implementation FSTQueryEvent {
  110. absl::optional<ViewSnapshot> _maybeViewSnapshot;
  111. }
  112. - (const absl::optional<ViewSnapshot> &)viewSnapshot {
  113. return _maybeViewSnapshot;
  114. }
  115. - (void)setViewSnapshot:(absl::optional<ViewSnapshot>)snapshot {
  116. _maybeViewSnapshot = std::move(snapshot);
  117. }
  118. - (NSString *)description {
  119. // The Query is also included in the view, so we skip it.
  120. std::string str = StringFormat("<FSTQueryEvent: viewSnapshot=%s, error=%s>",
  121. ToString(_maybeViewSnapshot), self.error);
  122. return MakeNSString(str);
  123. }
  124. @end
  125. @implementation FSTOutstandingWrite {
  126. Mutation _write;
  127. }
  128. - (const model::Mutation &)write {
  129. return _write;
  130. }
  131. - (void)setWrite:(model::Mutation)write {
  132. _write = std::move(write);
  133. }
  134. @end
  135. @interface FSTSyncEngineTestDriver ()
  136. #pragma mark - Parts of the Firestore system that the spec tests need to control.
  137. #pragma mark - Data structures for holding events sent by the watch stream.
  138. /** A block for the FSTEventAggregator to use to report events to the test. */
  139. @property(nonatomic, strong, readonly) void (^eventHandler)(FSTQueryEvent *);
  140. /** The events received by our eventHandler and not yet retrieved via capturedEventsSinceLastCall */
  141. @property(nonatomic, strong, readonly) NSMutableArray<FSTQueryEvent *> *events;
  142. #pragma mark - Data structures for holding events sent by the write stream.
  143. /** The names of the documents that the client acknowledged during the current spec test step */
  144. @property(nonatomic, strong, readonly) NSMutableArray<NSString *> *acknowledgedDocs;
  145. /** The names of the documents that the client rejected during the current spec test step */
  146. @property(nonatomic, strong, readonly) NSMutableArray<NSString *> *rejectedDocs;
  147. @end
  148. @implementation FSTSyncEngineTestDriver {
  149. size_t _maxConcurrentLimboResolutions;
  150. std::unique_ptr<Persistence> _persistence;
  151. LruDelegate *_lru_delegate;
  152. std::unique_ptr<LocalStore> _localStore;
  153. std::unique_ptr<SyncEngine> _syncEngine;
  154. std::shared_ptr<AsyncQueue> _workerQueue;
  155. std::unique_ptr<RemoteStore> _remoteStore;
  156. std::unique_ptr<ConnectivityMonitor> _connectivityMonitor;
  157. std::unique_ptr<FirebaseMetadataProvider> _firebaseMetadataProvider;
  158. DelayedConstructor<EventManager> _eventManager;
  159. // Set of active targets, keyed by target Id, mapped to corresponding resume token,
  160. // and list of `TargetData`.
  161. ActiveTargetMap _expectedActiveTargets;
  162. // ivar is declared as mutable.
  163. std::unordered_map<User, NSMutableArray<FSTOutstandingWrite *> *, HashUser> _outstandingWrites;
  164. DocumentKeySet _expectedActiveLimboDocuments;
  165. DocumentKeySet _expectedEnqueuedLimboDocuments;
  166. /** A dictionary for tracking the listens on queries. */
  167. std::unordered_map<Query, std::shared_ptr<QueryListener>> _queryListeners;
  168. DatabaseInfo _databaseInfo;
  169. User _currentUser;
  170. std::vector<std::shared_ptr<EventListener<Empty>>> _snapshotsInSyncListeners;
  171. std::shared_ptr<MockDatastore> _datastore;
  172. QueryEngine _queryEngine;
  173. int _snapshotsInSyncEvents;
  174. int _waitForPendingWritesEvents;
  175. }
  176. - (instancetype)initWithPersistence:(std::unique_ptr<Persistence>)persistence
  177. eagerGC:(BOOL)eagerGC
  178. initialUser:(const User &)initialUser
  179. outstandingWrites:(const FSTOutstandingWriteQueues &)outstandingWrites
  180. maxConcurrentLimboResolutions:(size_t)maxConcurrentLimboResolutions {
  181. if (self = [super init]) {
  182. _maxConcurrentLimboResolutions = maxConcurrentLimboResolutions;
  183. // Do a deep copy.
  184. for (const auto &pair : outstandingWrites) {
  185. _outstandingWrites[pair.first] = [pair.second mutableCopy];
  186. }
  187. _events = [NSMutableArray array];
  188. _databaseInfo = {DatabaseId{"test-project", "(default)"}, "persistence", "host", false};
  189. // Set up the sync engine and various stores.
  190. _workerQueue = AsyncQueueForTesting();
  191. _persistence = std::move(persistence);
  192. _localStore = absl::make_unique<LocalStore>(_persistence.get(), &_queryEngine, initialUser);
  193. if (!eagerGC) {
  194. _lru_delegate = static_cast<local::LruDelegate *>(_persistence->reference_delegate());
  195. }
  196. _connectivityMonitor = CreateNoOpConnectivityMonitor();
  197. _firebaseMetadataProvider = CreateFirebaseMetadataProviderNoOp();
  198. _datastore = std::make_shared<MockDatastore>(
  199. _databaseInfo, _workerQueue, std::make_shared<EmptyAuthCredentialsProvider>(),
  200. std::make_shared<EmptyAppCheckCredentialsProvider>(), _connectivityMonitor.get(),
  201. _firebaseMetadataProvider.get());
  202. _remoteStore = absl::make_unique<RemoteStore>(
  203. _localStore.get(), _datastore, _workerQueue, _connectivityMonitor.get(),
  204. [self](OnlineState onlineState) { _syncEngine->HandleOnlineStateChange(onlineState); });
  205. ;
  206. _syncEngine = absl::make_unique<SyncEngine>(_localStore.get(), _remoteStore.get(), initialUser,
  207. _maxConcurrentLimboResolutions);
  208. _remoteStore->set_sync_engine(_syncEngine.get());
  209. _eventManager.Init(_syncEngine.get());
  210. // Set up internal event tracking for the spec tests.
  211. NSMutableArray<FSTQueryEvent *> *events = [NSMutableArray array];
  212. _eventHandler = ^(FSTQueryEvent *e) {
  213. [events addObject:e];
  214. };
  215. _events = events;
  216. _currentUser = initialUser;
  217. _acknowledgedDocs = [NSMutableArray array];
  218. _rejectedDocs = [NSMutableArray array];
  219. }
  220. return self;
  221. }
  222. - (const FSTOutstandingWriteQueues &)outstandingWrites {
  223. return _outstandingWrites;
  224. }
  225. - (const DocumentKeySet &)expectedActiveLimboDocuments {
  226. return _expectedActiveLimboDocuments;
  227. }
  228. - (void)setExpectedActiveLimboDocuments:(DocumentKeySet)docs {
  229. _expectedActiveLimboDocuments = std::move(docs);
  230. }
  231. - (const DocumentKeySet &)expectedEnqueuedLimboDocuments {
  232. return _expectedEnqueuedLimboDocuments;
  233. }
  234. - (void)setExpectedEnqueuedLimboDocuments:(DocumentKeySet)docs {
  235. _expectedEnqueuedLimboDocuments = std::move(docs);
  236. }
  237. - (void)drainQueue {
  238. _workerQueue->EnqueueBlocking([] {});
  239. }
  240. - (const User &)currentUser {
  241. return _currentUser;
  242. }
  243. - (const DatabaseInfo &)databaseInfo {
  244. return _databaseInfo;
  245. }
  246. - (void)incrementSnapshotsInSyncEvents {
  247. _snapshotsInSyncEvents += 1;
  248. }
  249. - (void)resetSnapshotsInSyncEvents {
  250. _snapshotsInSyncEvents = 0;
  251. }
  252. - (void)incrementWaitForPendingWritesEvents {
  253. _waitForPendingWritesEvents += 1;
  254. }
  255. - (void)resetWaitForPendingWritesEvents {
  256. _waitForPendingWritesEvents = 0;
  257. }
  258. - (void)waitForPendingWrites {
  259. _syncEngine->RegisterPendingWritesCallback(
  260. [self](const Status &) { [self incrementWaitForPendingWritesEvents]; });
  261. }
  262. - (void)addSnapshotsInSyncListener {
  263. std::shared_ptr<EventListener<Empty>> eventListener = EventListener<Empty>::Create(
  264. [self](const StatusOr<Empty> &) { [self incrementSnapshotsInSyncEvents]; });
  265. _snapshotsInSyncListeners.push_back(eventListener);
  266. _eventManager->AddSnapshotsInSyncListener(eventListener);
  267. }
  268. - (void)removeSnapshotsInSyncListener {
  269. if (_snapshotsInSyncListeners.empty()) {
  270. HARD_FAIL("There must be a listener to unlisten to");
  271. } else {
  272. _eventManager->RemoveSnapshotsInSyncListener(_snapshotsInSyncListeners.back());
  273. _snapshotsInSyncListeners.pop_back();
  274. }
  275. }
  276. - (int)waitForPendingWritesEvents {
  277. return _waitForPendingWritesEvents;
  278. }
  279. - (int)snapshotsInSyncEvents {
  280. return _snapshotsInSyncEvents;
  281. }
  282. - (void)start {
  283. _workerQueue->EnqueueBlocking([&] {
  284. _localStore->Start();
  285. _remoteStore->Start();
  286. });
  287. }
  288. - (void)validateUsage {
  289. // We could relax this if we found a reason to.
  290. HARD_ASSERT(self.events.count == 0, "You must clear all pending events by calling"
  291. " capturedEventsSinceLastCall before calling shutdown.");
  292. }
  293. - (void)shutdown {
  294. _workerQueue->EnqueueBlocking([&] {
  295. _remoteStore->Shutdown();
  296. _persistence->Shutdown();
  297. });
  298. }
  299. - (void)validateNextWriteSent:(const Mutation &)expectedWrite {
  300. std::vector<Mutation> request = _datastore->NextSentWrite();
  301. // Make sure the write went through the pipe like we expected it to.
  302. HARD_ASSERT(request.size() == 1, "Only single mutation requests are supported at the moment");
  303. const Mutation &actualWrite = request[0];
  304. HARD_ASSERT(actualWrite == expectedWrite,
  305. "Mock datastore received write %s but first outstanding mutation was %s",
  306. actualWrite.ToString(), expectedWrite.ToString());
  307. LOG_DEBUG("A write was sent: %s", actualWrite.ToString());
  308. }
  309. - (int)sentWritesCount {
  310. return _datastore->WritesSent();
  311. }
  312. - (int)writeStreamRequestCount {
  313. return _datastore->write_stream_request_count();
  314. }
  315. - (int)watchStreamRequestCount {
  316. return _datastore->watch_stream_request_count();
  317. }
  318. - (void)disableNetwork {
  319. _workerQueue->EnqueueBlocking([&] {
  320. // Make sure to execute all writes that are currently queued. This allows us
  321. // to assert on the total number of requests sent before shutdown.
  322. _remoteStore->FillWritePipeline();
  323. _remoteStore->DisableNetwork();
  324. });
  325. }
  326. - (void)enableNetwork {
  327. _workerQueue->EnqueueBlocking([&] { _remoteStore->EnableNetwork(); });
  328. }
  329. - (void)runTimer:(TimerId)timerID {
  330. _workerQueue->RunScheduledOperationsUntil(timerID);
  331. }
  332. - (void)triggerLruGC:(NSNumber *)threshold {
  333. if (_lru_delegate != nullptr) {
  334. _workerQueue->EnqueueBlocking([&] {
  335. auto *gc = _lru_delegate->garbage_collector();
  336. // Change params to collect all possible garbages
  337. gc->set_lru_params(LruParams{/*min_bytes_threshold*/ threshold.longValue,
  338. /*percentile_to_collect*/ 100,
  339. /*maximum_sequence_numbers_to_collect*/ 1000});
  340. _localStore->CollectGarbage(gc);
  341. });
  342. }
  343. }
  344. - (void)changeUser:(const User &)user {
  345. _currentUser = user;
  346. _workerQueue->EnqueueBlocking([&] { _syncEngine->HandleCredentialChange(user); });
  347. }
  348. - (FSTOutstandingWrite *)receiveWriteAckWithVersion:(const SnapshotVersion &)commitVersion
  349. mutationResults:(std::vector<MutationResult>)mutationResults {
  350. FSTOutstandingWrite *write = [self currentOutstandingWrites].firstObject;
  351. [[self currentOutstandingWrites] removeObjectAtIndex:0];
  352. [self validateNextWriteSent:write.write];
  353. _workerQueue->EnqueueBlocking(
  354. [&] { _datastore->AckWrite(commitVersion, std::move(mutationResults)); });
  355. return write;
  356. }
  357. - (FSTOutstandingWrite *)receiveWriteError:(int)errorCode
  358. userInfo:(NSDictionary<NSString *, id> *)userInfo
  359. keepInQueue:(BOOL)keepInQueue {
  360. Status error{static_cast<Error>(errorCode), MakeString([userInfo description])};
  361. FSTOutstandingWrite *write = [self currentOutstandingWrites].firstObject;
  362. [self validateNextWriteSent:write.write];
  363. // If this is a permanent error, the mutation is not expected to be sent again so we remove it
  364. // from currentOutstandingWrites.
  365. if (!keepInQueue) {
  366. [[self currentOutstandingWrites] removeObjectAtIndex:0];
  367. }
  368. LOG_DEBUG("Failing a write.");
  369. _workerQueue->EnqueueBlocking([&] { _datastore->FailWrite(error); });
  370. return write;
  371. }
  372. - (NSArray<FSTQueryEvent *> *)capturedEventsSinceLastCall {
  373. NSArray<FSTQueryEvent *> *result = [self.events copy];
  374. [self.events removeAllObjects];
  375. return result;
  376. }
  377. - (NSArray<NSString *> *)capturedAcknowledgedWritesSinceLastCall {
  378. NSArray<NSString *> *result = [self.acknowledgedDocs copy];
  379. [self.acknowledgedDocs removeAllObjects];
  380. return result;
  381. }
  382. - (NSArray<NSString *> *)capturedRejectedWritesSinceLastCall {
  383. NSArray<NSString *> *result = [self.rejectedDocs copy];
  384. [self.rejectedDocs removeAllObjects];
  385. return result;
  386. }
  387. - (TargetId)addUserListenerWithQuery:(Query)query {
  388. // TODO(dimond): Allow customizing listen options in spec tests
  389. // TODO(dimond): Change spec tests to verify isFromCache on snapshots
  390. ListenOptions options = ListenOptions::FromIncludeMetadataChanges(true);
  391. auto listener = QueryListener::Create(
  392. query, options, [self, query](const StatusOr<ViewSnapshot> &maybe_snapshot) {
  393. FSTQueryEvent *event = [[FSTQueryEvent alloc] init];
  394. event.query = query;
  395. if (maybe_snapshot.ok()) {
  396. [event setViewSnapshot:maybe_snapshot.ValueOrDie()];
  397. } else {
  398. event.error = MakeNSError(maybe_snapshot.status());
  399. }
  400. [self.events addObject:event];
  401. });
  402. _queryListeners[query] = listener;
  403. TargetId targetID;
  404. _workerQueue->EnqueueBlocking([&] { targetID = _eventManager->AddQueryListener(listener); });
  405. return targetID;
  406. }
  407. - (void)removeUserListenerWithQuery:(const Query &)query {
  408. auto found_iter = _queryListeners.find(query);
  409. if (found_iter != _queryListeners.end()) {
  410. std::shared_ptr<QueryListener> listener = found_iter->second;
  411. _queryListeners.erase(found_iter);
  412. _workerQueue->EnqueueBlocking([&] { _eventManager->RemoveQueryListener(listener); });
  413. }
  414. }
  415. - (void)loadBundleWithReader:(std::shared_ptr<BundleReader>)reader
  416. task:(std::shared_ptr<LoadBundleTask>)task {
  417. _workerQueue->EnqueueBlocking(
  418. [=] { _syncEngine->LoadBundle(std::move(reader), std::move(task)); });
  419. }
  420. - (void)writeUserMutation:(Mutation)mutation {
  421. FSTOutstandingWrite *write = [[FSTOutstandingWrite alloc] init];
  422. write.write = mutation;
  423. [[self currentOutstandingWrites] addObject:write];
  424. LOG_DEBUG("sending a user write.");
  425. _workerQueue->EnqueueBlocking([=] {
  426. _syncEngine->WriteMutations({mutation}, [self, write, mutation](Status error) {
  427. LOG_DEBUG("A callback was called with error: %s", error.error_message());
  428. write.done = YES;
  429. write.error = error.ToNSError();
  430. NSString *mutationKey = MakeNSString(mutation.key().ToString());
  431. if (!error.ok()) {
  432. [self.rejectedDocs addObject:mutationKey];
  433. } else {
  434. [self.acknowledgedDocs addObject:mutationKey];
  435. }
  436. });
  437. });
  438. }
  439. - (void)receiveWatchChange:(const WatchChange &)change
  440. snapshotVersion:(const SnapshotVersion &)snapshot {
  441. _workerQueue->EnqueueBlocking([&] { _datastore->WriteWatchChange(change, snapshot); });
  442. }
  443. - (void)receiveWatchStreamError:(int)errorCode userInfo:(NSDictionary<NSString *, id> *)userInfo {
  444. Status error{static_cast<Error>(errorCode), MakeString([userInfo description])};
  445. _workerQueue->EnqueueBlocking([&] {
  446. _datastore->FailWatchStream(error);
  447. // Unlike web, stream should re-open synchronously (if we have any listeners)
  448. if (!_queryListeners.empty()) {
  449. HARD_ASSERT(_datastore->IsWatchStreamOpen(), "Watch stream is open");
  450. }
  451. });
  452. }
  453. - (std::map<DocumentKey, TargetId>)activeLimboDocumentResolutions {
  454. return _syncEngine->GetActiveLimboDocumentResolutions();
  455. }
  456. - (std::vector<DocumentKey>)enqueuedLimboDocumentResolutions {
  457. return _syncEngine->GetEnqueuedLimboDocumentResolutions();
  458. }
  459. - (const std::unordered_map<TargetId, TargetData> &)activeTargets {
  460. return _datastore->ActiveTargets();
  461. }
  462. - (const ActiveTargetMap &)expectedActiveTargets {
  463. return _expectedActiveTargets;
  464. }
  465. - (void)setExpectedActiveTargets:(ActiveTargetMap)targets {
  466. _expectedActiveTargets = std::move(targets);
  467. }
  468. #pragma mark - Helper Methods
  469. - (NSMutableArray<FSTOutstandingWrite *> *)currentOutstandingWrites {
  470. NSMutableArray<FSTOutstandingWrite *> *writes = _outstandingWrites[_currentUser];
  471. if (!writes) {
  472. writes = [NSMutableArray array];
  473. _outstandingWrites[_currentUser] = writes;
  474. }
  475. return writes;
  476. }
  477. @end
  478. NS_ASSUME_NONNULL_END