FIRFirestore.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. #import <FirebaseCore/FIRApp.h>
  18. #import <FirebaseCore/FIRAppInternal.h>
  19. #import <FirebaseCore/FIRComponentContainer.h>
  20. #import <FirebaseCore/FIROptions.h>
  21. #include <memory>
  22. #include <string>
  23. #include <utility>
  24. #import "FIRFirestoreSettings+Internal.h"
  25. #import "Firestore/Source/API/FIRCollectionReference+Internal.h"
  26. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  27. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  28. #import "Firestore/Source/API/FIRListenerRegistration+Internal.h"
  29. #import "Firestore/Source/API/FIRQuery+Internal.h"
  30. #import "Firestore/Source/API/FIRTransaction+Internal.h"
  31. #import "Firestore/Source/API/FIRWriteBatch+Internal.h"
  32. #import "Firestore/Source/API/FSTFirestoreComponent.h"
  33. #import "Firestore/Source/API/FSTUserDataConverter.h"
  34. #include "Firestore/core/src/firebase/firestore/api/collection_reference.h"
  35. #include "Firestore/core/src/firebase/firestore/api/firestore.h"
  36. #include "Firestore/core/src/firebase/firestore/api/write_batch.h"
  37. #include "Firestore/core/src/firebase/firestore/auth/credentials_provider.h"
  38. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  39. #include "Firestore/core/src/firebase/firestore/core/transaction.h"
  40. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  41. #include "Firestore/core/src/firebase/firestore/util/async_queue.h"
  42. #include "Firestore/core/src/firebase/firestore/util/empty.h"
  43. #include "Firestore/core/src/firebase/firestore/util/error_apple.h"
  44. #include "Firestore/core/src/firebase/firestore/util/exception.h"
  45. #include "Firestore/core/src/firebase/firestore/util/exception_apple.h"
  46. #include "Firestore/core/src/firebase/firestore/util/executor_libdispatch.h"
  47. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  48. #include "Firestore/core/src/firebase/firestore/util/log.h"
  49. #include "Firestore/core/src/firebase/firestore/util/status.h"
  50. #include "Firestore/core/src/firebase/firestore/util/statusor.h"
  51. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  52. namespace util = firebase::firestore::util;
  53. using firebase::firestore::api::DocumentReference;
  54. using firebase::firestore::api::Firestore;
  55. using firebase::firestore::api::ListenerRegistration;
  56. using firebase::firestore::auth::CredentialsProvider;
  57. using firebase::firestore::core::EventListener;
  58. using firebase::firestore::model::DatabaseId;
  59. using firebase::firestore::util::AsyncQueue;
  60. using firebase::firestore::util::Empty;
  61. using firebase::firestore::util::ObjcThrowHandler;
  62. using firebase::firestore::util::SetThrowHandler;
  63. using firebase::firestore::util::StatusOr;
  64. using firebase::firestore::util::ThrowIllegalState;
  65. using firebase::firestore::util::ThrowInvalidArgument;
  66. using UserUpdateBlock = id _Nullable (^)(FIRTransaction *, NSError **);
  67. using UserTransactionCompletion = void (^)(id _Nullable, NSError *_Nullable);
  68. NS_ASSUME_NONNULL_BEGIN
  69. #pragma mark - FIRFirestore
  70. @interface FIRFirestore ()
  71. @property(nonatomic, strong, readonly) FSTUserDataConverter *dataConverter;
  72. @end
  73. @implementation FIRFirestore {
  74. std::shared_ptr<Firestore> _firestore;
  75. FIRFirestoreSettings *_settings;
  76. __weak id<FSTFirestoreInstanceRegistry> _registry;
  77. }
  78. + (void)initialize {
  79. if (self == [FIRFirestore class]) {
  80. SetThrowHandler(ObjcThrowHandler);
  81. }
  82. }
  83. + (instancetype)firestore {
  84. FIRApp *app = [FIRApp defaultApp];
  85. if (!app) {
  86. ThrowIllegalState("Failed to get FirebaseApp instance. Please call FirebaseApp.configure() "
  87. "before using Firestore");
  88. }
  89. return [self firestoreForApp:app database:util::MakeNSString(DatabaseId::kDefault)];
  90. }
  91. + (instancetype)firestoreForApp:(FIRApp *)app {
  92. return [self firestoreForApp:app database:util::MakeNSString(DatabaseId::kDefault)];
  93. }
  94. // TODO(b/62410906): make this public
  95. + (instancetype)firestoreForApp:(FIRApp *)app database:(NSString *)database {
  96. if (!app) {
  97. ThrowInvalidArgument("FirebaseApp instance may not be nil. Use FirebaseApp.app() if you'd like "
  98. "to use the default FirebaseApp instance.");
  99. }
  100. if (!database) {
  101. ThrowInvalidArgument("Database identifier may not be nil. Use '%s' if you want the default "
  102. "database",
  103. DatabaseId::kDefault);
  104. }
  105. id<FSTFirestoreMultiDBProvider> provider =
  106. FIR_COMPONENT(FSTFirestoreMultiDBProvider, app.container);
  107. return [provider firestoreForDatabase:database];
  108. }
  109. - (instancetype)initWithDatabaseID:(model::DatabaseId)databaseID
  110. persistenceKey:(std::string)persistenceKey
  111. credentialsProvider:(std::shared_ptr<CredentialsProvider>)credentialsProvider
  112. workerQueue:(std::shared_ptr<AsyncQueue>)workerQueue
  113. firebaseApp:(FIRApp *)app
  114. instanceRegistry:(nullable id<FSTFirestoreInstanceRegistry>)registry {
  115. if (self = [super init]) {
  116. _firestore = std::make_shared<Firestore>(std::move(databaseID), std::move(persistenceKey),
  117. std::move(credentialsProvider), std::move(workerQueue),
  118. (__bridge void *)self);
  119. _app = app;
  120. _registry = registry;
  121. FSTPreConverterBlock block = ^id _Nullable(id _Nullable input) {
  122. if ([input isKindOfClass:[FIRDocumentReference class]]) {
  123. FIRDocumentReference *documentReference = (FIRDocumentReference *)input;
  124. return [[FSTDocumentKeyReference alloc] initWithKey:documentReference.key
  125. databaseID:documentReference.firestore.databaseID];
  126. } else {
  127. return input;
  128. }
  129. };
  130. _dataConverter = [[FSTUserDataConverter alloc] initWithDatabaseID:_firestore->database_id()
  131. preConverter:block];
  132. // Use the property setter so the default settings get plumbed into _firestoreClient.
  133. self.settings = [[FIRFirestoreSettings alloc] init];
  134. }
  135. return self;
  136. }
  137. - (FIRFirestoreSettings *)settings {
  138. // Disallow mutation of our internal settings
  139. return [_settings copy];
  140. }
  141. - (void)setSettings:(FIRFirestoreSettings *)settings {
  142. if (![settings isEqual:_settings]) {
  143. _settings = settings;
  144. _firestore->set_settings([settings internalSettings]);
  145. std::unique_ptr<util::Executor> user_executor =
  146. absl::make_unique<util::ExecutorLibdispatch>(settings.dispatchQueue);
  147. _firestore->set_user_executor(std::move(user_executor));
  148. }
  149. }
  150. - (FIRCollectionReference *)collectionWithPath:(NSString *)collectionPath {
  151. if (!collectionPath) {
  152. ThrowInvalidArgument("Collection path cannot be nil.");
  153. }
  154. if ([collectionPath containsString:@"//"]) {
  155. ThrowInvalidArgument("Invalid path (%s). Paths must not contain // in them.", collectionPath);
  156. }
  157. return [[FIRCollectionReference alloc]
  158. initWithReference:_firestore->GetCollection(util::MakeString(collectionPath))];
  159. }
  160. - (FIRDocumentReference *)documentWithPath:(NSString *)documentPath {
  161. if (!documentPath) {
  162. ThrowInvalidArgument("Document path cannot be nil.");
  163. }
  164. if ([documentPath containsString:@"//"]) {
  165. ThrowInvalidArgument("Invalid path (%s). Paths must not contain // in them.", documentPath);
  166. }
  167. DocumentReference documentReference = _firestore->GetDocument(util::MakeString(documentPath));
  168. return [[FIRDocumentReference alloc] initWithReference:std::move(documentReference)];
  169. }
  170. - (FIRQuery *)collectionGroupWithID:(NSString *)collectionID {
  171. if (!collectionID) {
  172. ThrowInvalidArgument("Collection ID cannot be nil.");
  173. }
  174. if ([collectionID containsString:@"/"]) {
  175. ThrowInvalidArgument("Invalid collection ID (%s). Collection IDs must not contain / in them.",
  176. collectionID);
  177. }
  178. auto query = _firestore->GetCollectionGroup(util::MakeString(collectionID));
  179. return [[FIRQuery alloc] initWithQuery:std::move(query) firestore:_firestore];
  180. }
  181. - (FIRWriteBatch *)batch {
  182. return [FIRWriteBatch writeBatchWithDataConverter:self.dataConverter
  183. writeBatch:_firestore->GetBatch()];
  184. }
  185. - (void)runTransactionWithBlock:(UserUpdateBlock)updateBlock
  186. dispatchQueue:(dispatch_queue_t)queue
  187. completion:(UserTransactionCompletion)completion {
  188. if (!updateBlock) {
  189. ThrowInvalidArgument("Transaction block cannot be nil.");
  190. }
  191. if (!completion) {
  192. ThrowInvalidArgument("Transaction completion block cannot be nil.");
  193. }
  194. class TransactionResult {
  195. public:
  196. TransactionResult(FIRFirestore *firestore,
  197. UserUpdateBlock update_block,
  198. dispatch_queue_t queue,
  199. UserTransactionCompletion completion)
  200. : firestore_(firestore),
  201. user_update_block_(update_block),
  202. queue_(queue),
  203. user_completion_(completion) {
  204. }
  205. void RunUpdateBlock(std::shared_ptr<core::Transaction> internalTransaction,
  206. core::TransactionResultCallback internalCallback) {
  207. dispatch_async(queue_, ^{
  208. auto transaction = [FIRTransaction transactionWithInternalTransaction:internalTransaction
  209. firestore:firestore_];
  210. NSError *_Nullable error = nil;
  211. user_result_ = user_update_block_(transaction, &error);
  212. // If the user set an error, disregard the result.
  213. if (error) {
  214. // If the error is a user error, set flag to not retry the transaction.
  215. if (error.domain != FIRFirestoreErrorDomain) {
  216. internalTransaction->MarkPermanentlyFailed();
  217. }
  218. internalCallback(util::Status::FromNSError(error));
  219. } else {
  220. internalCallback(util::Status::OK());
  221. }
  222. });
  223. }
  224. void HandleFinalStatus(const util::Status &status) {
  225. if (!status.ok()) {
  226. user_completion_(nil, util::MakeNSError(status));
  227. return;
  228. }
  229. user_completion_(user_result_, nil);
  230. }
  231. private:
  232. FIRFirestore *firestore_;
  233. UserUpdateBlock user_update_block_;
  234. dispatch_queue_t queue_;
  235. UserTransactionCompletion user_completion_;
  236. id _Nullable user_result_;
  237. };
  238. auto result_capture = std::make_shared<TransactionResult>(self, updateBlock, queue, completion);
  239. // Wrap the user-supplied updateBlock in a core C++ compatible callback. Wrap the result of the
  240. // updateBlock invocation up in a TransactionResult for tunneling through the internals of the
  241. // system.
  242. auto internalUpdateBlock = [result_capture](
  243. std::shared_ptr<core::Transaction> internalTransaction,
  244. core::TransactionResultCallback internalCallback) {
  245. result_capture->RunUpdateBlock(internalTransaction, internalCallback);
  246. };
  247. // Unpacks the TransactionResult value and calls the user completion handler.
  248. //
  249. // PORTING NOTE: Other platforms where the user return value is internally representable don't
  250. // need this wrapper.
  251. auto objcTranslator = [result_capture](const util::Status &status) {
  252. result_capture->HandleFinalStatus(status);
  253. };
  254. _firestore->RunTransaction(std::move(internalUpdateBlock), std::move(objcTranslator));
  255. }
  256. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **error))updateBlock
  257. completion:
  258. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  259. static dispatch_queue_t transactionDispatchQueue;
  260. static dispatch_once_t onceToken;
  261. dispatch_once(&onceToken, ^{
  262. transactionDispatchQueue = dispatch_queue_create("com.google.firebase.firestore.transaction",
  263. DISPATCH_QUEUE_CONCURRENT);
  264. });
  265. [self runTransactionWithBlock:updateBlock
  266. dispatchQueue:transactionDispatchQueue
  267. completion:completion];
  268. }
  269. + (void)enableLogging:(BOOL)logging {
  270. util::LogSetLevel(logging ? util::kLogLevelDebug : util::kLogLevelNotice);
  271. }
  272. - (void)enableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  273. _firestore->EnableNetwork(util::MakeCallback(completion));
  274. }
  275. - (void)disableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable))completion {
  276. _firestore->DisableNetwork(util::MakeCallback(completion));
  277. }
  278. - (void)clearPersistenceWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  279. _firestore->ClearPersistence(util::MakeCallback(completion));
  280. }
  281. - (void)waitForPendingWritesWithCompletion:(void (^)(NSError *_Nullable error))completion {
  282. _firestore->WaitForPendingWrites(util::MakeCallback(completion));
  283. }
  284. - (void)terminateWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  285. id<FSTFirestoreInstanceRegistry> strongRegistry = _registry;
  286. if (strongRegistry) {
  287. [strongRegistry
  288. removeInstanceWithDatabase:util::MakeNSString(_firestore->database_id().database_id())];
  289. }
  290. [self terminateInternalWithCompletion:completion];
  291. }
  292. - (id<FIRListenerRegistration>)addSnapshotsInSyncListener:(void (^)(void))listener {
  293. std::unique_ptr<core::EventListener<Empty>> eventListener =
  294. core::EventListener<Empty>::Create([listener](const StatusOr<Empty> &v) { listener(); });
  295. std::unique_ptr<ListenerRegistration> result =
  296. _firestore->AddSnapshotsInSyncListener(std::move(eventListener));
  297. return [[FSTListenerRegistration alloc] initWithRegistration:std::move(result)];
  298. }
  299. @end
  300. @implementation FIRFirestore (Internal)
  301. - (std::shared_ptr<Firestore>)wrapped {
  302. return _firestore;
  303. }
  304. - (const std::shared_ptr<util::AsyncQueue> &)workerQueue {
  305. return _firestore->worker_queue();
  306. }
  307. - (const DatabaseId &)databaseID {
  308. return _firestore->database_id();
  309. }
  310. + (BOOL)isLoggingEnabled {
  311. return util::LogIsLoggable(util::kLogLevelDebug);
  312. }
  313. + (FIRFirestore *)recoverFromFirestore:(std::shared_ptr<Firestore>)firestore {
  314. return (__bridge FIRFirestore *)firestore->extension();
  315. }
  316. - (void)terminateInternalWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  317. _firestore->Terminate(util::MakeCallback(completion));
  318. }
  319. @end
  320. NS_ASSUME_NONNULL_END