FSTSyncEngineTestDriver.mm 16 KB

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