FSTLevelDB.mm 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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:@"%@.%@", segment,
  97. util::WrapNSStringNoCopy(databaseInfo.database_id().database_id())];
  98. }
  99. directory = [directory stringByAppendingPathComponent:segment];
  100. // Reserve one additional path component to allow multiple physical databases
  101. directory = [directory stringByAppendingPathComponent:@"main"];
  102. return directory;
  103. }
  104. #pragma mark - Startup
  105. - (BOOL)start:(NSError **)error {
  106. FSTAssert(!self.isStarted, @"FSTLevelDB double-started!");
  107. self.started = YES;
  108. NSString *directory = self.directory;
  109. if (![self ensureDirectory:directory error:error]) {
  110. return NO;
  111. }
  112. DB *database = [self createDBWithDirectory:directory error:error];
  113. if (!database) {
  114. return NO;
  115. }
  116. _ptr.reset(database);
  117. [FSTLevelDBMigrations runMigrationsOnDB:_ptr];
  118. return YES;
  119. }
  120. /** Creates the directory at @a directory and marks it as excluded from iCloud backup. */
  121. - (BOOL)ensureDirectory:(NSString *)directory error:(NSError **)error {
  122. NSError *localError;
  123. NSFileManager *files = [NSFileManager defaultManager];
  124. BOOL success = [files createDirectoryAtPath:directory
  125. withIntermediateDirectories:YES
  126. attributes:nil
  127. error:&localError];
  128. if (!success) {
  129. *error =
  130. [NSError errorWithDomain:FIRFirestoreErrorDomain
  131. code:FIRFirestoreErrorCodeInternal
  132. userInfo:@{
  133. NSLocalizedDescriptionKey : @"Failed to create persistence directory",
  134. NSUnderlyingErrorKey : localError
  135. }];
  136. return NO;
  137. }
  138. NSURL *dirURL = [NSURL fileURLWithPath:directory];
  139. success = [dirURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:&localError];
  140. if (!success) {
  141. *error = [NSError errorWithDomain:FIRFirestoreErrorDomain
  142. code:FIRFirestoreErrorCodeInternal
  143. userInfo:@{
  144. NSLocalizedDescriptionKey :
  145. @"Failed mark persistence directory as excluded from backups",
  146. NSUnderlyingErrorKey : localError
  147. }];
  148. return NO;
  149. }
  150. return YES;
  151. }
  152. /** Opens the database within the given directory. */
  153. - (nullable DB *)createDBWithDirectory:(NSString *)directory error:(NSError **)error {
  154. Options options;
  155. options.create_if_missing = true;
  156. DB *database;
  157. Status status = DB::Open(options, [directory UTF8String], &database);
  158. if (!status.ok()) {
  159. if (error) {
  160. NSString *name = [directory lastPathComponent];
  161. *error =
  162. [FSTLevelDB errorWithStatus:status
  163. description:@"Failed to create database %@ at path %@", name, directory];
  164. }
  165. return nullptr;
  166. }
  167. return database;
  168. }
  169. #pragma mark - Persistence Factory methods
  170. - (id<FSTMutationQueue>)mutationQueueForUser:(const User &)user {
  171. return [FSTLevelDBMutationQueue mutationQueueWithUser:user db:_ptr serializer:self.serializer];
  172. }
  173. - (id<FSTQueryCache>)queryCache {
  174. return [[FSTLevelDBQueryCache alloc] initWithDB:_ptr serializer:self.serializer];
  175. }
  176. - (id<FSTRemoteDocumentCache>)remoteDocumentCache {
  177. return [[FSTLevelDBRemoteDocumentCache alloc] initWithDB:_ptr serializer:self.serializer];
  178. }
  179. - (FSTWriteGroup *)startGroupWithAction:(NSString *)action {
  180. return [self.writeGroupTracker startGroupWithAction:action];
  181. }
  182. - (void)commitGroup:(FSTWriteGroup *)group {
  183. [self.writeGroupTracker endGroup:group];
  184. NSString *description = [group description];
  185. FSTLog(@"Committing %@", description);
  186. Status status = [group writeToDB:_ptr];
  187. if (!status.ok()) {
  188. FSTFail(@"%@ failed with status: %s, description: %@", group.action, status.ToString().c_str(),
  189. description);
  190. }
  191. }
  192. - (void)shutdown {
  193. FSTAssert(self.isStarted, @"FSTLevelDB shutdown without start!");
  194. self.started = NO;
  195. _ptr.reset();
  196. }
  197. #pragma mark - Error and Status
  198. + (nullable NSError *)errorWithStatus:(Status)status description:(NSString *)description, ... {
  199. if (status.ok()) {
  200. return nil;
  201. }
  202. va_list args;
  203. va_start(args, description);
  204. NSString *message = [[NSString alloc] initWithFormat:description arguments:args];
  205. NSString *reason = [self descriptionOfStatus:status];
  206. NSError *result = [NSError errorWithDomain:FIRFirestoreErrorDomain
  207. code:FIRFirestoreErrorCodeInternal
  208. userInfo:@{
  209. NSLocalizedDescriptionKey : message,
  210. NSLocalizedFailureReasonErrorKey : reason
  211. }];
  212. va_end(args);
  213. return result;
  214. }
  215. + (NSString *)descriptionOfStatus:(Status)status {
  216. return [NSString stringWithCString:status.ToString().c_str() encoding:NSUTF8StringEncoding];
  217. }
  218. @end
  219. NS_ASSUME_NONNULL_END