FSTSyncEngineTestDriver.h 11 KB

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