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/auth/credentials_provider.h"
  22. #include "Firestore/core/src/auth/empty_credentials_provider.h"
  23. #include "Firestore/core/src/core/database_info.h"
  24. #include "Firestore/core/src/local/target_data.h"
  25. #include "Firestore/core/src/model/database_id.h"
  26. #include "Firestore/core/src/model/mutation.h"
  27. #include "Firestore/core/src/remote/connectivity_monitor.h"
  28. #include "Firestore/core/src/remote/datastore.h"
  29. #include "Firestore/core/src/remote/grpc_connection.h"
  30. #include "Firestore/core/src/remote/serializer.h"
  31. #include "Firestore/core/src/remote/stream.h"
  32. #include "Firestore/core/src/util/async_queue.h"
  33. #include "Firestore/core/src/util/log.h"
  34. #include "Firestore/core/src/util/string_apple.h"
  35. #include "Firestore/core/test/unit/remote/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::Status;
  56. namespace firebase {
  57. namespace firestore {
  58. namespace remote {
  59. class MockWatchStream : public WatchStream {
  60. public:
  61. MockWatchStream(const std::shared_ptr<AsyncQueue>& worker_queue,
  62. std::shared_ptr<CredentialsProvider> credentials_provider,
  63. Serializer serializer,
  64. GrpcConnection* grpc_connection,
  65. WatchStreamCallback* callback,
  66. MockDatastore* datastore)
  67. : WatchStream{worker_queue, credentials_provider, std::move(serializer), grpc_connection,
  68. callback},
  69. datastore_{datastore},
  70. callback_{callback} {
  71. }
  72. const std::unordered_map<TargetId, TargetData>& 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 TargetData& query) override {
  92. LOG_DEBUG("WatchQuery: %s: %s, %s", query.target_id(), query.target().ToString(),
  93. query.resume_token().ToString());
  94. // Snapshot version is ignored on the wire
  95. TargetData sentTargetData =
  96. query.WithResumeToken(query.resume_token(), SnapshotVersion::None());
  97. datastore_->IncrementWatchStreamRequests();
  98. active_targets_[query.target_id()] = sentTargetData;
  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 `Serializer::DecodeVersion:`.
  126. snap = SnapshotVersion::None();
  127. }
  128. }
  129. callback_->OnWatchStreamChange(change, snap);
  130. }
  131. private:
  132. bool open_ = false;
  133. std::unordered_map<TargetId, TargetData> 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. Serializer serializer,
  142. GrpcConnection* grpc_connection,
  143. WriteStreamCallback* callback,
  144. MockDatastore* datastore)
  145. : WriteStream{worker_queue, credentials_provider, std::move(serializer), grpc_connection,
  146. callback},
  147. datastore_{datastore},
  148. callback_{callback} {
  149. }
  150. void Start() override {
  151. HARD_ASSERT(!open_, "Trying to start already started write stream");
  152. open_ = true;
  153. sent_mutations_ = {};
  154. callback_->OnWriteStreamOpen();
  155. }
  156. void Stop() override {
  157. datastore_->IncrementWriteStreamRequests();
  158. WriteStream::Stop();
  159. sent_mutations_ = {};
  160. open_ = false;
  161. SetHandshakeComplete(false);
  162. }
  163. bool IsStarted() const override {
  164. return open_;
  165. }
  166. bool IsOpen() const override {
  167. return open_;
  168. }
  169. void WriteHandshake() override {
  170. datastore_->IncrementWriteStreamRequests();
  171. SetHandshakeComplete();
  172. callback_->OnWriteStreamHandshakeComplete();
  173. }
  174. void WriteMutations(const std::vector<Mutation>& mutations) override {
  175. datastore_->IncrementWriteStreamRequests();
  176. sent_mutations_.push(mutations);
  177. }
  178. /** Injects a write ack as though it had come from the backend in response to a write. */
  179. void AckWrite(const SnapshotVersion& commitVersion, std::vector<MutationResult> results) {
  180. callback_->OnWriteStreamMutationResult(commitVersion, std::move(results));
  181. }
  182. /** Injects a failed write response as though it had come from the backend. */
  183. void FailStream(const Status& error) {
  184. open_ = false;
  185. callback_->OnWriteStreamClose(error);
  186. }
  187. /**
  188. * Returns the next write that was "sent to the backend", failing if there are no queued sent
  189. */
  190. std::vector<Mutation> NextSentWrite() {
  191. HARD_ASSERT(!sent_mutations_.empty(),
  192. "Writes need to happen before you can call NextSentWrite.");
  193. std::vector<Mutation> result = std::move(sent_mutations_.front());
  194. sent_mutations_.pop();
  195. return result;
  196. }
  197. /**
  198. * Returns the number of mutations that have been sent to the backend but not retrieved via
  199. * nextSentWrite yet.
  200. */
  201. int sent_mutations_count() const {
  202. return static_cast<int>(sent_mutations_.size());
  203. }
  204. private:
  205. bool open_ = false;
  206. std::queue<std::vector<Mutation>> sent_mutations_;
  207. MockDatastore* datastore_ = nullptr;
  208. WriteStreamCallback* callback_ = nullptr;
  209. };
  210. MockDatastore::MockDatastore(const core::DatabaseInfo& database_info,
  211. const std::shared_ptr<util::AsyncQueue>& worker_queue,
  212. std::shared_ptr<auth::CredentialsProvider> credentials,
  213. ConnectivityMonitor* connectivity_monitor)
  214. : Datastore{database_info, worker_queue, credentials, connectivity_monitor},
  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