FSTFirestoreClient.mm 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. std::atomic<bool> _isShutdown;
  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. return _isShutdown;
  130. }
  131. + (instancetype)clientWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  132. settings:(const Settings &)settings
  133. credentialsProvider:
  134. (CredentialsProvider *)credentialsProvider // no passing ownership
  135. userExecutor:(std::shared_ptr<Executor>)userExecutor
  136. workerQueue:(std::shared_ptr<AsyncQueue>)workerQueue {
  137. return [[FSTFirestoreClient alloc] initWithDatabaseInfo:databaseInfo
  138. settings:settings
  139. credentialsProvider:credentialsProvider
  140. userExecutor:std::move(userExecutor)
  141. workerQueue:std::move(workerQueue)];
  142. }
  143. - (instancetype)initWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  144. settings:(const Settings &)settings
  145. credentialsProvider:
  146. (CredentialsProvider *)credentialsProvider // no passing ownership
  147. userExecutor:(std::shared_ptr<Executor>)userExecutor
  148. workerQueue:(std::shared_ptr<AsyncQueue>)workerQueue {
  149. if (self = [super init]) {
  150. _databaseInfo = databaseInfo;
  151. _credentialsProvider = credentialsProvider;
  152. _userExecutor = std::move(userExecutor);
  153. _workerQueue = std::move(workerQueue);
  154. _gcHasRun = false;
  155. _isShutdown = 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->Enqueue([self, callback] {
  273. if (!_isShutdown) {
  274. self->_credentialsProvider->SetCredentialChangeListener(nullptr);
  275. // If we've scheduled LRU garbage collection, cancel it.
  276. if (self->_lruCallback) {
  277. self->_lruCallback.Cancel();
  278. }
  279. _remoteStore->Shutdown();
  280. [self.persistence shutdown];
  281. self->_isShutdown = true;
  282. }
  283. if (callback) {
  284. self->_userExecutor->Execute([=] { callback(Status::OK()); });
  285. }
  286. });
  287. }
  288. - (void)verifyNotShutdown {
  289. if (_isShutdown) {
  290. ThrowIllegalState("The client has already been shutdown.");
  291. }
  292. }
  293. - (std::shared_ptr<QueryListener>)listenToQuery:(FSTQuery *)query
  294. options:(core::ListenOptions)options
  295. listener:(ViewSnapshot::SharedListener &&)listener {
  296. auto query_listener = QueryListener::Create(query, std::move(options), std::move(listener));
  297. _workerQueue->Enqueue([self, query_listener] { [self.eventManager addListener:query_listener]; });
  298. return query_listener;
  299. }
  300. - (void)removeListener:(const std::shared_ptr<QueryListener> &)listener {
  301. [self verifyNotShutdown];
  302. _workerQueue->Enqueue([self, listener] { [self.eventManager removeListener:listener]; });
  303. }
  304. - (void)getDocumentFromLocalCache:(const DocumentReference &)doc
  305. callback:(DocumentSnapshot::Listener &&)callback {
  306. [self verifyNotShutdown];
  307. // TODO(c++14): move `callback` into lambda.
  308. auto shared_callback = absl::ShareUniquePtr(std::move(callback));
  309. _workerQueue->Enqueue([self, doc, shared_callback] {
  310. FSTMaybeDocument *maybeDoc = [self.localStore readDocument:doc.key()];
  311. StatusOr<DocumentSnapshot> maybe_snapshot;
  312. if ([maybeDoc isKindOfClass:[FSTDocument class]]) {
  313. FSTDocument *document = (FSTDocument *)maybeDoc;
  314. maybe_snapshot = DocumentSnapshot{doc.firestore(), doc.key(), document,
  315. /*from_cache=*/true,
  316. /*has_pending_writes=*/document.hasLocalMutations};
  317. } else if ([maybeDoc isKindOfClass:[FSTDeletedDocument class]]) {
  318. maybe_snapshot = DocumentSnapshot{doc.firestore(), doc.key(), nil,
  319. /*from_cache=*/true,
  320. /*has_pending_writes=*/false};
  321. } else {
  322. maybe_snapshot = Status{FirestoreErrorCode::Unavailable,
  323. "Failed to get document from cache. (However, this document "
  324. "may exist on the server. Run again without setting source to "
  325. "FirestoreSourceCache to attempt to retrieve the document "};
  326. }
  327. if (shared_callback) {
  328. self->_userExecutor->Execute([=] { shared_callback->OnEvent(std::move(maybe_snapshot)); });
  329. }
  330. });
  331. }
  332. - (void)getDocumentsFromLocalCache:(const api::Query &)query
  333. callback:(api::QuerySnapshot::Listener &&)callback {
  334. [self verifyNotShutdown];
  335. // TODO(c++14): move `callback` into lambda.
  336. auto shared_callback = absl::ShareUniquePtr(std::move(callback));
  337. _workerQueue->Enqueue([self, query, shared_callback] {
  338. DocumentMap docs = [self.localStore executeQuery:query.query()];
  339. FSTView *view = [[FSTView alloc] initWithQuery:query.query() remoteDocuments:DocumentKeySet{}];
  340. FSTViewDocumentChanges *viewDocChanges =
  341. [view computeChangesWithDocuments:docs.underlying_map()];
  342. FSTViewChange *viewChange = [view applyChangesToDocuments:viewDocChanges];
  343. HARD_ASSERT(viewChange.limboChanges.count == 0,
  344. "View returned limbo documents during local-only query execution.");
  345. HARD_ASSERT(viewChange.snapshot.has_value(), "Expected a snapshot");
  346. ViewSnapshot snapshot = std::move(viewChange.snapshot).value();
  347. SnapshotMetadata metadata(snapshot.has_pending_writes(), snapshot.from_cache());
  348. api::QuerySnapshot result(query.firestore(), query.query(), std::move(snapshot),
  349. std::move(metadata));
  350. if (shared_callback) {
  351. self->_userExecutor->Execute([=] { shared_callback->OnEvent(std::move(result)); });
  352. }
  353. });
  354. }
  355. - (void)writeMutations:(std::vector<FSTMutation *> &&)mutations
  356. callback:(util::StatusCallback)callback {
  357. // TODO(c++14): move `mutations` into lambda (C++14).
  358. _workerQueue->Enqueue([self, mutations, callback]() mutable {
  359. [self verifyNotShutdown];
  360. if (mutations.empty()) {
  361. if (callback) {
  362. self->_userExecutor->Execute([=] { callback(Status::OK()); });
  363. }
  364. } else {
  365. [self.syncEngine
  366. writeMutations:std::move(mutations)
  367. completion:^(NSError *error) {
  368. // Dispatch the result back onto the user dispatch queue.
  369. if (callback) {
  370. self->_userExecutor->Execute([=] { callback(Status::FromNSError(error)); });
  371. }
  372. }];
  373. }
  374. });
  375. };
  376. - (void)transactionWithRetries:(int)retries
  377. updateCallback:(core::TransactionUpdateCallback)update_callback
  378. resultCallback:(core::TransactionResultCallback)resultCallback {
  379. // Dispatch the result back onto the user dispatch queue.
  380. auto async_callback = [self, resultCallback](util::StatusOr<absl::any> maybe_value) {
  381. [self verifyNotShutdown];
  382. if (resultCallback) {
  383. self->_userExecutor->Execute([=] { resultCallback(std::move(maybe_value)); });
  384. }
  385. };
  386. _workerQueue->Enqueue([self, retries, update_callback, async_callback] {
  387. [self.syncEngine transactionWithRetries:retries
  388. workerQueue:_workerQueue
  389. updateCallback:std::move(update_callback)
  390. resultCallback:std::move(async_callback)];
  391. });
  392. }
  393. - (const DatabaseInfo *)databaseInfo {
  394. return &_databaseInfo;
  395. }
  396. - (const DatabaseId &)databaseID {
  397. return _databaseInfo.database_id();
  398. }
  399. @end
  400. NS_ASSUME_NONNULL_END