FRepo.m 58 KB

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