FSTFirestoreClient.mm 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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::unique_ptr<Executor>)userExecutor
  96. workerQueue:(std::unique_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::unique_ptr<AsyncQueue> _workerQueue;
  113. std::unique_ptr<RemoteStore> _remoteStore;
  114. std::unique_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. - (Executor *)userExecutor {
  123. return _userExecutor.get();
  124. }
  125. - (AsyncQueue *)workerQueue {
  126. return _workerQueue.get();
  127. }
  128. + (instancetype)clientWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  129. settings:(const Settings &)settings
  130. credentialsProvider:
  131. (CredentialsProvider *)credentialsProvider // no passing ownership
  132. userExecutor:(std::unique_ptr<Executor>)userExecutor
  133. workerQueue:(std::unique_ptr<AsyncQueue>)workerQueue {
  134. return [[FSTFirestoreClient alloc] initWithDatabaseInfo:databaseInfo
  135. settings:settings
  136. credentialsProvider:credentialsProvider
  137. userExecutor:std::move(userExecutor)
  138. workerQueue:std::move(workerQueue)];
  139. }
  140. - (instancetype)initWithDatabaseInfo:(const DatabaseInfo &)databaseInfo
  141. settings:(const Settings &)settings
  142. credentialsProvider:
  143. (CredentialsProvider *)credentialsProvider // no passing ownership
  144. userExecutor:(std::unique_ptr<Executor>)userExecutor
  145. workerQueue:(std::unique_ptr<AsyncQueue>)workerQueue {
  146. if (self = [super init]) {
  147. _databaseInfo = databaseInfo;
  148. _credentialsProvider = credentialsProvider;
  149. _userExecutor = std::move(userExecutor);
  150. _workerQueue = std::move(workerQueue);
  151. _gcHasRun = false;
  152. _isShutdown = false;
  153. _initialGcDelay = FSTLruGcInitialDelay;
  154. _regularGcDelay = FSTLruGcRegularDelay;
  155. auto userPromise = std::make_shared<std::promise<User>>();
  156. bool initialized = false;
  157. __weak __typeof__(self) weakSelf = self;
  158. auto credentialChangeListener = [initialized, userPromise, weakSelf](User user) mutable {
  159. __typeof__(self) strongSelf = weakSelf;
  160. if (!strongSelf) return;
  161. if (!initialized) {
  162. initialized = true;
  163. userPromise->set_value(user);
  164. } else {
  165. strongSelf->_workerQueue->Enqueue(
  166. [strongSelf, user] { [strongSelf credentialDidChangeWithUser:user]; });
  167. }
  168. };
  169. _credentialsProvider->SetCredentialChangeListener(credentialChangeListener);
  170. // Defer initialization until we get the current user from the credentialChangeListener. This is
  171. // guaranteed to be synchronously dispatched onto our worker queue, so we will be initialized
  172. // before any subsequently queued work runs.
  173. _workerQueue->Enqueue([self, userPromise, settings] {
  174. User user = userPromise->get_future().get();
  175. [self initializeWithUser:user settings:settings];
  176. });
  177. }
  178. return self;
  179. }
  180. - (void)initializeWithUser:(const User &)user settings:(const Settings &)settings {
  181. // Do all of our initialization on our own dispatch queue.
  182. _workerQueue->VerifyIsCurrentQueue();
  183. LOG_DEBUG("Initializing. Current user: %s", user.uid());
  184. // Note: The initialization work must all be synchronous (we can't dispatch more work) since
  185. // external write/listen operations could get queued to run before that subsequent work
  186. // completes.
  187. if (settings.persistence_enabled()) {
  188. Path dir = [FSTLevelDB storageDirectoryForDatabaseInfo:*self.databaseInfo
  189. documentsDirectory:[FSTLevelDB documentsDirectory]];
  190. FSTSerializerBeta *remoteSerializer =
  191. [[FSTSerializerBeta alloc] initWithDatabaseID:&self.databaseInfo->database_id()];
  192. FSTLocalSerializer *serializer =
  193. [[FSTLocalSerializer alloc] initWithRemoteSerializer:remoteSerializer];
  194. FSTLevelDB *ldb;
  195. Status levelDbStatus =
  196. [FSTLevelDB dbWithDirectory:std::move(dir)
  197. serializer:serializer
  198. lruParams:LruParams::WithCacheSize(settings.cache_size_bytes())
  199. ptr:&ldb];
  200. if (!levelDbStatus.ok()) {
  201. // If leveldb fails to start then just throw up our hands: the error is unrecoverable.
  202. // There's nothing an end-user can do and nearly all failures indicate the developer is doing
  203. // something grossly wrong so we should stop them cold in their tracks with a failure they
  204. // can't ignore.
  205. [NSException raise:NSInternalInconsistencyException
  206. format:@"Failed to open DB: %s", levelDbStatus.ToString().c_str()];
  207. }
  208. _lruDelegate = ldb.referenceDelegate;
  209. _persistence = ldb;
  210. if (settings.gc_enabled()) {
  211. [self scheduleLruGarbageCollection];
  212. }
  213. } else {
  214. _persistence = [FSTMemoryPersistence persistenceWithEagerGC];
  215. }
  216. _localStore = [[FSTLocalStore alloc] initWithPersistence:_persistence initialUser:user];
  217. auto datastore =
  218. std::make_shared<Datastore>(*self.databaseInfo, _workerQueue.get(), _credentialsProvider);
  219. _remoteStore = absl::make_unique<RemoteStore>(
  220. _localStore, std::move(datastore), _workerQueue.get(),
  221. [self](OnlineState onlineState) { [self.syncEngine applyChangedOnlineState:onlineState]; });
  222. _syncEngine = [[FSTSyncEngine alloc] initWithLocalStore:_localStore
  223. remoteStore:_remoteStore.get()
  224. initialUser:user];
  225. _eventManager = [FSTEventManager eventManagerWithSyncEngine:_syncEngine];
  226. // Setup wiring for remote store.
  227. _remoteStore->set_sync_engine(_syncEngine);
  228. // NOTE: RemoteStore depends on LocalStore (for persisting stream tokens, refilling mutation
  229. // queue, etc.) so must be started after LocalStore.
  230. [_localStore start];
  231. _remoteStore->Start();
  232. }
  233. /**
  234. * Schedules a callback to try running LRU garbage collection. Reschedules itself after the GC has
  235. * run.
  236. */
  237. - (void)scheduleLruGarbageCollection {
  238. std::chrono::milliseconds delay = _gcHasRun ? _regularGcDelay : _initialGcDelay;
  239. _lruCallback = _workerQueue->EnqueueAfterDelay(delay, TimerId::GarbageCollectionDelay, [self]() {
  240. [self->_localStore collectGarbage:self->_lruDelegate.gc];
  241. self->_gcHasRun = true;
  242. [self scheduleLruGarbageCollection];
  243. });
  244. }
  245. - (void)credentialDidChangeWithUser:(const User &)user {
  246. _workerQueue->VerifyIsCurrentQueue();
  247. LOG_DEBUG("Credential Changed. Current user: %s", user.uid());
  248. [self.syncEngine credentialDidChangeWithUser:user];
  249. }
  250. - (void)disableNetworkWithCallback:(util::StatusCallback)callback {
  251. [self verifyNotShutdown];
  252. _workerQueue->Enqueue([self, callback] {
  253. _remoteStore->DisableNetwork();
  254. if (callback) {
  255. self->_userExecutor->Execute([=] { callback(Status::OK()); });
  256. }
  257. });
  258. }
  259. - (void)enableNetworkWithCallback:(util::StatusCallback)callback {
  260. [self verifyNotShutdown];
  261. _workerQueue->Enqueue([self, callback] {
  262. _remoteStore->EnableNetwork();
  263. if (callback) {
  264. self->_userExecutor->Execute([=] { callback(Status::OK()); });
  265. }
  266. });
  267. }
  268. - (void)shutdownWithCallback:(util::StatusCallback)callback {
  269. _workerQueue->Enqueue([self, callback] {
  270. if (!_isShutdown) {
  271. self->_credentialsProvider->SetCredentialChangeListener(nullptr);
  272. // If we've scheduled LRU garbage collection, cancel it.
  273. if (self->_lruCallback) {
  274. self->_lruCallback.Cancel();
  275. }
  276. _remoteStore->Shutdown();
  277. [self.persistence shutdown];
  278. self->_isShutdown = true;
  279. }
  280. if (callback) {
  281. self->_userExecutor->Execute([=] { callback(Status::OK()); });
  282. }
  283. });
  284. }
  285. - (void)verifyNotShutdown {
  286. if (_isShutdown) {
  287. ThrowIllegalState("The client has already been shutdown.");
  288. }
  289. }
  290. - (std::shared_ptr<QueryListener>)listenToQuery:(FSTQuery *)query
  291. options:(core::ListenOptions)options
  292. listener:(ViewSnapshot::SharedListener &&)listener {
  293. auto query_listener = QueryListener::Create(query, std::move(options), std::move(listener));
  294. _workerQueue->Enqueue([self, query_listener] { [self.eventManager addListener:query_listener]; });
  295. return query_listener;
  296. }
  297. - (void)removeListener:(const std::shared_ptr<QueryListener> &)listener {
  298. [self verifyNotShutdown];
  299. _workerQueue->Enqueue([self, listener] { [self.eventManager removeListener:listener]; });
  300. }
  301. - (void)getDocumentFromLocalCache:(const DocumentReference &)doc
  302. callback:(DocumentSnapshot::Listener &&)callback {
  303. [self verifyNotShutdown];
  304. // TODO(c++14): move `callback` into lambda.
  305. auto shared_callback = absl::ShareUniquePtr(std::move(callback));
  306. _workerQueue->Enqueue([self, doc, shared_callback] {
  307. FSTMaybeDocument *maybeDoc = [self.localStore readDocument:doc.key()];
  308. StatusOr<DocumentSnapshot> maybe_snapshot;
  309. if ([maybeDoc isKindOfClass:[FSTDocument class]]) {
  310. FSTDocument *document = (FSTDocument *)maybeDoc;
  311. maybe_snapshot = DocumentSnapshot{doc.firestore(), doc.key(), document,
  312. /*from_cache=*/true,
  313. /*has_pending_writes=*/document.hasLocalMutations};
  314. } else if ([maybeDoc isKindOfClass:[FSTDeletedDocument class]]) {
  315. maybe_snapshot = DocumentSnapshot{doc.firestore(), doc.key(), nil,
  316. /*from_cache=*/true,
  317. /*has_pending_writes=*/false};
  318. } else {
  319. maybe_snapshot = Status{FirestoreErrorCode::Unavailable,
  320. "Failed to get document from cache. (However, this document "
  321. "may exist on the server. Run again without setting source to "
  322. "FirestoreSourceCache to attempt to retrieve the document "};
  323. }
  324. if (shared_callback) {
  325. self->_userExecutor->Execute([=] { shared_callback->OnEvent(std::move(maybe_snapshot)); });
  326. }
  327. });
  328. }
  329. - (void)getDocumentsFromLocalCache:(const api::Query &)query
  330. callback:(api::QuerySnapshot::Listener &&)callback {
  331. [self verifyNotShutdown];
  332. // TODO(c++14): move `callback` into lambda.
  333. auto shared_callback = absl::ShareUniquePtr(std::move(callback));
  334. _workerQueue->Enqueue([self, query, shared_callback] {
  335. DocumentMap docs = [self.localStore executeQuery:query.query()];
  336. FSTView *view = [[FSTView alloc] initWithQuery:query.query() remoteDocuments:DocumentKeySet{}];
  337. FSTViewDocumentChanges *viewDocChanges =
  338. [view computeChangesWithDocuments:docs.underlying_map()];
  339. FSTViewChange *viewChange = [view applyChangesToDocuments:viewDocChanges];
  340. HARD_ASSERT(viewChange.limboChanges.count == 0,
  341. "View returned limbo documents during local-only query execution.");
  342. HARD_ASSERT(viewChange.snapshot.has_value(), "Expected a snapshot");
  343. ViewSnapshot snapshot = std::move(viewChange.snapshot).value();
  344. SnapshotMetadata metadata(snapshot.has_pending_writes(), snapshot.from_cache());
  345. api::QuerySnapshot result(query.firestore(), query.query(), std::move(snapshot),
  346. std::move(metadata));
  347. if (shared_callback) {
  348. self->_userExecutor->Execute([=] { shared_callback->OnEvent(std::move(result)); });
  349. }
  350. });
  351. }
  352. - (void)writeMutations:(std::vector<FSTMutation *> &&)mutations
  353. callback:(util::StatusCallback)callback {
  354. // TODO(c++14): move `mutations` into lambda (C++14).
  355. _workerQueue->Enqueue([self, mutations, callback]() mutable {
  356. [self verifyNotShutdown];
  357. if (mutations.empty()) {
  358. if (callback) {
  359. self->_userExecutor->Execute([=] { callback(Status::OK()); });
  360. }
  361. } else {
  362. [self.syncEngine
  363. writeMutations:std::move(mutations)
  364. completion:^(NSError *error) {
  365. // Dispatch the result back onto the user dispatch queue.
  366. if (callback) {
  367. self->_userExecutor->Execute([=] { callback(Status::FromNSError(error)); });
  368. }
  369. }];
  370. }
  371. });
  372. };
  373. - (void)transactionWithRetries:(int)retries
  374. updateCallback:(core::TransactionUpdateCallback)update_callback
  375. resultCallback:(core::TransactionResultCallback)resultCallback {
  376. // Dispatch the result back onto the user dispatch queue.
  377. auto async_callback = [self, resultCallback](util::StatusOr<absl::any> maybe_value) {
  378. [self verifyNotShutdown];
  379. if (resultCallback) {
  380. self->_userExecutor->Execute([=] { resultCallback(std::move(maybe_value)); });
  381. }
  382. };
  383. _workerQueue->Enqueue([self, retries, update_callback, async_callback] {
  384. [self.syncEngine transactionWithRetries:retries
  385. workerQueue:_workerQueue.get()
  386. updateCallback:std::move(update_callback)
  387. resultCallback:std::move(async_callback)];
  388. });
  389. }
  390. - (const DatabaseInfo *)databaseInfo {
  391. return &_databaseInfo;
  392. }
  393. - (const DatabaseId *)databaseID {
  394. return &_databaseInfo.database_id();
  395. }
  396. @end
  397. NS_ASSUME_NONNULL_END