FIRFirestore.mm 19 KB

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