FSTLevelDB.mm 8.0 KB

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