FSTLevelDB.mm 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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/Local/FSTLevelDB.h"
  17. #include <memory>
  18. #include <unordered_map>
  19. #include <utility>
  20. #import "FIRFirestoreErrors.h"
  21. #import "Firestore/Source/Remote/FSTSerializerBeta.h"
  22. #include "Firestore/core/include/firebase/firestore/firestore_errors.h"
  23. #include "Firestore/core/src/firebase/firestore/auth/user.h"
  24. #include "Firestore/core/src/firebase/firestore/core/database_info.h"
  25. #include "Firestore/core/src/firebase/firestore/local/index_manager.h"
  26. #include "Firestore/core/src/firebase/firestore/local/leveldb_index_manager.h"
  27. #include "Firestore/core/src/firebase/firestore/local/leveldb_key.h"
  28. #include "Firestore/core/src/firebase/firestore/local/leveldb_migrations.h"
  29. #include "Firestore/core/src/firebase/firestore/local/leveldb_mutation_queue.h"
  30. #include "Firestore/core/src/firebase/firestore/local/leveldb_query_cache.h"
  31. #include "Firestore/core/src/firebase/firestore/local/leveldb_remote_document_cache.h"
  32. #include "Firestore/core/src/firebase/firestore/local/leveldb_transaction.h"
  33. #include "Firestore/core/src/firebase/firestore/local/leveldb_util.h"
  34. #include "Firestore/core/src/firebase/firestore/local/listen_sequence.h"
  35. #include "Firestore/core/src/firebase/firestore/local/lru_garbage_collector.h"
  36. #include "Firestore/core/src/firebase/firestore/local/reference_delegate.h"
  37. #include "Firestore/core/src/firebase/firestore/local/reference_set.h"
  38. #include "Firestore/core/src/firebase/firestore/local/remote_document_cache.h"
  39. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  40. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  41. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  42. #include "Firestore/core/src/firebase/firestore/model/types.h"
  43. #include "Firestore/core/src/firebase/firestore/util/filesystem.h"
  44. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  45. #include "Firestore/core/src/firebase/firestore/util/log.h"
  46. #include "Firestore/core/src/firebase/firestore/util/ordered_code.h"
  47. #include "Firestore/core/src/firebase/firestore/util/statusor.h"
  48. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  49. #include "Firestore/core/src/firebase/firestore/util/string_util.h"
  50. #include "absl/memory/memory.h"
  51. #include "absl/strings/match.h"
  52. #include "absl/strings/str_cat.h"
  53. #include "leveldb/db.h"
  54. NS_ASSUME_NONNULL_BEGIN
  55. namespace util = firebase::firestore::util;
  56. using firebase::firestore::Error;
  57. using firebase::firestore::auth::User;
  58. using firebase::firestore::core::DatabaseInfo;
  59. using firebase::firestore::local::ConvertStatus;
  60. using firebase::firestore::local::IndexManager;
  61. using firebase::firestore::local::LevelDbDocumentMutationKey;
  62. using firebase::firestore::local::LevelDbDocumentTargetKey;
  63. using firebase::firestore::local::LevelDbIndexManager;
  64. using firebase::firestore::local::LevelDbMigrations;
  65. using firebase::firestore::local::LevelDbMutationKey;
  66. using firebase::firestore::local::LevelDbMutationQueue;
  67. using firebase::firestore::local::LevelDbQueryCache;
  68. using firebase::firestore::local::LevelDbRemoteDocumentCache;
  69. using firebase::firestore::local::LevelDbTransaction;
  70. using firebase::firestore::local::ListenSequence;
  71. using firebase::firestore::local::LruGarbageCollector;
  72. using firebase::firestore::local::LruParams;
  73. using firebase::firestore::local::OrphanedDocumentCallback;
  74. using firebase::firestore::local::QueryData;
  75. using firebase::firestore::local::ReferenceSet;
  76. using firebase::firestore::local::RemoteDocumentCache;
  77. using firebase::firestore::local::TargetCallback;
  78. using firebase::firestore::model::DocumentKey;
  79. using firebase::firestore::model::ListenSequenceNumber;
  80. using firebase::firestore::model::ResourcePath;
  81. using firebase::firestore::model::TargetId;
  82. using firebase::firestore::util::OrderedCode;
  83. using firebase::firestore::util::Path;
  84. using firebase::firestore::util::Status;
  85. using firebase::firestore::util::StatusOr;
  86. using firebase::firestore::util::StringFormat;
  87. using leveldb::DB;
  88. using leveldb::Options;
  89. using leveldb::ReadOptions;
  90. using leveldb::WriteOptions;
  91. static const char *kReservedPathComponent = "firestore";
  92. @interface FSTLevelDB ()
  93. - (size_t)byteSize;
  94. @property(nonatomic, assign, getter=isStarted) BOOL started;
  95. - (LevelDbQueryCache *)queryCache;
  96. - (LevelDbMutationQueue *)mutationQueueForUser:(const User &)user;
  97. @end
  98. /**
  99. * Provides LRU functionality for leveldb persistence.
  100. *
  101. * Although this could implement FSTTransactional, it doesn't because it is not directly tied to
  102. * a transaction runner, it just happens to be called from FSTLevelDB, which is FSTTransactional.
  103. */
  104. @interface FSTLevelDBLRUDelegate ()
  105. - (void)transactionWillStart;
  106. - (void)transactionWillCommit;
  107. - (void)start;
  108. @end
  109. @implementation FSTLevelDBLRUDelegate {
  110. local::LruDelegateBridge _delegateBridge;
  111. std::unique_ptr<LruGarbageCollector> _gc;
  112. // This delegate should have the same lifetime as the persistence layer, but mark as
  113. // weak to avoid retain cycle.
  114. __weak FSTLevelDB *_db;
  115. ReferenceSet *_additionalReferences;
  116. ListenSequenceNumber _currentSequenceNumber;
  117. // PORTING NOTE: doesn't need to be a pointer once this class is ported to C++.
  118. std::unique_ptr<ListenSequence> _listenSequence;
  119. }
  120. - (instancetype)initWithPersistence:(FSTLevelDB *)persistence lruParams:(LruParams)lruParams {
  121. if (self = [super init]) {
  122. _delegateBridge = local::LruDelegateBridge(self);
  123. _gc = absl::make_unique<LruGarbageCollector>(&_delegateBridge, lruParams);
  124. _db = persistence;
  125. _currentSequenceNumber = local::kListenSequenceNumberInvalid;
  126. }
  127. return self;
  128. }
  129. - (void)start {
  130. ListenSequenceNumber highestSequenceNumber = _db.queryCache->highest_listen_sequence_number();
  131. _listenSequence = absl::make_unique<ListenSequence>(highestSequenceNumber);
  132. }
  133. - (void)transactionWillStart {
  134. HARD_ASSERT(_currentSequenceNumber == local::kListenSequenceNumberInvalid,
  135. "Previous sequence number is still in effect");
  136. _currentSequenceNumber = _listenSequence->Next();
  137. }
  138. - (void)transactionWillCommit {
  139. _currentSequenceNumber = local::kListenSequenceNumberInvalid;
  140. }
  141. - (ListenSequenceNumber)currentSequenceNumber {
  142. HARD_ASSERT(_currentSequenceNumber != local::kListenSequenceNumberInvalid,
  143. "Asking for a sequence number outside of a transaction");
  144. return _currentSequenceNumber;
  145. }
  146. - (void)addInMemoryPins:(ReferenceSet *)set {
  147. // We should be able to assert that _additionalReferences is nil, but due to restarts in spec
  148. // tests it would fail.
  149. _additionalReferences = set;
  150. }
  151. - (void)removeTarget:(const QueryData &)queryData {
  152. QueryData updated = queryData.Copy(queryData.snapshot_version(), queryData.resume_token(),
  153. [self currentSequenceNumber]);
  154. _db.queryCache->UpdateTarget(std::move(updated));
  155. }
  156. - (void)addReference:(const DocumentKey &)key {
  157. [self writeSentinelForKey:key];
  158. }
  159. - (void)removeReference:(const DocumentKey &)key {
  160. [self writeSentinelForKey:key];
  161. }
  162. - (BOOL)mutationQueuesContainKey:(const DocumentKey &)docKey {
  163. const std::set<std::string> &users = _db.users;
  164. const ResourcePath &path = docKey.path();
  165. std::string buffer;
  166. auto it = _db.currentTransaction->NewIterator();
  167. // For each user, if there is any batch that contains this document in any batch, we know it's
  168. // pinned.
  169. for (const std::string &user : users) {
  170. std::string mutationKey = LevelDbDocumentMutationKey::KeyPrefix(user, path);
  171. it->Seek(mutationKey);
  172. if (it->Valid() && absl::StartsWith(it->key(), mutationKey)) {
  173. return YES;
  174. }
  175. }
  176. return NO;
  177. }
  178. - (BOOL)isPinned:(const DocumentKey &)docKey {
  179. if (_additionalReferences->ContainsKey(docKey)) {
  180. return YES;
  181. }
  182. if ([self mutationQueuesContainKey:docKey]) {
  183. return YES;
  184. }
  185. return NO;
  186. }
  187. - (void)enumerateTargetsUsingCallback:(const TargetCallback &)callback {
  188. _db.queryCache->EnumerateTargets(callback);
  189. }
  190. - (void)enumerateMutationsUsingCallback:(const OrphanedDocumentCallback &)callback {
  191. _db.queryCache->EnumerateOrphanedDocuments(callback);
  192. }
  193. - (int)removeOrphanedDocumentsThroughSequenceNumber:(ListenSequenceNumber)upperBound {
  194. int count = 0;
  195. _db.queryCache->EnumerateOrphanedDocuments(
  196. [&count, self, upperBound](const DocumentKey &docKey, ListenSequenceNumber sequenceNumber) {
  197. if (sequenceNumber <= upperBound) {
  198. if (![self isPinned:docKey]) {
  199. count++;
  200. self->_db.remoteDocumentCache->Remove(docKey);
  201. [self removeSentinel:docKey];
  202. }
  203. }
  204. });
  205. return count;
  206. }
  207. - (void)removeSentinel:(const DocumentKey &)key {
  208. _db.currentTransaction->Delete(LevelDbDocumentTargetKey::SentinelKey(key));
  209. }
  210. - (int)removeTargetsThroughSequenceNumber:(ListenSequenceNumber)sequenceNumber
  211. liveQueries:
  212. (const std::unordered_map<TargetId, QueryData> &)liveQueries {
  213. return _db.queryCache->RemoveTargets(sequenceNumber, liveQueries);
  214. }
  215. - (size_t)sequenceNumberCount {
  216. size_t totalCount = _db.queryCache->size();
  217. [self enumerateMutationsUsingCallback:[&totalCount](const DocumentKey &key,
  218. ListenSequenceNumber sequenceNumber) {
  219. totalCount++;
  220. }];
  221. return totalCount;
  222. }
  223. - (local::LruGarbageCollector *)gc {
  224. return _gc.get();
  225. }
  226. - (void)writeSentinelForKey:(const DocumentKey &)key {
  227. std::string sentinelKey = LevelDbDocumentTargetKey::SentinelKey(key);
  228. std::string encodedSequenceNumber =
  229. LevelDbDocumentTargetKey::EncodeSentinelValue([self currentSequenceNumber]);
  230. _db.currentTransaction->Put(sentinelKey, encodedSequenceNumber);
  231. }
  232. - (void)removeMutationReference:(const DocumentKey &)key {
  233. [self writeSentinelForKey:key];
  234. }
  235. - (void)limboDocumentUpdated:(const DocumentKey &)key {
  236. [self writeSentinelForKey:key];
  237. }
  238. - (size_t)byteSize {
  239. return [_db byteSize];
  240. }
  241. @end
  242. @implementation FSTLevelDB {
  243. Path _directory;
  244. std::unique_ptr<LevelDbTransaction> _transaction;
  245. std::unique_ptr<leveldb::DB> _ptr;
  246. std::unique_ptr<LevelDbRemoteDocumentCache> _documentCache;
  247. std::unique_ptr<LevelDbIndexManager> _indexManager;
  248. FSTTransactionRunner _transactionRunner;
  249. FSTLevelDBLRUDelegate *_referenceDelegate;
  250. std::unique_ptr<LevelDbQueryCache> _queryCache;
  251. std::set<std::string> _users;
  252. std::unique_ptr<LevelDbMutationQueue> _currentMutationQueue;
  253. }
  254. /**
  255. * For now this is paranoid, but perhaps disable that in production builds.
  256. */
  257. + (const ReadOptions)standardReadOptions {
  258. ReadOptions options;
  259. options.verify_checksums = true;
  260. return options;
  261. }
  262. + (std::set<std::string>)collectUserSet:(LevelDbTransaction *)transaction {
  263. std::set<std::string> users;
  264. std::string tablePrefix = LevelDbMutationKey::KeyPrefix();
  265. auto it = transaction->NewIterator();
  266. it->Seek(tablePrefix);
  267. LevelDbMutationKey rowKey;
  268. while (it->Valid() && absl::StartsWith(it->key(), tablePrefix) && rowKey.Decode(it->key())) {
  269. users.insert(rowKey.user_id());
  270. auto userEnd = LevelDbMutationKey::KeyPrefix(rowKey.user_id());
  271. userEnd = util::PrefixSuccessor(userEnd);
  272. it->Seek(userEnd);
  273. }
  274. return users;
  275. }
  276. + (firebase::firestore::util::Status)dbWithDirectory:(firebase::firestore::util::Path)directory
  277. serializer:(FSTLocalSerializer *)serializer
  278. lruParams:
  279. (firebase::firestore::local::LruParams)lruParams
  280. ptr:(FSTLevelDB **)ptr {
  281. Status status = [self ensureDirectory:directory];
  282. if (!status.ok()) return status;
  283. StatusOr<std::unique_ptr<DB>> database = [self createDBWithDirectory:directory];
  284. if (!database.status().ok()) {
  285. return database.status();
  286. }
  287. std::unique_ptr<DB> ldb = std::move(database.ValueOrDie());
  288. LevelDbMigrations::RunMigrations(ldb.get());
  289. LevelDbTransaction transaction(ldb.get(), "Start LevelDB");
  290. std::set<std::string> users = [self collectUserSet:&transaction];
  291. transaction.Commit();
  292. FSTLevelDB *db = [[self alloc] initWithLevelDB:std::move(ldb)
  293. users:users
  294. directory:directory
  295. serializer:serializer
  296. lruParams:lruParams];
  297. *ptr = db;
  298. return Status::OK();
  299. }
  300. + (Status)clearPersistence:(const DatabaseInfo &)databaseInfo {
  301. Path levelDBDir = [FSTLevelDB storageDirectoryForDatabaseInfo:databaseInfo
  302. documentsDirectory:[FSTLevelDB documentsDirectory]];
  303. LOG_DEBUG("Clearing persistence for path: %s", levelDBDir.ToUtf8String());
  304. return util::RecursivelyDelete(levelDBDir);
  305. }
  306. - (instancetype)initWithLevelDB:(std::unique_ptr<leveldb::DB>)db
  307. users:(std::set<std::string>)users
  308. directory:(firebase::firestore::util::Path)directory
  309. serializer:(FSTLocalSerializer *)serializer
  310. lruParams:(firebase::firestore::local::LruParams)lruParams {
  311. if (self = [super init]) {
  312. self.started = YES;
  313. _ptr = std::move(db);
  314. _directory = std::move(directory);
  315. _serializer = serializer;
  316. _queryCache = absl::make_unique<LevelDbQueryCache>(self, _serializer);
  317. _documentCache = absl::make_unique<LevelDbRemoteDocumentCache>(self, _serializer);
  318. _indexManager = absl::make_unique<LevelDbIndexManager>(self);
  319. _referenceDelegate = [[FSTLevelDBLRUDelegate alloc] initWithPersistence:self
  320. lruParams:lruParams];
  321. _transactionRunner.SetBackingPersistence(self);
  322. _users = std::move(users);
  323. // TODO(gsoltis): set up a leveldb transaction for these operations.
  324. _queryCache->Start();
  325. [_referenceDelegate start];
  326. }
  327. return self;
  328. }
  329. - (size_t)byteSize {
  330. int64_t count = 0;
  331. auto iter = util::DirectoryIterator::Create(_directory);
  332. for (; iter->Valid(); iter->Next()) {
  333. int64_t fileSize = util::FileSize(iter->file()).ValueOrDie();
  334. count += fileSize;
  335. }
  336. HARD_ASSERT(iter->status().ok(), "Failed to iterate leveldb directory: %s",
  337. iter->status().error_message().c_str());
  338. HARD_ASSERT(count >= 0 && count <= SIZE_MAX, "Overflowed counting bytes cached");
  339. return static_cast<size_t>(count);
  340. }
  341. - (const std::set<std::string> &)users {
  342. return _users;
  343. }
  344. - (leveldb::DB *)ptr {
  345. return _ptr.get();
  346. }
  347. - (const FSTTransactionRunner &)run {
  348. return _transactionRunner;
  349. }
  350. + (Path)documentsDirectory {
  351. #if TARGET_OS_IOS
  352. NSArray<NSString *> *directories =
  353. NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  354. return Path::FromNSString(directories[0]).AppendUtf8(kReservedPathComponent);
  355. #elif TARGET_OS_TV
  356. NSArray<NSString *> *directories =
  357. NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  358. return Path::FromNSString(directories[0]).AppendUtf8(kReservedPathComponent);
  359. #elif TARGET_OS_OSX
  360. std::string dotPrefixed = absl::StrCat(".", kReservedPathComponent);
  361. return Path::FromNSString(NSHomeDirectory()).AppendUtf8(dotPrefixed);
  362. #else
  363. #error "Don't know where to store documents on this platform."
  364. #endif
  365. }
  366. + (Path)storageDirectoryForDatabaseInfo:(const DatabaseInfo &)databaseInfo
  367. documentsDirectory:(const Path &)documentsDirectory {
  368. // Use two different path formats:
  369. //
  370. // * persistenceKey / projectID . databaseID / name
  371. // * persistenceKey / projectID / name
  372. //
  373. // projectIDs are DNS-compatible names and cannot contain dots so there's
  374. // no danger of collisions.
  375. std::string project_key = databaseInfo.database_id().project_id();
  376. if (!databaseInfo.database_id().IsDefaultDatabase()) {
  377. absl::StrAppend(&project_key, ".", databaseInfo.database_id().database_id());
  378. }
  379. // Reserve one additional path component to allow multiple physical databases
  380. return Path::JoinUtf8(documentsDirectory, databaseInfo.persistence_key(), project_key, "main");
  381. }
  382. #pragma mark - Startup
  383. /** Creates the directory at @a directory and marks it as excluded from iCloud backup. */
  384. + (Status)ensureDirectory:(const Path &)directory {
  385. Status status = util::RecursivelyCreateDir(directory);
  386. if (!status.ok()) {
  387. return Status{Error::Internal, "Failed to create persistence directory"}.CausedBy(status);
  388. }
  389. NSURL *dirURL = [NSURL fileURLWithPath:directory.ToNSString()];
  390. NSError *localError = nil;
  391. if (![dirURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:&localError]) {
  392. return Status{Error::Internal, "Failed to mark persistence directory as excluded from backups"}
  393. .CausedBy(Status::FromNSError(localError));
  394. }
  395. return Status::OK();
  396. }
  397. /** Opens the database within the given directory. */
  398. + (StatusOr<std::unique_ptr<DB>>)createDBWithDirectory:(const Path &)directory {
  399. Options options;
  400. options.create_if_missing = true;
  401. DB *database = nullptr;
  402. leveldb::Status status = DB::Open(options, directory.ToUtf8String(), &database);
  403. if (!status.ok()) {
  404. return Status{Error::Internal,
  405. StringFormat("Failed to open LevelDB database at %s", directory.ToUtf8String())}
  406. .CausedBy(ConvertStatus(status));
  407. }
  408. return std::unique_ptr<DB>(database);
  409. }
  410. - (LevelDbTransaction *)currentTransaction {
  411. HARD_ASSERT(_transaction != nullptr, "Attempting to access transaction before one has started");
  412. return _transaction.get();
  413. }
  414. #pragma mark - Persistence Factory methods
  415. - (LevelDbMutationQueue *)mutationQueueForUser:(const User &)user {
  416. _users.insert(user.uid());
  417. _currentMutationQueue.reset(new LevelDbMutationQueue(user, self, self.serializer));
  418. return _currentMutationQueue.get();
  419. }
  420. - (LevelDbQueryCache *)queryCache {
  421. return _queryCache.get();
  422. }
  423. - (RemoteDocumentCache *)remoteDocumentCache {
  424. return _documentCache.get();
  425. }
  426. - (IndexManager *)indexManager {
  427. return _indexManager.get();
  428. }
  429. - (void)startTransaction:(absl::string_view)label {
  430. HARD_ASSERT(_transaction == nullptr, "Starting a transaction while one is already outstanding");
  431. _transaction = absl::make_unique<LevelDbTransaction>(_ptr.get(), label);
  432. [_referenceDelegate transactionWillStart];
  433. }
  434. - (void)commitTransaction {
  435. HARD_ASSERT(_transaction != nullptr, "Committing a transaction before one is started");
  436. [_referenceDelegate transactionWillCommit];
  437. _transaction->Commit();
  438. _transaction.reset();
  439. }
  440. - (void)shutdown {
  441. HARD_ASSERT(self.isStarted, "FSTLevelDB shutdown without start!");
  442. self.started = NO;
  443. _ptr.reset();
  444. }
  445. - (id<FSTReferenceDelegate>)referenceDelegate {
  446. return _referenceDelegate;
  447. }
  448. - (ListenSequenceNumber)currentSequenceNumber {
  449. return [_referenceDelegate currentSequenceNumber];
  450. }
  451. @end
  452. NS_ASSUME_NONNULL_END