FSTFirestoreClient.mm 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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 "Firestore/Source/Core/FSTFirestoreClient.h"
  17. #include <chrono> // NOLINT(build/c++11)
  18. #include <future> // NOLINT(build/c++11)
  19. #include <memory>
  20. #include <utility>
  21. #import "FIRFirestoreErrors.h"
  22. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  23. #import "Firestore/Source/API/FIRDocumentSnapshot+Internal.h"
  24. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  25. #import "Firestore/Source/API/FIRQuery+Internal.h"
  26. #import "Firestore/Source/API/FIRQuerySnapshot+Internal.h"
  27. #import "Firestore/Source/API/FIRSnapshotMetadata+Internal.h"
  28. #import "Firestore/Source/Core/FSTSyncEngine.h"
  29. #import "Firestore/Source/Core/FSTView.h"
  30. #import "Firestore/Source/Local/FSTLRUGarbageCollector.h"
  31. #import "Firestore/Source/Local/FSTLevelDB.h"
  32. #import "Firestore/Source/Local/FSTLocalSerializer.h"
  33. #import "Firestore/Source/Local/FSTLocalStore.h"
  34. #import "Firestore/Source/Local/FSTMemoryPersistence.h"
  35. #import "Firestore/Source/Model/FSTDocument.h"
  36. #import "Firestore/Source/Remote/FSTSerializerBeta.h"
  37. #import "Firestore/Source/Util/FSTClasses.h"
  38. #include "Firestore/core/src/firebase/firestore/api/settings.h"
  39. #include "Firestore/core/src/firebase/firestore/auth/credentials_provider.h"
  40. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  41. #include "Firestore/core/src/firebase/firestore/core/event_manager.h"
  42. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  43. #include "Firestore/core/src/firebase/firestore/model/document_set.h"
  44. #include "Firestore/core/src/firebase/firestore/remote/datastore.h"
  45. #include "Firestore/core/src/firebase/firestore/remote/remote_store.h"
  46. #include "Firestore/core/src/firebase/firestore/util/async_queue.h"
  47. #include "Firestore/core/src/firebase/firestore/util/delayed_constructor.h"
  48. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  49. #include "Firestore/core/src/firebase/firestore/util/log.h"
  50. #include "Firestore/core/src/firebase/firestore/util/status.h"
  51. #include "Firestore/core/src/firebase/firestore/util/statusor.h"
  52. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  53. #include "absl/memory/memory.h"
  54. namespace util = firebase::firestore::util;
  55. using firebase::firestore::Error;
  56. using firebase::firestore::api::DocumentReference;
  57. using firebase::firestore::api::DocumentSnapshot;
  58. using firebase::firestore::api::Settings;
  59. using firebase::firestore::api::SnapshotMetadata;
  60. using firebase::firestore::api::ThrowIllegalState;
  61. using firebase::firestore::auth::CredentialsProvider;
  62. using firebase::firestore::auth::User;
  63. using firebase::firestore::core::DatabaseInfo;
  64. using firebase::firestore::core::ListenOptions;
  65. using firebase::firestore::core::EventManager;
  66. using firebase::firestore::core::Query;
  67. using firebase::firestore::core::QueryListener;
  68. using firebase::firestore::core::ViewSnapshot;
  69. using firebase::firestore::local::LruParams;
  70. using firebase::firestore::model::DatabaseId;
  71. using firebase::firestore::model::DocumentKeySet;
  72. using firebase::firestore::model::DocumentMap;
  73. using firebase::firestore::model::MaybeDocumentMap;
  74. using firebase::firestore::model::OnlineState;
  75. using firebase::firestore::remote::Datastore;
  76. using firebase::firestore::remote::RemoteStore;
  77. using firebase::firestore::util::Path;
  78. using firebase::firestore::util::AsyncQueue;
  79. using firebase::firestore::util::DelayedConstructor;
  80. using firebase::firestore::util::DelayedOperation;
  81. using firebase::firestore::util::Executor;
  82. using firebase::firestore::util::Status;
  83. using firebase::firestore::util::StatusOr;
  84. using firebase::firestore::util::StatusOrCallback;
  85. using firebase::firestore::util::TimerId;
  86. NS_ASSUME_NONNULL_BEGIN
  87. /** How long we wait to try running LRU GC after SDK initialization. */
  88. static const std::chrono::milliseconds FSTLruGcInitialDelay = std::chrono::minutes(1);
  89. /** Minimum amount of time between GC checks, after the first one. */
  90. static const std::chrono::milliseconds FSTLruGcRegularDelay = std::chrono::minutes(5);
  91. @interface FSTFirestoreClient () {
  92. DatabaseInfo _databaseInfo;
  93. }
  94. - (instancetype)initWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  95. settings:(const Settings &)settings
  96. credentialsProvider:(std::shared_ptr<CredentialsProvider>)credentialsProvider
  97. userExecutor:(std::shared_ptr<Executor>)userExecutor
  98. workerQueue:(std::shared_ptr<AsyncQueue>)queue NS_DESIGNATED_INITIALIZER;
  99. @property(nonatomic, assign, readonly) const DatabaseInfo *databaseInfo;
  100. @property(nonatomic, strong, readonly) id<FSTPersistence> persistence;
  101. @property(nonatomic, strong, readonly) FSTSyncEngine *syncEngine;
  102. @property(nonatomic, strong, readonly) FSTLocalStore *localStore;
  103. @end
  104. @implementation FSTFirestoreClient {
  105. /**
  106. * Async queue responsible for all of our internal processing. When we get incoming work from
  107. * the user (via public API) or the network (incoming gRPC messages), we should always dispatch
  108. * onto this queue. This ensures our internal data structures are never accessed from multiple
  109. * threads simultaneously.
  110. */
  111. std::shared_ptr<AsyncQueue> _workerQueue;
  112. std::unique_ptr<RemoteStore> _remoteStore;
  113. DelayedConstructor<EventManager> _eventManager;
  114. std::shared_ptr<Executor> _userExecutor;
  115. std::shared_ptr<CredentialsProvider> _credentialsProvider;
  116. std::chrono::milliseconds _initialGcDelay;
  117. std::chrono::milliseconds _regularGcDelay;
  118. bool _gcHasRun;
  119. _Nullable id<FSTLRUDelegate> _lruDelegate;
  120. DelayedOperation _lruCallback;
  121. }
  122. - (const std::shared_ptr<util::Executor> &)userExecutor {
  123. return _userExecutor;
  124. }
  125. - (const std::shared_ptr<util::AsyncQueue> &)workerQueue {
  126. return _workerQueue;
  127. }
  128. - (bool)isShutdown {
  129. // Technically, the asyncQueue is still running, but only accepting tasks related to shutdown
  130. // or supposed to be run after shutdown. It is effectively shut down to the eyes of users.
  131. return _workerQueue->is_shutting_down();
  132. }
  133. + (instancetype)clientWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  134. settings:(const Settings &)settings
  135. credentialsProvider:(std::shared_ptr<CredentialsProvider>)credentialsProvider
  136. userExecutor:(std::shared_ptr<Executor>)userExecutor
  137. workerQueue:(std::shared_ptr<AsyncQueue>)workerQueue {
  138. return [[FSTFirestoreClient alloc] initWithDatabaseInfo:databaseInfo
  139. settings:settings
  140. credentialsProvider:std::move(credentialsProvider)
  141. userExecutor:std::move(userExecutor)
  142. workerQueue:std::move(workerQueue)];
  143. }
  144. - (instancetype)initWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  145. settings:(const Settings &)settings
  146. credentialsProvider:(std::shared_ptr<CredentialsProvider>)credentialsProvider
  147. userExecutor:(std::shared_ptr<Executor>)userExecutor
  148. workerQueue:(std::shared_ptr<AsyncQueue>)workerQueue {
  149. if (self = [super init]) {
  150. _databaseInfo = databaseInfo;
  151. _credentialsProvider = std::move(credentialsProvider);
  152. _userExecutor = std::move(userExecutor);
  153. _workerQueue = std::move(workerQueue);
  154. _gcHasRun = false;
  155. _initialGcDelay = FSTLruGcInitialDelay;
  156. _regularGcDelay = FSTLruGcRegularDelay;
  157. auto userPromise = std::make_shared<std::promise<User>>();
  158. bool initialized = false;
  159. __weak __typeof__(self) weakSelf = self;
  160. auto credentialChangeListener = [initialized, userPromise, weakSelf](User user) mutable {
  161. __typeof__(self) strongSelf = weakSelf;
  162. if (!strongSelf) return;
  163. if (!initialized) {
  164. initialized = true;
  165. userPromise->set_value(user);
  166. } else {
  167. strongSelf->_workerQueue->Enqueue(
  168. [strongSelf, user] { [strongSelf credentialDidChangeWithUser:user]; });
  169. }
  170. };
  171. _credentialsProvider->SetCredentialChangeListener(credentialChangeListener);
  172. // Defer initialization until we get the current user from the credentialChangeListener. This is
  173. // guaranteed to be synchronously dispatched onto our worker queue, so we will be initialized
  174. // before any subsequently queued work runs.
  175. _workerQueue->Enqueue([self, userPromise, settings] {
  176. User user = userPromise->get_future().get();
  177. [self initializeWithUser:user settings:settings];
  178. });
  179. }
  180. return self;
  181. }
  182. - (void)initializeWithUser:(const User &)user settings:(const Settings &)settings {
  183. // Do all of our initialization on our own dispatch queue.
  184. _workerQueue->VerifyIsCurrentQueue();
  185. LOG_DEBUG("Initializing. Current user: %s", user.uid());
  186. // Note: The initialization work must all be synchronous (we can't dispatch more work) since
  187. // external write/listen operations could get queued to run before that subsequent work
  188. // completes.
  189. if (settings.persistence_enabled()) {
  190. Path dir = [FSTLevelDB storageDirectoryForDatabaseInfo:*self.databaseInfo
  191. documentsDirectory:[FSTLevelDB documentsDirectory]];
  192. FSTSerializerBeta *remoteSerializer =
  193. [[FSTSerializerBeta alloc] initWithDatabaseID:self.databaseInfo->database_id()];
  194. FSTLocalSerializer *serializer =
  195. [[FSTLocalSerializer alloc] initWithRemoteSerializer:remoteSerializer];
  196. FSTLevelDB *ldb;
  197. Status levelDbStatus =
  198. [FSTLevelDB dbWithDirectory:std::move(dir)
  199. serializer:serializer
  200. lruParams:LruParams::WithCacheSize(settings.cache_size_bytes())
  201. ptr:&ldb];
  202. if (!levelDbStatus.ok()) {
  203. // If leveldb fails to start then just throw up our hands: the error is unrecoverable.
  204. // There's nothing an end-user can do and nearly all failures indicate the developer is doing
  205. // something grossly wrong so we should stop them cold in their tracks with a failure they
  206. // can't ignore.
  207. [NSException raise:NSInternalInconsistencyException
  208. format:@"Failed to open DB: %s", levelDbStatus.ToString().c_str()];
  209. }
  210. _lruDelegate = ldb.referenceDelegate;
  211. _persistence = ldb;
  212. if (settings.gc_enabled()) {
  213. [self scheduleLruGarbageCollection];
  214. }
  215. } else {
  216. _persistence = [FSTMemoryPersistence persistenceWithEagerGC];
  217. }
  218. _localStore = [[FSTLocalStore alloc] initWithPersistence:_persistence initialUser:user];
  219. auto datastore =
  220. std::make_shared<Datastore>(*self.databaseInfo, _workerQueue, _credentialsProvider);
  221. _remoteStore = absl::make_unique<RemoteStore>(
  222. _localStore, std::move(datastore), _workerQueue,
  223. [self](OnlineState onlineState) { [self.syncEngine applyChangedOnlineState:onlineState]; });
  224. _syncEngine = [[FSTSyncEngine alloc] initWithLocalStore:_localStore
  225. remoteStore:_remoteStore.get()
  226. initialUser:user];
  227. _eventManager.Init(_syncEngine);
  228. // Setup wiring for remote store.
  229. _remoteStore->set_sync_engine(_syncEngine);
  230. // NOTE: RemoteStore depends on LocalStore (for persisting stream tokens, refilling mutation
  231. // queue, etc.) so must be started after LocalStore.
  232. [_localStore start];
  233. _remoteStore->Start();
  234. }
  235. /**
  236. * Schedules a callback to try running LRU garbage collection. Reschedules itself after the GC has
  237. * run.
  238. */
  239. - (void)scheduleLruGarbageCollection {
  240. std::chrono::milliseconds delay = _gcHasRun ? _regularGcDelay : _initialGcDelay;
  241. _lruCallback = _workerQueue->EnqueueAfterDelay(delay, TimerId::GarbageCollectionDelay, [self]() {
  242. [self->_localStore collectGarbage:self->_lruDelegate.gc];
  243. self->_gcHasRun = true;
  244. [self scheduleLruGarbageCollection];
  245. });
  246. }
  247. - (void)credentialDidChangeWithUser:(const User &)user {
  248. _workerQueue->VerifyIsCurrentQueue();
  249. LOG_DEBUG("Credential Changed. Current user: %s", user.uid());
  250. [self.syncEngine credentialDidChangeWithUser:user];
  251. }
  252. - (void)disableNetworkWithCallback:(util::StatusCallback)callback {
  253. [self verifyNotShutdown];
  254. _workerQueue->Enqueue([self, callback] {
  255. _remoteStore->DisableNetwork();
  256. if (callback) {
  257. self->_userExecutor->Execute([=] { callback(Status::OK()); });
  258. }
  259. });
  260. }
  261. - (void)enableNetworkWithCallback:(util::StatusCallback)callback {
  262. [self verifyNotShutdown];
  263. _workerQueue->Enqueue([self, callback] {
  264. _remoteStore->EnableNetwork();
  265. if (callback) {
  266. self->_userExecutor->Execute([=] { callback(Status::OK()); });
  267. }
  268. });
  269. }
  270. - (void)shutdownWithCallback:(util::StatusCallback)callback {
  271. _workerQueue->EnqueueAndInitiateShutdown([self, callback] {
  272. self->_credentialsProvider->SetCredentialChangeListener(nullptr);
  273. // If we've scheduled LRU garbage collection, cancel it.
  274. if (self->_lruCallback) {
  275. self->_lruCallback.Cancel();
  276. }
  277. _remoteStore->Shutdown();
  278. [self.persistence shutdown];
  279. });
  280. // This separate enqueue ensures if shutdown is called multiple times
  281. // every time the callback is triggered. If it is in the above
  282. // enqueue, it might not get executed because after first shutdown
  283. // all operations are not executed.
  284. _workerQueue->EnqueueEvenAfterShutdown([self, callback] {
  285. if (callback) {
  286. self->_userExecutor->Execute([=] { callback(Status::OK()); });
  287. }
  288. });
  289. }
  290. - (void)verifyNotShutdown {
  291. if (self.isShutdown) {
  292. ThrowIllegalState("The client has already been shutdown.");
  293. }
  294. }
  295. - (std::shared_ptr<QueryListener>)listenToQuery:(Query)query
  296. options:(core::ListenOptions)options
  297. listener:(ViewSnapshot::SharedListener &&)listener {
  298. auto query_listener =
  299. QueryListener::Create(std::move(query), std::move(options), std::move(listener));
  300. _workerQueue->Enqueue(
  301. [self, query_listener] { _eventManager->AddQueryListener(std::move(query_listener)); });
  302. return query_listener;
  303. }
  304. - (void)removeListener:(const std::shared_ptr<QueryListener> &)listener {
  305. [self verifyNotShutdown];
  306. _workerQueue->Enqueue([self, listener] { _eventManager->RemoveQueryListener(listener); });
  307. }
  308. - (void)getDocumentFromLocalCache:(const DocumentReference &)doc
  309. callback:(DocumentSnapshot::Listener &&)callback {
  310. [self verifyNotShutdown];
  311. // TODO(c++14): move `callback` into lambda.
  312. auto shared_callback = absl::ShareUniquePtr(std::move(callback));
  313. _workerQueue->Enqueue([self, doc, shared_callback] {
  314. FSTMaybeDocument *maybeDoc = [self.localStore readDocument:doc.key()];
  315. StatusOr<DocumentSnapshot> maybe_snapshot;
  316. if ([maybeDoc isKindOfClass:[FSTDocument class]]) {
  317. FSTDocument *document = (FSTDocument *)maybeDoc;
  318. maybe_snapshot = DocumentSnapshot{doc.firestore(), doc.key(), document,
  319. /*from_cache=*/true,
  320. /*has_pending_writes=*/document.hasLocalMutations};
  321. } else if ([maybeDoc isKindOfClass:[FSTDeletedDocument class]]) {
  322. maybe_snapshot = DocumentSnapshot{doc.firestore(), doc.key(), nil,
  323. /*from_cache=*/true,
  324. /*has_pending_writes=*/false};
  325. } else {
  326. maybe_snapshot =
  327. Status{Error::Unavailable, "Failed to get document from cache. (However, this document "
  328. "may exist on the server. Run again without setting source to "
  329. "FirestoreSourceCache to attempt to retrieve the document "};
  330. }
  331. if (shared_callback) {
  332. self->_userExecutor->Execute([=] { shared_callback->OnEvent(std::move(maybe_snapshot)); });
  333. }
  334. });
  335. }
  336. - (void)getDocumentsFromLocalCache:(const api::Query &)query
  337. callback:(api::QuerySnapshot::Listener &&)callback {
  338. [self verifyNotShutdown];
  339. // TODO(c++14): move `callback` into lambda.
  340. auto shared_callback = absl::ShareUniquePtr(std::move(callback));
  341. _workerQueue->Enqueue([self, query, shared_callback] {
  342. DocumentMap docs = [self.localStore executeQuery:query.query()];
  343. FSTView *view = [[FSTView alloc] initWithQuery:query.query() remoteDocuments:DocumentKeySet{}];
  344. FSTViewDocumentChanges *viewDocChanges =
  345. [view computeChangesWithDocuments:docs.underlying_map()];
  346. FSTViewChange *viewChange = [view applyChangesToDocuments:viewDocChanges];
  347. HARD_ASSERT(viewChange.limboChanges.count == 0,
  348. "View returned limbo documents during local-only query execution.");
  349. HARD_ASSERT(viewChange.snapshot.has_value(), "Expected a snapshot");
  350. ViewSnapshot snapshot = std::move(viewChange.snapshot).value();
  351. SnapshotMetadata metadata(snapshot.has_pending_writes(), snapshot.from_cache());
  352. api::QuerySnapshot result(query.firestore(), query.query(), std::move(snapshot),
  353. std::move(metadata));
  354. if (shared_callback) {
  355. self->_userExecutor->Execute([=] { shared_callback->OnEvent(std::move(result)); });
  356. }
  357. });
  358. }
  359. - (void)writeMutations:(std::vector<FSTMutation *> &&)mutations
  360. callback:(util::StatusCallback)callback {
  361. [self verifyNotShutdown];
  362. // TODO(c++14): move `mutations` into lambda (C++14).
  363. _workerQueue->Enqueue([self, mutations, callback]() mutable {
  364. if (mutations.empty()) {
  365. if (callback) {
  366. self->_userExecutor->Execute([=] { callback(Status::OK()); });
  367. }
  368. } else {
  369. [self.syncEngine
  370. writeMutations:std::move(mutations)
  371. completion:^(NSError *error) {
  372. // Dispatch the result back onto the user dispatch queue.
  373. if (callback) {
  374. self->_userExecutor->Execute([=] { callback(Status::FromNSError(error)); });
  375. }
  376. }];
  377. }
  378. });
  379. };
  380. - (void)transactionWithRetries:(int)retries
  381. updateCallback:(core::TransactionUpdateCallback)update_callback
  382. resultCallback:(core::TransactionResultCallback)resultCallback {
  383. [self verifyNotShutdown];
  384. // Dispatch the result back onto the user dispatch queue.
  385. auto async_callback = [self, resultCallback](util::StatusOr<absl::any> maybe_value) {
  386. if (resultCallback) {
  387. self->_userExecutor->Execute([=] { resultCallback(std::move(maybe_value)); });
  388. }
  389. };
  390. _workerQueue->Enqueue([self, retries, update_callback, async_callback] {
  391. [self.syncEngine transactionWithRetries:retries
  392. workerQueue:_workerQueue
  393. updateCallback:std::move(update_callback)
  394. resultCallback:std::move(async_callback)];
  395. });
  396. }
  397. - (const DatabaseInfo *)databaseInfo {
  398. return &_databaseInfo;
  399. }
  400. - (const DatabaseId &)databaseID {
  401. return _databaseInfo.database_id();
  402. }
  403. @end
  404. NS_ASSUME_NONNULL_END