FRepo.m 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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 <FirebaseCore/FIRLogger.h>
  18. #import <dlfcn.h>
  19. #import "FRepo.h"
  20. #import "FSnapshotUtilities.h"
  21. #import "FConstants.h"
  22. #import "FIRDatabaseQuery_Private.h"
  23. #import "FQuerySpec.h"
  24. #import "FTupleNodePath.h"
  25. #import "FRepo_Private.h"
  26. #import "FRepoManager.h"
  27. #import "FServerValues.h"
  28. #import "FTupleSetIdPath.h"
  29. #import "FSyncTree.h"
  30. #import "FEventRegistration.h"
  31. #import "FAtomicNumber.h"
  32. #import "FSyncTree.h"
  33. #import "FListenProvider.h"
  34. #import "FEventRaiser.h"
  35. #import "FSnapshotHolder.h"
  36. #import "FIRDatabaseConfig_Private.h"
  37. #import "FLevelDBStorageEngine.h"
  38. #import "FPersistenceManager.h"
  39. #import "FWriteRecord.h"
  40. #import "FCachePolicy.h"
  41. #import "FClock.h"
  42. #import "FIRDatabase_Private.h"
  43. #import "FTree.h"
  44. #import "FTupleTransaction.h"
  45. #import "FIRTransactionResult.h"
  46. #import "FIRTransactionResult_Private.h"
  47. #import "FIRMutableData.h"
  48. #import "FIRMutableData_Private.h"
  49. #import "FIRDataSnapshot.h"
  50. #import "FIRDataSnapshot_Private.h"
  51. #import "FValueEventRegistration.h"
  52. #import "FEmptyNode.h"
  53. #if TARGET_OS_IOS || TARGET_OS_TV
  54. #import <UIKit/UIKit.h>
  55. #endif
  56. @interface FRepo()
  57. @property (nonatomic, strong) FOffsetClock *serverClock;
  58. @property (nonatomic, strong) FPersistenceManager* persistenceManager;
  59. @property (nonatomic, strong) FIRDatabase *database;
  60. @property (nonatomic, strong, readwrite) FAuthenticationManager *auth;
  61. @property (nonatomic, strong) FSyncTree *infoSyncTree;
  62. @property (nonatomic) NSInteger writeIdCounter;
  63. @property (nonatomic) BOOL hijackHash;
  64. @property (nonatomic, strong) FTree *transactionQueueTree;
  65. @property (nonatomic) BOOL loggedTransactionPersistenceWarning;
  66. /**
  67. * Test only. For load testing the server.
  68. */
  69. @property (nonatomic, strong) id (^interceptServerDataCallback)(NSString *pathString, id data);
  70. @end
  71. @implementation FRepo
  72. - (id)initWithRepoInfo:(FRepoInfo*)info config:(FIRDatabaseConfig *)config database:(FIRDatabase *)database {
  73. self = [super init];
  74. if (self) {
  75. self.repoInfo = info;
  76. self.config = config;
  77. self.database = database;
  78. // Access can occur outside of shared queue, so the clock needs to be initialized here
  79. self.serverClock = [[FOffsetClock alloc] initWithClock:[FSystemClock clock] offset:0];
  80. self.connection = [[FPersistentConnection alloc] initWithRepoInfo:self.repoInfo dispatchQueue:[FIRDatabaseQuery sharedQueue] config:self.config];
  81. // Needs to be called before authentication manager is instantiated
  82. self.eventRaiser = [[FEventRaiser alloc] initWithQueue:self.config.callbackQueue];
  83. dispatch_async([FIRDatabaseQuery sharedQueue], ^{
  84. [self deferredInit];
  85. });
  86. }
  87. return self;
  88. }
  89. - (void)deferredInit {
  90. // TODO: cleanup on dealloc
  91. __weak FRepo *weakSelf = self;
  92. [self.config.authTokenProvider listenForTokenChanges:^(NSString *token) {
  93. [weakSelf.connection refreshAuthToken:token];
  94. }];
  95. // Open connection now so that by the time we are connected the deferred init has run
  96. // This relies on the fact that all callbacks run on repos queue
  97. self.connection.delegate = self;
  98. [self.connection open];
  99. self.dataUpdateCount = 0;
  100. self.rangeMergeUpdateCount = 0;
  101. self.interceptServerDataCallback = nil;
  102. if (self.config.persistenceEnabled) {
  103. NSString* repoHashString = [NSString stringWithFormat:@"%@_%@", self.repoInfo.host, self.repoInfo.namespace];
  104. NSString* persistencePrefix = [NSString stringWithFormat:@"%@/%@", self.config.sessionIdentifier, repoHashString];
  105. id<FCachePolicy> cachePolicy = [[FLRUCachePolicy alloc] initWithMaxSize:self.config.persistenceCacheSizeBytes];
  106. id<FStorageEngine> engine;
  107. if (self.config.forceStorageEngine != nil) {
  108. engine = self.config.forceStorageEngine;
  109. } else {
  110. FLevelDBStorageEngine *levelDBEngine = [[FLevelDBStorageEngine alloc] initWithPath:persistencePrefix];
  111. // We need the repo info to run the legacy migration. Future migrations will be managed by the database itself
  112. // Remove this once we are confident that no-one is using legacy migration anymore...
  113. [levelDBEngine runLegacyMigration:self.repoInfo];
  114. engine = levelDBEngine;
  115. }
  116. self.persistenceManager = [[FPersistenceManager alloc] initWithStorageEngine:engine cachePolicy:cachePolicy];
  117. } else {
  118. self.persistenceManager = nil;
  119. }
  120. [self initTransactions];
  121. // A list of data pieces and paths to be set when this client disconnects
  122. self.onDisconnect = [[FSparseSnapshotTree alloc] init];
  123. self.infoData = [[FSnapshotHolder alloc] init];
  124. FListenProvider *infoListenProvider = [[FListenProvider alloc] init];
  125. infoListenProvider.startListening = ^(FQuerySpec *query,
  126. NSNumber *tagId,
  127. id<FSyncTreeHash> hash,
  128. fbt_nsarray_nsstring onComplete) {
  129. NSArray *infoEvents = @[];
  130. FRepo *strongSelf = weakSelf;
  131. id<FNode> node = [strongSelf.infoData getNode:query.path];
  132. // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events
  133. // on initial data...
  134. if (![node isEmpty]) {
  135. infoEvents = [strongSelf.infoSyncTree applyServerOverwriteAtPath:query.path newData:node];
  136. [strongSelf.eventRaiser raiseCallback:^{
  137. onComplete(kFWPResponseForActionStatusOk);
  138. }];
  139. }
  140. return infoEvents;
  141. };
  142. infoListenProvider.stopListening = ^(FQuerySpec *query, NSNumber *tagId) {};
  143. self.infoSyncTree = [[FSyncTree alloc] initWithListenProvider:infoListenProvider];
  144. FListenProvider *serverListenProvider = [[FListenProvider alloc] init];
  145. serverListenProvider.startListening = ^(FQuerySpec *query,
  146. NSNumber *tagId,
  147. id<FSyncTreeHash> hash,
  148. fbt_nsarray_nsstring onComplete) {
  149. [weakSelf.connection listen:query tagId:tagId hash:hash onComplete:^(NSString *status) {
  150. NSArray *events = onComplete(status);
  151. [weakSelf.eventRaiser raiseEvents:events];
  152. }];
  153. // No synchronous events for network-backed sync trees
  154. return @[];
  155. };
  156. serverListenProvider.stopListening = ^(FQuerySpec *query, NSNumber *tag) {
  157. [weakSelf.connection unlisten:query tagId:tag];
  158. };
  159. self.serverSyncTree = [[FSyncTree alloc] initWithPersistenceManager:self.persistenceManager
  160. listenProvider:serverListenProvider];
  161. [self restoreWrites];
  162. [self updateInfo:kDotInfoConnected withValue:@NO];
  163. [self setupNotifications];
  164. }
  165. - (void) restoreWrites {
  166. NSArray *writes = self.persistenceManager.userWrites;
  167. NSDictionary *serverValues = [FServerValues generateServerValues:self.serverClock];
  168. __block NSInteger lastWriteId = NSIntegerMin;
  169. [writes enumerateObjectsUsingBlock:^(FWriteRecord *write, NSUInteger idx, BOOL *stop) {
  170. NSInteger writeId = write.writeId;
  171. fbt_void_nsstring_nsstring callback = ^(NSString *status, NSString *errorReason) {
  172. [self warnIfWriteFailedAtPath:write.path status:status message:@"Persisted write"];
  173. [self ackWrite:writeId rerunTransactionsAtPath:write.path status:status];
  174. };
  175. if (lastWriteId >= writeId) {
  176. [NSException raise:NSInternalInconsistencyException format:@"Restored writes were not in order!"];
  177. }
  178. lastWriteId = writeId;
  179. self.writeIdCounter = writeId + 1;
  180. if ([write isOverwrite]) {
  181. FFLog(@"I-RDB038001", @"Restoring overwrite with id %ld", (long)write.writeId);
  182. [self.connection putData:[write.overwrite valForExport:YES]
  183. forPath:[write.path toString]
  184. withHash:nil
  185. withCallback:callback];
  186. id<FNode> resolved = [FServerValues resolveDeferredValueSnapshot:write.overwrite withServerValues:serverValues];
  187. [self.serverSyncTree applyUserOverwriteAtPath:write.path newData:resolved writeId:writeId isVisible:YES];
  188. } else {
  189. FFLog(@"I-RDB038002", @"Restoring merge with id %ld", (long)write.writeId);
  190. [self.connection mergeData:[write.merge valForExport:YES]
  191. forPath:[write.path toString]
  192. withCallback:callback];
  193. FCompoundWrite *resolved = [FServerValues resolveDeferredValueCompoundWrite:write.merge withServerValues:serverValues];
  194. [self.serverSyncTree applyUserMergeAtPath:write.path changedChildren:resolved writeId:writeId];
  195. }
  196. }];
  197. }
  198. - (NSString*)name {
  199. return self.repoInfo.namespace;
  200. }
  201. - (NSString *) description {
  202. return [self.repoInfo description];
  203. }
  204. - (void) interrupt {
  205. [self.connection interruptForReason:kFInterruptReasonRepoInterrupt];
  206. }
  207. - (void) resume {
  208. [self.connection resumeForReason:kFInterruptReasonRepoInterrupt];
  209. }
  210. // NOTE: Typically if you're calling this, you should be in an @autoreleasepool block to make sure that ARC kicks
  211. // in and cleans up things no longer referenced (i.e. pendingPutsDB).
  212. - (void) dispose {
  213. [self.connection interruptForReason:kFInterruptReasonRepoInterrupt];
  214. // We need to nil out any references to LevelDB, to make sure the
  215. // LevelDB exclusive locks are released.
  216. [self.persistenceManager close];
  217. }
  218. - (NSInteger) nextWriteId {
  219. return self->_writeIdCounter++;
  220. }
  221. - (NSTimeInterval) serverTime {
  222. return [self.serverClock currentTime];
  223. }
  224. - (void) set:(FPath *)path withNode:(id<FNode>)node withCallback:(fbt_void_nserror_ref)onComplete {
  225. id value = [node valForExport:YES];
  226. FFLog(@"I-RDB038003", @"Setting: %@ with %@ pri: %@", [path toString], [value description], [[node getPriority] val]);
  227. // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or
  228. // (b) store unresolved paths on JSON parse
  229. NSDictionary* serverValues = [FServerValues generateServerValues:self.serverClock];
  230. id<FNode> newNode = [FServerValues resolveDeferredValueSnapshot:node withServerValues:serverValues];
  231. NSInteger writeId = [self nextWriteId];
  232. [self.persistenceManager saveUserOverwrite:node atPath:path writeId:writeId];
  233. NSArray *events = [self.serverSyncTree applyUserOverwriteAtPath:path newData:newNode writeId:writeId isVisible:YES];
  234. [self.eventRaiser raiseEvents:events];
  235. [self.connection putData:value forPath:[path toString] withHash:nil withCallback:^(NSString *status, NSString *errorReason) {
  236. [self warnIfWriteFailedAtPath:path status:status message:@"setValue: or removeValue:"];
  237. [self ackWrite:writeId rerunTransactionsAtPath:path status:status];
  238. [self callOnComplete:onComplete withStatus:status errorReason:errorReason andPath:path];
  239. }];
  240. FPath* affectedPath = [self abortTransactionsAtPath:path error:kFTransactionSet];
  241. [self rerunTransactionsForPath:affectedPath];
  242. }
  243. - (void) update:(FPath *)path withNodes:(FCompoundWrite *)nodes withCallback:(fbt_void_nserror_ref)callback {
  244. NSDictionary *values = [nodes valForExport:YES];
  245. FFLog(@"I-RDB038004", @"Updating: %@ with %@", [path toString], [values description]);
  246. NSDictionary* serverValues = [FServerValues generateServerValues:self.serverClock];
  247. FCompoundWrite *resolved = [FServerValues resolveDeferredValueCompoundWrite:nodes withServerValues:serverValues];
  248. if (!resolved.isEmpty) {
  249. NSInteger writeId = [self nextWriteId];
  250. [self.persistenceManager saveUserMerge:nodes atPath:path writeId:writeId];
  251. NSArray *events = [self.serverSyncTree applyUserMergeAtPath:path changedChildren:resolved writeId:writeId];
  252. [self.eventRaiser raiseEvents:events];
  253. [self.connection mergeData:values forPath:[path description] withCallback:^(NSString *status, NSString *errorReason) {
  254. [self warnIfWriteFailedAtPath:path status:status message:@"updateChildValues:"];
  255. [self ackWrite:writeId rerunTransactionsAtPath:path status:status];
  256. [self callOnComplete:callback withStatus:status errorReason:errorReason andPath:path];
  257. }];
  258. [nodes enumerateWrites:^(FPath *childPath, id<FNode> node, BOOL *stop) {
  259. FPath* pathFromRoot = [path child:childPath];
  260. FFLog(@"I-RDB038005", @"Cancelling transactions at path: %@", pathFromRoot);
  261. FPath *affectedPath = [self abortTransactionsAtPath:pathFromRoot error:kFTransactionSet];
  262. [self rerunTransactionsForPath:affectedPath];
  263. }];
  264. } else {
  265. FFLog(@"I-RDB038006", @"update called with empty data. Doing nothing");
  266. // Do nothing, just call the callback
  267. [self callOnComplete:callback withStatus:@"ok" errorReason:nil andPath:path];
  268. }
  269. }
  270. - (void) onDisconnectCancel:(FPath *)path withCallback:(fbt_void_nserror_ref)callback {
  271. [self.connection onDisconnectCancelPath:path withCallback:^(NSString *status, NSString *errorReason) {
  272. BOOL success = [status isEqualToString:kFWPResponseForActionStatusOk];
  273. if (success) {
  274. [self.onDisconnect forgetPath:path];
  275. } else {
  276. FFLog(@"I-RDB038007", @"cancelDisconnectOperations: at %@ failed: %@", path, status);
  277. }
  278. [self callOnComplete:callback withStatus:status errorReason:errorReason andPath:path];
  279. }];
  280. }
  281. - (void) onDisconnectSet:(FPath *)path withNode:(id<FNode>)node withCallback:(fbt_void_nserror_ref)callback {
  282. [self.connection onDisconnectPutData:[node valForExport:YES] forPath:path withCallback:^(NSString *status, NSString *errorReason) {
  283. BOOL success = [status isEqualToString:kFWPResponseForActionStatusOk];
  284. if (success) {
  285. [self.onDisconnect rememberData:node onPath:path];
  286. } else {
  287. FFWarn(@"I-RDB038008", @"onDisconnectSetValue: or onDisconnectRemoveValue: at %@ failed: %@", path, status);
  288. }
  289. [self callOnComplete:callback withStatus:status errorReason:errorReason andPath:path];
  290. }];
  291. }
  292. - (void) onDisconnectUpdate:(FPath *)path withNodes:(FCompoundWrite *)nodes withCallback:(fbt_void_nserror_ref)callback {
  293. if (!nodes.isEmpty) {
  294. NSDictionary *values = [nodes valForExport:YES];
  295. [self.connection onDisconnectMergeData:values forPath:path withCallback:^(NSString *status, NSString *errorReason) {
  296. BOOL success = [status isEqualToString:kFWPResponseForActionStatusOk];
  297. if (success) {
  298. [nodes enumerateWrites:^(FPath *relativePath, id<FNode> nodeUnresolved, BOOL *stop) {
  299. FPath* childPath = [path child:relativePath];
  300. [self.onDisconnect rememberData:nodeUnresolved onPath:childPath];
  301. }];
  302. } else {
  303. FFWarn(@"I-RDB038009", @"onDisconnectUpdateChildValues: at %@ failed %@", path, status);
  304. }
  305. [self callOnComplete:callback withStatus:status errorReason:errorReason andPath:path];
  306. }];
  307. } else {
  308. // Do nothing, just call the callback
  309. [self callOnComplete:callback withStatus:@"ok" errorReason:nil andPath:path];
  310. }
  311. }
  312. - (void) purgeOutstandingWrites {
  313. FFLog(@"I-RDB038010", @"Purging outstanding writes");
  314. NSArray *events = [self.serverSyncTree removeAllWrites];
  315. [self.eventRaiser raiseEvents:events];
  316. // Abort any transactions
  317. [self abortTransactionsAtPath:[FPath empty] error:kFErrorWriteCanceled];
  318. // Remove outstanding writes from connection
  319. [self.connection purgeOutstandingWrites];
  320. }
  321. - (void) addEventRegistration:(id <FEventRegistration>)eventRegistration forQuery:(FQuerySpec *)query {
  322. NSArray *events = nil;
  323. if ([[query.path getFront] isEqualToString:kDotInfoPrefix]) {
  324. events = [self.infoSyncTree addEventRegistration:eventRegistration forQuery:query];
  325. } else {
  326. events = [self.serverSyncTree addEventRegistration:eventRegistration forQuery:query];
  327. }
  328. [self.eventRaiser raiseEvents:events];
  329. }
  330. - (void) removeEventRegistration:(id<FEventRegistration>)eventRegistration forQuery:(FQuerySpec *)query {
  331. // These are guaranteed not to raise events, since we're not passing in a cancelError. However we can future-proof
  332. // a little bit by handling the return values anyways.
  333. FFLog(@"I-RDB038011", @"Removing event registration with hande: %lu", (unsigned long)eventRegistration.handle);
  334. NSArray *events = nil;
  335. if ([[query.path getFront] isEqualToString:kDotInfoPrefix]) {
  336. events = [self.infoSyncTree removeEventRegistration:eventRegistration forQuery:query cancelError:nil];
  337. } else {
  338. events = [self.serverSyncTree removeEventRegistration:eventRegistration forQuery:query cancelError:nil];
  339. }
  340. [self.eventRaiser raiseEvents:events];
  341. }
  342. - (void) keepQuery:(FQuerySpec *)query synced:(BOOL)synced {
  343. NSAssert(![[query.path getFront] isEqualToString:kDotInfoPrefix], @"Can't keep .info tree synced!");
  344. [self.serverSyncTree keepQuery:query synced:synced];
  345. }
  346. - (void) updateInfo:(NSString *) pathString withValue:(id)value {
  347. // hack to make serverTimeOffset available in a threadsafe way. Property is marked as atomic
  348. if ([pathString isEqualToString:kDotInfoServerTimeOffset]) {
  349. NSTimeInterval offset = [(NSNumber *)value doubleValue]/1000.0;
  350. self.serverClock = [[FOffsetClock alloc] initWithClock:[FSystemClock clock] offset:offset];
  351. }
  352. FPath* path = [[FPath alloc] initWith:[NSString stringWithFormat:@"%@/%@", kDotInfoPrefix, pathString]];
  353. id<FNode> newNode = [FSnapshotUtilities nodeFrom:value];
  354. [self.infoData updateSnapshot:path withNewSnapshot:newNode];
  355. NSArray *events = [self.infoSyncTree applyServerOverwriteAtPath:path newData:newNode];
  356. [self.eventRaiser raiseEvents:events];
  357. }
  358. - (void) callOnComplete:(fbt_void_nserror_ref)onComplete withStatus:(NSString *)status errorReason:(NSString *)errorReason andPath:(FPath *)path {
  359. if (onComplete) {
  360. FIRDatabaseReference * ref = [[FIRDatabaseReference alloc] initWithRepo:self path:path];
  361. BOOL statusOk = [status isEqualToString:kFWPResponseForActionStatusOk];
  362. NSError* err = nil;
  363. if (!statusOk) {
  364. err = [FUtilities errorForStatus:status andReason:errorReason];
  365. }
  366. [self.eventRaiser raiseCallback:^{
  367. onComplete(err, ref);
  368. }];
  369. }
  370. }
  371. - (void)ackWrite:(NSInteger)writeId rerunTransactionsAtPath:(FPath *)path status:(NSString *)status {
  372. if ([status isEqualToString:kFErrorWriteCanceled]) {
  373. // This write was already removed, we just need to ignore it...
  374. } else {
  375. BOOL success = [status isEqualToString:kFWPResponseForActionStatusOk];
  376. NSArray *clearEvents = [self.serverSyncTree ackUserWriteWithWriteId:writeId revert:!success persist:YES clock:self.serverClock];
  377. if ([clearEvents count] > 0) {
  378. [self rerunTransactionsForPath:path];
  379. }
  380. [self.eventRaiser raiseEvents:clearEvents];
  381. }
  382. }
  383. - (void) warnIfWriteFailedAtPath:(FPath *)path status:(NSString *)status message:(NSString *)message {
  384. if (!([status isEqualToString:kFWPResponseForActionStatusOk] || [status isEqualToString:kFErrorWriteCanceled])) {
  385. FFWarn(@"I-RDB038012", @"%@ at %@ failed: %@", message, path, status);
  386. }
  387. }
  388. #pragma mark -
  389. #pragma mark FPersistentConnectionDelegate methods
  390. - (void) onDataUpdate:(FPersistentConnection *)fpconnection forPath:(NSString *)pathString message:(id)data isMerge:(BOOL)isMerge tagId:(NSNumber *)tagId {
  391. FFLog(@"I-RDB038013", @"onDataUpdateForPath: %@ withMessage: %@", pathString, data);
  392. // For testing.
  393. self.dataUpdateCount++;
  394. FPath* path = [[FPath alloc] initWith:pathString];
  395. data = self.interceptServerDataCallback ? self.interceptServerDataCallback(pathString, data) : data;
  396. NSArray *events = nil;
  397. if (tagId != nil) {
  398. if (isMerge) {
  399. NSDictionary *message = data;
  400. FCompoundWrite *taggedChildren = [FCompoundWrite compoundWriteWithValueDictionary:message];
  401. events = [self.serverSyncTree applyTaggedQueryMergeAtPath:path changedChildren:taggedChildren tagId:tagId];
  402. } else {
  403. id<FNode> taggedSnap = [FSnapshotUtilities nodeFrom:data];
  404. events = [self.serverSyncTree applyTaggedQueryOverwriteAtPath:path newData:taggedSnap tagId:tagId];
  405. }
  406. } else if (isMerge) {
  407. NSDictionary *message = data;
  408. FCompoundWrite *changedChildren = [FCompoundWrite compoundWriteWithValueDictionary:message];
  409. events = [self.serverSyncTree applyServerMergeAtPath:path changedChildren:changedChildren];
  410. } else {
  411. id<FNode> snap = [FSnapshotUtilities nodeFrom:data];
  412. events = [self.serverSyncTree applyServerOverwriteAtPath:path newData:snap];
  413. }
  414. if ([events count] > 0) {
  415. // Since we have a listener outstanding for each transaction, receiving any events
  416. // is a proxy for some change having occurred.
  417. [self rerunTransactionsForPath:path];
  418. }
  419. [self.eventRaiser raiseEvents:events];
  420. }
  421. - (void)onRangeMerge:(NSArray *)ranges forPath:(NSString *)pathString tagId:(NSNumber *)tag {
  422. FFLog(@"I-RDB038014", @"onRangeMerge: %@ => %@", pathString, ranges);
  423. // For testing
  424. self.rangeMergeUpdateCount++;
  425. FPath* path = [[FPath alloc] initWith:pathString];
  426. NSArray *events;
  427. if (tag != nil) {
  428. events = [self.serverSyncTree applyTaggedServerRangeMergeAtPath:path updates:ranges tagId:tag];
  429. } else {
  430. events = [self.serverSyncTree applyServerRangeMergeAtPath:path updates:ranges];
  431. }
  432. if (events.count > 0) {
  433. // Since we have a listener outstanding for each transaction, receiving any events
  434. // is a proxy for some change having occurred.
  435. [self rerunTransactionsForPath:path];
  436. }
  437. [self.eventRaiser raiseEvents:events];
  438. }
  439. - (void)onConnect:(FPersistentConnection *)fpconnection {
  440. [self updateInfo:kDotInfoConnected withValue:@true];
  441. }
  442. - (void)onDisconnect:(FPersistentConnection *)fpconnection {
  443. [self updateInfo:kDotInfoConnected withValue:@false];
  444. [self runOnDisconnectEvents];
  445. }
  446. - (void)onServerInfoUpdate:(FPersistentConnection *)fpconnection updates:(NSDictionary *)updates {
  447. for (NSString* key in updates) {
  448. id val = [updates objectForKey:key];
  449. [self updateInfo:key withValue:val];
  450. }
  451. }
  452. - (void) setupNotifications {
  453. NSString * const *backgroundConstant = (NSString * const *) dlsym(RTLD_DEFAULT, "UIApplicationDidEnterBackgroundNotification");
  454. if (backgroundConstant) {
  455. FFLog(@"I-RDB038015", @"Registering for background notification.");
  456. [[NSNotificationCenter defaultCenter] addObserver:self
  457. selector:@selector(didEnterBackground)
  458. name:*backgroundConstant
  459. object:nil];
  460. } else {
  461. FFLog(@"I-RDB038016", @"Skipped registering for background notification.");
  462. }
  463. }
  464. - (void) didEnterBackground {
  465. if (!self.config.persistenceEnabled)
  466. return;
  467. // Targetted compilation is ONLY for testing. UIKit is weak-linked in actual release build.
  468. #if TARGET_OS_IOS || TARGET_OS_TV
  469. // The idea is to wait until any outstanding sets get written to disk. Since the sets might still be in our
  470. // dispatch queue, we wait for the dispatch queue to catch up and for persistence to catch up.
  471. // This may be undesirable though. The dispatch queue might just be processing a bunch of incoming data or
  472. // something. We might want to keep track of whether there are any unpersisted sets or something.
  473. FFLog(@"I-RDB038017", @"Entering background. Starting background task to finish work.");
  474. Class uiApplicationClass = NSClassFromString(@"UIApplication");
  475. assert(uiApplicationClass); // If we are here, we should be on iOS and UIApplication should be available.
  476. UIApplication *application = [uiApplicationClass sharedApplication];
  477. __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
  478. [application endBackgroundTask:bgTask];
  479. }];
  480. NSDate *start = [NSDate date];
  481. dispatch_async([FIRDatabaseQuery sharedQueue], ^{
  482. NSTimeInterval finishTime = [start timeIntervalSinceNow]*-1;
  483. FFLog(@"I-RDB038018", @"Background task completed. Queue time: %f", finishTime);
  484. [application endBackgroundTask:bgTask];
  485. });
  486. #endif
  487. }
  488. #pragma mark -
  489. #pragma mark Internal methods
  490. /**
  491. * Applies all the changes stored up in the onDisconnect tree
  492. */
  493. - (void) runOnDisconnectEvents {
  494. FFLog(@"I-RDB038019", @"Running onDisconnectEvents");
  495. NSDictionary* serverValues = [FServerValues generateServerValues:self.serverClock];
  496. FSparseSnapshotTree* resolvedTree = [FServerValues resolveDeferredValueTree:self.onDisconnect withServerValues:serverValues];
  497. NSMutableArray *events = [[NSMutableArray alloc] init];
  498. [resolvedTree forEachTreeAtPath:[FPath empty] do:^(FPath *path, id<FNode> node) {
  499. [events addObjectsFromArray:[self.serverSyncTree applyServerOverwriteAtPath:path newData:node]];
  500. FPath* affectedPath = [self abortTransactionsAtPath:path error:kFTransactionSet];
  501. [self rerunTransactionsForPath:affectedPath];
  502. }];
  503. self.onDisconnect = [[FSparseSnapshotTree alloc] init];
  504. [self.eventRaiser raiseEvents:events];
  505. }
  506. - (NSDictionary *) dumpListens {
  507. return [self.connection dumpListens];
  508. }
  509. #pragma mark -
  510. #pragma mark Transactions
  511. /**
  512. * Setup the transaction data structures
  513. */
  514. - (void) initTransactions {
  515. self.transactionQueueTree = [[FTree alloc] init];
  516. self.hijackHash = NO;
  517. self.loggedTransactionPersistenceWarning = NO;
  518. }
  519. /**
  520. * Creates a new transaction, add its to the transactions we're tracking, and sends it to the server if possible
  521. */
  522. - (void) startTransactionOnPath:(FPath *)path update:(fbt_transactionresult_mutabledata)update onComplete:(fbt_void_nserror_bool_datasnapshot)onComplete withLocalEvents:(BOOL)applyLocally {
  523. if (self.config.persistenceEnabled && !self.loggedTransactionPersistenceWarning) {
  524. self.loggedTransactionPersistenceWarning = YES;
  525. FFInfo(@"I-RDB038020", @"runTransactionBlock: usage detected while persistence is enabled. Please be aware that transactions "
  526. @"*will not* be persisted across app restarts. "
  527. @"See https://www.firebase.com/docs/ios/guide/offline-capabilities.html#section-handling-transactions-offline for more details.");
  528. }
  529. FIRDatabaseReference * watchRef = [[FIRDatabaseReference alloc] initWithRepo:self path:path];
  530. // make sure we're listening on this node
  531. // Note: we can't do this asynchronously. To preserve event ordering, it has to be done in this block.
  532. // This is ok, this block is guaranteed to be our own event loop
  533. NSUInteger handle = [[FUtilities LUIDGenerator] integerValue];
  534. fbt_void_datasnapshot cb = ^(FIRDataSnapshot *snapshot) {};
  535. FValueEventRegistration *registration = [[FValueEventRegistration alloc] initWithRepo:self
  536. handle:handle
  537. callback:cb
  538. cancelCallback:nil];
  539. [watchRef.repo addEventRegistration:registration forQuery:watchRef.querySpec];
  540. fbt_void_void unwatcher = ^{ [watchRef removeObserverWithHandle:handle]; };
  541. // Save all the data that represents this transaction
  542. FTupleTransaction* transaction = [[FTupleTransaction alloc] init];
  543. transaction.path = path;
  544. transaction.update = update;
  545. transaction.onComplete = onComplete;
  546. transaction.status = FTransactionInitializing;
  547. transaction.order = [FUtilities LUIDGenerator];
  548. transaction.applyLocally = applyLocally;
  549. transaction.retryCount = 0;
  550. transaction.unwatcher = unwatcher;
  551. transaction.currentWriteId = nil;
  552. transaction.currentInputSnapshot = nil;
  553. transaction.currentOutputSnapshotRaw = nil;
  554. transaction.currentOutputSnapshotResolved = nil;
  555. // Run transaction initially
  556. id<FNode> currentState = [self latestStateAtPath:path excludeWriteIds:nil];
  557. transaction.currentInputSnapshot = currentState;
  558. FIRMutableData * mutableCurrent = [[FIRMutableData alloc] initWithNode:currentState];
  559. FIRTransactionResult * result = transaction.update(mutableCurrent);
  560. if (!result.isSuccess) {
  561. // Abort the transaction
  562. transaction.unwatcher();
  563. transaction.currentOutputSnapshotRaw = nil;
  564. transaction.currentOutputSnapshotResolved = nil;
  565. if (transaction.onComplete) {
  566. FIRDatabaseReference *ref = [[FIRDatabaseReference alloc] initWithRepo:self path:transaction.path];
  567. FIndexedNode *indexedNode = [FIndexedNode indexedNodeWithNode:transaction.currentInputSnapshot];
  568. FIRDataSnapshot *snap = [[FIRDataSnapshot alloc] initWithRef:ref indexedNode:indexedNode];
  569. [self.eventRaiser raiseCallback:^{
  570. transaction.onComplete(nil, NO, snap);
  571. }];
  572. }
  573. } else {
  574. // Note: different from js. We don't need to validate, FIRMutableData does validation.
  575. // We also don't have to worry about priorities. Just mark as run and add to queue.
  576. transaction.status = FTransactionRun;
  577. FTree* queueNode = [self.transactionQueueTree subTree:transaction.path];
  578. NSMutableArray* nodeQueue = [queueNode getValue];
  579. if (nodeQueue == nil) {
  580. nodeQueue = [[NSMutableArray alloc] init];
  581. }
  582. [nodeQueue addObject:transaction];
  583. [queueNode setValue:nodeQueue];
  584. // Update visibleData and raise events
  585. // Note: We intentionally raise events after updating all of our transaction state, since the user could
  586. // start new transactions from the event callbacks
  587. NSDictionary* serverValues = [FServerValues generateServerValues:self.serverClock];
  588. id<FNode> newValUnresolved = [result.update nodeValue];
  589. id<FNode> newVal = [FServerValues resolveDeferredValueSnapshot:newValUnresolved withServerValues:serverValues];
  590. transaction.currentOutputSnapshotRaw = newValUnresolved;
  591. transaction.currentOutputSnapshotResolved = newVal;
  592. transaction.currentWriteId = [NSNumber numberWithInteger:[self nextWriteId]];
  593. NSArray *events = [self.serverSyncTree applyUserOverwriteAtPath:path newData:newVal
  594. writeId:[transaction.currentWriteId integerValue]
  595. isVisible:transaction.applyLocally];
  596. [self.eventRaiser raiseEvents:events];
  597. [self sendAllReadyTransactions];
  598. }
  599. }
  600. /**
  601. * @param writeIdsToExclude A specific set to exclude
  602. */
  603. - (id<FNode>) latestStateAtPath:(FPath *)path excludeWriteIds:(NSArray *)writeIdsToExclude {
  604. id<FNode> latestState = [self.serverSyncTree calcCompleteEventCacheAtPath:path excludeWriteIds:writeIdsToExclude];
  605. return latestState ? latestState : [FEmptyNode emptyNode];
  606. }
  607. /**
  608. * Sends any already-run transactions that aren't waiting for outstanding transactions to complete.
  609. *
  610. * Externally, call the version with no arguments.
  611. * Internally, calls itself recursively with a particular transactionQueueTree node to recurse through the tree
  612. */
  613. - (void) sendAllReadyTransactions {
  614. FTree* node = self.transactionQueueTree;
  615. [self pruneCompletedTransactionsBelowNode:node];
  616. [self sendReadyTransactionsForTree:node];
  617. }
  618. - (void) sendReadyTransactionsForTree:(FTree *)node {
  619. NSMutableArray* queue = [node getValue];
  620. if (queue != nil) {
  621. queue = [self buildTransactionQueueAtNode:node];
  622. NSAssert([queue count] > 0, @"Sending zero length transaction queue");
  623. NSUInteger notRunIndex = [queue indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
  624. return ((FTupleTransaction*)obj).status != FTransactionRun;
  625. }];
  626. // If they're all run (and not sent), we can send them. Else, we must wait.
  627. if (notRunIndex == NSNotFound) {
  628. [self sendTransactionQueue:queue atPath:node.path];
  629. }
  630. } else if ([node hasChildren]) {
  631. [node forEachChild:^(FTree *child) {
  632. [self sendReadyTransactionsForTree:child];
  633. }];
  634. }
  635. }
  636. /**
  637. * Given a list of run transactions, send them to the server and then handle the result (success or failure).
  638. */
  639. - (void) sendTransactionQueue:(NSMutableArray *)queue atPath:(FPath *)path {
  640. // Mark transactions as sent and bump the retry count
  641. NSMutableArray *writeIdsToExclude = [[NSMutableArray alloc] init];
  642. for (FTupleTransaction *transaction in queue) {
  643. [writeIdsToExclude addObject:transaction.currentWriteId];
  644. }
  645. id<FNode> latestState = [self latestStateAtPath:path excludeWriteIds:writeIdsToExclude];
  646. id<FNode> snapToSend = latestState;
  647. NSString *latestHash = [latestState dataHash];
  648. for (FTupleTransaction* transaction in queue) {
  649. NSAssert(transaction.status == FTransactionRun, @"[FRepo sendTransactionQueue:] items in queue should all be run.");
  650. FFLog(@"I-RDB038021", @"Transaction at %@ set to SENT", transaction.path);
  651. transaction.status = FTransactionSent;
  652. transaction.retryCount++;
  653. FPath *relativePath = [FPath relativePathFrom:path to:transaction.path];
  654. // If we've gotten to this point, the output snapshot must be defined.
  655. snapToSend = [snapToSend updateChild:relativePath withNewChild:transaction.currentOutputSnapshotRaw];
  656. }
  657. id dataToSend = [snapToSend valForExport:YES];
  658. NSString *pathToSend = [path description];
  659. latestHash = self.hijackHash ? @"badhash" : latestHash;
  660. // Send the put
  661. [self.connection putData:dataToSend forPath:pathToSend withHash:latestHash withCallback:^(NSString *status, NSString *errorReason) {
  662. FFLog(@"I-RDB038022", @"Transaction put response: %@ : %@", pathToSend, status);
  663. NSMutableArray *events = [[NSMutableArray alloc] init];
  664. if ([status isEqualToString:kFWPResponseForActionStatusOk]) {
  665. // Queue up the callbacks and fire them after cleaning up all of our transaction state, since
  666. // the callback could trigger more transactions or sets.
  667. NSMutableArray *callbacks = [[NSMutableArray alloc] init];
  668. for (FTupleTransaction *transaction in queue) {
  669. transaction.status = FTransactionCompleted;
  670. [events addObjectsFromArray:[self.serverSyncTree ackUserWriteWithWriteId:[transaction.currentWriteId integerValue]
  671. revert:NO
  672. persist:NO
  673. clock:self.serverClock]];
  674. if (transaction.onComplete) {
  675. // We never unset the output snapshot, and given that this transaction is complete, it should be set
  676. id <FNode> node = transaction.currentOutputSnapshotResolved;
  677. FIndexedNode *indexedNode = [FIndexedNode indexedNodeWithNode:node];
  678. FIRDatabaseReference *ref = [[FIRDatabaseReference alloc] initWithRepo:self path:transaction.path];
  679. FIRDataSnapshot *snapshot = [[FIRDataSnapshot alloc] initWithRef:ref indexedNode:indexedNode];
  680. fbt_void_void cb = ^{
  681. transaction.onComplete(nil, YES, snapshot);
  682. };
  683. [callbacks addObject:[cb copy]];
  684. }
  685. transaction.unwatcher();
  686. }
  687. // Now remove the completed transactions.
  688. [self pruneCompletedTransactionsBelowNode:[self.transactionQueueTree subTree:path]];
  689. // There may be pending transactions that we can now send.
  690. [self sendAllReadyTransactions];
  691. // Finally, trigger onComplete callbacks
  692. [self.eventRaiser raiseCallbacks:callbacks];
  693. } else {
  694. // transactions are no longer sent. Update their status appropriately.
  695. if ([status isEqualToString:kFWPResponseForActionStatusDataStale]) {
  696. for (FTupleTransaction *transaction in queue) {
  697. if (transaction.status == FTransactionSentNeedsAbort) {
  698. transaction.status = FTransactionNeedsAbort;
  699. } else {
  700. transaction.status = FTransactionRun;
  701. }
  702. }
  703. } else {
  704. FFWarn(@"I-RDB038023", @"runTransactionBlock: at %@ failed: %@", path, status);
  705. for (FTupleTransaction *transaction in queue) {
  706. transaction.status = FTransactionNeedsAbort;
  707. [transaction setAbortStatus:status reason:errorReason];
  708. }
  709. }
  710. }
  711. [self rerunTransactionsForPath:path];
  712. [self.eventRaiser raiseEvents:events];
  713. }];
  714. }
  715. /**
  716. * Finds all transactions dependent on the data at changed Path and reruns them.
  717. *
  718. * Should be called any time cached data changes.
  719. *
  720. * Return the highest path that was affected by rerunning transactions. This is the path at which events need to
  721. * be raised for.
  722. */
  723. - (FPath *) rerunTransactionsForPath:(FPath *)changedPath {
  724. // For the common case that there are no transactions going on, skip all this!
  725. if ([self.transactionQueueTree isEmpty]) {
  726. return changedPath;
  727. } else {
  728. FTree* rootMostTransactionNode = [self getAncestorTransactionNodeForPath:changedPath];
  729. FPath* path = rootMostTransactionNode.path;
  730. NSArray* queue = [self buildTransactionQueueAtNode:rootMostTransactionNode];
  731. [self rerunTransactionQueue:queue atPath:path];
  732. return path;
  733. }
  734. }
  735. /**
  736. * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot).
  737. */
  738. - (void) rerunTransactionQueue:(NSArray *)queue atPath:(FPath *)path {
  739. if (queue.count == 0) {
  740. return; // nothing to do
  741. }
  742. // Queue up the callbacks and fire them after cleaning up all of our transaction state, since
  743. // the callback could trigger more transactions or sets.
  744. NSMutableArray *events = [[NSMutableArray alloc] init];
  745. NSMutableArray *callbacks = [[NSMutableArray alloc] init];
  746. // Ignore, by default, all of the sets in this queue, since we're re-running all of them. However, we want to include
  747. // the results of new sets triggered as part of this re-run, so we don't want to ignore a range, just these specific
  748. // sets.
  749. NSMutableArray *writeIdsToExclude = [[NSMutableArray alloc] init];
  750. for (FTupleTransaction *transaction in queue) {
  751. [writeIdsToExclude addObject:transaction.currentWriteId];
  752. }
  753. for (FTupleTransaction* transaction in queue) {
  754. FPath* relativePath __unused = [FPath relativePathFrom:path to:transaction.path];
  755. BOOL abortTransaction = NO;
  756. NSAssert(relativePath != nil, @"[FRepo rerunTransactionsQueue:] relativePath should not be null.");
  757. if (transaction.status == FTransactionNeedsAbort) {
  758. abortTransaction = YES;
  759. if (![transaction.abortStatus isEqualToString:kFErrorWriteCanceled]) {
  760. NSArray *ackEvents = [self.serverSyncTree ackUserWriteWithWriteId:[transaction.currentWriteId integerValue]
  761. revert:YES
  762. persist:NO
  763. clock:self.serverClock];
  764. [events addObjectsFromArray:ackEvents];
  765. }
  766. } else if (transaction.status == FTransactionRun) {
  767. if (transaction.retryCount >= kFTransactionMaxRetries) {
  768. abortTransaction = YES;
  769. [transaction setAbortStatus:kFTransactionTooManyRetries reason:nil];
  770. [events addObjectsFromArray:[self.serverSyncTree ackUserWriteWithWriteId:[transaction.currentWriteId integerValue]
  771. revert:YES
  772. persist:NO
  773. clock:self.serverClock]];
  774. } else {
  775. // This code reruns a transaction
  776. id<FNode> currentNode = [self latestStateAtPath:transaction.path excludeWriteIds:writeIdsToExclude];
  777. transaction.currentInputSnapshot = currentNode;
  778. FIRMutableData * mutableCurrent = [[FIRMutableData alloc] initWithNode:currentNode];
  779. FIRTransactionResult * result = transaction.update(mutableCurrent);
  780. if (result.isSuccess) {
  781. NSNumber *oldWriteId = transaction.currentWriteId;
  782. NSDictionary* serverValues = [FServerValues generateServerValues:self.serverClock];
  783. id<FNode> newVal = [result.update nodeValue];
  784. id<FNode> newValResolved = [FServerValues resolveDeferredValueSnapshot:newVal withServerValues:serverValues];
  785. transaction.currentOutputSnapshotRaw = newVal;
  786. transaction.currentOutputSnapshotResolved = newValResolved;
  787. transaction.currentWriteId = [NSNumber numberWithInteger:[self nextWriteId]];
  788. // Mutates writeIdsToExclude in place
  789. [writeIdsToExclude removeObject:oldWriteId];
  790. [events addObjectsFromArray:[self.serverSyncTree applyUserOverwriteAtPath:transaction.path
  791. newData:transaction.currentOutputSnapshotResolved
  792. writeId:[transaction.currentWriteId integerValue]
  793. isVisible:transaction.applyLocally]];
  794. [events addObjectsFromArray:[self.serverSyncTree ackUserWriteWithWriteId:[oldWriteId integerValue]
  795. revert:YES
  796. persist:NO
  797. clock:self.serverClock]];
  798. } else {
  799. abortTransaction = YES;
  800. // The user aborted the transaction. JS treats ths as a "nodata" abort, but it's not an error, so we don't send them an error.
  801. [transaction setAbortStatus:nil reason:nil];
  802. [events addObjectsFromArray:[self.serverSyncTree ackUserWriteWithWriteId:[transaction.currentWriteId integerValue]
  803. revert:YES
  804. persist:NO
  805. clock:self.serverClock]];
  806. }
  807. }
  808. }
  809. [self.eventRaiser raiseEvents:events];
  810. events = nil;
  811. if (abortTransaction) {
  812. // Abort
  813. transaction.status = FTransactionCompleted;
  814. transaction.unwatcher();
  815. if (transaction.onComplete) {
  816. FIRDatabaseReference * ref = [[FIRDatabaseReference alloc] initWithRepo:self path:transaction.path];
  817. FIndexedNode *lastInput = [FIndexedNode indexedNodeWithNode:transaction.currentInputSnapshot];
  818. FIRDataSnapshot * snap = [[FIRDataSnapshot alloc] initWithRef:ref indexedNode:lastInput];
  819. fbt_void_void cb = ^{
  820. // Unlike JS, no need to check for "nodata" because ObjC has abortError = nil
  821. transaction.onComplete(transaction.abortError, NO, snap);
  822. };
  823. [callbacks addObject:[cb copy]];
  824. }
  825. }
  826. }
  827. // Note: unlike current js client, we don't need to preserve priority. Users can set priority via FIRMutableData
  828. // Clean up completed transactions.
  829. [self pruneCompletedTransactionsBelowNode:self.transactionQueueTree];
  830. // Now fire callbacks, now that we're in a good, known state.
  831. [self.eventRaiser raiseCallbacks:callbacks];
  832. // Try to send the transaction result to the server
  833. [self sendAllReadyTransactions];
  834. }
  835. - (FTree *) getAncestorTransactionNodeForPath:(FPath *)path {
  836. FTree* transactionNode = self.transactionQueueTree;
  837. while (![path isEmpty] && [transactionNode getValue] == nil) {
  838. NSString* front = [path getFront];
  839. transactionNode = [transactionNode subTree:[[FPath alloc] initWith:front]];
  840. path = [path popFront];
  841. }
  842. return transactionNode;
  843. }
  844. - (NSMutableArray *) buildTransactionQueueAtNode:(FTree *)node {
  845. NSMutableArray* queue = [[NSMutableArray alloc] init];
  846. [self aggregateTransactionQueuesForNode:node andQueue:queue];
  847. [queue sortUsingComparator:^NSComparisonResult(FTupleTransaction* obj1, FTupleTransaction* obj2) {
  848. return [obj1.order compare:obj2.order];
  849. }];
  850. return queue;
  851. }
  852. - (void) aggregateTransactionQueuesForNode:(FTree *)node andQueue:(NSMutableArray *)queue {
  853. NSArray* nodeQueue = [node getValue];
  854. [queue addObjectsFromArray:nodeQueue];
  855. [node forEachChild:^(FTree *child) {
  856. [self aggregateTransactionQueuesForNode:child andQueue:queue];
  857. }];
  858. }
  859. /**
  860. * Remove COMPLETED transactions at or below this node in the transactionQueueTree
  861. */
  862. - (void) pruneCompletedTransactionsBelowNode:(FTree *)node {
  863. NSMutableArray* queue = [node getValue];
  864. if (queue != nil) {
  865. int i = 0;
  866. // remove all of the completed transactions from the queue
  867. while (i < queue.count) {
  868. FTupleTransaction* transaction = [queue objectAtIndex:i];
  869. if (transaction.status == FTransactionCompleted) {
  870. [queue removeObjectAtIndex:i];
  871. } else {
  872. i++;
  873. }
  874. }
  875. if (queue.count > 0) {
  876. [node setValue:queue];
  877. } else {
  878. [node setValue:nil];
  879. }
  880. }
  881. [node forEachChildMutationSafe:^(FTree *child) {
  882. [self pruneCompletedTransactionsBelowNode:child];
  883. }];
  884. }
  885. /**
  886. * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a setValue: or
  887. * updateChildValues: since we consider them incompatible with transactions
  888. *
  889. * @param path path for which we want to abort related transactions.
  890. */
  891. - (FPath *) abortTransactionsAtPath:(FPath *)path error:(NSString *)error {
  892. // For the common case that there are no transactions going on, skip all this!
  893. if ([self.transactionQueueTree isEmpty]) {
  894. return path;
  895. } else {
  896. FPath* affectedPath = [self getAncestorTransactionNodeForPath:path].path;
  897. FTree* transactionNode = [self.transactionQueueTree subTree:path];
  898. [transactionNode forEachAncestor:^BOOL(FTree *ancestor) {
  899. [self abortTransactionsAtNode:ancestor error:error];
  900. return NO;
  901. }];
  902. [self abortTransactionsAtNode:transactionNode error:error];
  903. [transactionNode forEachDescendant:^(FTree *child) {
  904. [self abortTransactionsAtNode:child error:error];
  905. }];
  906. return affectedPath;
  907. }
  908. }
  909. /**
  910. * Abort transactions stored in this transactions queue node.
  911. *
  912. * @param node Node to abort transactions for.
  913. */
  914. - (void) abortTransactionsAtNode:(FTree *)node error:(NSString *)error {
  915. NSMutableArray* queue = [node getValue];
  916. if (queue != nil) {
  917. // Queue up the callbacks and fire them after cleaning up all of our transaction state, since
  918. // can be immediately aborted and removed.
  919. NSMutableArray* callbacks = [[NSMutableArray alloc] init];
  920. // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones
  921. // can be immediately aborted and removed
  922. NSMutableArray *events = [[NSMutableArray alloc] init];
  923. int lastSent = -1;
  924. // Note: all of the sent transactions will be at the front of the queue, so safe to increment lastSent
  925. for (FTupleTransaction* transaction in queue) {
  926. if (transaction.status == FTransactionSentNeedsAbort) {
  927. // No-op. already marked.
  928. } else if (transaction.status == FTransactionSent) {
  929. // Mark this transaction for abort when it returns
  930. lastSent++;
  931. transaction.status = FTransactionSentNeedsAbort;
  932. [transaction setAbortStatus:error reason:nil];
  933. } else {
  934. // we can abort this immediately
  935. transaction.unwatcher();
  936. if ([error isEqualToString:kFTransactionSet]) {
  937. [events addObjectsFromArray:[self.serverSyncTree ackUserWriteWithWriteId:[transaction.currentWriteId integerValue]
  938. revert:YES
  939. persist:NO
  940. clock:self.serverClock]];
  941. } else {
  942. // If it was cancelled it was already removed from the sync tree, no need to ack
  943. NSAssert([error isEqualToString:kFErrorWriteCanceled], nil);
  944. }
  945. if (transaction.onComplete) {
  946. NSError* abortReason = [FUtilities errorForStatus:error andReason:nil];
  947. FIRDataSnapshot * snapshot = nil;
  948. fbt_void_void cb = ^{
  949. transaction.onComplete(abortReason, NO, snapshot);
  950. };
  951. [callbacks addObject:[cb copy]];
  952. }
  953. }
  954. }
  955. if (lastSent == -1) {
  956. // We're not waiting for any sent transactions. We can clear the queue.
  957. [node setValue:nil];
  958. } else {
  959. // Remove the transactions we aborted
  960. NSRange theRange;
  961. theRange.location = lastSent + 1;
  962. theRange.length = queue.count - theRange.location;
  963. [queue removeObjectsInRange:theRange];
  964. }
  965. // Now fire the callbacks
  966. [self.eventRaiser raiseEvents:events];
  967. [self.eventRaiser raiseCallbacks:callbacks];
  968. }
  969. }
  970. @end