FSTSyncEngineTestDriver.mm 19 KB

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