FSTSyncEngineTestDriver.h 14 KB

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