FIRFirestore.mm 18 KB

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