FSTLevelDB.mm 19 KB

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