FRepo.m 64 KB

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