FRepo.m 64 KB

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