FIRFirestore.mm 15 KB

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