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