FSTSyncEngineTestDriver.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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 "FSTSyncEngineTestDriver.h"
  17. #import <GRPCClient/GRPCCall.h>
  18. #import "Auth/FSTUser.h"
  19. #import "Core/FSTEventManager.h"
  20. #import "Core/FSTQuery.h"
  21. #import "Core/FSTSnapshotVersion.h"
  22. #import "Core/FSTSyncEngine.h"
  23. #import "Firestore/FIRFirestoreErrors.h"
  24. #import "Local/FSTLocalStore.h"
  25. #import "Local/FSTPersistence.h"
  26. #import "Model/FSTMutation.h"
  27. #import "Remote/FSTDatastore.h"
  28. #import "Remote/FSTWatchChange.h"
  29. #import "Util/FSTAssert.h"
  30. #import "Util/FSTDispatchQueue.h"
  31. #import "Util/FSTLogger.h"
  32. #import "FSTMockDatastore.h"
  33. #import "FSTSyncEngine+Testing.h"
  34. NS_ASSUME_NONNULL_BEGIN
  35. @implementation FSTQueryEvent
  36. - (NSString *)description {
  37. // The Query is also included in the view, so we skip it.
  38. return [NSString stringWithFormat:@"<FSTQueryEvent: viewSnapshot=%@, error=%@>",
  39. self.viewSnapshot, self.error];
  40. }
  41. @end
  42. @implementation FSTOutstandingWrite
  43. @end
  44. @interface FSTSyncEngineTestDriver ()
  45. #pragma mark - Parts of the Firestore system that the spec tests need to control.
  46. @property(nonatomic, strong, readonly) FSTMockDatastore *datastore;
  47. @property(nonatomic, strong, readonly) FSTEventManager *eventManager;
  48. @property(nonatomic, strong, readonly) FSTRemoteStore *remoteStore;
  49. @property(nonatomic, strong, readonly) FSTLocalStore *localStore;
  50. @property(nonatomic, strong, readonly) FSTSyncEngine *syncEngine;
  51. #pragma mark - Data structures for holding events sent by the watch stream.
  52. /** A block for the FSTEventAggregator to use to report events to the test. */
  53. @property(nonatomic, strong, readonly) void (^eventHandler)(FSTQueryEvent *);
  54. /** The events received by our eventHandler and not yet retrieved via capturedEventsSinceLastCall */
  55. @property(nonatomic, strong, readonly) NSMutableArray<FSTQueryEvent *> *events;
  56. /** A dictionary for tracking the listens on queries. */
  57. @property(nonatomic, strong, readonly)
  58. NSMutableDictionary<FSTQuery *, FSTQueryListener *> *queryListeners;
  59. #pragma mark - Other data structures.
  60. @property(nonatomic, strong, readwrite) FSTUser *currentUser;
  61. @end
  62. @implementation FSTSyncEngineTestDriver {
  63. // ivar is declared as mutable.
  64. NSMutableDictionary<FSTUser *, NSMutableArray<FSTOutstandingWrite *> *> *_outstandingWrites;
  65. }
  66. - (instancetype)initWithPersistence:(id<FSTPersistence>)persistence
  67. garbageCollector:(id<FSTGarbageCollector>)garbageCollector {
  68. return [self initWithPersistence:persistence
  69. garbageCollector:garbageCollector
  70. initialUser:[FSTUser unauthenticatedUser]
  71. outstandingWrites:@{}];
  72. }
  73. - (instancetype)initWithPersistence:(id<FSTPersistence>)persistence
  74. garbageCollector:(id<FSTGarbageCollector>)garbageCollector
  75. initialUser:(FSTUser *)initialUser
  76. outstandingWrites:(FSTOutstandingWriteQueues *)outstandingWrites {
  77. if (self = [super init]) {
  78. // Create mutable copy of outstandingWrites.
  79. _outstandingWrites = [NSMutableDictionary dictionary];
  80. [outstandingWrites enumerateKeysAndObjectsUsingBlock:^(
  81. FSTUser *user, NSArray<FSTOutstandingWrite *> *writes, BOOL *stop) {
  82. _outstandingWrites[user] = [writes mutableCopy];
  83. }];
  84. _events = [NSMutableArray array];
  85. // Set up the sync engine and various stores.
  86. dispatch_queue_t mainQueue = dispatch_get_main_queue();
  87. FSTDispatchQueue *dispatchQueue = [FSTDispatchQueue queueWith:mainQueue];
  88. _localStore = [[FSTLocalStore alloc] initWithPersistence:persistence
  89. garbageCollector:garbageCollector
  90. initialUser:initialUser];
  91. _datastore = [FSTMockDatastore mockDatastoreWithWorkerDispatchQueue:dispatchQueue];
  92. _remoteStore = [FSTRemoteStore remoteStoreWithLocalStore:_localStore datastore:_datastore];
  93. _syncEngine = [[FSTSyncEngine alloc] initWithLocalStore:_localStore
  94. remoteStore:_remoteStore
  95. initialUser:initialUser];
  96. _remoteStore.syncEngine = _syncEngine;
  97. _eventManager = [FSTEventManager eventManagerWithSyncEngine:_syncEngine];
  98. _remoteStore.onlineStateDelegate = _eventManager;
  99. // Set up internal event tracking for the spec tests.
  100. NSMutableArray<FSTQueryEvent *> *events = [NSMutableArray array];
  101. _eventHandler = ^(FSTQueryEvent *e) {
  102. [events addObject:e];
  103. };
  104. _events = events;
  105. _queryListeners = [NSMutableDictionary dictionary];
  106. _expectedLimboDocuments = [NSSet set];
  107. _expectedActiveTargets = [NSDictionary dictionary];
  108. _currentUser = initialUser;
  109. }
  110. return self;
  111. }
  112. - (void)start {
  113. [self.localStore start];
  114. [self.remoteStore start];
  115. }
  116. - (void)validateUsage {
  117. // We could relax this if we found a reason to.
  118. FSTAssert(self.events.count == 0,
  119. @"You must clear all pending events by calling"
  120. " capturedEventsSinceLastCall before calling shutdown.");
  121. }
  122. - (void)shutdown {
  123. [self.remoteStore shutdown];
  124. [self.localStore shutdown];
  125. }
  126. - (void)validateNextWriteSent:(FSTMutation *)expectedWrite {
  127. NSArray<FSTMutation *> *request = [self.datastore nextSentWrite];
  128. // Make sure the write went through the pipe like we expected it to.
  129. FSTAssert(request.count == 1, @"Only single mutation requests are supported at the moment");
  130. FSTMutation *actualWrite = request[0];
  131. FSTAssert([actualWrite isEqual:expectedWrite],
  132. @"Mock datastore received write %@ but first outstanding mutation was %@", actualWrite,
  133. expectedWrite);
  134. FSTLog(@"A write was sent: %@", actualWrite);
  135. }
  136. - (int)sentWritesCount {
  137. return [self.datastore writesSent];
  138. }
  139. - (void)changeUser:(FSTUser *)user {
  140. self.currentUser = user;
  141. [self.syncEngine userDidChange:user];
  142. }
  143. - (FSTOutstandingWrite *)receiveWriteAckWithVersion:(FSTSnapshotVersion *)commitVersion
  144. mutationResults:
  145. (NSArray<FSTMutationResult *> *)mutationResults {
  146. FSTOutstandingWrite *write = [self currentOutstandingWrites].firstObject;
  147. [[self currentOutstandingWrites] removeObjectAtIndex:0];
  148. [self validateNextWriteSent:write.write];
  149. [self.datastore ackWriteWithVersion:commitVersion mutationResults:mutationResults];
  150. return write;
  151. }
  152. - (FSTOutstandingWrite *)receiveWriteError:(int)errorCode
  153. userInfo:(NSDictionary<NSString *, id> *)userInfo {
  154. NSError *error =
  155. [NSError errorWithDomain:FIRFirestoreErrorDomain code:errorCode userInfo:userInfo];
  156. FSTOutstandingWrite *write = [self currentOutstandingWrites].firstObject;
  157. [self validateNextWriteSent:write.write];
  158. // If this is a permanent error, the mutation is not expected to be sent again so we remove it
  159. // from currentOutstandingWrites.
  160. if ([FSTDatastore isPermanentWriteError:error]) {
  161. [[self currentOutstandingWrites] removeObjectAtIndex:0];
  162. }
  163. FSTLog(@"Failing a write.");
  164. [self.datastore failWriteWithError:error];
  165. return write;
  166. }
  167. - (NSArray<FSTQueryEvent *> *)capturedEventsSinceLastCall {
  168. NSArray<FSTQueryEvent *> *result = [self.events copy];
  169. [self.events removeAllObjects];
  170. return result;
  171. }
  172. - (FSTTargetID)addUserListenerWithQuery:(FSTQuery *)query {
  173. // TODO(dimond): Allow customizing listen options in spec tests
  174. // TODO(dimond): Change spec tests to verify isFromCache on snapshots
  175. FSTListenOptions *options = [[FSTListenOptions alloc] initWithIncludeQueryMetadataChanges:YES
  176. includeDocumentMetadataChanges:YES
  177. waitForSyncWhenOnline:NO];
  178. FSTQueryListener *listener = [[FSTQueryListener alloc]
  179. initWithQuery:query
  180. options:options
  181. viewSnapshotHandler:^(FSTViewSnapshot *_Nullable snapshot, NSError *_Nullable error) {
  182. FSTQueryEvent *event = [[FSTQueryEvent alloc] init];
  183. event.query = query;
  184. event.viewSnapshot = snapshot;
  185. event.error = error;
  186. [self.events addObject:event];
  187. }];
  188. self.queryListeners[query] = listener;
  189. return [self.eventManager addListener:listener];
  190. }
  191. - (void)removeUserListenerWithQuery:(FSTQuery *)query {
  192. FSTQueryListener *listener = self.queryListeners[query];
  193. [self.queryListeners removeObjectForKey:query];
  194. [self.eventManager removeListener:listener];
  195. }
  196. - (void)writeUserMutation:(FSTMutation *)mutation {
  197. FSTOutstandingWrite *write = [[FSTOutstandingWrite alloc] init];
  198. write.write = mutation;
  199. [[self currentOutstandingWrites] addObject:write];
  200. FSTLog(@"sending a user write.");
  201. [self.syncEngine writeMutations:@[ mutation ]
  202. completion:^(NSError *_Nullable error) {
  203. FSTLog(@"A callback was called with error: %@", error);
  204. write.done = YES;
  205. write.error = error;
  206. }];
  207. }
  208. - (void)receiveWatchChange:(FSTWatchChange *)change
  209. snapshotVersion:(FSTSnapshotVersion *_Nullable)snapshot {
  210. [self.datastore writeWatchChange:change snapshotVersion:snapshot];
  211. }
  212. - (void)receiveWatchStreamError:(int)errorCode userInfo:(NSDictionary<NSString *, id> *)userInfo {
  213. NSError *error =
  214. [NSError errorWithDomain:FIRFirestoreErrorDomain code:errorCode userInfo:userInfo];
  215. [self.datastore failWatchStreamWithError:error];
  216. // Unlike web, stream should re-open synchronously
  217. FSTAssert(self.datastore.isWatchStreamOpen, @"Watch stream is open");
  218. }
  219. - (NSDictionary<FSTDocumentKey *, FSTBoxedTargetID *> *)currentLimboDocuments {
  220. return [self.syncEngine currentLimboDocuments];
  221. }
  222. - (NSDictionary<FSTBoxedTargetID *, FSTQueryData *> *)activeTargets {
  223. return [[self.datastore activeTargets] copy];
  224. }
  225. #pragma mark - Helper Methods
  226. - (NSMutableArray<FSTOutstandingWrite *> *)currentOutstandingWrites {
  227. NSMutableArray<FSTOutstandingWrite *> *writes = _outstandingWrites[self.currentUser];
  228. if (!writes) {
  229. writes = [NSMutableArray array];
  230. _outstandingWrites[self.currentUser] = writes;
  231. }
  232. return writes;
  233. }
  234. @end
  235. NS_ASSUME_NONNULL_END