FSTDatastoreTests.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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 <FirebaseFirestore/FirebaseFirestore.h>
  17. #import <FirebaseFirestore/FIRTimestamp.h>
  18. #import <XCTest/XCTest.h>
  19. #include <memory>
  20. #include <vector>
  21. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  22. #import "Firestore/Source/API/FSTUserDataReader.h"
  23. #import "Firestore/Example/Tests/Util/FSTIntegrationTestCase.h"
  24. #include "Firestore/core/src/core/database_info.h"
  25. #include "Firestore/core/src/credentials/empty_credentials_provider.h"
  26. #include "Firestore/core/src/local/local_documents_view.h"
  27. #include "Firestore/core/src/local/local_store.h"
  28. #include "Firestore/core/src/local/memory_persistence.h"
  29. #include "Firestore/core/src/local/query_engine.h"
  30. #include "Firestore/core/src/local/target_data.h"
  31. #include "Firestore/core/src/model/database_id.h"
  32. #include "Firestore/core/src/model/document_key.h"
  33. #include "Firestore/core/src/model/mutation_batch_result.h"
  34. #include "Firestore/core/src/model/precondition.h"
  35. #include "Firestore/core/src/model/set_mutation.h"
  36. #include "Firestore/core/src/remote/connectivity_monitor.h"
  37. #include "Firestore/core/src/remote/datastore.h"
  38. #include "Firestore/core/src/remote/firebase_metadata_provider.h"
  39. #include "Firestore/core/src/remote/firebase_metadata_provider_noop.h"
  40. #include "Firestore/core/src/remote/remote_event.h"
  41. #include "Firestore/core/src/remote/remote_store.h"
  42. #include "Firestore/core/src/util/async_queue.h"
  43. #include "Firestore/core/src/util/hard_assert.h"
  44. #include "Firestore/core/src/util/status.h"
  45. #include "Firestore/core/src/util/string_apple.h"
  46. #include "Firestore/core/test/unit/remote/create_noop_connectivity_monitor.h"
  47. #include "Firestore/core/test/unit/testutil/async_testing.h"
  48. #include "Firestore/core/test/unit/testutil/testutil.h"
  49. #include "absl/memory/memory.h"
  50. using firebase::Timestamp;
  51. using firebase::firestore::google_firestore_v1_Value;
  52. using firebase::firestore::core::DatabaseInfo;
  53. using firebase::firestore::credentials::EmptyAppCheckCredentialsProvider;
  54. using firebase::firestore::credentials::EmptyAuthCredentialsProvider;
  55. using firebase::firestore::credentials::User;
  56. using firebase::firestore::local::LocalStore;
  57. using firebase::firestore::local::MemoryPersistence;
  58. using firebase::firestore::local::Persistence;
  59. using firebase::firestore::local::QueryEngine;
  60. using firebase::firestore::model::BatchId;
  61. using firebase::firestore::model::DatabaseId;
  62. using firebase::firestore::model::DocumentKeySet;
  63. using firebase::firestore::model::MutationBatch;
  64. using firebase::firestore::model::MutationBatchResult;
  65. using firebase::firestore::model::OnlineState;
  66. using firebase::firestore::model::TargetId;
  67. using firebase::firestore::remote::ConnectivityMonitor;
  68. using firebase::firestore::remote::CreateFirebaseMetadataProviderNoOp;
  69. using firebase::firestore::remote::CreateNoOpConnectivityMonitor;
  70. using firebase::firestore::remote::Datastore;
  71. using firebase::firestore::remote::FirebaseMetadataProvider;
  72. using firebase::firestore::remote::GrpcConnection;
  73. using firebase::firestore::remote::RemoteEvent;
  74. using firebase::firestore::remote::RemoteStore;
  75. using firebase::firestore::remote::RemoteStoreCallback;
  76. using firebase::firestore::testutil::AsyncQueueForTesting;
  77. using firebase::firestore::testutil::Map;
  78. using firebase::firestore::testutil::SetMutation;
  79. using firebase::firestore::util::AsyncQueue;
  80. using firebase::firestore::util::MakeString;
  81. using firebase::firestore::util::Status;
  82. NS_ASSUME_NONNULL_BEGIN
  83. #pragma mark - FSTRemoteStoreEventCapture
  84. @interface FSTRemoteStoreEventCapture : NSObject
  85. - (instancetype)init __attribute__((unavailable("Use initWithTestCase:")));
  86. - (instancetype)initWithTestCase:(XCTestCase *_Nullable)testCase NS_DESIGNATED_INITIALIZER;
  87. - (void)expectWriteEventWithDescription:(NSString *)description;
  88. - (void)expectListenEventWithDescription:(NSString *)description;
  89. @property(nonatomic, weak, nullable) XCTestCase *testCase;
  90. @property(nonatomic, strong) NSMutableArray<XCTestExpectation *> *writeEventExpectations;
  91. @property(nonatomic, strong) NSMutableArray<XCTestExpectation *> *listenEventExpectations;
  92. @end
  93. @implementation FSTRemoteStoreEventCapture {
  94. std::vector<RemoteEvent> _listenEvents;
  95. std::vector<MutationBatchResult> _writeEvents;
  96. }
  97. - (instancetype)initWithTestCase:(XCTestCase *_Nullable)testCase {
  98. if (self = [super init]) {
  99. _testCase = testCase;
  100. _writeEventExpectations = [NSMutableArray array];
  101. _listenEventExpectations = [NSMutableArray array];
  102. }
  103. return self;
  104. }
  105. - (void)expectWriteEventWithDescription:(NSString *)description {
  106. [self.writeEventExpectations
  107. addObject:[self.testCase
  108. expectationWithDescription:[NSString
  109. stringWithFormat:@"write event %lu: %@",
  110. (unsigned long)
  111. self.writeEventExpectations
  112. .count,
  113. description]]];
  114. }
  115. - (void)expectListenEventWithDescription:(NSString *)description {
  116. [self.listenEventExpectations
  117. addObject:[self.testCase
  118. expectationWithDescription:[NSString
  119. stringWithFormat:@"listen event %lu: %@",
  120. (unsigned long)
  121. self.listenEventExpectations
  122. .count,
  123. description]]];
  124. }
  125. - (void)applySuccessfulWriteWithResult:(MutationBatchResult)batchResult {
  126. _writeEvents.push_back(std::move(batchResult));
  127. XCTestExpectation *expectation = [self.writeEventExpectations objectAtIndex:0];
  128. [self.writeEventExpectations removeObjectAtIndex:0];
  129. [expectation fulfill];
  130. }
  131. - (void)rejectFailedWriteWithBatchID:(__unused BatchId)batchID error:(__unused NSError *)error {
  132. HARD_FAIL("Not implemented");
  133. }
  134. - (DocumentKeySet)remoteKeysForTarget:(__unused TargetId)targetId {
  135. return DocumentKeySet{};
  136. }
  137. - (void)applyRemoteEvent:(const RemoteEvent &)remoteEvent {
  138. _listenEvents.push_back(remoteEvent);
  139. XCTestExpectation *expectation = [self.listenEventExpectations objectAtIndex:0];
  140. [self.listenEventExpectations removeObjectAtIndex:0];
  141. [expectation fulfill];
  142. }
  143. - (void)rejectListenWithTargetID:(__unused const TargetId)targetID error:(__unused NSError *)error {
  144. HARD_FAIL("Not implemented");
  145. }
  146. @end
  147. class RemoteStoreEventCapture : public RemoteStoreCallback {
  148. public:
  149. explicit RemoteStoreEventCapture(XCTestCase *test_case)
  150. : underlying_capture_([[FSTRemoteStoreEventCapture alloc] initWithTestCase:test_case]) {
  151. }
  152. void ExpectWriteEvent(NSString *description) {
  153. [underlying_capture_ expectWriteEventWithDescription:description];
  154. }
  155. void ExpectListenEvent(NSString *description) {
  156. [underlying_capture_ expectListenEventWithDescription:description];
  157. }
  158. void ApplyRemoteEvent(const RemoteEvent &remote_event) override {
  159. [underlying_capture_ applyRemoteEvent:remote_event];
  160. }
  161. void HandleRejectedListen(TargetId target_id, Status error) override {
  162. [underlying_capture_ rejectListenWithTargetID:target_id error:error.ToNSError()];
  163. }
  164. void HandleSuccessfulWrite(MutationBatchResult batch_result) override {
  165. [underlying_capture_ applySuccessfulWriteWithResult:std::move(batch_result)];
  166. }
  167. void HandleRejectedWrite(BatchId batch_id, Status error) override {
  168. [underlying_capture_ rejectFailedWriteWithBatchID:batch_id error:error.ToNSError()];
  169. }
  170. void HandleOnlineStateChange(OnlineState) override {
  171. HARD_FAIL("Not implemented");
  172. }
  173. model::DocumentKeySet GetRemoteKeys(TargetId target_id) const override {
  174. return [underlying_capture_ remoteKeysForTarget:target_id];
  175. }
  176. private:
  177. FSTRemoteStoreEventCapture *underlying_capture_;
  178. };
  179. #pragma mark - FSTDatastoreTests
  180. @interface FSTDatastoreTests : XCTestCase
  181. @end
  182. @implementation FSTDatastoreTests {
  183. std::shared_ptr<AsyncQueue> _testWorkerQueue;
  184. std::unique_ptr<LocalStore> _localStore;
  185. std::unique_ptr<Persistence> _persistence;
  186. DatabaseInfo _databaseInfo;
  187. QueryEngine _queryEngine;
  188. std::unique_ptr<ConnectivityMonitor> _connectivityMonitor;
  189. std::unique_ptr<FirebaseMetadataProvider> _firebaseMetadataProvider;
  190. std::shared_ptr<Datastore> _datastore;
  191. std::unique_ptr<RemoteStore> _remoteStore;
  192. }
  193. - (void)setUp {
  194. [super setUp];
  195. NSString *projectID = [FSTIntegrationTestCase projectID];
  196. FIRFirestoreSettings *settings = [FSTIntegrationTestCase settings];
  197. if (!settings.sslEnabled) {
  198. GrpcConnection::UseInsecureChannel(MakeString(settings.host));
  199. }
  200. DatabaseId database_id(MakeString(projectID));
  201. _databaseInfo =
  202. DatabaseInfo(database_id, "test-key", MakeString(settings.host), settings.sslEnabled);
  203. _testWorkerQueue = AsyncQueueForTesting();
  204. _connectivityMonitor = CreateNoOpConnectivityMonitor();
  205. _firebaseMetadataProvider = CreateFirebaseMetadataProviderNoOp();
  206. _datastore = std::make_shared<Datastore>(
  207. _databaseInfo, _testWorkerQueue, std::make_shared<EmptyAuthCredentialsProvider>(),
  208. std::make_shared<EmptyAppCheckCredentialsProvider>(), _connectivityMonitor.get(),
  209. _firebaseMetadataProvider.get());
  210. _persistence = MemoryPersistence::WithEagerGarbageCollector();
  211. _localStore =
  212. absl::make_unique<LocalStore>(_persistence.get(), &_queryEngine, User::Unauthenticated());
  213. _remoteStore = absl::make_unique<RemoteStore>(_localStore.get(), _datastore, _testWorkerQueue,
  214. _connectivityMonitor.get(), [](OnlineState) {});
  215. _testWorkerQueue->Enqueue([=] { _remoteStore->Start(); });
  216. }
  217. - (void)tearDown {
  218. XCTestExpectation *completion = [self expectationWithDescription:@"shutdown"];
  219. _testWorkerQueue->Enqueue([=] {
  220. _remoteStore->Shutdown();
  221. [completion fulfill];
  222. });
  223. [self awaitExpectations];
  224. [super tearDown];
  225. }
  226. - (void)testCommit {
  227. XCTestExpectation *expectation = [self expectationWithDescription:@"commitWithCompletion"];
  228. _datastore->CommitMutations({}, [self, expectation](const Status &status) {
  229. (void)self; // Avoid unused lambda capture error in Xcode 12.
  230. XCTAssertTrue(status.ok(), @"Failed to commit");
  231. [expectation fulfill];
  232. });
  233. [self awaitExpectations];
  234. }
  235. - (void)testStreamingWrite {
  236. RemoteStoreEventCapture capture(self);
  237. capture.ExpectWriteEvent(@"write mutations");
  238. _remoteStore->set_sync_engine(&capture);
  239. auto mutation = SetMutation("rooms/eros", Map("name", "Eros"));
  240. MutationBatch batch = MutationBatch(23, Timestamp::Now(), {}, {mutation});
  241. _testWorkerQueue->Enqueue([=] {
  242. _remoteStore->AddToWritePipeline(batch);
  243. // The added batch won't be written immediately because write stream wasn't yet open --
  244. // trigger its opening.
  245. _remoteStore->FillWritePipeline();
  246. });
  247. [self awaitExpectations];
  248. }
  249. - (void)awaitExpectations {
  250. [self waitForExpectationsWithTimeout:4.0
  251. handler:^(NSError *_Nullable expectationError) {
  252. if (expectationError) {
  253. XCTFail(@"Error waiting for timeout: %@", expectationError);
  254. }
  255. }];
  256. }
  257. @end
  258. NS_ASSUME_NONNULL_END