FSTMockDatastore.mm 10 KB

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