aboutsummaryrefslogtreecommitdiffhomepage
path: root/Firestore/Source/Local/FSTLevelDB.mm
blob: bc2f2ebcf12430d1dff516792df0cf282ba18f74 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/*
 * Copyright 2017 Google
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#import "Firestore/Source/Local/FSTLevelDB.h"

#include <memory>

#import "FIRFirestoreErrors.h"
#import "Firestore/Source/Local/FSTLevelDBMigrations.h"
#import "Firestore/Source/Local/FSTLevelDBMutationQueue.h"
#import "Firestore/Source/Local/FSTLevelDBQueryCache.h"
#import "Firestore/Source/Local/FSTLevelDBRemoteDocumentCache.h"
#import "Firestore/Source/Remote/FSTSerializerBeta.h"
#import "Firestore/Source/Util/FSTAssert.h"
#import "Firestore/Source/Util/FSTLogger.h"

#include "Firestore/core/src/firebase/firestore/auth/user.h"
#include "Firestore/core/src/firebase/firestore/core/database_info.h"
#include "Firestore/core/src/firebase/firestore/local/leveldb_transaction.h"
#include "Firestore/core/src/firebase/firestore/model/database_id.h"
#include "Firestore/core/src/firebase/firestore/util/string_apple.h"
#include "absl/memory/memory.h"
#include "leveldb/db.h"

namespace util = firebase::firestore::util;
using firebase::firestore::auth::User;
using firebase::firestore::core::DatabaseInfo;
using firebase::firestore::model::DatabaseId;

NS_ASSUME_NONNULL_BEGIN

static NSString *const kReservedPathComponent = @"firestore";

using firebase::firestore::local::LevelDbTransaction;
using leveldb::DB;
using leveldb::Options;
using leveldb::ReadOptions;
using leveldb::Status;
using leveldb::WriteOptions;

@interface FSTLevelDB ()

@property(nonatomic, copy) NSString *directory;
@property(nonatomic, assign, getter=isStarted) BOOL started;
@property(nonatomic, strong, readonly) FSTLocalSerializer *serializer;

@end

@implementation FSTLevelDB {
  std::unique_ptr<LevelDbTransaction> _transaction;
  FSTTransactionRunner _transactionRunner;
}

/**
 * For now this is paranoid, but perhaps disable that in production builds.
 */
+ (const ReadOptions)standardReadOptions {
  ReadOptions options;
  options.verify_checksums = true;
  return options;
}

- (instancetype)initWithDirectory:(NSString *)directory
                       serializer:(FSTLocalSerializer *)serializer {
  if (self = [super init]) {
    _directory = [directory copy];
    _serializer = serializer;
    _transactionRunner.SetBackingPersistence(self);
  }
  return self;
}

- (const FSTTransactionRunner &)run {
  return _transactionRunner;
}

+ (NSString *)documentsDirectory {
#if TARGET_OS_IPHONE
  NSArray<NSString *> *directories =
      NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  return [directories[0] stringByAppendingPathComponent:kReservedPathComponent];

#elif TARGET_OS_MAC
  NSString *dotPrefixed = [@"." stringByAppendingString:kReservedPathComponent];
  return [NSHomeDirectory() stringByAppendingPathComponent:dotPrefixed];

#else
#error "local storage on tvOS"
  // TODO(mcg): Writing to NSDocumentsDirectory on tvOS will fail; we need to write to Caches
  // https://developer.apple.com/library/content/documentation/General/Conceptual/AppleTV_PG/

#endif
}

+ (NSString *)storageDirectoryForDatabaseInfo:(const DatabaseInfo &)databaseInfo
                           documentsDirectory:(NSString *)documentsDirectory {
  // Use two different path formats:
  //
  //   * persistenceKey / projectID . databaseID / name
  //   * persistenceKey / projectID / name
  //
  // projectIDs are DNS-compatible names and cannot contain dots so there's
  // no danger of collisions.
  NSString *directory = documentsDirectory;
  directory = [directory
      stringByAppendingPathComponent:util::WrapNSStringNoCopy(databaseInfo.persistence_key())];

  NSString *segment = util::WrapNSStringNoCopy(databaseInfo.database_id().project_id());
  if (!databaseInfo.database_id().IsDefaultDatabase()) {
    segment = [NSString
        stringWithFormat:@"%@.%s", segment, databaseInfo.database_id().database_id().c_str()];
  }
  directory = [directory stringByAppendingPathComponent:segment];

  // Reserve one additional path component to allow multiple physical databases
  directory = [directory stringByAppendingPathComponent:@"main"];
  return directory;
}

#pragma mark - Startup

- (BOOL)start:(NSError **)error {
  FSTAssert(!self.isStarted, @"FSTLevelDB double-started!");
  self.started = YES;
  NSString *directory = self.directory;
  if (![self ensureDirectory:directory error:error]) {
    return NO;
  }

  DB *database = [self createDBWithDirectory:directory error:error];
  if (!database) {
    return NO;
  }
  _ptr.reset(database);
  LevelDbTransaction transaction(_ptr.get(), "Start LevelDB");
  [FSTLevelDBMigrations runMigrationsWithTransaction:&transaction];
  transaction.Commit();
  return YES;
}

/** Creates the directory at @a directory and marks it as excluded from iCloud backup. */
- (BOOL)ensureDirectory:(NSString *)directory error:(NSError **)error {
  NSError *localError;
  NSFileManager *files = [NSFileManager defaultManager];

  BOOL success = [files createDirectoryAtPath:directory
                  withIntermediateDirectories:YES
                                   attributes:nil
                                        error:&localError];
  if (!success) {
    *error =
        [NSError errorWithDomain:FIRFirestoreErrorDomain
                            code:FIRFirestoreErrorCodeInternal
                        userInfo:@{
                          NSLocalizedDescriptionKey : @"Failed to create persistence directory",
                          NSUnderlyingErrorKey : localError
                        }];
    return NO;
  }

  NSURL *dirURL = [NSURL fileURLWithPath:directory];
  success = [dirURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:&localError];
  if (!success) {
    *error = [NSError errorWithDomain:FIRFirestoreErrorDomain
                                 code:FIRFirestoreErrorCodeInternal
                             userInfo:@{
                               NSLocalizedDescriptionKey :
                                   @"Failed mark persistence directory as excluded from backups",
                               NSUnderlyingErrorKey : localError
                             }];
    return NO;
  }

  return YES;
}

/** Opens the database within the given directory. */
- (nullable DB *)createDBWithDirectory:(NSString *)directory error:(NSError **)error {
  Options options;
  options.create_if_missing = true;

  DB *database;
  Status status = DB::Open(options, [directory UTF8String], &database);
  if (!status.ok()) {
    if (error) {
      NSString *name = [directory lastPathComponent];
      *error =
          [FSTLevelDB errorWithStatus:status
                          description:@"Failed to create database %@ at path %@", name, directory];
    }
    return nullptr;
  }

  return database;
}

- (LevelDbTransaction *)currentTransaction {
  FSTAssert(_transaction != nullptr, @"Attempting to access transaction before one has started");
  return _transaction.get();
}

#pragma mark - Persistence Factory methods

- (id<FSTMutationQueue>)mutationQueueForUser:(const User &)user {
  return [FSTLevelDBMutationQueue mutationQueueWithUser:user db:self serializer:self.serializer];
}

- (id<FSTQueryCache>)queryCache {
  return [[FSTLevelDBQueryCache alloc] initWithDB:self serializer:self.serializer];
}

- (id<FSTRemoteDocumentCache>)remoteDocumentCache {
  return [[FSTLevelDBRemoteDocumentCache alloc] initWithDB:self serializer:self.serializer];
}

- (void)startTransaction:(absl::string_view)label {
  FSTAssert(_transaction == nullptr, @"Starting a transaction while one is already outstanding");
  _transaction = absl::make_unique<LevelDbTransaction>(_ptr.get(), label);
}

- (void)commitTransaction {
  FSTAssert(_transaction != nullptr, @"Committing a transaction before one is started");
  _transaction->Commit();
  _transaction.reset();
}

- (void)shutdown {
  FSTAssert(self.isStarted, @"FSTLevelDB shutdown without start!");
  self.started = NO;
  _ptr.reset();
}

- (_Nullable id<FSTReferenceDelegate>)referenceDelegate {
  return nil;
}

#pragma mark - Error and Status

+ (nullable NSError *)errorWithStatus:(Status)status description:(NSString *)description, ... {
  if (status.ok()) {
    return nil;
  }

  va_list args;
  va_start(args, description);

  NSString *message = [[NSString alloc] initWithFormat:description arguments:args];
  NSString *reason = [self descriptionOfStatus:status];
  NSError *result = [NSError errorWithDomain:FIRFirestoreErrorDomain
                                        code:FIRFirestoreErrorCodeInternal
                                    userInfo:@{
                                      NSLocalizedDescriptionKey : message,
                                      NSLocalizedFailureReasonErrorKey : reason
                                    }];

  va_end(args);

  return result;
}

+ (NSString *)descriptionOfStatus:(Status)status {
  return [NSString stringWithCString:status.ToString().c_str() encoding:NSUTF8StringEncoding];
}

@end

NS_ASSUME_NONNULL_END