FSTLevelDB.mm 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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/reference_set.h"
  36. #include "Firestore/core/src/firebase/firestore/local/remote_document_cache.h"
  37. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  38. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  39. #include "Firestore/core/src/firebase/firestore/model/resource_path.h"
  40. #include "Firestore/core/src/firebase/firestore/model/types.h"
  41. #include "Firestore/core/src/firebase/firestore/util/filesystem.h"
  42. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  43. #include "Firestore/core/src/firebase/firestore/util/log.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::OrphanedDocumentCallback;
  71. using firebase::firestore::local::ReferenceSet;
  72. using firebase::firestore::local::RemoteDocumentCache;
  73. using firebase::firestore::local::TargetCallback;
  74. using firebase::firestore::model::DocumentKey;
  75. using firebase::firestore::model::ListenSequenceNumber;
  76. using firebase::firestore::model::ResourcePath;
  77. using firebase::firestore::model::TargetId;
  78. using firebase::firestore::util::OrderedCode;
  79. using firebase::firestore::util::Path;
  80. using firebase::firestore::util::Status;
  81. using firebase::firestore::util::StatusOr;
  82. using firebase::firestore::util::StringFormat;
  83. using leveldb::DB;
  84. using leveldb::Options;
  85. using leveldb::ReadOptions;
  86. using leveldb::WriteOptions;
  87. static const char *kReservedPathComponent = "firestore";
  88. @interface FSTLevelDB ()
  89. - (size_t)byteSize;
  90. @property(nonatomic, assign, getter=isStarted) BOOL started;
  91. - (LevelDbQueryCache *)queryCache;
  92. - (LevelDbMutationQueue *)mutationQueueForUser:(const User &)user;
  93. @end
  94. /**
  95. * Provides LRU functionality for leveldb persistence.
  96. *
  97. * Although this could implement FSTTransactional, it doesn't because it is not directly tied to
  98. * a transaction runner, it just happens to be called from FSTLevelDB, which is FSTTransactional.
  99. */
  100. @interface FSTLevelDBLRUDelegate ()
  101. - (void)transactionWillStart;
  102. - (void)transactionWillCommit;
  103. - (void)start;
  104. @end
  105. @implementation FSTLevelDBLRUDelegate {
  106. FSTLRUGarbageCollector *_gc;
  107. // This delegate should have the same lifetime as the persistence layer, but mark as
  108. // weak to avoid retain cycle.
  109. __weak FSTLevelDB *_db;
  110. ReferenceSet *_additionalReferences;
  111. ListenSequenceNumber _currentSequenceNumber;
  112. // PORTING NOTE: doesn't need to be a pointer once this class is ported to C++.
  113. std::unique_ptr<ListenSequence> _listenSequence;
  114. }
  115. - (instancetype)initWithPersistence:(FSTLevelDB *)persistence lruParams:(LruParams)lruParams {
  116. if (self = [super init]) {
  117. _gc = [[FSTLRUGarbageCollector alloc] initWithDelegate:self params:lruParams];
  118. _db = persistence;
  119. _currentSequenceNumber = kFSTListenSequenceNumberInvalid;
  120. }
  121. return self;
  122. }
  123. - (void)start {
  124. ListenSequenceNumber highestSequenceNumber = _db.queryCache->highest_listen_sequence_number();
  125. _listenSequence = absl::make_unique<ListenSequence>(highestSequenceNumber);
  126. }
  127. - (void)transactionWillStart {
  128. HARD_ASSERT(_currentSequenceNumber == kFSTListenSequenceNumberInvalid,
  129. "Previous sequence number is still in effect");
  130. _currentSequenceNumber = _listenSequence->Next();
  131. }
  132. - (void)transactionWillCommit {
  133. _currentSequenceNumber = kFSTListenSequenceNumberInvalid;
  134. }
  135. - (ListenSequenceNumber)currentSequenceNumber {
  136. HARD_ASSERT(_currentSequenceNumber != kFSTListenSequenceNumberInvalid,
  137. "Asking for a sequence number outside of a transaction");
  138. return _currentSequenceNumber;
  139. }
  140. - (void)addInMemoryPins:(ReferenceSet *)set {
  141. // We should be able to assert that _additionalReferences is nil, but due to restarts in spec
  142. // tests it would fail.
  143. _additionalReferences = set;
  144. }
  145. - (void)removeTarget:(FSTQueryData *)queryData {
  146. FSTQueryData *updated =
  147. [queryData queryDataByReplacingSnapshotVersion:queryData.snapshotVersion
  148. resumeToken:queryData.resumeToken
  149. sequenceNumber:[self currentSequenceNumber]];
  150. _db.queryCache->UpdateTarget(updated);
  151. }
  152. - (void)addReference:(const DocumentKey &)key {
  153. [self writeSentinelForKey:key];
  154. }
  155. - (void)removeReference:(const DocumentKey &)key {
  156. [self writeSentinelForKey:key];
  157. }
  158. - (BOOL)mutationQueuesContainKey:(const DocumentKey &)docKey {
  159. const std::set<std::string> &users = _db.users;
  160. const ResourcePath &path = docKey.path();
  161. std::string buffer;
  162. auto it = _db.currentTransaction->NewIterator();
  163. // For each user, if there is any batch that contains this document in any batch, we know it's
  164. // pinned.
  165. for (const std::string &user : users) {
  166. std::string mutationKey = LevelDbDocumentMutationKey::KeyPrefix(user, path);
  167. it->Seek(mutationKey);
  168. if (it->Valid() && absl::StartsWith(it->key(), mutationKey)) {
  169. return YES;
  170. }
  171. }
  172. return NO;
  173. }
  174. - (BOOL)isPinned:(const DocumentKey &)docKey {
  175. if (_additionalReferences->ContainsKey(docKey)) {
  176. return YES;
  177. }
  178. if ([self mutationQueuesContainKey:docKey]) {
  179. return YES;
  180. }
  181. return NO;
  182. }
  183. - (void)enumerateTargetsUsingCallback:(const TargetCallback &)callback {
  184. _db.queryCache->EnumerateTargets(callback);
  185. }
  186. - (void)enumerateMutationsUsingCallback:(const OrphanedDocumentCallback &)callback {
  187. _db.queryCache->EnumerateOrphanedDocuments(callback);
  188. }
  189. - (int)removeOrphanedDocumentsThroughSequenceNumber:(ListenSequenceNumber)upperBound {
  190. int count = 0;
  191. _db.queryCache->EnumerateOrphanedDocuments(
  192. [&count, self, upperBound](const DocumentKey &docKey, ListenSequenceNumber sequenceNumber) {
  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. size_t totalCount = _db.queryCache->size();
  213. [self enumerateMutationsUsingCallback:[&totalCount](const DocumentKey &key,
  214. ListenSequenceNumber sequenceNumber) {
  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. + (Status)clearPersistence:(const DatabaseInfo &)databaseInfo {
  297. Path levelDBDir = [FSTLevelDB storageDirectoryForDatabaseInfo:databaseInfo
  298. documentsDirectory:[FSTLevelDB documentsDirectory]];
  299. LOG_DEBUG("Clearing persistence for path: %s", levelDBDir.ToUtf8String());
  300. return util::RecursivelyDelete(levelDBDir);
  301. }
  302. - (instancetype)initWithLevelDB:(std::unique_ptr<leveldb::DB>)db
  303. users:(std::set<std::string>)users
  304. directory:(firebase::firestore::util::Path)directory
  305. serializer:(FSTLocalSerializer *)serializer
  306. lruParams:(firebase::firestore::local::LruParams)lruParams {
  307. if (self = [super init]) {
  308. self.started = YES;
  309. _ptr = std::move(db);
  310. _directory = std::move(directory);
  311. _serializer = serializer;
  312. _queryCache = absl::make_unique<LevelDbQueryCache>(self, _serializer);
  313. _documentCache = absl::make_unique<LevelDbRemoteDocumentCache>(self, _serializer);
  314. _indexManager = absl::make_unique<LevelDbIndexManager>(self);
  315. _referenceDelegate = [[FSTLevelDBLRUDelegate alloc] initWithPersistence:self
  316. lruParams:lruParams];
  317. _transactionRunner.SetBackingPersistence(self);
  318. _users = std::move(users);
  319. // TODO(gsoltis): set up a leveldb transaction for these operations.
  320. _queryCache->Start();
  321. [_referenceDelegate start];
  322. }
  323. return self;
  324. }
  325. - (size_t)byteSize {
  326. int64_t count = 0;
  327. auto iter = util::DirectoryIterator::Create(_directory);
  328. for (; iter->Valid(); iter->Next()) {
  329. int64_t fileSize = util::FileSize(iter->file()).ValueOrDie();
  330. count += fileSize;
  331. }
  332. HARD_ASSERT(iter->status().ok(), "Failed to iterate leveldb directory: %s",
  333. iter->status().error_message().c_str());
  334. HARD_ASSERT(count >= 0 && count <= SIZE_MAX, "Overflowed counting bytes cached");
  335. return static_cast<size_t>(count);
  336. }
  337. - (const std::set<std::string> &)users {
  338. return _users;
  339. }
  340. - (leveldb::DB *)ptr {
  341. return _ptr.get();
  342. }
  343. - (const FSTTransactionRunner &)run {
  344. return _transactionRunner;
  345. }
  346. + (Path)documentsDirectory {
  347. #if TARGET_OS_IOS
  348. NSArray<NSString *> *directories =
  349. NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  350. return Path::FromNSString(directories[0]).AppendUtf8(kReservedPathComponent);
  351. #elif TARGET_OS_TV
  352. NSArray<NSString *> *directories =
  353. NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  354. return Path::FromNSString(directories[0]).AppendUtf8(kReservedPathComponent);
  355. #elif TARGET_OS_OSX
  356. std::string dotPrefixed = absl::StrCat(".", kReservedPathComponent);
  357. return Path::FromNSString(NSHomeDirectory()).AppendUtf8(dotPrefixed);
  358. #else
  359. #error "Don't know where to store documents on this platform."
  360. #endif
  361. }
  362. + (Path)storageDirectoryForDatabaseInfo:(const DatabaseInfo &)databaseInfo
  363. documentsDirectory:(const Path &)documentsDirectory {
  364. // Use two different path formats:
  365. //
  366. // * persistenceKey / projectID . databaseID / name
  367. // * persistenceKey / projectID / name
  368. //
  369. // projectIDs are DNS-compatible names and cannot contain dots so there's
  370. // no danger of collisions.
  371. std::string project_key = databaseInfo.database_id().project_id();
  372. if (!databaseInfo.database_id().IsDefaultDatabase()) {
  373. absl::StrAppend(&project_key, ".", databaseInfo.database_id().database_id());
  374. }
  375. // Reserve one additional path component to allow multiple physical databases
  376. return Path::JoinUtf8(documentsDirectory, databaseInfo.persistence_key(), project_key, "main");
  377. }
  378. #pragma mark - Startup
  379. /** Creates the directory at @a directory and marks it as excluded from iCloud backup. */
  380. + (Status)ensureDirectory:(const Path &)directory {
  381. Status status = util::RecursivelyCreateDir(directory);
  382. if (!status.ok()) {
  383. return Status{FirestoreErrorCode::Internal, "Failed to create persistence directory"}.CausedBy(
  384. status);
  385. }
  386. NSURL *dirURL = [NSURL fileURLWithPath:directory.ToNSString()];
  387. NSError *localError = nil;
  388. if (![dirURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:&localError]) {
  389. return Status{FirestoreErrorCode::Internal,
  390. "Failed to mark persistence directory as excluded from backups"}
  391. .CausedBy(Status::FromNSError(localError));
  392. }
  393. return Status::OK();
  394. }
  395. /** Opens the database within the given directory. */
  396. + (StatusOr<std::unique_ptr<DB>>)createDBWithDirectory:(const Path &)directory {
  397. Options options;
  398. options.create_if_missing = true;
  399. DB *database = nullptr;
  400. leveldb::Status status = DB::Open(options, directory.ToUtf8String(), &database);
  401. if (!status.ok()) {
  402. return Status{FirestoreErrorCode::Internal,
  403. StringFormat("Failed to open LevelDB database at %s", directory.ToUtf8String())}
  404. .CausedBy(ConvertStatus(status));
  405. }
  406. return std::unique_ptr<DB>(database);
  407. }
  408. - (LevelDbTransaction *)currentTransaction {
  409. HARD_ASSERT(_transaction != nullptr, "Attempting to access transaction before one has started");
  410. return _transaction.get();
  411. }
  412. #pragma mark - Persistence Factory methods
  413. - (LevelDbMutationQueue *)mutationQueueForUser:(const User &)user {
  414. _users.insert(user.uid());
  415. _currentMutationQueue.reset(new LevelDbMutationQueue(user, self, self.serializer));
  416. return _currentMutationQueue.get();
  417. }
  418. - (LevelDbQueryCache *)queryCache {
  419. return _queryCache.get();
  420. }
  421. - (RemoteDocumentCache *)remoteDocumentCache {
  422. return _documentCache.get();
  423. }
  424. - (IndexManager *)indexManager {
  425. return _indexManager.get();
  426. }
  427. - (void)startTransaction:(absl::string_view)label {
  428. HARD_ASSERT(_transaction == nullptr, "Starting a transaction while one is already outstanding");
  429. _transaction = absl::make_unique<LevelDbTransaction>(_ptr.get(), label);
  430. [_referenceDelegate transactionWillStart];
  431. }
  432. - (void)commitTransaction {
  433. HARD_ASSERT(_transaction != nullptr, "Committing a transaction before one is started");
  434. [_referenceDelegate transactionWillCommit];
  435. _transaction->Commit();
  436. _transaction.reset();
  437. }
  438. - (void)shutdown {
  439. HARD_ASSERT(self.isStarted, "FSTLevelDB shutdown without start!");
  440. self.started = NO;
  441. _ptr.reset();
  442. }
  443. - (id<FSTReferenceDelegate>)referenceDelegate {
  444. return _referenceDelegate;
  445. }
  446. - (ListenSequenceNumber)currentSequenceNumber {
  447. return [_referenceDelegate currentSequenceNumber];
  448. }
  449. @end
  450. NS_ASSUME_NONNULL_END