FSTSyncEngineTestDriver.mm 18 KB

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