FLevelDBStorageEngine.m 42 KB

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