FSTSyncEngineTestDriver.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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 <Foundation/Foundation.h>
  17. #include <unordered_map>
  18. #import "Firestore/Source/Core/FSTTypes.h"
  19. #import "Firestore/Source/Remote/FSTRemoteStore.h"
  20. #import "Firestore/Source/Util/FSTDispatchQueue.h"
  21. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  22. @class FSTDocumentKey;
  23. @class FSTMutation;
  24. @class FSTMutationResult;
  25. @class FSTQuery;
  26. @class FSTQueryData;
  27. @class FSTSnapshotVersion;
  28. @class FSTViewSnapshot;
  29. @class FSTWatchChange;
  30. @protocol FSTGarbageCollector;
  31. @protocol FSTPersistence;
  32. NS_ASSUME_NONNULL_BEGIN
  33. /**
  34. * Interface used for object that contain exactly one of either a view snapshot or an error for the
  35. * given query.
  36. */
  37. @interface FSTQueryEvent : NSObject
  38. @property(nonatomic, strong) FSTQuery *query;
  39. @property(nonatomic, strong, nullable) FSTViewSnapshot *viewSnapshot;
  40. @property(nonatomic, strong, nullable) NSError *error;
  41. @end
  42. /** Holds an outstanding write and its result. */
  43. @interface FSTOutstandingWrite : NSObject
  44. /** The write that is outstanding. */
  45. @property(nonatomic, strong, readwrite) FSTMutation *write;
  46. /** Whether this write is done (regardless of whether it was successful or not). */
  47. @property(nonatomic, assign, readwrite) BOOL done;
  48. /** The error - if any - of this write. */
  49. @property(nonatomic, strong, nullable, readwrite) NSError *error;
  50. @end
  51. /** Mapping of user => array of FSTMutations for that user. */
  52. typedef std::unordered_map<firebase::firestore::auth::User,
  53. NSMutableArray<FSTOutstandingWrite *> *,
  54. firebase::firestore::auth::HashUser>
  55. FSTOutstandingWriteQueues;
  56. /**
  57. * A test driver for FSTSyncEngine that allows simulated event delivery and capture. As much as
  58. * possible, all sources of nondeterminism are removed so that test execution is consistent and
  59. * reliable.
  60. *
  61. * FSTSyncEngineTestDriver:
  62. *
  63. * + constructs an FSTSyncEngine using a mocked FSTDatastore for the backend;
  64. * + allows the caller to trigger events (user API calls and incoming FSTDatastore messages);
  65. * + performs sequencing validation internally (e.g. that when a user mutation is initiated, the
  66. * FSTSyncEngine correctly sends it to the remote store); and
  67. * + exposes the set of FSTQueryEvents generated for the caller to verify.
  68. *
  69. * Events come in three major flavors:
  70. *
  71. * + user events: simulate user API calls
  72. * + watch events: simulate RPC interactions with the Watch backend
  73. * + write events: simulate RPC interactions with the Streaming Write backend
  74. *
  75. * Each method on the driver injects a different event into the system.
  76. */
  77. @interface FSTSyncEngineTestDriver : NSObject <FSTOnlineStateDelegate>
  78. /**
  79. * Initializes the underlying FSTSyncEngine with the given local persistence implementation and
  80. * garbage collection policy.
  81. */
  82. - (instancetype)initWithPersistence:(id<FSTPersistence>)persistence
  83. garbageCollector:(id<FSTGarbageCollector>)garbageCollector;
  84. /**
  85. * Initializes the underlying FSTSyncEngine with the given local persistence implementation and
  86. * a set of existing outstandingWrites (useful when your FSTPersistence object has
  87. * persisted mutation queues).
  88. */
  89. - (instancetype)initWithPersistence:(id<FSTPersistence>)persistence
  90. garbageCollector:(id<FSTGarbageCollector>)garbageCollector
  91. initialUser:(const firebase::firestore::auth::User &)initialUser
  92. outstandingWrites:(const FSTOutstandingWriteQueues &)outstandingWrites
  93. NS_DESIGNATED_INITIALIZER;
  94. - (instancetype)init NS_UNAVAILABLE;
  95. /** Starts the FSTSyncEngine and its underlying components. */
  96. - (void)start;
  97. /** Validates that the API has been used correctly after a test is complete. */
  98. - (void)validateUsage;
  99. /** Shuts the FSTSyncEngine down. */
  100. - (void)shutdown;
  101. /**
  102. * Adds a listener to the FSTSyncEngine as if the user had initiated a new listen for the given
  103. * query.
  104. *
  105. * Resulting events are captured and made available via the capturedEventsSinceLastCall method.
  106. *
  107. * @param query A valid query to execute against the backend.
  108. * @return The target ID assigned by the system to track the query.
  109. */
  110. - (FSTTargetID)addUserListenerWithQuery:(FSTQuery *)query;
  111. /**
  112. * Removes a listener from the FSTSyncEngine as if the user had removed a listener corresponding
  113. * to the given query.
  114. *
  115. * Resulting events are captured and made available via the capturedEventsSinceLastCall method.
  116. *
  117. * @param query An identical query corresponding to one passed to -addUserListenerWithQuery.
  118. */
  119. - (void)removeUserListenerWithQuery:(FSTQuery *)query;
  120. /**
  121. * Delivers a WatchChange RPC to the FSTSyncEngine as if it were received from the backend watch
  122. * service, either in response to addUserListener: or removeUserListener calls or because the
  123. * simulated backend has new data.
  124. *
  125. * Resulting events are captured and made available via the capturedEventsSinceLastCall method.
  126. *
  127. * @param change Any type of watch change
  128. * @param snapshot A snapshot version to attach, if applicable. This should be sent when
  129. * simulating the server having sent a complete snapshot.
  130. */
  131. - (void)receiveWatchChange:(FSTWatchChange *)change
  132. snapshotVersion:(FSTSnapshotVersion *_Nullable)snapshot;
  133. /**
  134. * Delivers a watch stream error as if the Streaming Watch backend has generated some kind of error.
  135. *
  136. * @param errorCode A FIRFirestoreErrorCode value, from FIRFirestoreErrors.h
  137. * @param userInfo Any additional details that the server might have sent along with the error.
  138. * For the moment this is effectively unused, but is logged.
  139. */
  140. - (void)receiveWatchStreamError:(int)errorCode userInfo:(NSDictionary<NSString *, id> *)userInfo;
  141. /**
  142. * Performs a mutation against the FSTSyncEngine as if the user had written the mutation through
  143. * the API.
  144. *
  145. * Also retains the mutation so that the driver can validate that the sync engine sent the mutation
  146. * to the remote store before receiveWatchChange:snapshotVersion: and receiveWriteError:userInfo:
  147. * events are processed.
  148. *
  149. * @param mutation Any type of valid mutation.
  150. */
  151. - (void)writeUserMutation:(FSTMutation *)mutation;
  152. /**
  153. * Delivers a write error as if the Streaming Write backend has generated some kind of error.
  154. *
  155. * For the moment write errors are usually must be in response to a mutation that has been written
  156. * with writeUserMutation:. Spontaneously errors due to idle timeout, server restart, or credential
  157. * expiration aren't yet supported.
  158. *
  159. * @param errorCode A FIRFirestoreErrorCode value, from FIRFirestoreErrors.h
  160. * @param userInfo Any additional details that the server might have sent along with the error.
  161. * For the moment this is effectively unused, but is logged.
  162. */
  163. - (FSTOutstandingWrite *)receiveWriteError:(int)errorCode
  164. userInfo:(NSDictionary<NSString *, id> *)userInfo;
  165. /**
  166. * Delivers a write acknowledgement as if the Streaming Write backend has acknowledged a write with
  167. * the snapshot version at which the write was committed.
  168. *
  169. * @param commitVersion The snapshot version at which the simulated server has committed
  170. * the mutation. Snapshot versions must be monotonically increasing.
  171. * @param mutationResults The mutation results for the write that is being acked.
  172. */
  173. - (FSTOutstandingWrite *)receiveWriteAckWithVersion:(FSTSnapshotVersion *)commitVersion
  174. mutationResults:(NSArray<FSTMutationResult *> *)mutationResults;
  175. /**
  176. * A count of the mutations written to the write stream by the FSTSyncEngine, but not yet
  177. * acknowledged via receiveWriteError: or receiveWriteAckWithVersion:mutationResults.
  178. */
  179. @property(nonatomic, readonly) int sentWritesCount;
  180. /**
  181. * A count of the total number of requests sent to the write stream since the beginning of the test
  182. * case.
  183. */
  184. @property(nonatomic, readonly) int writeStreamRequestCount;
  185. /**
  186. * A count of the total number of requests sent to the watch stream since the beginning of the test
  187. * case.
  188. */
  189. @property(nonatomic, readonly) int watchStreamRequestCount;
  190. /**
  191. * Disables RemoteStore's network connection and shuts down all streams.
  192. */
  193. - (void)disableNetwork;
  194. /**
  195. * Enables RemoteStore's network connection.
  196. */
  197. - (void)enableNetwork;
  198. /**
  199. * Runs a pending timer callback on the FSTDispatchQueue.
  200. */
  201. - (void)runTimer:(FSTTimerID)timerID;
  202. /**
  203. * Switches the FSTSyncEngine to a new user. The test driver tracks the outstanding mutations for
  204. * each user, so future receiveWriteAck/Error operations will validate the write sent to the mock
  205. * datastore matches the next outstanding write for that user.
  206. */
  207. - (void)changeUser:(const firebase::firestore::auth::User &)user;
  208. /**
  209. * Returns all query events generated by the FSTSyncEngine in response to the event injection
  210. * methods called previously. The events are cleared after each invocation of this method.
  211. */
  212. - (NSArray<FSTQueryEvent *> *)capturedEventsSinceLastCall;
  213. /**
  214. * The writes that have been sent to the FSTSyncEngine via writeUserMutation: but not yet
  215. * acknowledged by calling receiveWriteAck/Error:. They are tracked per-user.
  216. *
  217. * It is mostly an implementation detail used internally to validate that the writes sent to the
  218. * mock backend by the FSTSyncEngine match the user mutations that initiated them.
  219. *
  220. * It is exposed specifically for use with the
  221. * initWithPersistence:GCEnabled:outstandingWrites: initializer to test persistence
  222. * scenarios where the FSTSyncEngine is restarted while the FSTPersistence implementation still has
  223. * outstanding persisted mutations.
  224. *
  225. * Note: The size of the list for the current user will generally be the same as
  226. * sentWritesCount, but not necessarily, since the FSTRemoteStore limits the number of
  227. * outstanding writes to the backend at a given time.
  228. */
  229. @property(nonatomic, assign, readonly) const FSTOutstandingWriteQueues &outstandingWrites;
  230. /** The current user for the FSTSyncEngine; determines which mutation queue is active. */
  231. @property(nonatomic, assign, readonly) const firebase::firestore::auth::User &currentUser;
  232. /** The current set of documents in limbo. */
  233. @property(nonatomic, strong, readonly)
  234. NSDictionary<FSTDocumentKey *, FSTBoxedTargetID *> *currentLimboDocuments;
  235. /** The expected set of documents in limbo. */
  236. @property(nonatomic, strong, readwrite) NSSet<FSTDocumentKey *> *expectedLimboDocuments;
  237. /** The set of active targets as observed on the watch stream. */
  238. @property(nonatomic, strong, readonly)
  239. NSDictionary<FSTBoxedTargetID *, FSTQueryData *> *activeTargets;
  240. /** The expected set of active targets, keyed by target ID. */
  241. @property(nonatomic, strong, readwrite)
  242. NSDictionary<FSTBoxedTargetID *, FSTQueryData *> *expectedActiveTargets;
  243. @end
  244. NS_ASSUME_NONNULL_END