FSTLevelDB.mm 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. #import "FIRFirestoreErrors.h"
  19. #import "Firestore/Source/Local/FSTLevelDBMigrations.h"
  20. #import "Firestore/Source/Local/FSTLevelDBMutationQueue.h"
  21. #import "Firestore/Source/Local/FSTLevelDBQueryCache.h"
  22. #import "Firestore/Source/Local/FSTLevelDBRemoteDocumentCache.h"
  23. #import "Firestore/Source/Remote/FSTSerializerBeta.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_transaction.h"
  27. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  28. #include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
  29. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  30. #include "absl/memory/memory.h"
  31. #include "leveldb/db.h"
  32. namespace util = firebase::firestore::util;
  33. using firebase::firestore::auth::User;
  34. using firebase::firestore::core::DatabaseInfo;
  35. using firebase::firestore::model::DatabaseId;
  36. NS_ASSUME_NONNULL_BEGIN
  37. static NSString *const kReservedPathComponent = @"firestore";
  38. using firebase::firestore::local::LevelDbTransaction;
  39. using leveldb::DB;
  40. using leveldb::Options;
  41. using leveldb::ReadOptions;
  42. using leveldb::Status;
  43. using leveldb::WriteOptions;
  44. @interface FSTLevelDB ()
  45. @property(nonatomic, copy) NSString *directory;
  46. @property(nonatomic, assign, getter=isStarted) BOOL started;
  47. @property(nonatomic, strong, readonly) FSTLocalSerializer *serializer;
  48. @end
  49. @implementation FSTLevelDB {
  50. std::unique_ptr<LevelDbTransaction> _transaction;
  51. FSTTransactionRunner _transactionRunner;
  52. }
  53. /**
  54. * For now this is paranoid, but perhaps disable that in production builds.
  55. */
  56. + (const ReadOptions)standardReadOptions {
  57. ReadOptions options;
  58. options.verify_checksums = true;
  59. return options;
  60. }
  61. - (instancetype)initWithDirectory:(NSString *)directory
  62. serializer:(FSTLocalSerializer *)serializer {
  63. if (self = [super init]) {
  64. _directory = [directory copy];
  65. _serializer = serializer;
  66. _transactionRunner.SetBackingPersistence(self);
  67. }
  68. return self;
  69. }
  70. - (const FSTTransactionRunner &)run {
  71. return _transactionRunner;
  72. }
  73. + (NSString *)documentsDirectory {
  74. #if TARGET_OS_IPHONE
  75. NSArray<NSString *> *directories =
  76. NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  77. return [directories[0] stringByAppendingPathComponent:kReservedPathComponent];
  78. #elif TARGET_OS_MAC
  79. NSString *dotPrefixed = [@"." stringByAppendingString:kReservedPathComponent];
  80. return [NSHomeDirectory() stringByAppendingPathComponent:dotPrefixed];
  81. #else
  82. #error "local storage on tvOS"
  83. // TODO(mcg): Writing to NSDocumentsDirectory on tvOS will fail; we need to write to Caches
  84. // https://developer.apple.com/library/content/documentation/General/Conceptual/AppleTV_PG/
  85. #endif
  86. }
  87. + (NSString *)storageDirectoryForDatabaseInfo:(const DatabaseInfo &)databaseInfo
  88. documentsDirectory:(NSString *)documentsDirectory {
  89. // Use two different path formats:
  90. //
  91. // * persistenceKey / projectID . databaseID / name
  92. // * persistenceKey / projectID / name
  93. //
  94. // projectIDs are DNS-compatible names and cannot contain dots so there's
  95. // no danger of collisions.
  96. NSString *directory = documentsDirectory;
  97. directory =
  98. [directory stringByAppendingPathComponent:util::WrapNSString(databaseInfo.persistence_key())];
  99. NSString *segment = util::WrapNSString(databaseInfo.database_id().project_id());
  100. if (!databaseInfo.database_id().IsDefaultDatabase()) {
  101. segment = [NSString
  102. stringWithFormat:@"%@.%s", segment, databaseInfo.database_id().database_id().c_str()];
  103. }
  104. directory = [directory stringByAppendingPathComponent:segment];
  105. // Reserve one additional path component to allow multiple physical databases
  106. directory = [directory stringByAppendingPathComponent:@"main"];
  107. return directory;
  108. }
  109. #pragma mark - Startup
  110. - (BOOL)start:(NSError **)error {
  111. HARD_ASSERT(!self.isStarted, "FSTLevelDB double-started!");
  112. self.started = YES;
  113. NSString *directory = self.directory;
  114. if (![self ensureDirectory:directory error:error]) {
  115. return NO;
  116. }
  117. DB *database = [self createDBWithDirectory:directory error:error];
  118. if (!database) {
  119. return NO;
  120. }
  121. _ptr.reset(database);
  122. LevelDbTransaction transaction(_ptr.get(), "Start LevelDB");
  123. [FSTLevelDBMigrations runMigrationsWithTransaction:&transaction];
  124. transaction.Commit();
  125. return YES;
  126. }
  127. /** Creates the directory at @a directory and marks it as excluded from iCloud backup. */
  128. - (BOOL)ensureDirectory:(NSString *)directory error:(NSError **)error {
  129. NSError *localError;
  130. NSFileManager *files = [NSFileManager defaultManager];
  131. BOOL success = [files createDirectoryAtPath:directory
  132. withIntermediateDirectories:YES
  133. attributes:nil
  134. error:&localError];
  135. if (!success) {
  136. *error =
  137. [NSError errorWithDomain:FIRFirestoreErrorDomain
  138. code:FIRFirestoreErrorCodeInternal
  139. userInfo:@{
  140. NSLocalizedDescriptionKey : @"Failed to create persistence directory",
  141. NSUnderlyingErrorKey : localError
  142. }];
  143. return NO;
  144. }
  145. NSURL *dirURL = [NSURL fileURLWithPath:directory];
  146. success = [dirURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:&localError];
  147. if (!success) {
  148. *error = [NSError errorWithDomain:FIRFirestoreErrorDomain
  149. code:FIRFirestoreErrorCodeInternal
  150. userInfo:@{
  151. NSLocalizedDescriptionKey :
  152. @"Failed mark persistence directory as excluded from backups",
  153. NSUnderlyingErrorKey : localError
  154. }];
  155. return NO;
  156. }
  157. return YES;
  158. }
  159. /** Opens the database within the given directory. */
  160. - (nullable DB *)createDBWithDirectory:(NSString *)directory error:(NSError **)error {
  161. Options options;
  162. options.create_if_missing = true;
  163. DB *database;
  164. Status status = DB::Open(options, [directory UTF8String], &database);
  165. if (!status.ok()) {
  166. if (error) {
  167. NSString *name = [directory lastPathComponent];
  168. *error =
  169. [FSTLevelDB errorWithStatus:status
  170. description:@"Failed to create database %@ at path %@", name, directory];
  171. }
  172. return nullptr;
  173. }
  174. return database;
  175. }
  176. - (LevelDbTransaction *)currentTransaction {
  177. HARD_ASSERT(_transaction != nullptr, "Attempting to access transaction before one has started");
  178. return _transaction.get();
  179. }
  180. #pragma mark - Persistence Factory methods
  181. - (id<FSTMutationQueue>)mutationQueueForUser:(const User &)user {
  182. return [FSTLevelDBMutationQueue mutationQueueWithUser:user db:self serializer:self.serializer];
  183. }
  184. - (id<FSTQueryCache>)queryCache {
  185. return [[FSTLevelDBQueryCache alloc] initWithDB:self serializer:self.serializer];
  186. }
  187. - (id<FSTRemoteDocumentCache>)remoteDocumentCache {
  188. return [[FSTLevelDBRemoteDocumentCache alloc] initWithDB:self serializer:self.serializer];
  189. }
  190. - (void)startTransaction:(absl::string_view)label {
  191. HARD_ASSERT(_transaction == nullptr, "Starting a transaction while one is already outstanding");
  192. _transaction = absl::make_unique<LevelDbTransaction>(_ptr.get(), label);
  193. }
  194. - (void)commitTransaction {
  195. HARD_ASSERT(_transaction != nullptr, "Committing a transaction before one is started");
  196. _transaction->Commit();
  197. _transaction.reset();
  198. }
  199. - (void)shutdown {
  200. HARD_ASSERT(self.isStarted, "FSTLevelDB shutdown without start!");
  201. self.started = NO;
  202. _ptr.reset();
  203. }
  204. - (_Nullable id<FSTReferenceDelegate>)referenceDelegate {
  205. return nil;
  206. }
  207. #pragma mark - Error and Status
  208. + (nullable NSError *)errorWithStatus:(Status)status description:(NSString *)description, ... {
  209. if (status.ok()) {
  210. return nil;
  211. }
  212. va_list args;
  213. va_start(args, description);
  214. NSString *message = [[NSString alloc] initWithFormat:description arguments:args];
  215. NSString *reason = [self descriptionOfStatus:status];
  216. NSError *result = [NSError errorWithDomain:FIRFirestoreErrorDomain
  217. code:FIRFirestoreErrorCodeInternal
  218. userInfo:@{
  219. NSLocalizedDescriptionKey : message,
  220. NSLocalizedFailureReasonErrorKey : reason
  221. }];
  222. va_end(args);
  223. return result;
  224. }
  225. + (NSString *)descriptionOfStatus:(Status)status {
  226. return [NSString stringWithCString:status.ToString().c_str() encoding:NSUTF8StringEncoding];
  227. }
  228. @end
  229. NS_ASSUME_NONNULL_END