FSTLevelDB.mm 18 KB

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