FSTSyncEngineTestDriver.mm 16 KB

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