FSTMockDatastore.mm 10 KB

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