FRepo.m 63 KB

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