FLevelDBStorageEngine.m 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  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 <Foundation/Foundation.h>
  17. #import "FirebaseDatabase/Sources/Persistence/FLevelDBStorageEngine.h"
  18. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  19. #import "FirebaseDatabase/Sources/Core/FQueryParams.h"
  20. #import "FirebaseDatabase/Sources/Core/FWriteRecord.h"
  21. #import "FirebaseDatabase/Sources/Persistence/FPendingPut.h"
  22. #import "FirebaseDatabase/Sources/Persistence/FPruneForest.h"
  23. #import "FirebaseDatabase/Sources/Persistence/FTrackedQuery.h"
  24. #import "FirebaseDatabase/Sources/Snapshot/FEmptyNode.h"
  25. #import "FirebaseDatabase/Sources/Snapshot/FSnapshotUtilities.h"
  26. #import "FirebaseDatabase/Sources/Utilities/FUtilities.h"
  27. #import "FirebaseDatabase/Sources/third_party/Wrap-leveldb/APLevelDB.h"
  28. @interface FLevelDBStorageEngine ()
  29. @property(nonatomic, strong) NSString *basePath;
  30. @property(nonatomic, strong) APLevelDB *writesDB;
  31. @property(nonatomic, strong) APLevelDB *serverCacheDB;
  32. @end
  33. // WARNING: If you change this, you need to write a migration script
  34. static NSString *const kFPersistenceVersion = @"1";
  35. static NSString *const kFServerDBPath = @"server_data";
  36. static NSString *const kFWritesDBPath = @"writes";
  37. static NSString *const kFUserWriteId = @"id";
  38. static NSString *const kFUserWritePath = @"path";
  39. static NSString *const kFUserWriteOverwrite = @"o";
  40. static NSString *const kFUserWriteMerge = @"m";
  41. static NSString *const kFTrackedQueryId = @"id";
  42. static NSString *const kFTrackedQueryPath = @"path";
  43. static NSString *const kFTrackedQueryParams = @"p";
  44. static NSString *const kFTrackedQueryLastUse = @"lu";
  45. static NSString *const kFTrackedQueryIsComplete = @"c";
  46. static NSString *const kFTrackedQueryIsActive = @"a";
  47. static NSString *const kFServerCachePrefix = @"/server_cache/";
  48. // '~' is the last non-control character in the ASCII table until 127
  49. // We wan't the entire range of thing stored in the DB
  50. static NSString *const kFServerCacheRangeEnd = @"/server_cache~";
  51. static NSString *const kFTrackedQueriesPrefix = @"/tracked_queries/";
  52. static NSString *const kFTrackedQueryKeysPrefix = @"/tracked_query_keys/";
  53. // Failed to load JSON because a valid JSON turns out to be NaN while
  54. // deserializing
  55. static const NSInteger kFNanFailureCode = 3840;
  56. static NSString *writeRecordKey(NSUInteger writeId) {
  57. return [NSString stringWithFormat:@"%lu", (unsigned long)(writeId)];
  58. }
  59. static NSString *serverCacheKey(FPath *path) {
  60. return [NSString stringWithFormat:@"%@%@", kFServerCachePrefix,
  61. ([path toStringWithTrailingSlash])];
  62. }
  63. static NSString *trackedQueryKey(NSUInteger trackedQueryId) {
  64. return [NSString stringWithFormat:@"%@%lu", kFTrackedQueriesPrefix,
  65. (unsigned long)trackedQueryId];
  66. }
  67. static NSString *trackedQueryKeysKeyPrefix(NSUInteger trackedQueryId) {
  68. return [NSString stringWithFormat:@"%@%lu/", kFTrackedQueryKeysPrefix,
  69. (unsigned long)trackedQueryId];
  70. }
  71. static NSString *trackedQueryKeysKey(NSUInteger trackedQueryId, NSString *key) {
  72. return [NSString stringWithFormat:@"%@%lu/%@", kFTrackedQueryKeysPrefix,
  73. (unsigned long)trackedQueryId, key];
  74. }
  75. @implementation FLevelDBStorageEngine
  76. #pragma mark - Constructors
  77. - (id)initWithPath:(NSString *)dbPath {
  78. self = [super init];
  79. if (self) {
  80. self.basePath = [[FLevelDBStorageEngine firebaseDir]
  81. stringByAppendingPathComponent:dbPath];
  82. /* For reference:
  83. serverDataDB = [aPersistence createDbByName:@"server_data"];
  84. FPangolinDB *completenessDb = [aPersistence
  85. createDbByName:@"server_complete"];
  86. */
  87. [FLevelDBStorageEngine ensureDir:self.basePath markAsDoNotBackup:YES];
  88. [self runMigration];
  89. [self openDatabases];
  90. }
  91. return self;
  92. }
  93. - (void)runMigration {
  94. // Currently we're at version 1, so all we need to do is write that to a
  95. // file
  96. NSString *versionFile =
  97. [self.basePath stringByAppendingPathComponent:@"version"];
  98. NSError *error;
  99. NSString *oldVersion =
  100. [NSString stringWithContentsOfFile:versionFile
  101. encoding:NSUTF8StringEncoding
  102. error:&error];
  103. if (!oldVersion) {
  104. // This is probably fine, we don't have a version file yet
  105. BOOL success = [kFPersistenceVersion writeToFile:versionFile
  106. atomically:NO
  107. encoding:NSUTF8StringEncoding
  108. error:&error];
  109. if (!success) {
  110. FFWarn(@"I-RDB076001", @"Failed to write version for database: %@",
  111. error);
  112. }
  113. } else if ([oldVersion isEqualToString:kFPersistenceVersion]) {
  114. // Everythings fine no need for migration
  115. } else if ([oldVersion length] == 0) {
  116. FFWarn(@"I-RDB076036",
  117. @"Version file empty. Assuming database version 1.");
  118. } else {
  119. // If we add more versions in the future, we need to run migration here
  120. [NSException raise:NSInternalInconsistencyException
  121. format:@"Unrecognized database version: %@", oldVersion];
  122. }
  123. }
  124. - (void)runLegacyMigration:(FRepoInfo *)info {
  125. NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(
  126. NSDocumentDirectory, NSUserDomainMask, YES);
  127. NSString *documentsDir = [dirPaths objectAtIndex:0];
  128. NSString *firebaseDir =
  129. [documentsDir stringByAppendingPathComponent:@"firebase"];
  130. NSString *repoHashString =
  131. [NSString stringWithFormat:@"%@_%@", info.host, info.namespace];
  132. NSString *legacyBaseDir =
  133. [NSString stringWithFormat:@"%@/1/%@/v1", firebaseDir, repoHashString];
  134. if ([[NSFileManager defaultManager] fileExistsAtPath:legacyBaseDir]) {
  135. FFWarn(@"I-RDB076002", @"Legacy database found, migrating...");
  136. // We only need to migrate writes
  137. NSError *error = nil;
  138. APLevelDB *writes = [APLevelDB
  139. levelDBWithPath:[legacyBaseDir stringByAppendingPathComponent:
  140. @"outstanding_puts"]
  141. error:&error];
  142. if (writes != nil) {
  143. __block NSUInteger numberOfWritesRestored = 0;
  144. // Maybe we could use write batches, but what the heck, I'm sure
  145. // it'll go fine :P
  146. [writes enumerateKeysAndValuesAsData:^(NSString *key, NSData *data,
  147. BOOL *stop) {
  148. #pragma clang diagnostic push
  149. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  150. // Update the deprecated API when minimum iOS version is 11+.
  151. id pendingPut = [NSKeyedUnarchiver unarchiveObjectWithData:data];
  152. #pragma clang diagnostic pop
  153. if ([pendingPut isKindOfClass:[FPendingPut class]]) {
  154. FPendingPut *put = pendingPut;
  155. id<FNode> newNode =
  156. [FSnapshotUtilities nodeFrom:put.data
  157. priority:put.priority];
  158. [self saveUserOverwrite:newNode
  159. atPath:put.path
  160. writeId:[key integerValue]];
  161. numberOfWritesRestored++;
  162. } else if ([pendingPut
  163. isKindOfClass:[FPendingPutPriority class]]) {
  164. // This is for backwards compatibility. Older clients will
  165. // save FPendingPutPriority. New ones will need to read it and
  166. // translate.
  167. FPendingPutPriority *putPriority = pendingPut;
  168. FPath *priorityPath =
  169. [putPriority.path childFromString:@".priority"];
  170. id<FNode> newNode =
  171. [FSnapshotUtilities nodeFrom:putPriority.priority
  172. priority:nil];
  173. [self saveUserOverwrite:newNode
  174. atPath:priorityPath
  175. writeId:[key integerValue]];
  176. numberOfWritesRestored++;
  177. } else if ([pendingPut isKindOfClass:[FPendingUpdate class]]) {
  178. FPendingUpdate *update = pendingPut;
  179. FCompoundWrite *merge = [FCompoundWrite
  180. compoundWriteWithValueDictionary:update.data];
  181. [self saveUserMerge:merge
  182. atPath:update.path
  183. writeId:[key integerValue]];
  184. numberOfWritesRestored++;
  185. } else {
  186. FFWarn(@"I-RDB076003",
  187. @"Failed to migrate legacy write, meh!");
  188. }
  189. }];
  190. FFWarn(@"I-RDB076004", @"Migrated %lu writes",
  191. (unsigned long)numberOfWritesRestored);
  192. [writes close];
  193. FFWarn(@"I-RDB076005", @"Deleting legacy database...");
  194. BOOL success =
  195. [[NSFileManager defaultManager] removeItemAtPath:legacyBaseDir
  196. error:&error];
  197. if (!success) {
  198. FFWarn(@"I-RDB076006", @"Failed to delete legacy database: %@",
  199. error);
  200. } else {
  201. FFWarn(@"I-RDB076007", @"Finished migrating legacy database.");
  202. }
  203. } else {
  204. FFWarn(@"I-RDB076008", @"Failed to migrate old database: %@",
  205. error);
  206. }
  207. }
  208. }
  209. - (void)openDatabases {
  210. self.serverCacheDB = [self createDB:kFServerDBPath];
  211. self.writesDB = [self createDB:kFWritesDBPath];
  212. }
  213. - (void)purgeDatabase:(NSString *)dbPath {
  214. NSString *path = [self.basePath stringByAppendingPathComponent:dbPath];
  215. NSError *error;
  216. FFWarn(@"I-RDB076009", @"Deleting database at path %@", path);
  217. BOOL success = [[NSFileManager defaultManager] removeItemAtPath:path
  218. error:&error];
  219. if (!success) {
  220. [NSException raise:NSInternalInconsistencyException
  221. format:@"Failed to delete database files: %@", error];
  222. }
  223. }
  224. - (void)purgeEverything {
  225. [self close];
  226. [@[ kFServerDBPath, kFWritesDBPath ]
  227. enumerateObjectsUsingBlock:^(NSString *dbPath, NSUInteger idx,
  228. BOOL *stop) {
  229. [self purgeDatabase:dbPath];
  230. }];
  231. [self openDatabases];
  232. }
  233. - (void)close {
  234. // autoreleasepool will cause deallocation which will close the DB
  235. @autoreleasepool {
  236. [self.serverCacheDB close];
  237. self.serverCacheDB = nil;
  238. [self.writesDB close];
  239. self.writesDB = nil;
  240. }
  241. }
  242. + (NSString *)firebaseDir {
  243. #if TARGET_OS_IOS || TARGET_OS_TV
  244. NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(
  245. NSDocumentDirectory, NSUserDomainMask, YES);
  246. NSString *documentsDir = [dirPaths objectAtIndex:0];
  247. return [documentsDir stringByAppendingPathComponent:@"firebase"];
  248. #elif TARGET_OS_OSX
  249. return [NSHomeDirectory() stringByAppendingPathComponent:@".firebase"];
  250. #endif
  251. }
  252. - (APLevelDB *)createDB:(NSString *)dbName {
  253. NSError *err = nil;
  254. NSString *path = [self.basePath stringByAppendingPathComponent:dbName];
  255. APLevelDB *db = [APLevelDB levelDBWithPath:path error:&err];
  256. if (err) {
  257. FFWarn(@"I-RDB076036",
  258. @"Failed to read database persistence file '%@': %@", dbName,
  259. [err localizedDescription]);
  260. err = nil;
  261. // Delete the database and try again.
  262. [self purgeDatabase:dbName];
  263. db = [APLevelDB levelDBWithPath:path error:&err];
  264. if (err) {
  265. NSString *reason = [NSString
  266. stringWithFormat:@"Error initializing persistence: %@",
  267. [err description]];
  268. @throw [NSException
  269. exceptionWithName:@"FirebaseDatabasePersistenceFailure"
  270. reason:reason
  271. userInfo:nil];
  272. }
  273. }
  274. return db;
  275. }
  276. - (void)saveUserOverwrite:(id<FNode>)node
  277. atPath:(FPath *)path
  278. writeId:(NSUInteger)writeId {
  279. NSDictionary *write = @{
  280. kFUserWriteId : @(writeId),
  281. kFUserWritePath : [path toStringWithTrailingSlash],
  282. kFUserWriteOverwrite : [node valForExport:YES]
  283. };
  284. NSError *error = nil;
  285. NSData *data = [NSJSONSerialization dataWithJSONObject:write
  286. options:0
  287. error:&error];
  288. NSAssert(data, @"Failed to serialize user overwrite: %@, (Error: %@)",
  289. write, error);
  290. [self.writesDB setData:data forKey:writeRecordKey(writeId)];
  291. }
  292. - (void)saveUserMerge:(FCompoundWrite *)merge
  293. atPath:(FPath *)path
  294. writeId:(NSUInteger)writeId {
  295. NSDictionary *write = @{
  296. kFUserWriteId : @(writeId),
  297. kFUserWritePath : [path toStringWithTrailingSlash],
  298. kFUserWriteMerge : [merge valForExport:YES]
  299. };
  300. NSError *error = nil;
  301. NSData *data = [NSJSONSerialization dataWithJSONObject:write
  302. options:0
  303. error:&error];
  304. NSAssert(data, @"Failed to serialize user merge: %@ (Error: %@)", write,
  305. error);
  306. [self.writesDB setData:data forKey:writeRecordKey(writeId)];
  307. }
  308. - (void)removeUserWrite:(NSUInteger)writeId {
  309. [self.writesDB removeKey:writeRecordKey(writeId)];
  310. }
  311. - (void)removeAllUserWrites {
  312. __block NSUInteger count = 0;
  313. NSDate *start = [NSDate date];
  314. id<APLevelDBWriteBatch> batch = [self.writesDB beginWriteBatch];
  315. [self.writesDB enumerateKeys:^(NSString *key, BOOL *stop) {
  316. [batch removeKey:key];
  317. count++;
  318. }];
  319. BOOL success = [batch commit];
  320. if (!success) {
  321. FFWarn(@"I-RDB076010", @"Failed to remove all users writes on disk!");
  322. } else {
  323. FFDebug(@"I-RDB076011", @"Removed %lu writes in %fms",
  324. (unsigned long)count, [start timeIntervalSinceNow] * -1000);
  325. }
  326. }
  327. - (NSArray *)userWrites {
  328. NSDate *date = [NSDate date];
  329. NSMutableArray *writes = [NSMutableArray array];
  330. [self.writesDB enumerateKeysAndValuesAsData:^(NSString *key, NSData *data,
  331. BOOL *stop) {
  332. NSError *error = nil;
  333. NSDictionary *writeJSON = [NSJSONSerialization JSONObjectWithData:data
  334. options:0
  335. error:&error];
  336. if (writeJSON == nil) {
  337. if (error.code == kFNanFailureCode) {
  338. FFWarn(@"I-RDB076012",
  339. @"Failed to deserialize write (%@), likely because of out "
  340. @"of range doubles (Error: %@)",
  341. [[NSString alloc] initWithData:data
  342. encoding:NSUTF8StringEncoding],
  343. error);
  344. FFWarn(@"I-RDB076013", @"Removing failed write with key %@", key);
  345. [self.writesDB removeKey:key];
  346. } else {
  347. [NSException raise:NSInternalInconsistencyException
  348. format:@"Failed to deserialize write: %@", error];
  349. }
  350. } else {
  351. NSInteger writeId =
  352. ((NSNumber *)writeJSON[kFUserWriteId]).integerValue;
  353. FPath *path = [FPath pathWithString:writeJSON[kFUserWritePath]];
  354. FWriteRecord *writeRecord;
  355. if (writeJSON[kFUserWriteMerge] != nil) {
  356. // It's a merge
  357. FCompoundWrite *merge = [FCompoundWrite
  358. compoundWriteWithValueDictionary:writeJSON[kFUserWriteMerge]];
  359. writeRecord = [[FWriteRecord alloc] initWithPath:path
  360. merge:merge
  361. writeId:writeId];
  362. } else {
  363. // It's an overwrite
  364. NSAssert(writeJSON[kFUserWriteOverwrite] != nil,
  365. @"Persisted write did not contain merge or overwrite!");
  366. id<FNode> node =
  367. [FSnapshotUtilities nodeFrom:writeJSON[kFUserWriteOverwrite]];
  368. writeRecord = [[FWriteRecord alloc] initWithPath:path
  369. overwrite:node
  370. writeId:writeId
  371. visible:YES];
  372. }
  373. [writes addObject:writeRecord];
  374. }
  375. }];
  376. // Make sure writes are sorted
  377. [writes sortUsingComparator:^NSComparisonResult(FWriteRecord *one,
  378. FWriteRecord *two) {
  379. if (one.writeId < two.writeId) {
  380. return NSOrderedAscending;
  381. } else if (one.writeId > two.writeId) {
  382. return NSOrderedDescending;
  383. } else {
  384. return NSOrderedSame;
  385. }
  386. }];
  387. FFDebug(@"I-RDB076014", @"Loaded %lu writes in %fms",
  388. (unsigned long)writes.count, [date timeIntervalSinceNow] * -1000);
  389. return writes;
  390. }
  391. - (id<FNode>)serverCacheAtPath:(FPath *)path {
  392. NSDate *start = [NSDate date];
  393. id data = [self internalNestedDataForPath:path];
  394. id<FNode> node = [FSnapshotUtilities nodeFrom:data];
  395. FFDebug(@"I-RDB076015", @"Loaded node with %d children at %@ in %fms",
  396. [node numChildren], path, [start timeIntervalSinceNow] * -1000);
  397. return node;
  398. }
  399. - (id<FNode>)serverCacheForKeys:(NSSet *)keys atPath:(FPath *)path {
  400. NSDate *start = [NSDate date];
  401. __block id<FNode> node = [FEmptyNode emptyNode];
  402. [keys enumerateObjectsUsingBlock:^(NSString *key, BOOL *stop) {
  403. id data = [self internalNestedDataForPath:[path childFromString:key]];
  404. node = [node updateImmediateChild:key
  405. withNewChild:[FSnapshotUtilities nodeFrom:data]];
  406. }];
  407. FFDebug(@"I-RDB076016",
  408. @"Loaded node with %d children for %lu keys at %@ in %fms",
  409. [node numChildren], (unsigned long)keys.count, path,
  410. [start timeIntervalSinceNow] * -1000);
  411. return node;
  412. }
  413. - (void)updateServerCache:(id<FNode>)node
  414. atPath:(FPath *)path
  415. merge:(BOOL)merge {
  416. NSDate *start = [NSDate date];
  417. id<APLevelDBWriteBatch> batch = [self.serverCacheDB beginWriteBatch];
  418. // Remove any leaf nodes that might be higher up
  419. [self removeAllLeafNodesOnPath:path batch:batch];
  420. __block NSUInteger counter = 0;
  421. if (merge) {
  422. // remove any children that exist
  423. [node enumerateChildrenUsingBlock:^(NSString *childKey,
  424. id<FNode> childNode, BOOL *stop) {
  425. FPath *childPath = [path childFromString:childKey];
  426. [self removeAllWithPrefix:serverCacheKey(childPath)
  427. batch:batch
  428. database:self.serverCacheDB];
  429. [self saveNodeInternal:childNode
  430. atPath:childPath
  431. batch:batch
  432. counter:&counter];
  433. }];
  434. } else {
  435. // remove everything
  436. [self removeAllWithPrefix:serverCacheKey(path)
  437. batch:batch
  438. database:self.serverCacheDB];
  439. [self saveNodeInternal:node atPath:path batch:batch counter:&counter];
  440. }
  441. BOOL success = [batch commit];
  442. if (!success) {
  443. FFWarn(@"I-RDB076017", @"Failed to update server cache on disk!");
  444. } else {
  445. FFDebug(@"I-RDB076018", @"Saved %lu leaf nodes for overwrite in %fms",
  446. (unsigned long)counter, [start timeIntervalSinceNow] * -1000);
  447. }
  448. }
  449. - (void)updateServerCacheWithMerge:(FCompoundWrite *)merge
  450. atPath:(FPath *)path {
  451. NSDate *start = [NSDate date];
  452. __block NSUInteger counter = 0;
  453. id<APLevelDBWriteBatch> batch = [self.serverCacheDB beginWriteBatch];
  454. // Remove any leaf nodes that might be higher up
  455. [self removeAllLeafNodesOnPath:path batch:batch];
  456. [merge enumerateWrites:^(FPath *relativePath, id<FNode> node, BOOL *stop) {
  457. FPath *childPath = [path child:relativePath];
  458. [self removeAllWithPrefix:serverCacheKey(childPath)
  459. batch:batch
  460. database:self.serverCacheDB];
  461. [self saveNodeInternal:node
  462. atPath:childPath
  463. batch:batch
  464. counter:&counter];
  465. }];
  466. BOOL success = [batch commit];
  467. if (!success) {
  468. FFWarn(@"I-RDB076019", @"Failed to update server cache on disk!");
  469. } else {
  470. FFDebug(@"I-RDB076020", @"Saved %lu leaf nodes for merge in %fms",
  471. (unsigned long)counter, [start timeIntervalSinceNow] * -1000);
  472. }
  473. }
  474. - (void)saveNodeInternal:(id<FNode>)node
  475. atPath:(FPath *)path
  476. batch:(id<APLevelDBWriteBatch>)batch
  477. counter:(NSUInteger *)counter {
  478. id data = [node valForExport:YES];
  479. if (data != nil && ![data isKindOfClass:[NSNull class]]) {
  480. [self internalSetNestedData:data
  481. forKey:serverCacheKey(path)
  482. withBatch:batch
  483. counter:counter];
  484. }
  485. }
  486. - (NSUInteger)serverCacheEstimatedSizeInBytes {
  487. // Use the exact size, because for pruning the approximate size can lead to
  488. // weird situations where we prune everything because no compaction is ever
  489. // run
  490. return [self.serverCacheDB exactSizeFrom:kFServerCachePrefix
  491. to:kFServerCacheRangeEnd];
  492. }
  493. - (void)pruneCache:(FPruneForest *)pruneForest atPath:(FPath *)path {
  494. // TODO: be more intelligent, don't scan entire database...
  495. __block NSUInteger pruned = 0;
  496. __block NSUInteger kept = 0;
  497. NSDate *start = [NSDate date];
  498. NSString *prefix = serverCacheKey(path);
  499. id<APLevelDBWriteBatch> batch = [self.serverCacheDB beginWriteBatch];
  500. [self.serverCacheDB
  501. enumerateKeysWithPrefix:prefix
  502. usingBlock:^(NSString *dbKey, BOOL *stop) {
  503. NSString *pathStr =
  504. [dbKey substringFromIndex:prefix.length];
  505. FPath *relativePath = [[FPath alloc] initWith:pathStr];
  506. if ([pruneForest shouldPruneUnkeptDescendantsAtPath:
  507. relativePath]) {
  508. pruned++;
  509. [batch removeKey:dbKey];
  510. } else {
  511. kept++;
  512. }
  513. }];
  514. BOOL success = [batch commit];
  515. if (!success) {
  516. FFWarn(@"I-RDB076021", @"Failed to prune cache on disk!");
  517. } else {
  518. FFDebug(@"I-RDB076022", @"Pruned %lu paths, kept %lu paths in %fms",
  519. (unsigned long)pruned, (unsigned long)kept,
  520. [start timeIntervalSinceNow] * -1000);
  521. }
  522. }
  523. #pragma mark - Tracked Queries
  524. - (NSArray *)loadTrackedQueries {
  525. NSDate *date = [NSDate date];
  526. NSMutableArray *trackedQueries = [NSMutableArray array];
  527. [self.serverCacheDB
  528. enumerateKeysWithPrefix:kFTrackedQueriesPrefix
  529. asData:^(NSString *key, NSData *data, BOOL *stop) {
  530. NSError *error = nil;
  531. NSDictionary *queryJSON =
  532. [NSJSONSerialization JSONObjectWithData:data
  533. options:0
  534. error:&error];
  535. if (queryJSON == nil) {
  536. if (error.code == kFNanFailureCode) {
  537. FFWarn(
  538. @"I-RDB076023",
  539. @"Failed to deserialize tracked query "
  540. @"(%@), likely because of out of range "
  541. @"doubles (Error: %@)",
  542. [[NSString alloc]
  543. initWithData:data
  544. encoding:NSUTF8StringEncoding],
  545. error);
  546. FFWarn(@"I-RDB076024",
  547. @"Removing failed tracked query with "
  548. @"key %@",
  549. key);
  550. [self.serverCacheDB removeKey:key];
  551. } else {
  552. [NSException
  553. raise:NSInternalInconsistencyException
  554. format:@"Failed to deserialize tracked "
  555. @"query: %@",
  556. error];
  557. }
  558. } else {
  559. NSUInteger queryId =
  560. ((NSNumber *)queryJSON[kFTrackedQueryId])
  561. .unsignedIntegerValue;
  562. FPath *path =
  563. [FPath pathWithString:
  564. queryJSON[kFTrackedQueryPath]];
  565. FQueryParams *params = [FQueryParams
  566. fromQueryObject:queryJSON
  567. [kFTrackedQueryParams]];
  568. FQuerySpec *query =
  569. [[FQuerySpec alloc] initWithPath:path
  570. params:params];
  571. BOOL isComplete =
  572. [queryJSON[kFTrackedQueryIsComplete]
  573. boolValue];
  574. BOOL isActive =
  575. [queryJSON[kFTrackedQueryIsActive]
  576. boolValue];
  577. NSTimeInterval lastUse =
  578. [queryJSON[kFTrackedQueryLastUse]
  579. doubleValue];
  580. FTrackedQuery *trackedQuery =
  581. [[FTrackedQuery alloc]
  582. initWithId:queryId
  583. query:query
  584. lastUse:lastUse
  585. isActive:isActive
  586. isComplete:isComplete];
  587. [trackedQueries addObject:trackedQuery];
  588. }
  589. }];
  590. FFDebug(@"I-RDB076025", @"Loaded %lu tracked queries in %fms",
  591. (unsigned long)trackedQueries.count,
  592. [date timeIntervalSinceNow] * -1000);
  593. return trackedQueries;
  594. }
  595. - (void)removeTrackedQuery:(NSUInteger)queryId {
  596. NSDate *start = [NSDate date];
  597. id<APLevelDBWriteBatch> batch = [self.serverCacheDB beginWriteBatch];
  598. [batch removeKey:trackedQueryKey(queryId)];
  599. __block NSUInteger keyCount = 0;
  600. [self.serverCacheDB
  601. enumerateKeysWithPrefix:trackedQueryKeysKeyPrefix(queryId)
  602. usingBlock:^(NSString *key, BOOL *stop) {
  603. [batch removeKey:key];
  604. keyCount++;
  605. }];
  606. BOOL success = [batch commit];
  607. if (!success) {
  608. FFWarn(@"I-RDB076026", @"Failed to remove tracked query on disk!");
  609. } else {
  610. FFDebug(@"I-RDB076027",
  611. @"Removed query with id %lu (and removed %lu keys) in %fms",
  612. (unsigned long)queryId, (unsigned long)keyCount,
  613. [start timeIntervalSinceNow] * -1000);
  614. }
  615. }
  616. - (void)saveTrackedQuery:(FTrackedQuery *)query {
  617. NSDate *start = [NSDate date];
  618. NSDictionary *trackedQuery = @{
  619. kFTrackedQueryId : @(query.queryId),
  620. kFTrackedQueryPath : [query.query.path toStringWithTrailingSlash],
  621. kFTrackedQueryParams : [query.query.params wireProtocolParams],
  622. kFTrackedQueryLastUse : @(query.lastUse),
  623. kFTrackedQueryIsComplete : @(query.isComplete),
  624. kFTrackedQueryIsActive : @(query.isActive)
  625. };
  626. NSError *error = nil;
  627. NSData *data = [NSJSONSerialization dataWithJSONObject:trackedQuery
  628. options:0
  629. error:&error];
  630. NSAssert(data, @"Failed to serialize tracked query (Error: %@)", error);
  631. [self.serverCacheDB setData:data forKey:trackedQueryKey(query.queryId)];
  632. FFDebug(@"I-RDB076028", @"Saved tracked query %lu in %fms",
  633. (unsigned long)query.queryId, [start timeIntervalSinceNow] * -1000);
  634. }
  635. - (void)setTrackedQueryKeys:(NSSet *)keys forQueryId:(NSUInteger)queryId {
  636. NSDate *start = [NSDate date];
  637. __block NSUInteger removed = 0;
  638. __block NSUInteger added = 0;
  639. id<APLevelDBWriteBatch> batch = [self.serverCacheDB beginWriteBatch];
  640. NSMutableSet *seenKeys = [NSMutableSet set];
  641. // First, delete any keys that might be stored and are not part of the
  642. // current keys
  643. [self.serverCacheDB
  644. enumerateKeysWithPrefix:trackedQueryKeysKeyPrefix(queryId)
  645. asStrings:^(NSString *dbKey, NSString *actualKey,
  646. BOOL *stop) {
  647. if ([keys containsObject:actualKey]) {
  648. // Already in DB
  649. [seenKeys addObject:actualKey];
  650. } else {
  651. // Not part of set, delete key
  652. [batch removeKey:dbKey];
  653. removed++;
  654. }
  655. }];
  656. // Next add any keys that are missing in the database
  657. [keys enumerateObjectsUsingBlock:^(NSString *childKey, BOOL *stop) {
  658. if (![seenKeys containsObject:childKey]) {
  659. [batch setString:childKey
  660. forKey:trackedQueryKeysKey(queryId, childKey)];
  661. added++;
  662. }
  663. }];
  664. BOOL success = [batch commit];
  665. if (!success) {
  666. FFWarn(@"I-RDB076029", @"Failed to set tracked queries on disk!");
  667. } else {
  668. FFDebug(@"I-RDB076030",
  669. @"Set %lu tracked keys (%lu added, %lu removed) for query %lu "
  670. @"in %fms",
  671. (unsigned long)keys.count, (unsigned long)added,
  672. (unsigned long)removed, (unsigned long)queryId,
  673. [start timeIntervalSinceNow] * -1000);
  674. }
  675. }
  676. - (void)updateTrackedQueryKeysWithAddedKeys:(NSSet *)added
  677. removedKeys:(NSSet *)removed
  678. forQueryId:(NSUInteger)queryId {
  679. NSDate *start = [NSDate date];
  680. id<APLevelDBWriteBatch> batch = [self.serverCacheDB beginWriteBatch];
  681. [removed enumerateObjectsUsingBlock:^(NSString *key, BOOL *stop) {
  682. [batch removeKey:trackedQueryKeysKey(queryId, key)];
  683. }];
  684. [added enumerateObjectsUsingBlock:^(NSString *key, BOOL *stop) {
  685. [batch setString:key forKey:trackedQueryKeysKey(queryId, key)];
  686. }];
  687. BOOL success = [batch commit];
  688. if (!success) {
  689. FFWarn(@"I-RDB076031", @"Failed to update tracked queries on disk!");
  690. } else {
  691. FFDebug(@"I-RDB076032",
  692. @"Added %lu tracked keys, removed %lu for query %lu in %fms",
  693. (unsigned long)added.count, (unsigned long)removed.count,
  694. (unsigned long)queryId, [start timeIntervalSinceNow] * -1000);
  695. }
  696. }
  697. - (NSSet *)trackedQueryKeysForQuery:(NSUInteger)queryId {
  698. NSDate *start = [NSDate date];
  699. NSMutableSet *set = [NSMutableSet set];
  700. [self.serverCacheDB
  701. enumerateKeysWithPrefix:trackedQueryKeysKeyPrefix(queryId)
  702. asStrings:^(NSString *dbKey, NSString *actualKey,
  703. BOOL *stop) {
  704. [set addObject:actualKey];
  705. }];
  706. FFDebug(@"I-RDB076033", @"Loaded %lu tracked keys for query %lu in %fms",
  707. (unsigned long)set.count, (unsigned long)queryId,
  708. [start timeIntervalSinceNow] * -1000);
  709. return set;
  710. }
  711. #pragma mark - Internal methods
  712. - (void)removeAllLeafNodesOnPath:(FPath *)path
  713. batch:(id<APLevelDBWriteBatch>)batch {
  714. while (!path.isEmpty) {
  715. [batch removeKey:serverCacheKey(path)];
  716. path = [path parent];
  717. }
  718. // Make sure to delete any nodes at the root
  719. [batch removeKey:serverCacheKey([FPath empty])];
  720. }
  721. - (void)removeAllWithPrefix:(NSString *)prefix
  722. batch:(id<APLevelDBWriteBatch>)batch
  723. database:(APLevelDB *)database {
  724. assert(prefix != nil);
  725. [database enumerateKeysWithPrefix:prefix
  726. usingBlock:^(NSString *key, BOOL *stop) {
  727. [batch removeKey:key];
  728. }];
  729. }
  730. #pragma mark - Internal helper methods
  731. - (void)internalSetNestedData:(id)value
  732. forKey:(NSString *)key
  733. withBatch:(id<APLevelDBWriteBatch>)batch
  734. counter:(NSUInteger *)counter {
  735. if ([value isKindOfClass:[NSDictionary class]]) {
  736. NSDictionary *dictionary = value;
  737. [dictionary enumerateKeysAndObjectsUsingBlock:^(id childKey, id obj,
  738. BOOL *stop) {
  739. assert(obj != nil);
  740. NSString *childPath =
  741. [NSString stringWithFormat:@"%@%@/", key, childKey];
  742. [self internalSetNestedData:obj
  743. forKey:childPath
  744. withBatch:batch
  745. counter:counter];
  746. }];
  747. } else {
  748. NSData *data = [self serializePrimitive:value];
  749. [batch setData:data forKey:key];
  750. (*counter)++;
  751. }
  752. }
  753. - (id)internalNestedDataForPath:(FPath *)path {
  754. NSAssert(path != nil, @"Path was nil!");
  755. NSString *baseKey = serverCacheKey(path);
  756. // HACK to make sure iter is freed now to avoid race conditions (if self.db
  757. // is deleted before iter, you get an access violation).
  758. @autoreleasepool {
  759. APLevelDBIterator *iter =
  760. [APLevelDBIterator iteratorWithLevelDB:self.serverCacheDB];
  761. [iter seekToKey:baseKey];
  762. if (iter.key == nil || ![iter.key hasPrefix:baseKey]) {
  763. // No data.
  764. return nil;
  765. } else {
  766. return [self internalNestedDataFromIterator:iter
  767. andKeyPrefix:baseKey];
  768. }
  769. }
  770. }
  771. - (id)internalNestedDataFromIterator:(APLevelDBIterator *)iterator
  772. andKeyPrefix:(NSString *)prefix {
  773. NSString *key = iterator.key;
  774. if ([key isEqualToString:prefix]) {
  775. id result = [self deserializePrimitive:iterator.valueAsData];
  776. [iterator nextKey];
  777. return result;
  778. } else {
  779. NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
  780. while (key != nil && [key hasPrefix:prefix]) {
  781. NSString *relativePath = [key substringFromIndex:prefix.length];
  782. NSArray *pathPieces =
  783. [relativePath componentsSeparatedByString:@"/"];
  784. assert(pathPieces.count > 0);
  785. NSString *childName = pathPieces[0];
  786. NSString *childPath =
  787. [NSString stringWithFormat:@"%@%@/", prefix, childName];
  788. id childValue = [self internalNestedDataFromIterator:iterator
  789. andKeyPrefix:childPath];
  790. [dict setValue:childValue forKey:childName];
  791. key = iterator.key;
  792. }
  793. return dict;
  794. }
  795. }
  796. - (NSData *)serializePrimitive:(id)value {
  797. // HACK: The built-in serialization only works on dicts and arrays. So we
  798. // create an array and then strip off the leading / trailing byte (the [ and
  799. // ]).
  800. NSError *error = nil;
  801. NSData *data = [NSJSONSerialization dataWithJSONObject:@[ value ]
  802. options:0
  803. error:&error];
  804. NSAssert(data, @"Failed to serialize primitive: %@", error);
  805. return [data subdataWithRange:NSMakeRange(1, data.length - 2)];
  806. }
  807. - (id)fixDoubleParsing:(id)value
  808. __attribute__((no_sanitize("float-cast-overflow"))) {
  809. if ([value isKindOfClass:[NSDecimalNumber class]]) {
  810. // In case the value is an NSDecimalNumber, we may be dealing with
  811. // precisions that are higher than what can be represented in a double.
  812. // In this case it does not suffice to check for integral numbers by
  813. // casting the [value doubleValue] to an int64_t, because this will
  814. // cause the compared values to be rounded to double precision.
  815. // Coupled with a bug in [NSDecimalNumber longLongValue] that triggers
  816. // when converting values with high precision, this would cause
  817. // values of high precision, but with an integral 'doubleValue'
  818. // representation to be converted to bogus values.
  819. // A radar for the NSDecimalNumber issue can be found here:
  820. // http://www.openradar.me/radar?id=5007005597040640
  821. // Consider the NSDecimalNumber value: 999.9999999999999487
  822. // This number has a 'doubleValue' of 1000. Using the previous version
  823. // of this method would cause the value to be interpreted to be integral
  824. // and then the resulting value would be based on the longLongValue
  825. // which due to the NSDecimalNumber issue would turn out as -844.
  826. // By using NSDecimal logic to test for integral values,
  827. // 999.9999999999999487 will not be considered integral, and instead
  828. // of triggering the 'longLongValue' issue, it will be returned as
  829. // the 'doubleValue' representation (1000).
  830. // Please note, that even without the NSDecimalNumber issue, the
  831. // 'correct' longLongValue of 999.9999999999999487 is 999 and not 1000,
  832. // so the previous code would cause issues even without the bug
  833. // referenced in the radar.
  834. NSDecimal original = [(NSDecimalNumber *)value decimalValue];
  835. NSDecimal rounded;
  836. NSDecimalRound(&rounded, &original, 0, NSRoundPlain);
  837. if (NSDecimalCompare(&original, &rounded) != NSOrderedSame) {
  838. NSString *doubleString = [value stringValue];
  839. return [NSNumber numberWithDouble:[doubleString doubleValue]];
  840. } else {
  841. return [NSNumber numberWithLongLong:[value longLongValue]];
  842. }
  843. } else if ([value isKindOfClass:[NSNumber class]]) {
  844. // The parser for double values in JSONSerialization at the root takes
  845. // some short-cuts and delivers wrong results (wrong rounding) for some
  846. // double values, including 2.47. Because we use the exact bytes for
  847. // hashing on the server this will lead to hash mismatches. The parser
  848. // of NSNumber seems to be more in line with what the server expects, so
  849. // we use that here
  850. CFNumberType type = CFNumberGetType((CFNumberRef)value);
  851. if (type == kCFNumberDoubleType || type == kCFNumberFloatType) {
  852. // The NSJSON parser returns all numbers as double values, even
  853. // those that contain no exponent. To make sure that the String
  854. // conversion below doesn't unexpectedly reduce precision, we make
  855. // sure that our number is indeed not an integer.
  856. if ((double)(int64_t)[value doubleValue] != [value doubleValue]) {
  857. NSString *doubleString = [value stringValue];
  858. return [NSNumber numberWithDouble:[doubleString doubleValue]];
  859. } else {
  860. return [NSNumber numberWithLongLong:[value longLongValue]];
  861. }
  862. }
  863. }
  864. return value;
  865. }
  866. - (id)deserializePrimitive:(NSData *)data {
  867. NSError *error = nil;
  868. id result =
  869. [NSJSONSerialization JSONObjectWithData:data
  870. options:NSJSONReadingAllowFragments
  871. error:&error];
  872. if (result != nil) {
  873. return [self fixDoubleParsing:result];
  874. } else {
  875. if (error.code == kFNanFailureCode) {
  876. FFWarn(@"I-RDB076034",
  877. @"Failed to load primitive %@, likely because doubles where "
  878. @"out of range (Error: %@)",
  879. [[NSString alloc] initWithData:data
  880. encoding:NSUTF8StringEncoding],
  881. error);
  882. return [NSNull null];
  883. } else {
  884. [NSException raise:NSInternalInconsistencyException
  885. format:@"Failed to deserialiaze primitive: %@", error];
  886. return nil;
  887. }
  888. }
  889. }
  890. + (void)ensureDir:(NSString *)path markAsDoNotBackup:(BOOL)markAsDoNotBackup {
  891. NSError *error;
  892. BOOL success =
  893. [[NSFileManager defaultManager] createDirectoryAtPath:path
  894. withIntermediateDirectories:YES
  895. attributes:nil
  896. error:&error];
  897. if (!success) {
  898. @throw [NSException
  899. exceptionWithName:@"FailedToCreatePersistenceDir"
  900. reason:@"Failed to create persistence directory."
  901. userInfo:@{@"path" : path}];
  902. }
  903. if (markAsDoNotBackup) {
  904. NSURL *firebaseDirURL = [NSURL fileURLWithPath:path];
  905. success = [firebaseDirURL setResourceValue:@YES
  906. forKey:NSURLIsExcludedFromBackupKey
  907. error:&error];
  908. if (!success) {
  909. FFWarn(
  910. @"I-RDB076035",
  911. @"Failed to mark firebase database folder as do not backup: %@",
  912. error);
  913. [NSException raise:@"Error marking as do not backup"
  914. format:@"Failed to mark folder %@ as do not backup",
  915. firebaseDirURL];
  916. }
  917. }
  918. }
  919. @end