FSTSyncEngineTestDriver.mm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. #import <GRPCClient/GRPCCall.h>
  19. #include <map>
  20. #include <unordered_map>
  21. #import "Firestore/Source/Core/FSTEventManager.h"
  22. #import "Firestore/Source/Core/FSTQuery.h"
  23. #import "Firestore/Source/Core/FSTSyncEngine.h"
  24. #import "Firestore/Source/Local/FSTLocalStore.h"
  25. #import "Firestore/Source/Local/FSTPersistence.h"
  26. #import "Firestore/Source/Model/FSTMutation.h"
  27. #import "Firestore/Source/Remote/FSTDatastore.h"
  28. #import "Firestore/Source/Remote/FSTWatchChange.h"
  29. #import "Firestore/Example/Tests/Core/FSTSyncEngine+Testing.h"
  30. #import "Firestore/Example/Tests/SpecTests/FSTMockDatastore.h"
  31. #include "Firestore/core/src/firebase/firestore/auth/empty_credentials_provider.h"
  32. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  33. #include "Firestore/core/src/firebase/firestore/core/database_info.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/util/hard_assert.h"
  37. #include "Firestore/core/src/firebase/firestore/util/log.h"
  38. using firebase::firestore::auth::EmptyCredentialsProvider;
  39. using firebase::firestore::auth::HashUser;
  40. using firebase::firestore::auth::User;
  41. using firebase::firestore::core::DatabaseInfo;
  42. using firebase::firestore::model::DatabaseId;
  43. using firebase::firestore::model::DocumentKey;
  44. using firebase::firestore::model::OnlineState;
  45. using firebase::firestore::model::SnapshotVersion;
  46. using firebase::firestore::model::TargetId;
  47. NS_ASSUME_NONNULL_BEGIN
  48. @implementation FSTQueryEvent
  49. - (NSString *)description {
  50. // The Query is also included in the view, so we skip it.
  51. return [NSString stringWithFormat:@"<FSTQueryEvent: viewSnapshot=%@, error=%@>",
  52. self.viewSnapshot, self.error];
  53. }
  54. @end
  55. @implementation FSTOutstandingWrite
  56. @end
  57. @interface FSTSyncEngineTestDriver ()
  58. #pragma mark - Parts of the Firestore system that the spec tests need to control.
  59. @property(nonatomic, strong, readonly) FSTMockDatastore *datastore;
  60. @property(nonatomic, strong, readonly) FSTEventManager *eventManager;
  61. @property(nonatomic, strong, readonly) FSTRemoteStore *remoteStore;
  62. @property(nonatomic, strong, readonly) FSTLocalStore *localStore;
  63. @property(nonatomic, strong, readonly) FSTSyncEngine *syncEngine;
  64. @property(nonatomic, strong, readonly) FSTDispatchQueue *dispatchQueue;
  65. #pragma mark - Data structures for holding events sent by the watch stream.
  66. /** A block for the FSTEventAggregator to use to report events to the test. */
  67. @property(nonatomic, strong, readonly) void (^eventHandler)(FSTQueryEvent *);
  68. /** The events received by our eventHandler and not yet retrieved via capturedEventsSinceLastCall */
  69. @property(nonatomic, strong, readonly) NSMutableArray<FSTQueryEvent *> *events;
  70. /** A dictionary for tracking the listens on queries. */
  71. @property(nonatomic, strong, readonly)
  72. NSMutableDictionary<FSTQuery *, FSTQueryListener *> *queryListeners;
  73. #pragma mark - Data structures for holding events sent by the write stream.
  74. /** The names of the documents that the client acknowledged during the current spec test step */
  75. @property(nonatomic, strong, readonly) NSMutableArray<NSString *> *acknowledgedDocs;
  76. /** The names of the documents that the client rejected during the current spec test step */
  77. @property(nonatomic, strong, readonly) NSMutableArray<NSString *> *rejectedDocs;
  78. @end
  79. @implementation FSTSyncEngineTestDriver {
  80. // ivar is declared as mutable.
  81. std::unordered_map<User, NSMutableArray<FSTOutstandingWrite *> *, HashUser> _outstandingWrites;
  82. DatabaseInfo _databaseInfo;
  83. User _currentUser;
  84. EmptyCredentialsProvider _credentialProvider;
  85. }
  86. - (instancetype)initWithPersistence:(id<FSTPersistence>)persistence {
  87. return [self initWithPersistence:persistence
  88. initialUser:User::Unauthenticated()
  89. outstandingWrites:{}];
  90. }
  91. - (instancetype)initWithPersistence:(id<FSTPersistence>)persistence
  92. initialUser:(const User &)initialUser
  93. outstandingWrites:(const FSTOutstandingWriteQueues &)outstandingWrites {
  94. if (self = [super init]) {
  95. // Do a deep copy.
  96. for (const auto &pair : outstandingWrites) {
  97. _outstandingWrites[pair.first] = [pair.second mutableCopy];
  98. }
  99. _events = [NSMutableArray array];
  100. _databaseInfo = {DatabaseId{"project", "database"}, "persistence", "host", false};
  101. // Set up the sync engine and various stores.
  102. dispatch_queue_t queue =
  103. dispatch_queue_create("sync_engine_test_driver", DISPATCH_QUEUE_SERIAL);
  104. _dispatchQueue = [FSTDispatchQueue queueWith:queue];
  105. _localStore = [[FSTLocalStore alloc] initWithPersistence:persistence initialUser:initialUser];
  106. _datastore = [[FSTMockDatastore alloc] initWithDatabaseInfo:&_databaseInfo
  107. workerDispatchQueue:_dispatchQueue
  108. credentials:&_credentialProvider];
  109. _remoteStore = [[FSTRemoteStore alloc] initWithLocalStore:_localStore
  110. datastore:_datastore
  111. workerDispatchQueue:_dispatchQueue];
  112. _syncEngine = [[FSTSyncEngine alloc] initWithLocalStore:_localStore
  113. remoteStore:_remoteStore
  114. initialUser:initialUser];
  115. _remoteStore.syncEngine = _syncEngine;
  116. _eventManager = [FSTEventManager eventManagerWithSyncEngine:_syncEngine];
  117. _remoteStore.onlineStateDelegate = self;
  118. // Set up internal event tracking for the spec tests.
  119. NSMutableArray<FSTQueryEvent *> *events = [NSMutableArray array];
  120. _eventHandler = ^(FSTQueryEvent *e) {
  121. [events addObject:e];
  122. };
  123. _events = events;
  124. _queryListeners = [NSMutableDictionary dictionary];
  125. _expectedLimboDocuments = [NSSet set];
  126. _expectedActiveTargets = [NSDictionary dictionary];
  127. _currentUser = initialUser;
  128. _acknowledgedDocs = [NSMutableArray array];
  129. _rejectedDocs = [NSMutableArray array];
  130. }
  131. return self;
  132. }
  133. - (const FSTOutstandingWriteQueues &)outstandingWrites {
  134. return _outstandingWrites;
  135. }
  136. - (void)drainQueue {
  137. [_dispatchQueue dispatchSync:^(){
  138. }];
  139. }
  140. - (const User &)currentUser {
  141. return _currentUser;
  142. }
  143. - (void)applyChangedOnlineState:(OnlineState)onlineState {
  144. [self.syncEngine applyChangedOnlineState:onlineState];
  145. [self.eventManager applyChangedOnlineState:onlineState];
  146. }
  147. - (void)start {
  148. [self.dispatchQueue dispatchSync:^{
  149. [self.localStore start];
  150. [self.remoteStore start];
  151. }];
  152. }
  153. - (void)validateUsage {
  154. // We could relax this if we found a reason to.
  155. HARD_ASSERT(self.events.count == 0,
  156. "You must clear all pending events by calling"
  157. " capturedEventsSinceLastCall before calling shutdown.");
  158. }
  159. - (void)shutdown {
  160. [self.dispatchQueue dispatchSync:^{
  161. [self.remoteStore shutdown];
  162. }];
  163. }
  164. - (void)validateNextWriteSent:(FSTMutation *)expectedWrite {
  165. NSArray<FSTMutation *> *request = [self.datastore nextSentWrite];
  166. // Make sure the write went through the pipe like we expected it to.
  167. HARD_ASSERT(request.count == 1, "Only single mutation requests are supported at the moment");
  168. FSTMutation *actualWrite = request[0];
  169. HARD_ASSERT([actualWrite isEqual:expectedWrite],
  170. "Mock datastore received write %s but first outstanding mutation was %s", actualWrite,
  171. expectedWrite);
  172. LOG_DEBUG("A write was sent: %s", actualWrite);
  173. }
  174. - (int)sentWritesCount {
  175. return [self.datastore writesSent];
  176. }
  177. - (int)writeStreamRequestCount {
  178. return [self.datastore writeStreamRequestCount];
  179. }
  180. - (int)watchStreamRequestCount {
  181. return [self.datastore watchStreamRequestCount];
  182. }
  183. - (void)disableNetwork {
  184. [self.dispatchQueue dispatchSync:^{
  185. // Make sure to execute all writes that are currently queued. This allows us
  186. // to assert on the total number of requests sent before shutdown.
  187. [self.remoteStore fillWritePipeline];
  188. [self.remoteStore disableNetwork];
  189. }];
  190. }
  191. - (void)enableNetwork {
  192. [self.dispatchQueue dispatchSync:^{
  193. [self.remoteStore enableNetwork];
  194. }];
  195. }
  196. - (void)runTimer:(FSTTimerID)timerID {
  197. [self.dispatchQueue runDelayedCallbacksUntil:timerID];
  198. }
  199. - (void)changeUser:(const User &)user {
  200. _currentUser = user;
  201. [self.dispatchQueue dispatchSync:^{
  202. [self.syncEngine credentialDidChangeWithUser:user];
  203. }];
  204. }
  205. - (FSTOutstandingWrite *)receiveWriteAckWithVersion:(const SnapshotVersion &)commitVersion
  206. mutationResults:
  207. (NSArray<FSTMutationResult *> *)mutationResults {
  208. FSTOutstandingWrite *write = [self currentOutstandingWrites].firstObject;
  209. [[self currentOutstandingWrites] removeObjectAtIndex:0];
  210. [self validateNextWriteSent:write.write];
  211. [self.dispatchQueue dispatchSync:^{
  212. [self.datastore ackWriteWithVersion:commitVersion mutationResults:mutationResults];
  213. }];
  214. return write;
  215. }
  216. - (FSTOutstandingWrite *)receiveWriteError:(int)errorCode
  217. userInfo:(NSDictionary<NSString *, id> *)userInfo
  218. keepInQueue:(BOOL)keepInQueue {
  219. NSError *error =
  220. [NSError errorWithDomain:FIRFirestoreErrorDomain code:errorCode userInfo:userInfo];
  221. FSTOutstandingWrite *write = [self currentOutstandingWrites].firstObject;
  222. [self validateNextWriteSent:write.write];
  223. // If this is a permanent error, the mutation is not expected to be sent again so we remove it
  224. // from currentOutstandingWrites.
  225. if (!keepInQueue) {
  226. [[self currentOutstandingWrites] removeObjectAtIndex:0];
  227. }
  228. LOG_DEBUG("Failing a write.");
  229. [self.dispatchQueue dispatchSync:^{
  230. [self.datastore failWriteWithError:error];
  231. }];
  232. return write;
  233. }
  234. - (NSArray<FSTQueryEvent *> *)capturedEventsSinceLastCall {
  235. NSArray<FSTQueryEvent *> *result = [self.events copy];
  236. [self.events removeAllObjects];
  237. return result;
  238. }
  239. - (NSArray<NSString *> *)capturedAcknowledgedWritesSinceLastCall {
  240. NSArray<NSString *> *result = [self.acknowledgedDocs copy];
  241. [self.acknowledgedDocs removeAllObjects];
  242. return result;
  243. }
  244. - (NSArray<NSString *> *)capturedRejectedWritesSinceLastCall {
  245. NSArray<NSString *> *result = [self.rejectedDocs copy];
  246. [self.rejectedDocs removeAllObjects];
  247. return result;
  248. }
  249. - (TargetId)addUserListenerWithQuery:(FSTQuery *)query {
  250. // TODO(dimond): Allow customizing listen options in spec tests
  251. // TODO(dimond): Change spec tests to verify isFromCache on snapshots
  252. FSTListenOptions *options = [[FSTListenOptions alloc] initWithIncludeQueryMetadataChanges:YES
  253. includeDocumentMetadataChanges:YES
  254. waitForSyncWhenOnline:NO];
  255. FSTQueryListener *listener = [[FSTQueryListener alloc]
  256. initWithQuery:query
  257. options:options
  258. viewSnapshotHandler:^(FSTViewSnapshot *_Nullable snapshot, NSError *_Nullable error) {
  259. FSTQueryEvent *event = [[FSTQueryEvent alloc] init];
  260. event.query = query;
  261. event.viewSnapshot = snapshot;
  262. event.error = error;
  263. [self.events addObject:event];
  264. }];
  265. self.queryListeners[query] = listener;
  266. __block TargetId targetID;
  267. [self.dispatchQueue dispatchSync:^{
  268. targetID = [self.eventManager addListener:listener];
  269. }];
  270. return targetID;
  271. }
  272. - (void)removeUserListenerWithQuery:(FSTQuery *)query {
  273. FSTQueryListener *listener = self.queryListeners[query];
  274. [self.queryListeners removeObjectForKey:query];
  275. [self.dispatchQueue dispatchSync:^{
  276. [self.eventManager removeListener:listener];
  277. }];
  278. }
  279. - (void)writeUserMutation:(FSTMutation *)mutation {
  280. FSTOutstandingWrite *write = [[FSTOutstandingWrite alloc] init];
  281. write.write = mutation;
  282. [[self currentOutstandingWrites] addObject:write];
  283. LOG_DEBUG("sending a user write.");
  284. [self.dispatchQueue dispatchSync:^{
  285. [self.syncEngine writeMutations:@[ mutation ]
  286. completion:^(NSError *_Nullable error) {
  287. LOG_DEBUG("A callback was called with error: %s", error);
  288. write.done = YES;
  289. write.error = error;
  290. NSString *mutationKey =
  291. [NSString stringWithCString:mutation.key.ToString().c_str()
  292. encoding:[NSString defaultCStringEncoding]];
  293. if (error) {
  294. [self.rejectedDocs addObject:mutationKey];
  295. } else {
  296. [self.acknowledgedDocs addObject:mutationKey];
  297. }
  298. }];
  299. }];
  300. }
  301. - (void)receiveWatchChange:(FSTWatchChange *)change
  302. snapshotVersion:(const SnapshotVersion &)snapshot {
  303. [self.dispatchQueue dispatchSync:^{
  304. [self.datastore writeWatchChange:change snapshotVersion:snapshot];
  305. }];
  306. }
  307. - (void)receiveWatchStreamError:(int)errorCode userInfo:(NSDictionary<NSString *, id> *)userInfo {
  308. NSError *error =
  309. [NSError errorWithDomain:FIRFirestoreErrorDomain code:errorCode userInfo:userInfo];
  310. [self.dispatchQueue dispatchSync:^{
  311. [self.datastore failWatchStreamWithError:error];
  312. // Unlike web, stream should re-open synchronously (if we have any listeners)
  313. if (self.queryListeners.count > 0) {
  314. HARD_ASSERT(self.datastore.isWatchStreamOpen, "Watch stream is open");
  315. }
  316. }];
  317. }
  318. - (std::map<DocumentKey, TargetId>)currentLimboDocuments {
  319. return [self.syncEngine currentLimboDocuments];
  320. }
  321. - (NSDictionary<FSTBoxedTargetID *, FSTQueryData *> *)activeTargets {
  322. return [[self.datastore activeTargets] copy];
  323. }
  324. #pragma mark - Helper Methods
  325. - (NSMutableArray<FSTOutstandingWrite *> *)currentOutstandingWrites {
  326. NSMutableArray<FSTOutstandingWrite *> *writes = _outstandingWrites[_currentUser];
  327. if (!writes) {
  328. writes = [NSMutableArray array];
  329. _outstandingWrites[_currentUser] = writes;
  330. }
  331. return writes;
  332. }
  333. @end
  334. NS_ASSUME_NONNULL_END