FSTLevelDB.mm 16 KB

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