FRepo.m 64 KB

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