FSTSyncEngineTestDriver.h 15 KB

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