FRepo.m 64 KB

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