FSTSyncEngineTestDriver.mm 17 KB

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