FSTSyncEngineTestDriver.h 13 KB

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