FSTMockDatastore.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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 "Firestore/Example/Tests/SpecTests/FSTMockDatastore.h"
  17. #include <map>
  18. #include <memory>
  19. #include <queue>
  20. #include <utility>
  21. #import "Firestore/Source/Core/FSTQuery.h"
  22. #import "Firestore/Source/Local/FSTQueryData.h"
  23. #import "Firestore/Source/Model/FSTMutation.h"
  24. #import "Firestore/Source/Remote/FSTSerializerBeta.h"
  25. #import "Firestore/Source/Remote/FSTStream.h"
  26. #import "Firestore/Example/Tests/Remote/FSTWatchChange+Testing.h"
  27. #include "Firestore/core/src/firebase/firestore/auth/credentials_provider.h"
  28. #include "Firestore/core/src/firebase/firestore/auth/empty_credentials_provider.h"
  29. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  30. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  31. #include "Firestore/core/src/firebase/firestore/remote/connectivity_monitor.h"
  32. #include "Firestore/core/src/firebase/firestore/remote/grpc_connection.h"
  33. #include "Firestore/core/src/firebase/firestore/remote/stream.h"
  34. #include "Firestore/core/src/firebase/firestore/util/async_queue.h"
  35. #include "Firestore/core/src/firebase/firestore/util/log.h"
  36. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  37. #include "Firestore/core/test/firebase/firestore/util/create_noop_connectivity_monitor.h"
  38. #include "absl/memory/memory.h"
  39. #include "grpcpp/completion_queue.h"
  40. using firebase::firestore::auth::CredentialsProvider;
  41. using firebase::firestore::auth::EmptyCredentialsProvider;
  42. using firebase::firestore::core::DatabaseInfo;
  43. using firebase::firestore::model::DatabaseId;
  44. using firebase::firestore::model::SnapshotVersion;
  45. using firebase::firestore::model::TargetId;
  46. using firebase::firestore::remote::ConnectivityMonitor;
  47. using firebase::firestore::remote::GrpcConnection;
  48. using firebase::firestore::remote::WatchStream;
  49. using firebase::firestore::remote::WriteStream;
  50. using firebase::firestore::util::AsyncQueue;
  51. using firebase::firestore::util::CreateNoOpConnectivityMonitor;
  52. NS_ASSUME_NONNULL_BEGIN
  53. #pragma mark - FSTMockWatchStream
  54. namespace firebase {
  55. namespace firestore {
  56. namespace remote {
  57. class MockWatchStream : public WatchStream {
  58. public:
  59. MockWatchStream(AsyncQueue *worker_queue,
  60. CredentialsProvider *credentials_provider,
  61. FSTSerializerBeta *serializer,
  62. GrpcConnection *grpc_connection,
  63. id<FSTWatchStreamDelegate> delegate,
  64. FSTMockDatastore *datastore)
  65. : WatchStream{worker_queue, credentials_provider, serializer, grpc_connection, delegate},
  66. datastore_{datastore},
  67. delegate_{delegate} {
  68. active_targets_ = [NSMutableDictionary dictionary];
  69. }
  70. NSDictionary<FSTBoxedTargetID *, FSTQueryData *> *ActiveTargets() const {
  71. return [active_targets_ copy];
  72. }
  73. void Start() override {
  74. HARD_ASSERT(!open_, "Trying to start already started watch stream");
  75. open_ = true;
  76. [delegate_ watchStreamDidOpen];
  77. }
  78. void Stop() override {
  79. WatchStream::Stop();
  80. open_ = false;
  81. [active_targets_ removeAllObjects];
  82. }
  83. bool IsStarted() const override {
  84. return open_;
  85. }
  86. bool IsOpen() const override {
  87. return open_;
  88. }
  89. void WatchQuery(FSTQueryData *query) override {
  90. LOG_DEBUG("WatchQuery: %s: %s, %s", query.targetID, query.query, query.resumeToken);
  91. // Snapshot version is ignored on the wire
  92. FSTQueryData *sentQueryData = [query queryDataByReplacingSnapshotVersion:SnapshotVersion::None()
  93. resumeToken:query.resumeToken
  94. sequenceNumber:query.sequenceNumber];
  95. datastore_.watchStreamRequestCount += 1;
  96. active_targets_[@(query.targetID)] = sentQueryData;
  97. }
  98. void UnwatchTargetId(model::TargetId target_id) override {
  99. LOG_DEBUG("UnwatchTargetId: %s", target_id);
  100. [active_targets_ removeObjectForKey:@(target_id)];
  101. }
  102. void FailStreamWithError(NSError *error) {
  103. open_ = false;
  104. [delegate_ watchStreamWasInterruptedWithError:error];
  105. }
  106. void WriteWatchChange(FSTWatchChange *change, SnapshotVersion snap) {
  107. if ([change isKindOfClass:[FSTWatchTargetChange class]]) {
  108. FSTWatchTargetChange *targetChange = (FSTWatchTargetChange *)change;
  109. if (targetChange.cause) {
  110. for (NSNumber *target_id in targetChange.targetIDs) {
  111. if (!active_targets_[target_id]) {
  112. // Technically removing an unknown target is valid (e.g. it could race with a
  113. // server-side removal), but we want to pay extra careful attention in tests
  114. // that we only remove targets we listened to.
  115. HARD_FAIL("Removing a non-active target");
  116. }
  117. [active_targets_ removeObjectForKey:target_id];
  118. }
  119. }
  120. if ([targetChange.targetIDs count] != 0) {
  121. // If the list of target IDs is not empty, we reset the snapshot version to NONE as
  122. // done in `FSTSerializerBeta.versionFromListenResponse:`.
  123. snap = SnapshotVersion::None();
  124. }
  125. }
  126. [delegate_ watchStreamDidChange:change snapshotVersion:snap];
  127. }
  128. private:
  129. bool open_ = false;
  130. NSMutableDictionary<FSTBoxedTargetID *, FSTQueryData *> *active_targets_ = nullptr;
  131. FSTMockDatastore *datastore_ = nullptr;
  132. id<FSTWatchStreamDelegate> delegate_ = nullptr;
  133. };
  134. class MockWriteStream : public WriteStream {
  135. public:
  136. MockWriteStream(AsyncQueue *worker_queue,
  137. CredentialsProvider *credentials_provider,
  138. FSTSerializerBeta *serializer,
  139. GrpcConnection *grpc_connection,
  140. id<FSTWriteStreamDelegate> delegate,
  141. FSTMockDatastore *datastore)
  142. : WriteStream{worker_queue, credentials_provider, serializer, grpc_connection, delegate},
  143. datastore_{datastore},
  144. delegate_{delegate} {
  145. }
  146. void Start() override {
  147. HARD_ASSERT(!open_, "Trying to start already started write stream");
  148. open_ = true;
  149. sent_mutations_ = {};
  150. [delegate_ writeStreamDidOpen];
  151. }
  152. void Stop() override {
  153. datastore_.writeStreamRequestCount += 1;
  154. WriteStream::Stop();
  155. sent_mutations_ = {};
  156. open_ = false;
  157. SetHandshakeComplete(false);
  158. }
  159. bool IsStarted() const override {
  160. return open_;
  161. }
  162. bool IsOpen() const override {
  163. return open_;
  164. }
  165. void WriteHandshake() override {
  166. datastore_.writeStreamRequestCount += 1;
  167. SetHandshakeComplete();
  168. [delegate_ writeStreamDidCompleteHandshake];
  169. }
  170. void WriteMutations(NSArray<FSTMutation *> *mutations) override {
  171. datastore_.writeStreamRequestCount += 1;
  172. sent_mutations_.push(mutations);
  173. }
  174. /** Injects a write ack as though it had come from the backend in response to a write. */
  175. void AckWrite(const SnapshotVersion &commitVersion, NSArray<FSTMutationResult *> *results) {
  176. [delegate_ writeStreamDidReceiveResponseWithVersion:commitVersion mutationResults:results];
  177. }
  178. /** Injects a failed write response as though it had come from the backend. */
  179. void FailStreamWithError(NSError *error) {
  180. open_ = false;
  181. [delegate_ writeStreamWasInterruptedWithError:error];
  182. }
  183. /**
  184. * Returns the next write that was "sent to the backend", failing if there are no queued sent
  185. */
  186. NSArray<FSTMutation *> *NextSentWrite() {
  187. HARD_ASSERT(!sent_mutations_.empty(),
  188. "Writes need to happen before you can call NextSentWrite.");
  189. NSArray<FSTMutation *> *result = std::move(sent_mutations_.front());
  190. sent_mutations_.pop();
  191. return result;
  192. }
  193. /**
  194. * Returns the number of mutations that have been sent to the backend but not retrieved via
  195. * nextSentWrite yet.
  196. */
  197. int sent_mutations_count() const {
  198. return static_cast<int>(sent_mutations_.size());
  199. }
  200. private:
  201. bool open_ = false;
  202. std::queue<NSArray<FSTMutation *> *> sent_mutations_;
  203. FSTMockDatastore *datastore_ = nullptr;
  204. id<FSTWriteStreamDelegate> delegate_ = nullptr;
  205. };
  206. } // namespace remote
  207. } // namespace firestore
  208. } // namespace firebase
  209. using firebase::firestore::remote::MockWatchStream;
  210. using firebase::firestore::remote::MockWriteStream;
  211. @interface FSTMockDatastore ()
  212. /** Properties implemented in FSTDatastore that are nonpublic. */
  213. @property(nonatomic, assign, readonly) CredentialsProvider *credentials;
  214. @end
  215. @implementation FSTMockDatastore {
  216. AsyncQueue *_workerQueue;
  217. std::shared_ptr<MockWatchStream> _watchStream;
  218. std::shared_ptr<MockWriteStream> _writeStream;
  219. std::unique_ptr<ConnectivityMonitor> _connectivityMonitor;
  220. grpc::CompletionQueue _grpcQueue;
  221. std::unique_ptr<GrpcConnection> _grpcConnection;
  222. }
  223. #pragma mark - Overridden FSTDatastore methods.
  224. - (instancetype)initWithDatabaseInfo:(const DatabaseInfo *)databaseInfo
  225. workerQueue:(AsyncQueue *)workerQueue
  226. credentials:(CredentialsProvider *)credentials {
  227. if (self = [super initWithDatabaseInfo:databaseInfo
  228. workerQueue:workerQueue
  229. credentials:credentials]) {
  230. _workerQueue = workerQueue;
  231. _credentials = credentials;
  232. _connectivityMonitor = CreateNoOpConnectivityMonitor();
  233. _grpcConnection = absl::make_unique<GrpcConnection>(*databaseInfo, workerQueue, &_grpcQueue,
  234. _connectivityMonitor.get());
  235. }
  236. return self;
  237. }
  238. - (std::shared_ptr<WatchStream>)createWatchStreamWithDelegate:(id<FSTWatchStreamDelegate>)delegate {
  239. _watchStream = std::make_shared<MockWatchStream>(
  240. _workerQueue, self.credentials,
  241. [[FSTSerializerBeta alloc] initWithDatabaseID:&self.databaseInfo->database_id()],
  242. _grpcConnection.get(), delegate, self);
  243. return _watchStream;
  244. }
  245. - (std::shared_ptr<WriteStream>)createWriteStreamWithDelegate:(id<FSTWriteStreamDelegate>)delegate {
  246. _writeStream = std::make_shared<MockWriteStream>(
  247. _workerQueue, self.credentials,
  248. [[FSTSerializerBeta alloc] initWithDatabaseID:&self.databaseInfo->database_id()],
  249. _grpcConnection.get(), delegate, self);
  250. return _writeStream;
  251. }
  252. #pragma mark - Method exposed for tests to call.
  253. - (NSArray<FSTMutation *> *)nextSentWrite {
  254. return _writeStream->NextSentWrite();
  255. }
  256. - (int)writesSent {
  257. return _writeStream->sent_mutations_count();
  258. }
  259. - (void)ackWriteWithVersion:(const SnapshotVersion &)version
  260. mutationResults:(NSArray<FSTMutationResult *> *)results {
  261. _writeStream->AckWrite(version, results);
  262. }
  263. - (void)failWriteWithError:(NSError *_Nullable)error {
  264. _writeStream->FailStreamWithError(error);
  265. }
  266. - (void)writeWatchChange:(FSTWatchChange *)change snapshotVersion:(const SnapshotVersion &)snap {
  267. _watchStream->WriteWatchChange(change, snap);
  268. }
  269. - (void)failWatchStreamWithError:(NSError *)error {
  270. _watchStream->FailStreamWithError(error);
  271. }
  272. - (NSDictionary<FSTBoxedTargetID *, FSTQueryData *> *)activeTargets {
  273. return _watchStream->ActiveTargets();
  274. }
  275. - (BOOL)isWatchStreamOpen {
  276. return _watchStream->IsOpen();
  277. }
  278. @end
  279. NS_ASSUME_NONNULL_END