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. #import "Firestore/Source/Remote/FSTStream.h"
  26. #import "Firestore/Example/Tests/Remote/FSTWatchChange+Testing.h"
  27. #include "Firestore/core/src/firebase/firestore/auth/credentials_provider.h"
  28. #include "Firestore/core/src/firebase/firestore/auth/empty_credentials_provider.h"
  29. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  30. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  31. #include "Firestore/core/src/firebase/firestore/remote/connectivity_monitor.h"
  32. #include "Firestore/core/src/firebase/firestore/remote/datastore.h"
  33. #include "Firestore/core/src/firebase/firestore/remote/grpc_connection.h"
  34. #include "Firestore/core/src/firebase/firestore/remote/stream.h"
  35. #include "Firestore/core/src/firebase/firestore/util/async_queue.h"
  36. #include "Firestore/core/src/firebase/firestore/util/log.h"
  37. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  38. #include "Firestore/core/test/firebase/firestore/util/create_noop_connectivity_monitor.h"
  39. #include "absl/memory/memory.h"
  40. #include "grpcpp/completion_queue.h"
  41. NS_ASSUME_NONNULL_BEGIN
  42. using firebase::firestore::auth::CredentialsProvider;
  43. using firebase::firestore::auth::EmptyCredentialsProvider;
  44. using firebase::firestore::core::DatabaseInfo;
  45. using firebase::firestore::model::DatabaseId;
  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::WatchStream;
  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(AsyncQueue* worker_queue,
  61. CredentialsProvider* credentials_provider,
  62. FSTSerializerBeta* serializer,
  63. GrpcConnection* grpc_connection,
  64. id<FSTWatchStreamDelegate> delegate,
  65. MockDatastore* datastore)
  66. : WatchStream{worker_queue, credentials_provider, serializer, grpc_connection, delegate},
  67. datastore_{datastore},
  68. delegate_{delegate} {
  69. active_targets_ = [NSMutableDictionary dictionary];
  70. }
  71. NSDictionary<FSTBoxedTargetID*, FSTQueryData*>* ActiveTargets() const {
  72. return [active_targets_ copy];
  73. }
  74. void Start() override {
  75. HARD_ASSERT(!open_, "Trying to start already started watch stream");
  76. open_ = true;
  77. [delegate_ watchStreamDidOpen];
  78. }
  79. void Stop() override {
  80. WatchStream::Stop();
  81. open_ = false;
  82. [active_targets_ removeAllObjects];
  83. }
  84. bool IsStarted() const override {
  85. return open_;
  86. }
  87. bool IsOpen() const override {
  88. return open_;
  89. }
  90. void WatchQuery(FSTQueryData* query) override {
  91. LOG_DEBUG("WatchQuery: %s: %s, %s", query.targetID, query.query, query.resumeToken);
  92. // Snapshot version is ignored on the wire
  93. FSTQueryData* sentQueryData = [query queryDataByReplacingSnapshotVersion:SnapshotVersion::None()
  94. resumeToken:query.resumeToken
  95. sequenceNumber:query.sequenceNumber];
  96. datastore_->IncrementWatchStreamRequests();
  97. active_targets_[@(query.targetID)] = sentQueryData;
  98. }
  99. void UnwatchTargetId(model::TargetId target_id) override {
  100. LOG_DEBUG("UnwatchTargetId: %s", target_id);
  101. [active_targets_ removeObjectForKey:@(target_id)];
  102. }
  103. void FailStream(const Status& error) {
  104. open_ = false;
  105. [delegate_ watchStreamWasInterruptedWithError:error];
  106. }
  107. void WriteWatchChange(FSTWatchChange* change, SnapshotVersion snap) {
  108. if ([change isKindOfClass:[FSTWatchTargetChange class]]) {
  109. FSTWatchTargetChange* targetChange = (FSTWatchTargetChange*)change;
  110. if (targetChange.cause) {
  111. for (NSNumber* target_id in targetChange.targetIDs) {
  112. if (!active_targets_[target_id]) {
  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_ removeObjectForKey:target_id];
  119. }
  120. }
  121. if ([targetChange.targetIDs count] != 0) {
  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. [delegate_ watchStreamDidChange:change snapshotVersion:snap];
  128. }
  129. private:
  130. bool open_ = false;
  131. NSMutableDictionary<FSTBoxedTargetID*, FSTQueryData*>* active_targets_ = nullptr;
  132. MockDatastore* datastore_ = nullptr;
  133. id<FSTWatchStreamDelegate> delegate_ = nullptr;
  134. };
  135. class MockWriteStream : public WriteStream {
  136. public:
  137. MockWriteStream(AsyncQueue* worker_queue,
  138. CredentialsProvider* credentials_provider,
  139. FSTSerializerBeta* serializer,
  140. GrpcConnection* grpc_connection,
  141. id<FSTWriteStreamDelegate> delegate,
  142. MockDatastore* datastore)
  143. : WriteStream{worker_queue, credentials_provider, serializer, grpc_connection, delegate},
  144. datastore_{datastore},
  145. delegate_{delegate} {
  146. }
  147. void Start() override {
  148. HARD_ASSERT(!open_, "Trying to start already started write stream");
  149. open_ = true;
  150. sent_mutations_ = {};
  151. [delegate_ writeStreamDidOpen];
  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. [delegate_ writeStreamDidCompleteHandshake];
  170. }
  171. void WriteMutations(NSArray<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, NSArray<FSTMutationResult*>* results) {
  177. [delegate_ writeStreamDidReceiveResponseWithVersion:commitVersion mutationResults: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. [delegate_ writeStreamWasInterruptedWithError:error];
  183. }
  184. /**
  185. * Returns the next write that was "sent to the backend", failing if there are no queued sent
  186. */
  187. NSArray<FSTMutation*>* NextSentWrite() {
  188. HARD_ASSERT(!sent_mutations_.empty(),
  189. "Writes need to happen before you can call NextSentWrite.");
  190. NSArray<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<NSArray<FSTMutation*>*> sent_mutations_;
  204. MockDatastore* datastore_ = nullptr;
  205. id<FSTWriteStreamDelegate> delegate_ = nullptr;
  206. };
  207. MockDatastore::MockDatastore(const core::DatabaseInfo& database_info,
  208. 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(id<FSTWatchStreamDelegate> delegate) {
  216. watch_stream_ = std::make_shared<MockWatchStream>(
  217. worker_queue_, credentials_,
  218. [[FSTSerializerBeta alloc] initWithDatabaseID:&database_info_->database_id()],
  219. grpc_connection(), delegate, this);
  220. return watch_stream_;
  221. }
  222. std::shared_ptr<WriteStream> MockDatastore::CreateWriteStream(id<FSTWriteStreamDelegate> delegate) {
  223. write_stream_ = std::make_shared<MockWriteStream>(
  224. worker_queue_, credentials_,
  225. [[FSTSerializerBeta alloc] initWithDatabaseID:&database_info_->database_id()],
  226. grpc_connection(), delegate, this);
  227. return write_stream_;
  228. }
  229. void MockDatastore::WriteWatchChange(FSTWatchChange* 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. NSDictionary<FSTBoxedTargetID*, FSTQueryData*>* MockDatastore::ActiveTargets() const {
  236. return watch_stream_->ActiveTargets();
  237. }
  238. bool MockDatastore::IsWatchStreamOpen() const {
  239. return watch_stream_->IsOpen();
  240. }
  241. NSArray<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, NSArray<FSTMutationResult*>* results) {
  248. write_stream_->AckWrite(version, 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