FLevelDBStorageEngine.m 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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 "FSnapshotUtilities.h"
  20. #import "FWriteRecord.h"
  21. #import "FTrackedQuery.h"
  22. #import "FQueryParams.h"
  23. #import "FEmptyNode.h"
  24. #import "FPruneForest.h"
  25. #import "FUtilities.h"
  26. #import "FPendingPut.h" // For legacy migration
  27. @interface FLevelDBStorageEngine ()
  28. @property (nonatomic, strong) NSString *basePath;
  29. @property (nonatomic, strong) APLevelDB *writesDB;
  30. @property (nonatomic, strong) APLevelDB *serverCacheDB;
  31. @end
  32. // WARNING: If you change this, you need to write a migration script
  33. static NSString * const kFPersistenceVersion = @"1";
  34. static NSString * const kFServerDBPath = @"server_data";
  35. static NSString * const kFWritesDBPath = @"writes";
  36. static NSString * const kFUserWriteId = @"id";
  37. static NSString * const kFUserWritePath = @"path";
  38. static NSString * const kFUserWriteOverwrite = @"o";
  39. static NSString * const kFUserWriteMerge = @"m";
  40. static NSString * const kFTrackedQueryId = @"id";
  41. static NSString * const kFTrackedQueryPath = @"path";
  42. static NSString * const kFTrackedQueryParams = @"p";
  43. static NSString * const kFTrackedQueryLastUse = @"lu";
  44. static NSString * const kFTrackedQueryIsComplete = @"c";
  45. static NSString * const kFTrackedQueryIsActive = @"a";
  46. static NSString * const kFServerCachePrefix = @"/server_cache/";
  47. // '~' is the last non-control character in the ASCII table until 127
  48. // We wan't the entire range of thing stored in the DB
  49. static NSString * const kFServerCacheRangeEnd = @"/server_cache~";
  50. static NSString * const kFTrackedQueriesPrefix = @"/tracked_queries/";
  51. static NSString * const kFTrackedQueryKeysPrefix = @"/tracked_query_keys/";
  52. // Failed to load JSON because a valid JSON turns out to be NaN while deserializing
  53. static const NSInteger kFNanFailureCode = 3840;
  54. static NSString* writeRecordKey(NSUInteger writeId) {
  55. return [NSString stringWithFormat:@"%lu", (unsigned long)(writeId)];
  56. }
  57. static NSString* serverCacheKey(FPath *path) {
  58. return [NSString stringWithFormat:@"%@%@", kFServerCachePrefix, ([path toStringWithTrailingSlash])];
  59. }
  60. static NSString* trackedQueryKey(NSUInteger trackedQueryId) {
  61. return [NSString stringWithFormat:@"%@%lu", kFTrackedQueriesPrefix, (unsigned long)trackedQueryId];
  62. }
  63. static NSString* trackedQueryKeysKeyPrefix(NSUInteger trackedQueryId) {
  64. return [NSString stringWithFormat:@"%@%lu/", kFTrackedQueryKeysPrefix, (unsigned long)trackedQueryId];
  65. }
  66. static NSString* trackedQueryKeysKey(NSUInteger trackedQueryId, NSString *key) {
  67. return [NSString stringWithFormat:@"%@%lu/%@", kFTrackedQueryKeysPrefix, (unsigned long)trackedQueryId, key];
  68. }
  69. @implementation FLevelDBStorageEngine
  70. #pragma mark - Constructors
  71. - (id)initWithPath:(NSString*)dbPath
  72. {
  73. self = [super init];
  74. if (self) {
  75. self.basePath = [[FLevelDBStorageEngine firebaseDir] stringByAppendingPathComponent:dbPath];
  76. /* For reference:
  77. serverDataDB = [aPersistence createDbByName:@"server_data"];
  78. FPangolinDB *completenessDb = [aPersistence createDbByName:@"server_complete"];
  79. */
  80. [FLevelDBStorageEngine ensureDir:self.basePath markAsDoNotBackup:YES];
  81. [self runMigration];
  82. [self openDatabases];
  83. }
  84. return self;
  85. }
  86. - (void)runMigration {
  87. // Currently we're at version 1, so all we need to do is write that to a file
  88. NSString *versionFile = [self.basePath stringByAppendingPathComponent:@"version"];
  89. NSError *error;
  90. NSString *oldVersion = [NSString stringWithContentsOfFile:versionFile encoding:NSUTF8StringEncoding error:&error];
  91. if (!oldVersion) {
  92. // This is probably fine, we don't have a version file yet
  93. BOOL success = [kFPersistenceVersion writeToFile:versionFile atomically:NO encoding:NSUTF8StringEncoding error:&error];
  94. if (!success) {
  95. FFWarn(@"I-RDB076001", @"Failed to write version for database: %@", error);
  96. }
  97. } else if ([oldVersion isEqualToString:kFPersistenceVersion]) {
  98. // Everythings fine no need for migration
  99. } else {
  100. // If we add more versions in the future, we need to run migration here
  101. [NSException raise:NSInternalInconsistencyException format:@"Unrecognized database version: %@", oldVersion];
  102. }
  103. }
  104. - (void)runLegacyMigration:(FRepoInfo *)info {
  105. NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  106. NSString *documentsDir = [dirPaths objectAtIndex:0];
  107. NSString *firebaseDir = [documentsDir stringByAppendingPathComponent:@"firebase"];
  108. NSString* repoHashString = [NSString stringWithFormat:@"%@_%@", info.host, info.namespace];
  109. NSString *legacyBaseDir = [NSString stringWithFormat:@"%@/1/%@/v1", firebaseDir, repoHashString];
  110. if ([[NSFileManager defaultManager] fileExistsAtPath:legacyBaseDir]) {
  111. FFWarn(@"I-RDB076002", @"Legacy database found, migrating...");
  112. // We only need to migrate writes
  113. NSError *error = nil;
  114. APLevelDB *writes = [APLevelDB levelDBWithPath:[legacyBaseDir stringByAppendingPathComponent:@"outstanding_puts"] error:&error];
  115. if (writes != nil) {
  116. __block NSUInteger numberOfWritesRestored = 0;
  117. // Maybe we could use write batches, but what the heck, I'm sure it'll go fine :P
  118. [writes enumerateKeysAndValuesAsData:^(NSString *key, NSData *data, BOOL *stop) {
  119. id pendingPut = [NSKeyedUnarchiver unarchiveObjectWithData:data];
  120. if ([pendingPut isKindOfClass:[FPendingPut class]]) {
  121. FPendingPut *put = pendingPut;
  122. id<FNode> newNode = [FSnapshotUtilities nodeFrom:put.data priority:put.priority];
  123. [self saveUserOverwrite:newNode atPath:put.path writeId:[key integerValue]];
  124. numberOfWritesRestored++;
  125. } else if ([pendingPut isKindOfClass:[FPendingPutPriority class]]) {
  126. // This is for backwards compatibility. Older clients will save FPendingPutPriority. New ones will need to read it and translate.
  127. FPendingPutPriority *putPriority = pendingPut;
  128. FPath *priorityPath = [putPriority.path childFromString:@".priority"];
  129. id<FNode> newNode = [FSnapshotUtilities nodeFrom:putPriority.priority priority:nil];
  130. [self saveUserOverwrite:newNode atPath:priorityPath writeId:[key integerValue]];
  131. numberOfWritesRestored++;
  132. } else if ([pendingPut isKindOfClass:[FPendingUpdate class]]) {
  133. FPendingUpdate *update = pendingPut;
  134. FCompoundWrite *merge = [FCompoundWrite compoundWriteWithValueDictionary:update.data];
  135. [self saveUserMerge:merge atPath:update.path writeId:[key integerValue]];
  136. numberOfWritesRestored++;
  137. } else {
  138. FFWarn(@"I-RDB076003", @"Failed to migrate legacy write, meh!");
  139. }
  140. }];
  141. FFWarn(@"I-RDB076004", @"Migrated %lu writes", (unsigned long)numberOfWritesRestored);
  142. [writes close];
  143. FFWarn(@"I-RDB076005", @"Deleting legacy database...");
  144. BOOL success = [[NSFileManager defaultManager] removeItemAtPath:legacyBaseDir error:&error];
  145. if (!success) {
  146. FFWarn(@"I-RDB076006", @"Failed to delete legacy database: %@", error);
  147. } else {
  148. FFWarn(@"I-RDB076007", @"Finished migrating legacy database.");
  149. }
  150. } else {
  151. FFWarn(@"I-RDB076008", @"Failed to migrate old database: %@", error);
  152. }
  153. }
  154. }
  155. - (void)openDatabases {
  156. self.serverCacheDB = [self createDB:kFServerDBPath];
  157. self.writesDB = [self createDB:kFWritesDBPath];
  158. }
  159. - (void)purgeEverything {
  160. [self close];
  161. [@[kFServerDBPath, kFWritesDBPath]
  162. enumerateObjectsUsingBlock:^(NSString *dbPath, NSUInteger idx, BOOL *stop) {
  163. NSString *path = [self.basePath stringByAppendingPathComponent:dbPath];
  164. NSError *error;
  165. FFDebug(@"I-RDB076009", @"Deleting database at path %@", path);
  166. BOOL success = [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
  167. if (!success) {
  168. [NSException raise:NSInternalInconsistencyException format:@"Failed to delete database files: %@", error];
  169. }
  170. }];
  171. [self openDatabases];
  172. }
  173. - (void)close {
  174. // autoreleasepool will cause deallocation which will close the DB
  175. @autoreleasepool {
  176. [self.serverCacheDB close];
  177. self.serverCacheDB = nil;
  178. [self.writesDB close];
  179. self.writesDB = nil;
  180. }
  181. }
  182. + (NSString *) firebaseDir {
  183. #if TARGET_OS_IOS
  184. NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  185. NSString *documentsDir = [dirPaths objectAtIndex:0];
  186. return [documentsDir stringByAppendingPathComponent:@"firebase"];
  187. #elif TARGET_OS_OSX
  188. return [NSHomeDirectory() stringByAppendingPathComponent:@".firebase"];
  189. #endif
  190. }
  191. - (APLevelDB *)createDB:(NSString *)name {
  192. NSError *err = nil;
  193. NSString *path = [self.basePath stringByAppendingPathComponent:name];
  194. APLevelDB *db = [APLevelDB levelDBWithPath:path error:&err];
  195. if(err) {
  196. NSString *reason = [NSString stringWithFormat:@"Error initializing persistence: %@", [err description]];
  197. @throw [NSException exceptionWithName:@"FirebaseDatabasePersistenceFailure" reason:reason userInfo:nil];
  198. }
  199. return db;
  200. }
  201. - (void)saveUserOverwrite:(id<FNode>)node atPath:(FPath *)path writeId:(NSUInteger)writeId {
  202. NSDictionary *write =
  203. @{ kFUserWriteId: @(writeId),
  204. kFUserWritePath: [path toStringWithTrailingSlash],
  205. kFUserWriteOverwrite: [node valForExport:YES] };
  206. NSError *error = nil;
  207. NSData *data = [NSJSONSerialization dataWithJSONObject:write options:0 error:&error];
  208. NSAssert(data, @"Failed to serialize user overwrite: %@, (Error: %@)", write, error);
  209. [self.writesDB setData:data forKey:writeRecordKey(writeId)];
  210. }
  211. - (void)saveUserMerge:(FCompoundWrite *)merge atPath:(FPath *)path writeId:(NSUInteger)writeId {
  212. NSDictionary *write =
  213. @{ kFUserWriteId: @(writeId),
  214. kFUserWritePath: [path toStringWithTrailingSlash],
  215. kFUserWriteMerge: [merge valForExport:YES] };
  216. NSError *error = nil;
  217. NSData *data = [NSJSONSerialization dataWithJSONObject:write options:0 error:&error];
  218. NSAssert(data, @"Failed to serialize user merge: %@ (Error: %@)", write, error);
  219. [self.writesDB setData:data forKey:writeRecordKey(writeId)];
  220. }
  221. - (void)removeUserWrite:(NSUInteger)writeId {
  222. [self.writesDB removeKey:writeRecordKey(writeId)];
  223. }
  224. - (void)removeAllUserWrites {
  225. __block NSUInteger count = 0;
  226. NSDate *start = [NSDate date];
  227. id<APLevelDBWriteBatch> batch = [self.writesDB beginWriteBatch];
  228. [self.writesDB enumerateKeys:^(NSString *key, BOOL *stop) {
  229. [batch removeKey:key];
  230. count++;
  231. }];
  232. BOOL success = [batch commit];
  233. if (!success) {
  234. FFWarn(@"I-RDB076010", @"Failed to remove all users writes on disk!");
  235. } else {
  236. FFDebug(@"I-RDB076011", @"Removed %lu writes in %fms", (unsigned long)count, [start timeIntervalSinceNow]*-1000);
  237. }
  238. }
  239. - (NSArray *)userWrites {
  240. NSDate *date = [NSDate date];
  241. NSMutableArray *writes = [NSMutableArray array];
  242. [self.writesDB enumerateKeysAndValuesAsData:^(NSString *key, NSData *data, BOOL *stop) {
  243. NSError *error = nil;
  244. NSDictionary *writeJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  245. if (writeJSON == nil) {
  246. if (error.code == kFNanFailureCode) {
  247. FFWarn(@"I-RDB076012", @"Failed to deserialize write (%@), likely because of out of range doubles (Error: %@)",
  248. [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding],
  249. error);
  250. FFWarn(@"I-RDB076013", @"Removing failed write with key %@", key);
  251. [self.writesDB removeKey:key];
  252. } else {
  253. [NSException raise:NSInternalInconsistencyException format:@"Failed to deserialize write: %@", error];
  254. }
  255. } else {
  256. NSInteger writeId = ((NSNumber *)writeJSON[kFUserWriteId]).integerValue;
  257. FPath *path = [FPath pathWithString:writeJSON[kFUserWritePath]];
  258. FWriteRecord *writeRecord;
  259. if (writeJSON[kFUserWriteMerge] != nil) {
  260. // It's a merge
  261. FCompoundWrite *merge = [FCompoundWrite compoundWriteWithValueDictionary:writeJSON[kFUserWriteMerge]];
  262. writeRecord = [[FWriteRecord alloc] initWithPath:path merge:merge writeId:writeId];
  263. } else {
  264. // It's an overwrite
  265. NSAssert(writeJSON[kFUserWriteOverwrite] != nil, @"Persisted write did not contain merge or overwrite!");
  266. id<FNode> node = [FSnapshotUtilities nodeFrom:writeJSON[kFUserWriteOverwrite]];
  267. writeRecord = [[FWriteRecord alloc] initWithPath:path overwrite:node writeId:writeId visible:YES];
  268. }
  269. [writes addObject:writeRecord];
  270. }
  271. }];
  272. // Make sure writes are sorted
  273. [writes sortUsingComparator:^NSComparisonResult(FWriteRecord *one, FWriteRecord *two) {
  274. if (one.writeId < two.writeId) {
  275. return NSOrderedAscending;
  276. } else if (one.writeId > two.writeId) {
  277. return NSOrderedDescending;
  278. } else {
  279. return NSOrderedSame;
  280. }
  281. }];
  282. FFDebug(@"I-RDB076014", @"Loaded %lu writes in %fms", (unsigned long)writes.count, [date timeIntervalSinceNow]*-1000);
  283. return writes;
  284. }
  285. - (id<FNode>)serverCacheAtPath:(FPath *)path {
  286. NSDate *start = [NSDate date];
  287. id data = [self internalNestedDataForPath:path];
  288. id<FNode> node = [FSnapshotUtilities nodeFrom:data];
  289. FFDebug(@"I-RDB076015", @"Loaded node with %d children at %@ in %fms", [node numChildren], path, [start timeIntervalSinceNow]*-1000);
  290. return node;
  291. }
  292. - (id<FNode>)serverCacheForKeys:(NSSet *)keys atPath:(FPath *)path {
  293. NSDate *start = [NSDate date];
  294. __block id<FNode> node = [FEmptyNode emptyNode];
  295. [keys enumerateObjectsUsingBlock:^(NSString *key, BOOL *stop) {
  296. id data = [self internalNestedDataForPath:[path childFromString:key]];
  297. node = [node updateImmediateChild:key withNewChild:[FSnapshotUtilities nodeFrom:data]];
  298. }];
  299. FFDebug(@"I-RDB076016", @"Loaded node with %d children for %lu keys at %@ in %fms", [node numChildren], (unsigned long)keys.count, path, [start timeIntervalSinceNow]*-1000);
  300. return node;
  301. }
  302. - (void)updateServerCache:(id<FNode>)node atPath:(FPath *)path merge:(BOOL)merge {
  303. NSDate *start = [NSDate date];
  304. id<APLevelDBWriteBatch> batch = [self.serverCacheDB beginWriteBatch];
  305. // Remove any leaf nodes that might be higher up
  306. [self removeAllLeafNodesOnPath:path batch:batch];
  307. __block NSUInteger counter = 0;
  308. if (merge) {
  309. // remove any children that exist
  310. [node enumerateChildrenUsingBlock:^(NSString *childKey, id<FNode> childNode, BOOL *stop) {
  311. FPath *childPath = [path childFromString:childKey];
  312. [self removeAllWithPrefix:serverCacheKey(childPath) batch:batch database:self.serverCacheDB];
  313. [self saveNodeInternal:childNode atPath:childPath batch:batch counter:&counter];
  314. }];
  315. } else {
  316. // remove everything
  317. [self removeAllWithPrefix:serverCacheKey(path) batch:batch database:self.serverCacheDB];
  318. [self saveNodeInternal:node atPath:path batch:batch counter:&counter];
  319. }
  320. BOOL success = [batch commit];
  321. if (!success) {
  322. FFWarn(@"I-RDB076017", @"Failed to update server cache on disk!");
  323. } else {
  324. FFDebug(@"I-RDB076018", @"Saved %lu leaf nodes for overwrite in %fms", (unsigned long)counter, [start timeIntervalSinceNow]*-1000);
  325. }
  326. }
  327. - (void)updateServerCacheWithMerge:(FCompoundWrite *)merge atPath:(FPath *)path {
  328. NSDate *start = [NSDate date];
  329. __block NSUInteger counter = 0;
  330. id<APLevelDBWriteBatch> batch = [self.serverCacheDB beginWriteBatch];
  331. // Remove any leaf nodes that might be higher up
  332. [self removeAllLeafNodesOnPath:path batch:batch];
  333. [merge enumerateWrites:^(FPath *relativePath, id<FNode> node, BOOL *stop) {
  334. FPath *childPath = [path child:relativePath];
  335. [self removeAllWithPrefix:serverCacheKey(childPath) batch:batch database:self.serverCacheDB];
  336. [self saveNodeInternal:node atPath:childPath batch:batch counter:&counter];
  337. }];
  338. BOOL success = [batch commit];
  339. if (!success) {
  340. FFWarn(@"I-RDB076019", @"Failed to update server cache on disk!");
  341. } else {
  342. FFDebug(@"I-RDB076020", @"Saved %lu leaf nodes for merge in %fms", (unsigned long)counter, [start timeIntervalSinceNow]*-1000);
  343. }
  344. }
  345. - (void)saveNodeInternal:(id<FNode>)node atPath:(FPath *)path batch:(id<APLevelDBWriteBatch>)batch counter:(NSUInteger *)counter {
  346. id data = [node valForExport:YES];
  347. if(data != nil && ![data isKindOfClass:[NSNull class]]) {
  348. [self internalSetNestedData:data forKey:serverCacheKey(path) withBatch:batch counter:counter];
  349. }
  350. }
  351. - (NSUInteger)serverCacheEstimatedSizeInBytes {
  352. // Use the exact size, because for pruning the approximate size can lead to weird situations where we prune everything
  353. // because no compaction is ever run
  354. return [self.serverCacheDB exactSizeFrom:kFServerCachePrefix to:kFServerCacheRangeEnd];
  355. }
  356. - (void)pruneCache:(FPruneForest *)pruneForest atPath:(FPath *)path {
  357. // TODO: be more intelligent, don't scan entire database...
  358. __block NSUInteger pruned = 0;
  359. __block NSUInteger kept = 0;
  360. NSDate *start = [NSDate date];
  361. NSString *prefix = serverCacheKey(path);
  362. id<APLevelDBWriteBatch> batch = [self.serverCacheDB beginWriteBatch];
  363. [self.serverCacheDB enumerateKeysWithPrefix:prefix usingBlock:^(NSString *dbKey, BOOL *stop) {
  364. NSString *pathStr = [dbKey substringFromIndex:prefix.length];
  365. FPath *relativePath = [[FPath alloc] initWith:pathStr];
  366. if ([pruneForest shouldPruneUnkeptDescendantsAtPath:relativePath]) {
  367. pruned++;
  368. [batch removeKey:dbKey];
  369. } else {
  370. kept++;
  371. }
  372. }];
  373. BOOL success = [batch commit];
  374. if (!success) {
  375. FFWarn(@"I-RDB076021", @"Failed to prune cache on disk!");
  376. } else {
  377. FFDebug(@"I-RDB076022", @"Pruned %lu paths, kept %lu paths in %fms", (unsigned long)pruned, (unsigned long)kept, [start timeIntervalSinceNow]*-1000);
  378. }
  379. }
  380. #pragma mark - Tracked Queries
  381. - (NSArray *)loadTrackedQueries {
  382. NSDate *date = [NSDate date];
  383. NSMutableArray *trackedQueries = [NSMutableArray array];
  384. [self.serverCacheDB enumerateKeysWithPrefix:kFTrackedQueriesPrefix asData:^(NSString *key, NSData *data, BOOL *stop) {
  385. NSError *error = nil;
  386. NSDictionary *queryJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  387. if (queryJSON == nil) {
  388. if (error.code == kFNanFailureCode) {
  389. FFWarn(@"I-RDB076023", @"Failed to deserialize tracked query (%@), likely because of out of range doubles (Error: %@)",
  390. [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding],
  391. error);
  392. FFWarn(@"I-RDB076024", @"Removing failed tracked query with key %@", key);
  393. [self.serverCacheDB removeKey:key];
  394. } else {
  395. [NSException raise:NSInternalInconsistencyException format:@"Failed to deserialize tracked query: %@", error];
  396. }
  397. } else {
  398. NSUInteger queryId = ((NSNumber *)queryJSON[kFTrackedQueryId]).unsignedIntegerValue;
  399. FPath *path = [FPath pathWithString:queryJSON[kFTrackedQueryPath]];
  400. FQueryParams *params = [FQueryParams fromQueryObject:queryJSON[kFTrackedQueryParams]];
  401. FQuerySpec *query = [[FQuerySpec alloc] initWithPath:path params:params];
  402. BOOL isComplete = [queryJSON[kFTrackedQueryIsComplete] boolValue];
  403. BOOL isActive = [queryJSON[kFTrackedQueryIsActive] boolValue];
  404. NSTimeInterval lastUse = [queryJSON[kFTrackedQueryLastUse] doubleValue];
  405. FTrackedQuery *trackedQuery = [[FTrackedQuery alloc] initWithId:queryId
  406. query:query
  407. lastUse:lastUse
  408. isActive:isActive
  409. isComplete:isComplete];
  410. [trackedQueries addObject:trackedQuery];
  411. }
  412. }];
  413. FFDebug(@"I-RDB076025", @"Loaded %lu tracked queries in %fms", (unsigned long)trackedQueries.count, [date timeIntervalSinceNow]*-1000);
  414. return trackedQueries;
  415. }
  416. - (void)removeTrackedQuery:(NSUInteger)queryId {
  417. NSDate *start = [NSDate date];
  418. id<APLevelDBWriteBatch> batch = [self.serverCacheDB beginWriteBatch];
  419. [batch removeKey:trackedQueryKey(queryId)];
  420. __block NSUInteger keyCount = 0;
  421. [self.serverCacheDB enumerateKeysWithPrefix:trackedQueryKeysKeyPrefix(queryId) usingBlock:^(NSString *key, BOOL *stop) {
  422. [batch removeKey:key];
  423. keyCount++;
  424. }];
  425. BOOL success = [batch commit];
  426. if (!success) {
  427. FFWarn(@"I-RDB076026", @"Failed to remove tracked query on disk!");
  428. } else {
  429. FFDebug(@"I-RDB076027", @"Removed query with id %lu (and removed %lu keys) in %fms",
  430. (unsigned long)queryId,
  431. (unsigned long)keyCount,
  432. [start timeIntervalSinceNow]*-1000);
  433. }
  434. }
  435. - (void)saveTrackedQuery:(FTrackedQuery *)query {
  436. NSDate *start = [NSDate date];
  437. NSDictionary *trackedQuery =
  438. @{
  439. kFTrackedQueryId: @(query.queryId),
  440. kFTrackedQueryPath: [query.query.path toStringWithTrailingSlash],
  441. kFTrackedQueryParams: [query.query.params wireProtocolParams],
  442. kFTrackedQueryLastUse: @(query.lastUse),
  443. kFTrackedQueryIsComplete: @(query.isComplete),
  444. kFTrackedQueryIsActive: @(query.isActive)
  445. };
  446. NSError *error = nil;
  447. NSData *data = [NSJSONSerialization dataWithJSONObject:trackedQuery options:0 error:&error];
  448. NSAssert(data, @"Failed to serialize tracked query (Error: %@)", error);
  449. [self.serverCacheDB setData:data forKey:trackedQueryKey(query.queryId)];
  450. FFDebug(@"I-RDB076028", @"Saved tracked query %lu in %fms", (unsigned long)query.queryId, [start timeIntervalSinceNow]*-1000);
  451. }
  452. - (void)setTrackedQueryKeys:(NSSet *)keys forQueryId:(NSUInteger)queryId {
  453. NSDate *start = [NSDate date];
  454. __block NSUInteger removed = 0;
  455. __block NSUInteger added = 0;
  456. id<APLevelDBWriteBatch> batch = [self.serverCacheDB beginWriteBatch];
  457. NSMutableSet *seenKeys = [NSMutableSet set];
  458. // First, delete any keys that might be stored and are not part of the current keys
  459. [self.serverCacheDB enumerateKeysWithPrefix:trackedQueryKeysKeyPrefix(queryId) asStrings:^(NSString *dbKey, NSString *actualKey, BOOL *stop) {
  460. if ([keys containsObject:actualKey]) {
  461. // Already in DB
  462. [seenKeys addObject:actualKey];
  463. } else {
  464. // Not part of set, delete key
  465. [batch removeKey:dbKey];
  466. removed++;
  467. }
  468. }];
  469. // Next add any keys that are missing in the database
  470. [keys enumerateObjectsUsingBlock:^(NSString *childKey, BOOL *stop) {
  471. if (![seenKeys containsObject:childKey]) {
  472. [batch setString:childKey forKey:trackedQueryKeysKey(queryId, childKey)];
  473. added++;
  474. }
  475. }];
  476. BOOL success = [batch commit];
  477. if (!success) {
  478. FFWarn(@"I-RDB076029", @"Failed to set tracked queries on disk!");
  479. } else {
  480. FFDebug(@"I-RDB076030", @"Set %lu tracked keys (%lu added, %lu removed) for query %lu in %fms",
  481. (unsigned long)keys.count,
  482. (unsigned long)added,
  483. (unsigned long)removed,
  484. (unsigned long)queryId,
  485. [start timeIntervalSinceNow]*-1000);
  486. }
  487. }
  488. - (void)updateTrackedQueryKeysWithAddedKeys:(NSSet *)added removedKeys:(NSSet *)removed forQueryId:(NSUInteger)queryId {
  489. NSDate *start = [NSDate date];
  490. id<APLevelDBWriteBatch> batch = [self.serverCacheDB beginWriteBatch];
  491. [removed enumerateObjectsUsingBlock:^(NSString *key, BOOL *stop) {
  492. [batch removeKey:trackedQueryKeysKey(queryId, key)];
  493. }];
  494. [added enumerateObjectsUsingBlock:^(NSString *key, BOOL *stop) {
  495. [batch setString:key forKey:trackedQueryKeysKey(queryId, key)];
  496. }];
  497. BOOL success = [batch commit];
  498. if (!success) {
  499. FFWarn(@"I-RDB076031", @"Failed to update tracked queries on disk!");
  500. } else {
  501. FFDebug(@"I-RDB076032", @"Added %lu tracked keys, removed %lu for query %lu in %fms", (unsigned long)added.count, (unsigned long)removed.count, (unsigned long)queryId, [start timeIntervalSinceNow]*-1000);
  502. }
  503. }
  504. - (NSSet *)trackedQueryKeysForQuery:(NSUInteger)queryId {
  505. NSDate *start = [NSDate date];
  506. NSMutableSet *set = [NSMutableSet set];
  507. [self.serverCacheDB enumerateKeysWithPrefix:trackedQueryKeysKeyPrefix(queryId) asStrings:^(NSString *dbKey, NSString *actualKey, BOOL *stop) {
  508. [set addObject:actualKey];
  509. }];
  510. FFDebug(@"I-RDB076033", @"Loaded %lu tracked keys for query %lu in %fms", (unsigned long)set.count, (unsigned long)queryId, [start timeIntervalSinceNow]*-1000);
  511. return set;
  512. }
  513. #pragma mark - Internal methods
  514. - (void)removeAllLeafNodesOnPath:(FPath *)path batch:(id<APLevelDBWriteBatch>)batch {
  515. while (!path.isEmpty) {
  516. [batch removeKey:serverCacheKey(path)];
  517. path = [path parent];
  518. }
  519. // Make sure to delete any nodes at the root
  520. [batch removeKey:serverCacheKey([FPath empty])];
  521. }
  522. - (void)removeAllWithPrefix:(NSString *)prefix batch:(id<APLevelDBWriteBatch>)batch database:(APLevelDB *)database {
  523. assert(prefix != nil);
  524. [database enumerateKeysWithPrefix:prefix usingBlock:^(NSString *key, BOOL *stop) {
  525. [batch removeKey:key];
  526. }];
  527. }
  528. #pragma mark - Internal helper methods
  529. - (void)internalSetNestedData:(id)value forKey:(NSString *)key withBatch:(id<APLevelDBWriteBatch>)batch counter:(NSUInteger *)counter {
  530. if([value isKindOfClass:[NSDictionary class]]) {
  531. NSDictionary* dictionary = value;
  532. [dictionary enumerateKeysAndObjectsUsingBlock:^(id childKey, id obj, BOOL *stop) {
  533. assert(obj != nil);
  534. NSString* childPath = [NSString stringWithFormat:@"%@%@/", key, childKey];
  535. [self internalSetNestedData:obj forKey:childPath withBatch:batch counter:counter];
  536. }];
  537. }
  538. else {
  539. NSData *data = [self serializePrimitive:value];
  540. [batch setData:data forKey:key];
  541. (*counter)++;
  542. }
  543. }
  544. - (id)internalNestedDataForPath:(FPath *)path {
  545. NSAssert(path != nil, @"Path was nil!");
  546. NSString *baseKey = serverCacheKey(path);
  547. // HACK to make sure iter is freed now to avoid race conditions (if self.db is deleted before iter, you get an access violation).
  548. @autoreleasepool {
  549. APLevelDBIterator* iter = [APLevelDBIterator iteratorWithLevelDB:self.serverCacheDB];
  550. [iter seekToKey:baseKey];
  551. if (iter.key == nil || ![iter.key hasPrefix:baseKey]) {
  552. // No data.
  553. return nil;
  554. } else {
  555. return [self internalNestedDataFromIterator:iter andKeyPrefix:baseKey];
  556. }
  557. }
  558. }
  559. - (id) internalNestedDataFromIterator:(APLevelDBIterator*)iterator andKeyPrefix:(NSString*)prefix {
  560. NSString* key = iterator.key;
  561. if ([key isEqualToString:prefix]) {
  562. id result = [self deserializePrimitive:iterator.valueAsData];
  563. [iterator nextKey];
  564. return result;
  565. } else {
  566. NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
  567. while (key != nil && [key hasPrefix:prefix]) {
  568. NSString *relativePath = [key substringFromIndex:prefix.length];
  569. NSArray* pathPieces = [relativePath componentsSeparatedByString:@"/"];
  570. assert(pathPieces.count > 0);
  571. NSString *childName = pathPieces[0];
  572. NSString *childPath = [NSString stringWithFormat:@"%@%@/", prefix, childName];
  573. id childValue = [self internalNestedDataFromIterator:iterator andKeyPrefix:childPath];
  574. [dict setValue:childValue forKey:childName];
  575. key = iterator.key;
  576. }
  577. return dict;
  578. }
  579. }
  580. - (NSData*) serializePrimitive:(id)value {
  581. // HACK: The built-in serialization only works on dicts and arrays. So we create an array and then strip off
  582. // the leading / trailing byte (the [ and ]).
  583. NSError *error = nil;
  584. NSData *data = [NSJSONSerialization dataWithJSONObject:@[value] options:0 error:&error];
  585. NSAssert(data, @"Failed to serialize primitive: %@", error);
  586. return [data subdataWithRange:NSMakeRange(1, data.length - 2)];
  587. }
  588. - (id)fixDoubleParsing:(id)value {
  589. // The parser for double values in JSONSerialization at the root takes some short-cuts and delivers wrong results
  590. // (wrong rounding) for some double values, including 2.47. Because we use the exact bytes for hashing on the server
  591. // this will lead to hash mismatches. The parser of NSNumber seems to be more in line with what the server expects,
  592. // so we use that here
  593. if ([value isKindOfClass:[NSNumber class]]) {
  594. CFNumberType type = CFNumberGetType((CFNumberRef)value);
  595. if (type == kCFNumberDoubleType || type == kCFNumberFloatType) {
  596. // The NSJSON parser returns all numbers as double values, even those that contain no exponent. To
  597. // make sure that the String conversion below doesn't unexpectedly reduce precision, we make sure that
  598. // our number is indeed not an integer.
  599. if ((double)(long long)[value doubleValue] != [value doubleValue]) {
  600. NSString *doubleString = [value stringValue];
  601. return [NSNumber numberWithDouble:[doubleString doubleValue]];
  602. }
  603. }
  604. }
  605. return value;
  606. }
  607. - (id) deserializePrimitive:(NSData*)data {
  608. NSError *error = nil;
  609. id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
  610. if (result != nil) {
  611. return [self fixDoubleParsing:result];
  612. } else {
  613. if (error.code == kFNanFailureCode) {
  614. FFWarn(@"I-RDB076034", @"Failed to load primitive %@, likely because doubles where out of range (Error: %@)",
  615. [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding], error);
  616. return [NSNull null];
  617. } else {
  618. [NSException raise:NSInternalInconsistencyException format:@"Failed to deserialiaze primitive: %@", error];
  619. return nil;
  620. }
  621. }
  622. }
  623. + (void)ensureDir:(NSString*)path markAsDoNotBackup:(BOOL)markAsDoNotBackup {
  624. NSError* error;
  625. BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:path
  626. withIntermediateDirectories:YES
  627. attributes:nil
  628. error:&error];
  629. if (!success) {
  630. @throw [NSException exceptionWithName:@"FailedToCreatePersistenceDir" reason:@"Failed to create persistence directory." userInfo:@{ @"path": path }];
  631. }
  632. if (markAsDoNotBackup) {
  633. NSURL *firebaseDirURL = [NSURL fileURLWithPath:path];
  634. success = [firebaseDirURL setResourceValue:@YES
  635. forKey:NSURLIsExcludedFromBackupKey
  636. error:&error];
  637. if (!success) {
  638. FFWarn(@"I-RDB076035", @"Failed to mark firebase database folder as do not backup: %@", error);
  639. [NSException raise:@"Error marking as do not backup" format:@"Failed to mark folder %@ as do not backup", firebaseDirURL];
  640. }
  641. }
  642. }
  643. @end