FSTMockDatastore.mm 11 KB

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