FIRFirestore.mm 20 KB

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