FSTLevelDB.mm 8.8 KB

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