FIRFirestore.mm 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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 "FIRFirestore+Internal.h"
  17. #include <memory>
  18. #include <string>
  19. #include <utility>
  20. #import "FIRFirestoreSettings+Internal.h"
  21. #import "FirebaseCore/Extension/FIRAppInternal.h"
  22. #import "FirebaseCore/Extension/FIRComponentContainer.h"
  23. #import "FirebaseCore/Extension/FIRComponentType.h"
  24. #import "Firestore/Source/API/FIRCollectionReference+Internal.h"
  25. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  26. #import "Firestore/Source/API/FIRListenerRegistration+Internal.h"
  27. #import "Firestore/Source/API/FIRLoadBundleTask+Internal.h"
  28. #import "Firestore/Source/API/FIRQuery+Internal.h"
  29. #import "Firestore/Source/API/FIRTransaction+Internal.h"
  30. #import "Firestore/Source/API/FIRWriteBatch+Internal.h"
  31. #import "Firestore/Source/API/FSTFirestoreComponent.h"
  32. #import "Firestore/Source/API/FSTUserDataReader.h"
  33. #include "Firestore/core/src/api/collection_reference.h"
  34. #include "Firestore/core/src/api/document_reference.h"
  35. #include "Firestore/core/src/api/firestore.h"
  36. #include "Firestore/core/src/api/write_batch.h"
  37. #include "Firestore/core/src/core/database_info.h"
  38. #include "Firestore/core/src/core/event_listener.h"
  39. #include "Firestore/core/src/core/transaction.h"
  40. #include "Firestore/core/src/credentials/credentials_provider.h"
  41. #include "Firestore/core/src/model/database_id.h"
  42. #include "Firestore/core/src/remote/firebase_metadata_provider.h"
  43. #include "Firestore/core/src/util/async_queue.h"
  44. #include "Firestore/core/src/util/byte_stream_apple.h"
  45. #include "Firestore/core/src/util/config.h"
  46. #include "Firestore/core/src/util/empty.h"
  47. #include "Firestore/core/src/util/error_apple.h"
  48. #include "Firestore/core/src/util/exception.h"
  49. #include "Firestore/core/src/util/exception_apple.h"
  50. #include "Firestore/core/src/util/executor_libdispatch.h"
  51. #include "Firestore/core/src/util/hard_assert.h"
  52. #include "Firestore/core/src/util/log.h"
  53. #include "Firestore/core/src/util/status.h"
  54. #include "Firestore/core/src/util/statusor.h"
  55. #include "Firestore/core/src/util/string_apple.h"
  56. #include "absl/memory/memory.h"
  57. using firebase::firestore::api::DocumentReference;
  58. using firebase::firestore::api::Firestore;
  59. using firebase::firestore::api::ListenerRegistration;
  60. using firebase::firestore::core::EventListener;
  61. using firebase::firestore::credentials::AuthCredentialsProvider;
  62. using firebase::firestore::model::DatabaseId;
  63. using firebase::firestore::remote::FirebaseMetadataProvider;
  64. using firebase::firestore::util::AsyncQueue;
  65. using firebase::firestore::util::ByteStreamApple;
  66. using firebase::firestore::util::Empty;
  67. using firebase::firestore::util::Executor;
  68. using firebase::firestore::util::ExecutorLibdispatch;
  69. using firebase::firestore::util::LogSetLevel;
  70. using firebase::firestore::util::MakeCallback;
  71. using firebase::firestore::util::MakeNSError;
  72. using firebase::firestore::util::MakeNSString;
  73. using firebase::firestore::util::MakeString;
  74. using firebase::firestore::util::ObjcThrowHandler;
  75. using firebase::firestore::util::SetThrowHandler;
  76. using firebase::firestore::util::Status;
  77. using firebase::firestore::util::StatusOr;
  78. using firebase::firestore::util::ThrowIllegalState;
  79. using firebase::firestore::util::ThrowInvalidArgument;
  80. using firebase::firestore::util::kLogLevelDebug;
  81. using firebase::firestore::util::kLogLevelNotice;
  82. using UserUpdateBlock = id _Nullable (^)(FIRTransaction *, NSError **);
  83. using UserTransactionCompletion = void (^)(id _Nullable, NSError *_Nullable);
  84. NS_ASSUME_NONNULL_BEGIN
  85. #pragma mark - FIRFirestore
  86. @interface FIRFirestore ()
  87. @property(nonatomic, strong, readonly) FSTUserDataReader *dataReader;
  88. @end
  89. @implementation FIRFirestore {
  90. std::shared_ptr<Firestore> _firestore;
  91. FIRFirestoreSettings *_settings;
  92. __weak id<FSTFirestoreInstanceRegistry> _registry;
  93. }
  94. + (void)initialize {
  95. if (self == [FIRFirestore class]) {
  96. SetThrowHandler(ObjcThrowHandler);
  97. Firestore::SetClientLanguage("gl-objc/");
  98. }
  99. }
  100. + (instancetype)firestore {
  101. FIRApp *app = [FIRApp defaultApp];
  102. if (!app) {
  103. ThrowIllegalState("Failed to get FirebaseApp instance. Please call FirebaseApp.configure() "
  104. "before using Firestore");
  105. }
  106. return [self firestoreForApp:app database:MakeNSString(DatabaseId::kDefault)];
  107. }
  108. + (instancetype)firestoreForApp:(FIRApp *)app {
  109. return [self firestoreForApp:app database:MakeNSString(DatabaseId::kDefault)];
  110. }
  111. // TODO(b/62410906): make this public
  112. + (instancetype)firestoreForApp:(FIRApp *)app database:(NSString *)database {
  113. if (!app) {
  114. ThrowInvalidArgument("FirebaseApp instance may not be nil. Use FirebaseApp.app() if you'd like "
  115. "to use the default FirebaseApp instance.");
  116. }
  117. if (!database) {
  118. ThrowInvalidArgument("Database identifier may not be nil. Use '%s' if you want the default "
  119. "database",
  120. DatabaseId::kDefault);
  121. }
  122. id<FSTFirestoreMultiDBProvider> provider =
  123. FIR_COMPONENT(FSTFirestoreMultiDBProvider, app.container);
  124. return [provider firestoreForDatabase:database];
  125. }
  126. - (instancetype)initWithDatabaseID:(model::DatabaseId)databaseID
  127. persistenceKey:(std::string)persistenceKey
  128. authCredentialsProvider:
  129. (std::shared_ptr<credentials::AuthCredentialsProvider>)authCredentialsProvider
  130. appCheckCredentialsProvider:
  131. (std::shared_ptr<credentials::AppCheckCredentialsProvider>)appCheckCredentialsProvider
  132. workerQueue:(std::shared_ptr<AsyncQueue>)workerQueue
  133. firebaseMetadataProvider:
  134. (std::unique_ptr<FirebaseMetadataProvider>)firebaseMetadataProvider
  135. firebaseApp:(FIRApp *)app
  136. instanceRegistry:(nullable id<FSTFirestoreInstanceRegistry>)registry {
  137. if (self = [super init]) {
  138. _firestore = std::make_shared<Firestore>(
  139. std::move(databaseID), std::move(persistenceKey), std::move(authCredentialsProvider),
  140. std::move(appCheckCredentialsProvider), std::move(workerQueue),
  141. std::move(firebaseMetadataProvider), (__bridge void *)self);
  142. _app = app;
  143. _registry = registry;
  144. FSTPreConverterBlock block = ^id _Nullable(id _Nullable input) {
  145. if ([input isKindOfClass:[FIRDocumentReference class]]) {
  146. auto documentReference = (FIRDocumentReference *)input;
  147. return [[FSTDocumentKeyReference alloc] initWithKey:documentReference.key
  148. databaseID:documentReference.firestore.databaseID];
  149. } else {
  150. return input;
  151. }
  152. };
  153. _dataReader = [[FSTUserDataReader alloc] initWithDatabaseID:_firestore->database_id()
  154. preConverter:block];
  155. // Use the property setter so the default settings get plumbed into _firestoreClient.
  156. self.settings = [[FIRFirestoreSettings alloc] init];
  157. }
  158. return self;
  159. }
  160. - (FIRFirestoreSettings *)settings {
  161. // Disallow mutation of our internal settings
  162. return [_settings copy];
  163. }
  164. - (void)setSettings:(FIRFirestoreSettings *)settings {
  165. if (![settings isEqual:_settings]) {
  166. _settings = settings;
  167. _firestore->set_settings([settings internalSettings]);
  168. #if HAVE_LIBDISPATCH
  169. std::unique_ptr<Executor> user_executor =
  170. absl::make_unique<ExecutorLibdispatch>(settings.dispatchQueue);
  171. #else
  172. // It's possible to build without libdispatch on macOS for testing purposes.
  173. // In this case, avoid breaking the build.
  174. std::unique_ptr<Executor> user_executor =
  175. Executor::CreateSerial("com.google.firebase.firestore.user");
  176. #endif // HAVE_LIBDISPATCH
  177. _firestore->set_user_executor(std::move(user_executor));
  178. }
  179. }
  180. - (FIRCollectionReference *)collectionWithPath:(NSString *)collectionPath {
  181. if (!collectionPath) {
  182. ThrowInvalidArgument("Collection path cannot be nil.");
  183. }
  184. if (!collectionPath.length) {
  185. ThrowInvalidArgument("Collection path cannot be empty.");
  186. }
  187. if ([collectionPath containsString:@"//"]) {
  188. ThrowInvalidArgument("Invalid path (%s). Paths must not contain // in them.", collectionPath);
  189. }
  190. return [[FIRCollectionReference alloc]
  191. initWithReference:_firestore->GetCollection(MakeString(collectionPath))];
  192. }
  193. - (FIRDocumentReference *)documentWithPath:(NSString *)documentPath {
  194. if (!documentPath) {
  195. ThrowInvalidArgument("Document path cannot be nil.");
  196. }
  197. if (!documentPath.length) {
  198. ThrowInvalidArgument("Document path cannot be empty.");
  199. }
  200. if ([documentPath containsString:@"//"]) {
  201. ThrowInvalidArgument("Invalid path (%s). Paths must not contain // in them.", documentPath);
  202. }
  203. DocumentReference documentReference = _firestore->GetDocument(MakeString(documentPath));
  204. return [[FIRDocumentReference alloc] initWithReference:std::move(documentReference)];
  205. }
  206. - (FIRQuery *)collectionGroupWithID:(NSString *)collectionID {
  207. if (!collectionID) {
  208. ThrowInvalidArgument("Collection ID cannot be nil.");
  209. }
  210. if (!collectionID.length) {
  211. ThrowInvalidArgument("Collection ID cannot be empty.");
  212. }
  213. if ([collectionID containsString:@"/"]) {
  214. ThrowInvalidArgument("Invalid collection ID (%s). Collection IDs must not contain / in them.",
  215. collectionID);
  216. }
  217. auto query = _firestore->GetCollectionGroup(MakeString(collectionID));
  218. return [[FIRQuery alloc] initWithQuery:std::move(query) firestore:_firestore];
  219. }
  220. - (FIRWriteBatch *)batch {
  221. return [FIRWriteBatch writeBatchWithDataReader:self.dataReader writeBatch:_firestore->GetBatch()];
  222. }
  223. - (void)runTransactionWithBlock:(UserUpdateBlock)updateBlock
  224. dispatchQueue:(dispatch_queue_t)queue
  225. completion:(UserTransactionCompletion)completion {
  226. if (!updateBlock) {
  227. ThrowInvalidArgument("Transaction block cannot be nil.");
  228. }
  229. if (!completion) {
  230. ThrowInvalidArgument("Transaction completion block cannot be nil.");
  231. }
  232. class TransactionResult {
  233. public:
  234. TransactionResult(FIRFirestore *firestore,
  235. UserUpdateBlock update_block,
  236. dispatch_queue_t queue,
  237. UserTransactionCompletion completion)
  238. : firestore_(firestore),
  239. user_update_block_(update_block),
  240. queue_(queue),
  241. user_completion_(completion) {
  242. }
  243. void RunUpdateBlock(std::shared_ptr<core::Transaction> internalTransaction,
  244. core::TransactionResultCallback internalCallback) {
  245. dispatch_async(queue_, ^{
  246. auto transaction = [FIRTransaction transactionWithInternalTransaction:internalTransaction
  247. firestore:firestore_];
  248. NSError *_Nullable error = nil;
  249. user_result_ = user_update_block_(transaction, &error);
  250. // If the user set an error, disregard the result.
  251. if (error) {
  252. // If the error is a user error, set flag to not retry the transaction.
  253. if (error.domain != FIRFirestoreErrorDomain) {
  254. internalTransaction->MarkPermanentlyFailed();
  255. }
  256. internalCallback(Status::FromNSError(error));
  257. } else {
  258. internalCallback(Status::OK());
  259. }
  260. });
  261. }
  262. void HandleFinalStatus(const Status &status) {
  263. if (!status.ok()) {
  264. user_completion_(nil, MakeNSError(status));
  265. return;
  266. }
  267. user_completion_(user_result_, nil);
  268. }
  269. private:
  270. FIRFirestore *firestore_;
  271. UserUpdateBlock user_update_block_;
  272. dispatch_queue_t queue_;
  273. UserTransactionCompletion user_completion_;
  274. id _Nullable user_result_;
  275. };
  276. auto result_capture = std::make_shared<TransactionResult>(self, updateBlock, queue, completion);
  277. // Wrap the user-supplied updateBlock in a core C++ compatible callback. Wrap the result of the
  278. // updateBlock invocation up in a TransactionResult for tunneling through the internals of the
  279. // system.
  280. auto internalUpdateBlock = [result_capture](
  281. std::shared_ptr<core::Transaction> internalTransaction,
  282. core::TransactionResultCallback internalCallback) {
  283. result_capture->RunUpdateBlock(internalTransaction, internalCallback);
  284. };
  285. // Unpacks the TransactionResult value and calls the user completion handler.
  286. //
  287. // PORTING NOTE: Other platforms where the user return value is internally representable don't
  288. // need this wrapper.
  289. auto objcTranslator = [result_capture](const Status &status) {
  290. result_capture->HandleFinalStatus(status);
  291. };
  292. _firestore->RunTransaction(std::move(internalUpdateBlock), std::move(objcTranslator));
  293. }
  294. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **error))updateBlock
  295. completion:
  296. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  297. static dispatch_queue_t transactionDispatchQueue;
  298. static dispatch_once_t onceToken;
  299. dispatch_once(&onceToken, ^{
  300. transactionDispatchQueue = dispatch_queue_create("com.google.firebase.firestore.transaction",
  301. DISPATCH_QUEUE_CONCURRENT);
  302. });
  303. [self runTransactionWithBlock:updateBlock
  304. dispatchQueue:transactionDispatchQueue
  305. completion:completion];
  306. }
  307. + (void)enableLogging:(BOOL)logging {
  308. LogSetLevel(logging ? kLogLevelDebug : kLogLevelNotice);
  309. }
  310. - (void)useEmulatorWithHost:(NSString *)host port:(NSInteger)port {
  311. if (!host.length) {
  312. ThrowInvalidArgument("Host cannot be nil or empty.");
  313. }
  314. if (!_settings.isUsingDefaultHost) {
  315. LOG_WARN("Overriding previously-set host value: %@", _settings.host);
  316. }
  317. // Use a new settings so the new settings are automatically plumbed
  318. // to the underlying Firestore objects.
  319. NSString *settingsHost = [NSString stringWithFormat:@"%@:%li", host, (long)port];
  320. FIRFirestoreSettings *newSettings = [_settings copy];
  321. newSettings.host = settingsHost;
  322. self.settings = newSettings;
  323. }
  324. - (void)enableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  325. _firestore->EnableNetwork(MakeCallback(completion));
  326. }
  327. - (void)disableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable))completion {
  328. _firestore->DisableNetwork(MakeCallback(completion));
  329. }
  330. - (void)clearPersistenceWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  331. _firestore->ClearPersistence(MakeCallback(completion));
  332. }
  333. - (void)waitForPendingWritesWithCompletion:(void (^)(NSError *_Nullable error))completion {
  334. _firestore->WaitForPendingWrites(MakeCallback(completion));
  335. }
  336. - (void)terminateWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  337. id<FSTFirestoreInstanceRegistry> strongRegistry = _registry;
  338. if (strongRegistry) {
  339. [strongRegistry
  340. removeInstanceWithDatabase:MakeNSString(_firestore->database_id().database_id())];
  341. }
  342. [self terminateInternalWithCompletion:completion];
  343. }
  344. - (id<FIRListenerRegistration>)addSnapshotsInSyncListener:(void (^)(void))listener {
  345. std::unique_ptr<core::EventListener<Empty>> eventListener =
  346. core::EventListener<Empty>::Create([listener](const StatusOr<Empty> &) { listener(); });
  347. std::unique_ptr<ListenerRegistration> result =
  348. _firestore->AddSnapshotsInSyncListener(std::move(eventListener));
  349. return [[FSTListenerRegistration alloc] initWithRegistration:std::move(result)];
  350. }
  351. - (FIRLoadBundleTask *)loadBundle:(nonnull NSData *)bundleData {
  352. auto stream = absl::make_unique<ByteStreamApple>([[NSInputStream alloc] initWithData:bundleData]);
  353. return [self loadBundleStream:[[NSInputStream alloc] initWithData:bundleData] completion:nil];
  354. }
  355. - (FIRLoadBundleTask *)loadBundle:(NSData *)bundleData
  356. completion:(nullable void (^)(FIRLoadBundleTaskProgress *_Nullable progress,
  357. NSError *_Nullable error))completion {
  358. return [self loadBundleStream:[[NSInputStream alloc] initWithData:bundleData]
  359. completion:completion];
  360. }
  361. - (FIRLoadBundleTask *)loadBundleStream:(NSInputStream *)bundleStream {
  362. return [self loadBundleStream:bundleStream completion:nil];
  363. }
  364. - (FIRLoadBundleTask *)loadBundleStream:(NSInputStream *)bundleStream
  365. completion:
  366. (nullable void (^)(FIRLoadBundleTaskProgress *_Nullable progress,
  367. NSError *_Nullable error))completion {
  368. auto stream = absl::make_unique<ByteStreamApple>(bundleStream);
  369. std::shared_ptr<api::LoadBundleTask> task = _firestore->LoadBundle(std::move(stream));
  370. auto callback = [completion](api::LoadBundleTaskProgress progress) {
  371. if (!completion) {
  372. return;
  373. }
  374. // Ignoring `kInProgress` because we are setting up for completion callback.
  375. if (progress.state() == api::LoadBundleTaskState::kSuccess) {
  376. completion([[FIRLoadBundleTaskProgress alloc] initWithInternal:progress], nil);
  377. } else if (progress.state() == api::LoadBundleTaskState::kError) {
  378. NSError *error = nil;
  379. if (!progress.error_status().ok()) {
  380. LOG_WARN("Progress set to Error, but error_status() is ok()");
  381. error = MakeNSError(firebase::firestore::Error::kErrorUnknown,
  382. "Loading bundle failed with unknown error");
  383. } else {
  384. error = MakeNSError(progress.error_status());
  385. }
  386. completion([[FIRLoadBundleTaskProgress alloc] initWithInternal:progress], error);
  387. }
  388. };
  389. task->SetLastObserver(callback);
  390. return [[FIRLoadBundleTask alloc] initWithTask:task];
  391. }
  392. - (void)getQueryNamed:(NSString *)name completion:(void (^)(FIRQuery *_Nullable query))completion {
  393. auto firestore = _firestore;
  394. auto callback = [completion, firestore](core::Query query, bool found) {
  395. if (!completion) {
  396. return;
  397. }
  398. if (found) {
  399. FIRQuery *firQuery = [[FIRQuery alloc] initWithQuery:std::move(query) firestore:firestore];
  400. completion(firQuery);
  401. } else {
  402. completion(nil);
  403. }
  404. };
  405. _firestore->GetNamedQuery(MakeString(name), callback);
  406. }
  407. @end
  408. @implementation FIRFirestore (Internal)
  409. - (std::shared_ptr<Firestore>)wrapped {
  410. return _firestore;
  411. }
  412. - (const std::shared_ptr<AsyncQueue> &)workerQueue {
  413. return _firestore->worker_queue();
  414. }
  415. - (const DatabaseId &)databaseID {
  416. return _firestore->database_id();
  417. }
  418. + (FIRFirestore *)recoverFromFirestore:(std::shared_ptr<Firestore>)firestore {
  419. return (__bridge FIRFirestore *)firestore->extension();
  420. }
  421. - (void)terminateInternalWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  422. _firestore->Terminate(MakeCallback(completion));
  423. }
  424. @end
  425. NS_ASSUME_NONNULL_END