FSTMockDatastore.mm 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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/Remote/FSTSerializerBeta.h"
  22. #include "Firestore/core/src/firebase/firestore/auth/credentials_provider.h"
  23. #include "Firestore/core/src/firebase/firestore/auth/empty_credentials_provider.h"
  24. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  25. #include "Firestore/core/src/firebase/firestore/local/query_data.h"
  26. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  27. #include "Firestore/core/src/firebase/firestore/model/mutation.h"
  28. #include "Firestore/core/src/firebase/firestore/remote/connectivity_monitor.h"
  29. #include "Firestore/core/src/firebase/firestore/remote/datastore.h"
  30. #include "Firestore/core/src/firebase/firestore/remote/grpc_connection.h"
  31. #include "Firestore/core/src/firebase/firestore/remote/stream.h"
  32. #include "Firestore/core/src/firebase/firestore/util/async_queue.h"
  33. #include "Firestore/core/src/firebase/firestore/util/log.h"
  34. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  35. #include "Firestore/core/test/firebase/firestore/util/create_noop_connectivity_monitor.h"
  36. #include "absl/memory/memory.h"
  37. #include "grpcpp/completion_queue.h"
  38. NS_ASSUME_NONNULL_BEGIN
  39. using firebase::firestore::auth::CredentialsProvider;
  40. using firebase::firestore::auth::EmptyCredentialsProvider;
  41. using firebase::firestore::core::DatabaseInfo;
  42. using firebase::firestore::local::QueryData;
  43. using firebase::firestore::model::DatabaseId;
  44. using firebase::firestore::model::Mutation;
  45. using firebase::firestore::model::MutationResult;
  46. using firebase::firestore::model::SnapshotVersion;
  47. using firebase::firestore::model::TargetId;
  48. using firebase::firestore::remote::ConnectivityMonitor;
  49. using firebase::firestore::remote::GrpcConnection;
  50. using firebase::firestore::remote::WatchChange;
  51. using firebase::firestore::remote::WatchStream;
  52. using firebase::firestore::remote::WatchTargetChange;
  53. using firebase::firestore::remote::WriteStream;
  54. using firebase::firestore::util::AsyncQueue;
  55. using firebase::firestore::util::CreateNoOpConnectivityMonitor;
  56. using firebase::firestore::util::Status;
  57. namespace firebase {
  58. namespace firestore {
  59. namespace remote {
  60. class MockWatchStream : public WatchStream {
  61. public:
  62. MockWatchStream(const std::shared_ptr<AsyncQueue>& worker_queue,
  63. std::shared_ptr<CredentialsProvider> credentials_provider,
  64. FSTSerializerBeta* serializer,
  65. GrpcConnection* grpc_connection,
  66. WatchStreamCallback* callback,
  67. MockDatastore* datastore)
  68. : WatchStream{worker_queue, credentials_provider, serializer, grpc_connection, callback},
  69. datastore_{datastore},
  70. callback_{callback} {
  71. }
  72. const std::unordered_map<TargetId, QueryData>& ActiveTargets() const {
  73. return active_targets_;
  74. }
  75. void Start() override {
  76. HARD_ASSERT(!open_, "Trying to start already started watch stream");
  77. open_ = true;
  78. callback_->OnWatchStreamOpen();
  79. }
  80. void Stop() override {
  81. WatchStream::Stop();
  82. open_ = false;
  83. active_targets_.clear();
  84. }
  85. bool IsStarted() const override {
  86. return open_;
  87. }
  88. bool IsOpen() const override {
  89. return open_;
  90. }
  91. void WatchQuery(const QueryData& query) override {
  92. LOG_DEBUG("WatchQuery: %s: %s, %s", query.target_id(), query.query().ToString(),
  93. query.resume_token().ToString());
  94. // Snapshot version is ignored on the wire
  95. QueryData sentQueryData =
  96. query.Copy(SnapshotVersion::None(), query.resume_token(), query.sequence_number());
  97. datastore_->IncrementWatchStreamRequests();
  98. active_targets_[query.target_id()] = sentQueryData;
  99. }
  100. void UnwatchTargetId(model::TargetId target_id) override {
  101. LOG_DEBUG("UnwatchTargetId: %s", target_id);
  102. active_targets_.erase(target_id);
  103. }
  104. void FailStream(const Status& error) {
  105. open_ = false;
  106. callback_->OnWatchStreamClose(error);
  107. }
  108. void WriteWatchChange(const WatchChange& change, SnapshotVersion snap) {
  109. if (change.type() == WatchChange::Type::TargetChange) {
  110. const auto& targetChange = static_cast<const WatchTargetChange&>(change);
  111. if (!targetChange.cause().ok()) {
  112. for (TargetId target_id : targetChange.target_ids()) {
  113. auto found = active_targets_.find(target_id);
  114. if (found == active_targets_.end()) {
  115. // Technically removing an unknown target is valid (e.g. it could race with a
  116. // server-side removal), but we want to pay extra careful attention in tests
  117. // that we only remove targets we listened to.
  118. HARD_FAIL("Removing a non-active target");
  119. }
  120. active_targets_.erase(found);
  121. }
  122. }
  123. if (!targetChange.target_ids().empty()) {
  124. // If the list of target IDs is not empty, we reset the snapshot version to NONE as
  125. // done in `FSTSerializerBeta.versionFromListenResponse:`.
  126. snap = SnapshotVersion::None();
  127. }
  128. }
  129. callback_->OnWatchStreamChange(change, snap);
  130. }
  131. private:
  132. bool open_ = false;
  133. std::unordered_map<TargetId, QueryData> active_targets_;
  134. MockDatastore* datastore_ = nullptr;
  135. WatchStreamCallback* callback_ = nullptr;
  136. };
  137. class MockWriteStream : public WriteStream {
  138. public:
  139. MockWriteStream(const std::shared_ptr<AsyncQueue>& worker_queue,
  140. std::shared_ptr<CredentialsProvider> credentials_provider,
  141. FSTSerializerBeta* serializer,
  142. GrpcConnection* grpc_connection,
  143. WriteStreamCallback* callback,
  144. MockDatastore* datastore)
  145. : WriteStream{worker_queue, credentials_provider, serializer, grpc_connection, callback},
  146. datastore_{datastore},
  147. callback_{callback} {
  148. }
  149. void Start() override {
  150. HARD_ASSERT(!open_, "Trying to start already started write stream");
  151. open_ = true;
  152. sent_mutations_ = {};
  153. callback_->OnWriteStreamOpen();
  154. }
  155. void Stop() override {
  156. datastore_->IncrementWriteStreamRequests();
  157. WriteStream::Stop();
  158. sent_mutations_ = {};
  159. open_ = false;
  160. SetHandshakeComplete(false);
  161. }
  162. bool IsStarted() const override {
  163. return open_;
  164. }
  165. bool IsOpen() const override {
  166. return open_;
  167. }
  168. void WriteHandshake() override {
  169. datastore_->IncrementWriteStreamRequests();
  170. SetHandshakeComplete();
  171. callback_->OnWriteStreamHandshakeComplete();
  172. }
  173. void WriteMutations(const std::vector<Mutation>& mutations) override {
  174. datastore_->IncrementWriteStreamRequests();
  175. sent_mutations_.push(mutations);
  176. }
  177. /** Injects a write ack as though it had come from the backend in response to a write. */
  178. void AckWrite(const SnapshotVersion& commitVersion, std::vector<MutationResult> results) {
  179. callback_->OnWriteStreamMutationResult(commitVersion, std::move(results));
  180. }
  181. /** Injects a failed write response as though it had come from the backend. */
  182. void FailStream(const Status& error) {
  183. open_ = false;
  184. callback_->OnWriteStreamClose(error);
  185. }
  186. /**
  187. * Returns the next write that was "sent to the backend", failing if there are no queued sent
  188. */
  189. std::vector<Mutation> NextSentWrite() {
  190. HARD_ASSERT(!sent_mutations_.empty(),
  191. "Writes need to happen before you can call NextSentWrite.");
  192. std::vector<Mutation> result = std::move(sent_mutations_.front());
  193. sent_mutations_.pop();
  194. return result;
  195. }
  196. /**
  197. * Returns the number of mutations that have been sent to the backend but not retrieved via
  198. * nextSentWrite yet.
  199. */
  200. int sent_mutations_count() const {
  201. return static_cast<int>(sent_mutations_.size());
  202. }
  203. private:
  204. bool open_ = false;
  205. std::queue<std::vector<Mutation>> sent_mutations_;
  206. MockDatastore* datastore_ = nullptr;
  207. WriteStreamCallback* callback_ = nullptr;
  208. };
  209. MockDatastore::MockDatastore(const core::DatabaseInfo& database_info,
  210. const std::shared_ptr<util::AsyncQueue>& worker_queue,
  211. std::shared_ptr<auth::CredentialsProvider> credentials)
  212. : Datastore{database_info, worker_queue, credentials, CreateNoOpConnectivityMonitor()},
  213. database_info_{&database_info},
  214. worker_queue_{worker_queue},
  215. credentials_{credentials} {
  216. }
  217. std::shared_ptr<WatchStream> MockDatastore::CreateWatchStream(WatchStreamCallback* callback) {
  218. watch_stream_ = std::make_shared<MockWatchStream>(
  219. worker_queue_, credentials_,
  220. [[FSTSerializerBeta alloc] initWithDatabaseID:database_info_->database_id()],
  221. grpc_connection(), callback, this);
  222. return watch_stream_;
  223. }
  224. std::shared_ptr<WriteStream> MockDatastore::CreateWriteStream(WriteStreamCallback* callback) {
  225. write_stream_ = std::make_shared<MockWriteStream>(
  226. worker_queue_, credentials_,
  227. [[FSTSerializerBeta alloc] initWithDatabaseID:database_info_->database_id()],
  228. grpc_connection(), callback, this);
  229. return write_stream_;
  230. }
  231. void MockDatastore::WriteWatchChange(const WatchChange& change, const SnapshotVersion& snap) {
  232. watch_stream_->WriteWatchChange(change, snap);
  233. }
  234. void MockDatastore::FailWatchStream(const Status& error) {
  235. watch_stream_->FailStream(error);
  236. }
  237. const std::unordered_map<TargetId, QueryData>& MockDatastore::ActiveTargets() const {
  238. return watch_stream_->ActiveTargets();
  239. }
  240. bool MockDatastore::IsWatchStreamOpen() const {
  241. return watch_stream_->IsOpen();
  242. }
  243. std::vector<Mutation> MockDatastore::NextSentWrite() {
  244. return write_stream_->NextSentWrite();
  245. }
  246. int MockDatastore::WritesSent() const {
  247. return write_stream_->sent_mutations_count();
  248. }
  249. void MockDatastore::AckWrite(const SnapshotVersion& version, std::vector<MutationResult> results) {
  250. write_stream_->AckWrite(version, std::move(results));
  251. }
  252. void MockDatastore::FailWrite(const Status& error) {
  253. write_stream_->FailStream(error);
  254. }
  255. } // namespace remote
  256. } // namespace firestore
  257. } // namespace firebase
  258. NS_ASSUME_NONNULL_END