FIRFirestore.mm 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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. // TODO(csi): Delete this once setIndexConfigurationFromJSON and setIndexConfigurationFromStream
  17. // are removed.
  18. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  19. #import "FIRFirestore+Internal.h"
  20. #include <memory>
  21. #include <string>
  22. #include <utility>
  23. #import "FIRFirestoreSettings+Internal.h"
  24. #import "FIRPersistentCacheIndexManager+Internal.h"
  25. #import "FIRTransactionOptions+Internal.h"
  26. #import "FIRTransactionOptions.h"
  27. #import "FirebaseCore/Extension/FIRAppInternal.h"
  28. #import "FirebaseCore/Extension/FIRComponentContainer.h"
  29. #import "FirebaseCore/Extension/FIRComponentType.h"
  30. #import "Firestore/Source/API/FIRCollectionReference+Internal.h"
  31. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  32. #import "Firestore/Source/API/FIRListenerRegistration+Internal.h"
  33. #import "Firestore/Source/API/FIRLoadBundleTask+Internal.h"
  34. #import "Firestore/Source/API/FIRQuery+Internal.h"
  35. #import "Firestore/Source/API/FIRTransaction+Internal.h"
  36. #import "Firestore/Source/API/FIRWriteBatch+Internal.h"
  37. #import "Firestore/Source/API/FSTFirestoreComponent.h"
  38. #import "Firestore/Source/API/FSTUserDataReader.h"
  39. #include "Firestore/core/src/api/collection_reference.h"
  40. #include "Firestore/core/src/api/document_reference.h"
  41. #include "Firestore/core/src/api/firestore.h"
  42. #include "Firestore/core/src/api/write_batch.h"
  43. #include "Firestore/core/src/core/database_info.h"
  44. #include "Firestore/core/src/core/event_listener.h"
  45. #include "Firestore/core/src/core/transaction.h"
  46. #include "Firestore/core/src/credentials/credentials_provider.h"
  47. #include "Firestore/core/src/model/database_id.h"
  48. #include "Firestore/core/src/remote/firebase_metadata_provider.h"
  49. #include "Firestore/core/src/util/async_queue.h"
  50. #include "Firestore/core/src/util/byte_stream_apple.h"
  51. #include "Firestore/core/src/util/config.h"
  52. #include "Firestore/core/src/util/empty.h"
  53. #include "Firestore/core/src/util/error_apple.h"
  54. #include "Firestore/core/src/util/exception.h"
  55. #include "Firestore/core/src/util/exception_apple.h"
  56. #include "Firestore/core/src/util/executor_libdispatch.h"
  57. #include "Firestore/core/src/util/hard_assert.h"
  58. #include "Firestore/core/src/util/log.h"
  59. #include "Firestore/core/src/util/status.h"
  60. #include "Firestore/core/src/util/statusor.h"
  61. #include "Firestore/core/src/util/string_apple.h"
  62. #include "absl/memory/memory.h"
  63. using firebase::firestore::api::DocumentReference;
  64. using firebase::firestore::api::Firestore;
  65. using firebase::firestore::api::ListenerRegistration;
  66. using firebase::firestore::core::EventListener;
  67. using firebase::firestore::credentials::AuthCredentialsProvider;
  68. using firebase::firestore::model::DatabaseId;
  69. using firebase::firestore::remote::FirebaseMetadataProvider;
  70. using firebase::firestore::util::AsyncQueue;
  71. using firebase::firestore::util::ByteStreamApple;
  72. using firebase::firestore::util::Empty;
  73. using firebase::firestore::util::Executor;
  74. using firebase::firestore::util::ExecutorLibdispatch;
  75. using firebase::firestore::util::kLogLevelDebug;
  76. using firebase::firestore::util::kLogLevelNotice;
  77. using firebase::firestore::util::LogSetLevel;
  78. using firebase::firestore::util::MakeCallback;
  79. using firebase::firestore::util::MakeNSError;
  80. using firebase::firestore::util::MakeNSString;
  81. using firebase::firestore::util::MakeString;
  82. using firebase::firestore::util::ObjcThrowHandler;
  83. using firebase::firestore::util::SetThrowHandler;
  84. using firebase::firestore::util::Status;
  85. using firebase::firestore::util::StatusOr;
  86. using firebase::firestore::util::StreamReadResult;
  87. using firebase::firestore::util::ThrowIllegalState;
  88. using firebase::firestore::util::ThrowInvalidArgument;
  89. using UserUpdateBlock = id _Nullable (^)(FIRTransaction *, NSError **);
  90. using UserTransactionCompletion = void (^)(id _Nullable, NSError *_Nullable);
  91. NS_ASSUME_NONNULL_BEGIN
  92. #pragma mark - FIRFirestore
  93. @interface FIRFirestore ()
  94. @property(nonatomic, strong, readonly) FSTUserDataReader *dataReader;
  95. @end
  96. @implementation FIRFirestore {
  97. std::shared_ptr<Firestore> _firestore;
  98. FIRFirestoreSettings *_settings;
  99. __weak id<FSTFirestoreInstanceRegistry> _registry;
  100. FIRPersistentCacheIndexManager *_indexManager;
  101. }
  102. + (void)initialize {
  103. if (self == [FIRFirestore class]) {
  104. SetThrowHandler(ObjcThrowHandler);
  105. Firestore::SetClientLanguage("gl-objc/");
  106. }
  107. }
  108. + (instancetype)firestore {
  109. FIRApp *app = [FIRApp defaultApp];
  110. if (!app) {
  111. ThrowIllegalState("Failed to get FirebaseApp instance. Please call FirebaseApp.configure() "
  112. "before using Firestore");
  113. }
  114. return [self firestoreForApp:app database:MakeNSString(DatabaseId::kDefault)];
  115. }
  116. + (instancetype)firestoreForApp:(FIRApp *)app {
  117. return [self firestoreForApp:app database:MakeNSString(DatabaseId::kDefault)];
  118. }
  119. - (instancetype)initWithDatabaseID:(model::DatabaseId)databaseID
  120. persistenceKey:(std::string)persistenceKey
  121. authCredentialsProvider:
  122. (std::shared_ptr<credentials::AuthCredentialsProvider>)authCredentialsProvider
  123. appCheckCredentialsProvider:
  124. (std::shared_ptr<credentials::AppCheckCredentialsProvider>)appCheckCredentialsProvider
  125. workerQueue:(std::shared_ptr<AsyncQueue>)workerQueue
  126. firebaseMetadataProvider:
  127. (std::unique_ptr<FirebaseMetadataProvider>)firebaseMetadataProvider
  128. firebaseApp:(FIRApp *)app
  129. instanceRegistry:(nullable id<FSTFirestoreInstanceRegistry>)registry {
  130. if (self = [super init]) {
  131. _firestore = std::make_shared<Firestore>(
  132. std::move(databaseID), std::move(persistenceKey), std::move(authCredentialsProvider),
  133. std::move(appCheckCredentialsProvider), std::move(workerQueue),
  134. std::move(firebaseMetadataProvider), (__bridge void *)self);
  135. _app = app;
  136. _registry = registry;
  137. FSTPreConverterBlock block = ^id _Nullable(id _Nullable input) {
  138. if ([input isKindOfClass:[FIRDocumentReference class]]) {
  139. auto documentReference = (FIRDocumentReference *)input;
  140. return [[FSTDocumentKeyReference alloc] initWithKey:documentReference.key
  141. databaseID:documentReference.firestore.databaseID];
  142. } else {
  143. return input;
  144. }
  145. };
  146. _dataReader = [[FSTUserDataReader alloc] initWithDatabaseID:_firestore->database_id()
  147. preConverter:block];
  148. // Use the property setter so the default settings get plumbed into _firestoreClient.
  149. self.settings = [[FIRFirestoreSettings alloc] init];
  150. }
  151. return self;
  152. }
  153. + (instancetype)firestoreForApp:(FIRApp *)app database:(NSString *)database {
  154. if (!app) {
  155. ThrowInvalidArgument("FirebaseApp instance may not be nil. Use FirebaseApp.app() if you'd like "
  156. "to use the default FirebaseApp instance.");
  157. }
  158. if (!database) {
  159. ThrowInvalidArgument("Database identifier may not be nil. Use '%s' if you want the default "
  160. "database",
  161. DatabaseId::kDefault);
  162. }
  163. id<FSTFirestoreMultiDBProvider> provider =
  164. FIR_COMPONENT(FSTFirestoreMultiDBProvider, app.container);
  165. return [provider firestoreForDatabase:database];
  166. }
  167. + (instancetype)firestoreForDatabase:(NSString *)database {
  168. FIRApp *app = [FIRApp defaultApp];
  169. if (!app) {
  170. ThrowIllegalState("Failed to get FirebaseApp instance. Please call FirebaseApp.configure() "
  171. "before using Firestore");
  172. }
  173. return [self firestoreForApp:app database:database];
  174. }
  175. - (FIRFirestoreSettings *)settings {
  176. // Disallow mutation of our internal settings
  177. return [_settings copy];
  178. }
  179. - (void)setSettings:(FIRFirestoreSettings *)settings {
  180. if (![settings isEqual:_settings]) {
  181. _settings = settings;
  182. _firestore->set_settings([settings internalSettings]);
  183. #if HAVE_LIBDISPATCH
  184. std::unique_ptr<Executor> user_executor =
  185. absl::make_unique<ExecutorLibdispatch>(settings.dispatchQueue);
  186. #else
  187. // It's possible to build without libdispatch on macOS for testing purposes.
  188. // In this case, avoid breaking the build.
  189. std::unique_ptr<Executor> user_executor =
  190. Executor::CreateSerial("com.google.firebase.firestore.user");
  191. #endif // HAVE_LIBDISPATCH
  192. _firestore->set_user_executor(std::move(user_executor));
  193. }
  194. }
  195. - (void)setIndexConfigurationFromJSON:(NSString *)json
  196. completion:(nullable void (^)(NSError *_Nullable error))completion {
  197. _firestore->SetIndexConfiguration(MakeString(json), MakeCallback(completion));
  198. }
  199. - (void)setIndexConfigurationFromStream:(NSInputStream *)stream
  200. completion:(nullable void (^)(NSError *_Nullable error))completion {
  201. auto input = absl::make_unique<ByteStreamApple>(stream);
  202. auto callback = MakeCallback(completion);
  203. std::string json;
  204. bool eof = false;
  205. while (!eof) {
  206. StreamReadResult result = input->Read(1024ul);
  207. if (!result.ok()) {
  208. callback(result.status());
  209. return;
  210. }
  211. eof = result.eof();
  212. json.append(std::move(result).ValueOrDie());
  213. }
  214. _firestore->SetIndexConfiguration(json, callback);
  215. }
  216. - (FIRCollectionReference *)collectionWithPath:(NSString *)collectionPath {
  217. if (!collectionPath) {
  218. ThrowInvalidArgument("Collection path cannot be nil.");
  219. }
  220. if (!collectionPath.length) {
  221. ThrowInvalidArgument("Collection path cannot be empty.");
  222. }
  223. if ([collectionPath containsString:@"//"]) {
  224. ThrowInvalidArgument("Invalid path (%s). Paths must not contain // in them.", collectionPath);
  225. }
  226. return [[FIRCollectionReference alloc]
  227. initWithReference:_firestore->GetCollection(MakeString(collectionPath))];
  228. }
  229. - (FIRDocumentReference *)documentWithPath:(NSString *)documentPath {
  230. if (!documentPath) {
  231. ThrowInvalidArgument("Document path cannot be nil.");
  232. }
  233. if (!documentPath.length) {
  234. ThrowInvalidArgument("Document path cannot be empty.");
  235. }
  236. if ([documentPath containsString:@"//"]) {
  237. ThrowInvalidArgument("Invalid path (%s). Paths must not contain // in them.", documentPath);
  238. }
  239. DocumentReference documentReference = _firestore->GetDocument(MakeString(documentPath));
  240. return [[FIRDocumentReference alloc] initWithReference:std::move(documentReference)];
  241. }
  242. - (FIRQuery *)collectionGroupWithID:(NSString *)collectionID {
  243. if (!collectionID) {
  244. ThrowInvalidArgument("Collection ID cannot be nil.");
  245. }
  246. if (!collectionID.length) {
  247. ThrowInvalidArgument("Collection ID cannot be empty.");
  248. }
  249. if ([collectionID containsString:@"/"]) {
  250. ThrowInvalidArgument("Invalid collection ID (%s). Collection IDs must not contain / in them.",
  251. collectionID);
  252. }
  253. auto query = _firestore->GetCollectionGroup(MakeString(collectionID));
  254. return [[FIRQuery alloc] initWithQuery:std::move(query) firestore:_firestore];
  255. }
  256. - (FIRWriteBatch *)batch {
  257. return [FIRWriteBatch writeBatchWithDataReader:self.dataReader writeBatch:_firestore->GetBatch()];
  258. }
  259. - (void)runTransactionWithOptions:(FIRTransactionOptions *_Nullable)options
  260. block:(UserUpdateBlock)updateBlock
  261. dispatchQueue:(dispatch_queue_t)queue
  262. completion:(UserTransactionCompletion)completion {
  263. if (!updateBlock) {
  264. ThrowInvalidArgument("Transaction block cannot be nil.");
  265. }
  266. if (!completion) {
  267. ThrowInvalidArgument("Transaction completion block cannot be nil.");
  268. }
  269. class TransactionResult {
  270. public:
  271. TransactionResult(FIRFirestore *firestore,
  272. UserUpdateBlock update_block,
  273. dispatch_queue_t queue,
  274. UserTransactionCompletion completion)
  275. : firestore_(firestore),
  276. user_update_block_(update_block),
  277. queue_(queue),
  278. user_completion_(completion) {
  279. }
  280. void RunUpdateBlock(std::shared_ptr<core::Transaction> internalTransaction,
  281. core::TransactionResultCallback internalCallback) {
  282. dispatch_async(queue_, ^{
  283. auto transaction = [FIRTransaction transactionWithInternalTransaction:internalTransaction
  284. firestore:firestore_];
  285. NSError *_Nullable error = nil;
  286. user_result_ = user_update_block_(transaction, &error);
  287. // If the user set an error, disregard the result.
  288. if (error) {
  289. // If the error is a user error, set flag to not retry the transaction.
  290. if (error.domain != FIRFirestoreErrorDomain) {
  291. internalTransaction->MarkPermanentlyFailed();
  292. }
  293. internalCallback(Status::FromNSError(error));
  294. } else {
  295. internalCallback(Status::OK());
  296. }
  297. });
  298. }
  299. void HandleFinalStatus(const Status &status) {
  300. if (!status.ok()) {
  301. user_completion_(nil, MakeNSError(status));
  302. return;
  303. }
  304. user_completion_(user_result_, nil);
  305. }
  306. private:
  307. FIRFirestore *firestore_;
  308. UserUpdateBlock user_update_block_;
  309. dispatch_queue_t queue_;
  310. UserTransactionCompletion user_completion_;
  311. id _Nullable user_result_;
  312. };
  313. auto result_capture = std::make_shared<TransactionResult>(self, updateBlock, queue, completion);
  314. // Wrap the user-supplied updateBlock in a core C++ compatible callback. Wrap the result of the
  315. // updateBlock invocation up in a TransactionResult for tunneling through the internals of the
  316. // system.
  317. auto internalUpdateBlock = [result_capture](
  318. std::shared_ptr<core::Transaction> internalTransaction,
  319. core::TransactionResultCallback internalCallback) {
  320. result_capture->RunUpdateBlock(internalTransaction, internalCallback);
  321. };
  322. // Unpacks the TransactionResult value and calls the user completion handler.
  323. //
  324. // PORTING NOTE: Other platforms where the user return value is internally representable don't
  325. // need this wrapper.
  326. auto objcTranslator = [result_capture](const Status &status) {
  327. result_capture->HandleFinalStatus(status);
  328. };
  329. int max_attempts = [FIRTransactionOptions defaultMaxAttempts];
  330. if (options) {
  331. // Note: The cast of `maxAttempts` from `NSInteger` to `int` is safe (i.e. lossless) because
  332. // `FIRTransactionOptions` does not allow values greater than `INT32_MAX` to be set.
  333. max_attempts = static_cast<int>(options.maxAttempts);
  334. }
  335. _firestore->RunTransaction(std::move(internalUpdateBlock), std::move(objcTranslator),
  336. max_attempts);
  337. }
  338. - (void)runTransactionWithBlock:(id _Nullable (^)(FIRTransaction *, NSError **error))updateBlock
  339. completion:
  340. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  341. [self runTransactionWithOptions:nil block:updateBlock completion:completion];
  342. }
  343. - (void)runTransactionWithOptions:(FIRTransactionOptions *_Nullable)options
  344. block:(id _Nullable (^)(FIRTransaction *, NSError **))updateBlock
  345. completion:
  346. (void (^)(id _Nullable result, NSError *_Nullable error))completion {
  347. static dispatch_queue_t transactionDispatchQueue;
  348. static dispatch_once_t onceToken;
  349. dispatch_once(&onceToken, ^{
  350. transactionDispatchQueue = dispatch_queue_create("com.google.firebase.firestore.transaction",
  351. DISPATCH_QUEUE_CONCURRENT);
  352. });
  353. [self runTransactionWithOptions:options
  354. block:updateBlock
  355. dispatchQueue:transactionDispatchQueue
  356. completion:completion];
  357. }
  358. + (void)enableLogging:(BOOL)logging {
  359. LogSetLevel(logging ? kLogLevelDebug : kLogLevelNotice);
  360. }
  361. - (void)useEmulatorWithHost:(NSString *)host port:(NSInteger)port {
  362. if (!host.length) {
  363. ThrowInvalidArgument("Host cannot be nil or empty.");
  364. }
  365. if (!_settings.isUsingDefaultHost) {
  366. LOG_WARN("Overriding previously-set host value: %@", _settings.host);
  367. }
  368. // Use a new settings so the new settings are automatically plumbed
  369. // to the underlying Firestore objects.
  370. NSString *settingsHost = [NSString stringWithFormat:@"%@:%li", host, (long)port];
  371. FIRFirestoreSettings *newSettings = [_settings copy];
  372. newSettings.host = settingsHost;
  373. self.settings = newSettings;
  374. }
  375. - (void)enableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  376. _firestore->EnableNetwork(MakeCallback(completion));
  377. }
  378. - (void)disableNetworkWithCompletion:(nullable void (^)(NSError *_Nullable))completion {
  379. _firestore->DisableNetwork(MakeCallback(completion));
  380. }
  381. - (void)clearPersistenceWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  382. _firestore->ClearPersistence(MakeCallback(completion));
  383. }
  384. - (void)waitForPendingWritesWithCompletion:(void (^)(NSError *_Nullable error))completion {
  385. _firestore->WaitForPendingWrites(MakeCallback(completion));
  386. }
  387. - (void)terminateWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  388. id<FSTFirestoreInstanceRegistry> strongRegistry = _registry;
  389. if (strongRegistry) {
  390. [strongRegistry
  391. removeInstanceWithDatabase:MakeNSString(_firestore->database_id().database_id())];
  392. }
  393. [self terminateInternalWithCompletion:completion];
  394. }
  395. - (id<FIRListenerRegistration>)addSnapshotsInSyncListener:(void (^)(void))listener {
  396. std::unique_ptr<core::EventListener<Empty>> eventListener =
  397. core::EventListener<Empty>::Create([listener](const StatusOr<Empty> &) { listener(); });
  398. std::unique_ptr<ListenerRegistration> result =
  399. _firestore->AddSnapshotsInSyncListener(std::move(eventListener));
  400. return [[FSTListenerRegistration alloc] initWithRegistration:std::move(result)];
  401. }
  402. - (FIRLoadBundleTask *)loadBundle:(nonnull NSData *)bundleData {
  403. auto stream = absl::make_unique<ByteStreamApple>([[NSInputStream alloc] initWithData:bundleData]);
  404. return [self loadBundleStream:[[NSInputStream alloc] initWithData:bundleData] completion:nil];
  405. }
  406. - (FIRLoadBundleTask *)loadBundle:(NSData *)bundleData
  407. completion:(nullable void (^)(FIRLoadBundleTaskProgress *_Nullable progress,
  408. NSError *_Nullable error))completion {
  409. return [self loadBundleStream:[[NSInputStream alloc] initWithData:bundleData]
  410. completion:completion];
  411. }
  412. - (FIRLoadBundleTask *)loadBundleStream:(NSInputStream *)bundleStream {
  413. return [self loadBundleStream:bundleStream completion:nil];
  414. }
  415. - (FIRLoadBundleTask *)loadBundleStream:(NSInputStream *)bundleStream
  416. completion:
  417. (nullable void (^)(FIRLoadBundleTaskProgress *_Nullable progress,
  418. NSError *_Nullable error))completion {
  419. auto stream = absl::make_unique<ByteStreamApple>(bundleStream);
  420. std::shared_ptr<api::LoadBundleTask> task = _firestore->LoadBundle(std::move(stream));
  421. auto callback = [completion](api::LoadBundleTaskProgress progress) {
  422. if (!completion) {
  423. return;
  424. }
  425. // Ignoring `kInProgress` because we are setting up for completion callback.
  426. if (progress.state() == api::LoadBundleTaskState::kSuccess) {
  427. completion([[FIRLoadBundleTaskProgress alloc] initWithInternal:progress], nil);
  428. } else if (progress.state() == api::LoadBundleTaskState::kError) {
  429. NSError *error = nil;
  430. if (!progress.error_status().ok()) {
  431. LOG_WARN("Progress set to Error, but error_status() is ok()");
  432. error = MakeNSError(firebase::firestore::Error::kErrorUnknown,
  433. "Loading bundle failed with unknown error");
  434. } else {
  435. error = MakeNSError(progress.error_status());
  436. }
  437. completion([[FIRLoadBundleTaskProgress alloc] initWithInternal:progress], error);
  438. }
  439. };
  440. task->SetLastObserver(callback);
  441. return [[FIRLoadBundleTask alloc] initWithTask:task];
  442. }
  443. - (void)getQueryNamed:(NSString *)name completion:(void (^)(FIRQuery *_Nullable query))completion {
  444. auto firestore = _firestore;
  445. auto callback = [completion, firestore](core::Query query, bool found) {
  446. if (!completion) {
  447. return;
  448. }
  449. if (found) {
  450. FIRQuery *firQuery = [[FIRQuery alloc] initWithQuery:std::move(query) firestore:firestore];
  451. completion(firQuery);
  452. } else {
  453. completion(nil);
  454. }
  455. };
  456. _firestore->GetNamedQuery(MakeString(name), callback);
  457. }
  458. @end
  459. @implementation FIRFirestore (Internal)
  460. - (std::shared_ptr<Firestore>)wrapped {
  461. return _firestore;
  462. }
  463. - (const std::shared_ptr<AsyncQueue> &)workerQueue {
  464. return _firestore->worker_queue();
  465. }
  466. - (nullable FIRPersistentCacheIndexManager *)persistentCacheIndexManager {
  467. if (!_indexManager) {
  468. auto index_manager = _firestore->persistent_cache_index_manager();
  469. if (index_manager) {
  470. _indexManager = [[FIRPersistentCacheIndexManager alloc]
  471. initWithPersistentCacheIndexManager:index_manager];
  472. } else {
  473. return nil;
  474. }
  475. }
  476. return _indexManager;
  477. }
  478. - (const DatabaseId &)databaseID {
  479. return _firestore->database_id();
  480. }
  481. + (FIRFirestore *)recoverFromFirestore:(std::shared_ptr<Firestore>)firestore {
  482. return (__bridge FIRFirestore *)firestore->extension();
  483. }
  484. - (void)terminateInternalWithCompletion:(nullable void (^)(NSError *_Nullable error))completion {
  485. _firestore->Terminate(MakeCallback(completion));
  486. }
  487. #pragma mark - Force Link Unreferenced Symbols
  488. extern void FSTIncludeFSTFirestoreComponent(void);
  489. /// This method forces the linker to include all the Analytics categories without requiring app
  490. /// developers to include the '-ObjC' linker flag in their projects. DO NOT CALL THIS METHOD.
  491. + (void)notCalled {
  492. NSAssert(NO, @"+notCalled should never be called");
  493. FSTIncludeFSTFirestoreComponent();
  494. }
  495. @end
  496. NS_ASSUME_NONNULL_END