FSTSyncEngineTestDriver.h 11 KB

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