FSTFirestoreClient.mm 19 KB

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