FLevelDBStorageEngine.m 42 KB

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