FSTSyncEngineTestDriver.mm 13 KB

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