FLevelDBStorageEngine.m 42 KB

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