FSTLevelDB.mm 18 KB

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