FIRFirestore.mm 14 KB

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