FSTMockDatastore.mm 10 KB

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