FRepo.m 66 KB

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