FIRFirestore.mm 13 KB

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