FSTLevelDB.mm 9.1 KB

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