FSTSyncEngineTestDriver.h 13 KB

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