FPersistentConnection.m 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334
  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/FIRDatabaseConfig.h"
  19. #import "FirebaseDatabase/Sources/Constants/FConstants.h"
  20. #import "FirebaseDatabase/Sources/Core/FCompoundHash.h"
  21. #import "FirebaseDatabase/Sources/Core/FPersistentConnection.h"
  22. #import "FirebaseDatabase/Sources/Core/FQueryParams.h"
  23. #import "FirebaseDatabase/Sources/Core/FQuerySpec.h"
  24. #import "FirebaseDatabase/Sources/Core/FRangeMerge.h"
  25. #import "FirebaseDatabase/Sources/Core/FSyncTree.h"
  26. #import "FirebaseDatabase/Sources/Core/Utilities/FIRRetryHelper.h"
  27. #import "FirebaseDatabase/Sources/FIRDatabaseConfig_Private.h"
  28. #import "FirebaseDatabase/Sources/FIndex.h"
  29. #import "FirebaseDatabase/Sources/Login/FIRDatabaseConnectionContextProvider.h"
  30. #import "FirebaseDatabase/Sources/Public/FirebaseDatabase/FIRDatabaseReference.h"
  31. #import "FirebaseDatabase/Sources/Snapshot/FSnapshotUtilities.h"
  32. #import "FirebaseDatabase/Sources/Utilities/FAtomicNumber.h"
  33. #import "FirebaseDatabase/Sources/Utilities/FUtilities.h"
  34. #import "FirebaseDatabase/Sources/Utilities/Tuples/FTupleCallbackStatus.h"
  35. #import "FirebaseDatabase/Sources/Utilities/Tuples/FTupleOnDisconnect.h"
  36. #if TARGET_OS_WATCH
  37. #import <WatchKit/WatchKit.h>
  38. #else
  39. #import <SystemConfiguration/SystemConfiguration.h>
  40. #endif // TARGET_OS_WATCH
  41. #import <dlfcn.h>
  42. #import <netinet/in.h>
  43. @interface FOutstandingQuery : NSObject
  44. @property(nonatomic, strong) FQuerySpec *query;
  45. @property(nonatomic, strong) NSNumber *tagId;
  46. @property(nonatomic, strong) id<FSyncTreeHash> syncTreeHash;
  47. @property(nonatomic, copy) fbt_void_nsstring onComplete;
  48. @end
  49. @implementation FOutstandingQuery
  50. @end
  51. @interface FOutstandingPut : NSObject
  52. @property(nonatomic, strong) NSString *action;
  53. @property(nonatomic, strong) NSDictionary *request;
  54. @property(nonatomic, copy) fbt_void_nsstring_nsstring onCompleteBlock;
  55. @property(nonatomic) BOOL sent;
  56. @end
  57. @implementation FOutstandingPut
  58. @end
  59. @interface FOutstandingGet : NSObject
  60. @property(nonatomic, strong) NSDictionary *request;
  61. @property(nonatomic, copy) fbt_void_nsstring_id_nsstring onCompleteBlock;
  62. @property(nonatomic) BOOL sent;
  63. @end
  64. @implementation FOutstandingGet
  65. @end
  66. typedef enum {
  67. ConnectionStateDisconnected,
  68. ConnectionStateGettingToken,
  69. ConnectionStateConnecting,
  70. ConnectionStateAuthenticating,
  71. ConnectionStateConnected
  72. } ConnectionState;
  73. @interface FPersistentConnection () {
  74. ConnectionState connectionState;
  75. BOOL firstConnection;
  76. NSTimeInterval reconnectDelay;
  77. NSTimeInterval lastConnectionAttemptTime;
  78. NSTimeInterval lastConnectionEstablishedTime;
  79. #if !TARGET_OS_WATCH
  80. SCNetworkReachabilityRef reachability;
  81. #endif // !TARGET_OS_WATCH
  82. }
  83. - (int)getNextRequestNumber;
  84. - (void)onDataPushWithAction:(NSString *)action andBody:(NSDictionary *)body;
  85. - (void)handleTimestamp:(NSNumber *)timestamp;
  86. - (void)sendOnDisconnectAction:(NSString *)action
  87. forPath:(NSString *)pathString
  88. withData:(id)data
  89. andCallback:(fbt_void_nsstring_nsstring)callback;
  90. @property(nonatomic, strong) FConnection *realtime;
  91. @property(nonatomic, strong) NSMutableDictionary *listens;
  92. @property(nonatomic, strong) NSMutableDictionary *outstandingPuts;
  93. @property(nonatomic, strong) NSMutableDictionary *outstandingGets;
  94. @property(nonatomic, strong) NSMutableArray *onDisconnectQueue;
  95. @property(nonatomic, strong) FRepoInfo *repoInfo;
  96. @property(nonatomic, strong) FAtomicNumber *putCounter;
  97. @property(nonatomic, strong) FAtomicNumber *getCounter;
  98. @property(nonatomic, strong) FAtomicNumber *requestNumber;
  99. @property(nonatomic, strong) NSMutableDictionary *requestCBHash;
  100. @property(nonatomic, strong) FIRDatabaseConfig *config;
  101. @property(nonatomic) NSUInteger unackedListensCount;
  102. @property(nonatomic, strong) NSMutableArray *putsToAck;
  103. @property(nonatomic, strong) dispatch_queue_t dispatchQueue;
  104. @property(nonatomic, strong) NSString *lastSessionID;
  105. @property(nonatomic, strong) NSMutableSet *interruptReasons;
  106. @property(nonatomic, strong) FIRRetryHelper *retryHelper;
  107. @property(nonatomic, strong) id<FIRDatabaseConnectionContextProvider>
  108. contextProvider;
  109. @property(nonatomic, strong) NSString *authToken;
  110. @property(nonatomic) BOOL forceTokenRefreshes;
  111. @property(nonatomic) NSUInteger currentFetchTokenAttempt;
  112. @end
  113. @implementation FPersistentConnection
  114. - (id)initWithRepoInfo:(FRepoInfo *)repoInfo
  115. dispatchQueue:(dispatch_queue_t)dispatchQueue
  116. config:(FIRDatabaseConfig *)config {
  117. self = [super init];
  118. if (self) {
  119. self->_config = config;
  120. self->_repoInfo = repoInfo;
  121. self->_dispatchQueue = dispatchQueue;
  122. self->_contextProvider = config.contextProvider;
  123. NSAssert(self->_contextProvider != nil,
  124. @"Expected auth token provider");
  125. self.interruptReasons = [NSMutableSet set];
  126. self.listens = [[NSMutableDictionary alloc] init];
  127. self.outstandingPuts = [[NSMutableDictionary alloc] init];
  128. self.outstandingGets = [[NSMutableDictionary alloc] init];
  129. self.onDisconnectQueue = [[NSMutableArray alloc] init];
  130. self.putCounter = [[FAtomicNumber alloc] init];
  131. self.getCounter = [[FAtomicNumber alloc] init];
  132. self.requestNumber = [[FAtomicNumber alloc] init];
  133. self.requestCBHash = [[NSMutableDictionary alloc] init];
  134. self.unackedListensCount = 0;
  135. self.putsToAck = [NSMutableArray array];
  136. connectionState = ConnectionStateDisconnected;
  137. firstConnection = YES;
  138. reconnectDelay = kPersistentConnReconnectMinDelay;
  139. self->_retryHelper = [[FIRRetryHelper alloc]
  140. initWithDispatchQueue:dispatchQueue
  141. minRetryDelayAfterFailure:kPersistentConnReconnectMinDelay
  142. maxRetryDelay:kPersistentConnReconnectMaxDelay
  143. retryExponent:kPersistentConnReconnectMultiplier
  144. jitterFactor:0.7];
  145. [self setupNotifications];
  146. // Make sure we don't actually connect until open is called
  147. [self interruptForReason:kFInterruptReasonWaitingForOpen];
  148. }
  149. // nb: The reason establishConnection isn't called here like the JS version
  150. // is because callers need to set the delegate first. The ctor can be
  151. // modified to accept the delegate but that deviates from normal ios
  152. // conventions. After the delegate has been set, the caller is responsible
  153. // for calling establishConnection:
  154. return self;
  155. }
  156. - (void)dealloc {
  157. #if !TARGET_OS_WATCH
  158. if (reachability) {
  159. // Unschedule the notifications
  160. SCNetworkReachabilitySetDispatchQueue(reachability, NULL);
  161. CFRelease(reachability);
  162. }
  163. #endif // !TARGET_OS_WATCH
  164. }
  165. #pragma mark -
  166. #pragma mark Public methods
  167. - (void)open {
  168. [self resumeForReason:kFInterruptReasonWaitingForOpen];
  169. }
  170. /**
  171. * Note that the listens dictionary has a type of Map[String (pathString),
  172. * Map[FQueryParams, FOutstandingQuery]]
  173. *
  174. * This means, for each path we care about, there are sets of queryParams that
  175. * correspond to an FOutstandingQuery object. There can be multiple sets at a
  176. * path since we overlap listens for a short time while adding or removing a
  177. * query from a location in the tree.
  178. */
  179. - (void)listen:(FQuerySpec *)query
  180. tagId:(NSNumber *)tagId
  181. hash:(id<FSyncTreeHash>)hash
  182. onComplete:(fbt_void_nsstring)onComplete {
  183. FFLog(@"I-RDB034001", @"Listen called for %@", query);
  184. NSAssert(self.listens[query] == nil,
  185. @"listen() called twice for the same query");
  186. NSAssert(query.isDefault || !query.loadsAllData,
  187. @"listen called for non-default but complete query");
  188. FOutstandingQuery *outstanding = [[FOutstandingQuery alloc] init];
  189. outstanding.query = query;
  190. outstanding.tagId = tagId;
  191. outstanding.syncTreeHash = hash;
  192. outstanding.onComplete = onComplete;
  193. [self.listens setObject:outstanding forKey:query];
  194. if ([self connected]) {
  195. [self sendListen:outstanding];
  196. }
  197. }
  198. - (void)putData:(id)data
  199. forPath:(NSString *)pathString
  200. withHash:(NSString *)hash
  201. withCallback:(fbt_void_nsstring_nsstring)onComplete {
  202. [self putInternal:data
  203. forAction:kFWPRequestActionPut
  204. forPath:pathString
  205. withHash:hash
  206. withCallback:onComplete];
  207. }
  208. - (void)mergeData:(id)data
  209. forPath:(NSString *)pathString
  210. withCallback:(fbt_void_nsstring_nsstring)onComplete {
  211. [self putInternal:data
  212. forAction:kFWPRequestActionMerge
  213. forPath:pathString
  214. withHash:nil
  215. withCallback:onComplete];
  216. }
  217. - (void)onDisconnectPutData:(id)data
  218. forPath:(FPath *)path
  219. withCallback:(fbt_void_nsstring_nsstring)callback {
  220. if ([self canSendWrites]) {
  221. [self sendOnDisconnectAction:kFWPRequestActionDisconnectPut
  222. forPath:[path description]
  223. withData:data
  224. andCallback:callback];
  225. } else {
  226. FTupleOnDisconnect *tuple = [[FTupleOnDisconnect alloc] init];
  227. tuple.pathString = [path description];
  228. tuple.action = kFWPRequestActionDisconnectPut;
  229. tuple.data = data;
  230. tuple.onComplete = callback;
  231. [self.onDisconnectQueue addObject:tuple];
  232. }
  233. }
  234. - (void)onDisconnectMergeData:(id)data
  235. forPath:(FPath *)path
  236. withCallback:(fbt_void_nsstring_nsstring)callback {
  237. if ([self canSendWrites]) {
  238. [self sendOnDisconnectAction:kFWPRequestActionDisconnectMerge
  239. forPath:[path description]
  240. withData:data
  241. andCallback:callback];
  242. } else {
  243. FTupleOnDisconnect *tuple = [[FTupleOnDisconnect alloc] init];
  244. tuple.pathString = [path description];
  245. tuple.action = kFWPRequestActionDisconnectMerge;
  246. tuple.data = data;
  247. tuple.onComplete = callback;
  248. [self.onDisconnectQueue addObject:tuple];
  249. }
  250. }
  251. - (void)onDisconnectCancelPath:(FPath *)path
  252. withCallback:(fbt_void_nsstring_nsstring)callback {
  253. if ([self canSendWrites]) {
  254. [self sendOnDisconnectAction:kFWPRequestActionDisconnectCancel
  255. forPath:[path description]
  256. withData:[NSNull null]
  257. andCallback:callback];
  258. } else {
  259. FTupleOnDisconnect *tuple = [[FTupleOnDisconnect alloc] init];
  260. tuple.pathString = [path description];
  261. tuple.action = kFWPRequestActionDisconnectCancel;
  262. tuple.data = [NSNull null];
  263. tuple.onComplete = callback;
  264. [self.onDisconnectQueue addObject:tuple];
  265. }
  266. }
  267. - (void)unlisten:(FQuerySpec *)query tagId:(NSNumber *)tagId {
  268. FPath *path = query.path;
  269. FFLog(@"I-RDB034002", @"Unlistening for %@", query);
  270. NSArray *outstanding = [self removeListen:query];
  271. if (outstanding.count > 0 && [self connected]) {
  272. [self sendUnlisten:path queryParams:query.params tagId:tagId];
  273. }
  274. }
  275. - (void)refreshAuthToken:(NSString *)token {
  276. self.authToken = token;
  277. if ([self connected]) {
  278. if (token != nil) {
  279. [self sendAuthAndRestoreStateAfterComplete:NO];
  280. } else {
  281. [self sendUnauth];
  282. }
  283. }
  284. }
  285. #pragma mark -
  286. #pragma mark Connection status
  287. - (BOOL)connected {
  288. return self->connectionState == ConnectionStateAuthenticating ||
  289. self->connectionState == ConnectionStateConnected;
  290. }
  291. - (BOOL)canSendWrites {
  292. return self->connectionState == ConnectionStateConnected;
  293. }
  294. - (BOOL)canSendReads {
  295. return self->connectionState == ConnectionStateConnected;
  296. }
  297. #pragma mark -
  298. #pragma mark FConnection delegate methods
  299. - (void)onReady:(FConnection *)fconnection
  300. atTime:(NSNumber *)timestamp
  301. sessionID:(NSString *)sessionID {
  302. FFLog(@"I-RDB034003", @"On ready");
  303. lastConnectionEstablishedTime = [[NSDate date] timeIntervalSince1970];
  304. [self handleTimestamp:timestamp];
  305. if (firstConnection) {
  306. [self sendConnectStats];
  307. }
  308. [self restoreAuth];
  309. firstConnection = NO;
  310. self.lastSessionID = sessionID;
  311. dispatch_async(self.dispatchQueue, ^{
  312. [self.delegate onConnect:self];
  313. });
  314. }
  315. - (void)onDataMessage:(FConnection *)fconnection
  316. withMessage:(NSDictionary *)message {
  317. if (message[kFWPRequestNumber] != nil) {
  318. // this is a response to a request we sent
  319. NSNumber *rn = [NSNumber
  320. numberWithInt:[[message objectForKey:kFWPRequestNumber] intValue]];
  321. if ([self.requestCBHash objectForKey:rn]) {
  322. void (^callback)(NSDictionary *) =
  323. [self.requestCBHash objectForKey:rn];
  324. [self.requestCBHash removeObjectForKey:rn];
  325. if (callback) {
  326. // dispatch_async(self.dispatchQueue, ^{
  327. callback([message objectForKey:kFWPResponseForRNData]);
  328. //});
  329. }
  330. }
  331. } else if (message[kFWPRequestError] != nil) {
  332. NSString *error = [message objectForKey:kFWPRequestError];
  333. @throw [[NSException alloc] initWithName:@"FirebaseDatabaseServerError"
  334. reason:error
  335. userInfo:nil];
  336. } else if (message[kFWPAsyncServerAction] != nil) {
  337. // this is a server push of some sort
  338. NSString *action = [message objectForKey:kFWPAsyncServerAction];
  339. NSDictionary *body = [message objectForKey:kFWPAsyncServerPayloadBody];
  340. [self onDataPushWithAction:action andBody:body];
  341. }
  342. }
  343. - (void)onDisconnect:(FConnection *)fconnection
  344. withReason:(FDisconnectReason)reason {
  345. FFLog(@"I-RDB034004", @"Got on disconnect due to %s",
  346. (reason == DISCONNECT_REASON_SERVER_RESET) ? "server_reset"
  347. : "other");
  348. connectionState = ConnectionStateDisconnected;
  349. // Drop the realtime connection
  350. self.realtime = nil;
  351. [self cancelSentTransactions];
  352. [self.requestCBHash removeAllObjects];
  353. self.unackedListensCount = 0;
  354. if ([self shouldReconnect]) {
  355. NSTimeInterval timeSinceLastConnectSucceeded =
  356. [[NSDate date] timeIntervalSince1970] -
  357. lastConnectionEstablishedTime;
  358. BOOL lastConnectionWasSuccessful;
  359. if (lastConnectionEstablishedTime > 0) {
  360. lastConnectionWasSuccessful =
  361. timeSinceLastConnectSucceeded >
  362. kPersistentConnSuccessfulConnectionEstablishedDelay;
  363. } else {
  364. lastConnectionWasSuccessful = NO;
  365. }
  366. if (reason == DISCONNECT_REASON_SERVER_RESET ||
  367. lastConnectionWasSuccessful) {
  368. [self.retryHelper signalSuccess];
  369. }
  370. [self tryScheduleReconnect];
  371. }
  372. lastConnectionEstablishedTime = 0;
  373. [self.delegate onDisconnect:self];
  374. }
  375. - (void)onKill:(FConnection *)fconnection withReason:(NSString *)reason {
  376. FFWarn(@"I-RDB034005",
  377. @"Firebase Database connection was forcefully killed by the server. "
  378. @" Will not attempt reconnect. Reason: %@",
  379. reason);
  380. [self interruptForReason:kFInterruptReasonServerKill];
  381. }
  382. #pragma mark -
  383. #pragma mark Connection handling methods
  384. - (void)interruptForReason:(NSString *)reason {
  385. FFLog(@"I-RDB034006", @"Connection interrupted for: %@", reason);
  386. [self.interruptReasons addObject:reason];
  387. if (self.realtime) {
  388. // Will call onDisconnect and set the connection state to Disconnected
  389. [self.realtime close];
  390. self.realtime = nil;
  391. } else {
  392. [self.retryHelper cancel];
  393. self->connectionState = ConnectionStateDisconnected;
  394. }
  395. // Reset timeouts
  396. [self.retryHelper signalSuccess];
  397. }
  398. - (void)resumeForReason:(NSString *)reason {
  399. FFLog(@"I-RDB034007", @"Connection no longer interrupted for: %@", reason);
  400. [self.interruptReasons removeObject:reason];
  401. if ([self shouldReconnect] &&
  402. connectionState == ConnectionStateDisconnected) {
  403. [self tryScheduleReconnect];
  404. }
  405. }
  406. - (BOOL)shouldReconnect {
  407. return self.interruptReasons.count == 0;
  408. }
  409. - (BOOL)isInterruptedForReason:(NSString *)reason {
  410. return [self.interruptReasons containsObject:reason];
  411. }
  412. #pragma mark -
  413. #pragma mark Private methods
  414. - (void)tryScheduleReconnect {
  415. if ([self shouldReconnect]) {
  416. NSAssert(self->connectionState == ConnectionStateDisconnected,
  417. @"Not in disconnected state: %d", self->connectionState);
  418. BOOL forceRefresh = self.forceTokenRefreshes;
  419. self.forceTokenRefreshes = NO;
  420. FFLog(@"I-RDB034008", @"Scheduling connection attempt");
  421. [self.retryHelper retry:^{
  422. FFLog(@"I-RDB034009", @"Trying to fetch auth token");
  423. NSAssert(self->connectionState == ConnectionStateDisconnected,
  424. @"Not in disconnected state: %d", self->connectionState);
  425. self->connectionState = ConnectionStateGettingToken;
  426. self.currentFetchTokenAttempt++;
  427. NSUInteger thisFetchTokenAttempt = self.currentFetchTokenAttempt;
  428. [self.contextProvider
  429. fetchContextForcingRefresh:forceRefresh
  430. withCallback:^(
  431. FIRDatabaseConnectionContext *context,
  432. NSError *error) {
  433. if (thisFetchTokenAttempt ==
  434. self.currentFetchTokenAttempt) {
  435. if (error != nil) {
  436. self->connectionState =
  437. ConnectionStateDisconnected;
  438. FFLog(@"I-RDB034010",
  439. @"Error fetching token: %@", error);
  440. [self tryScheduleReconnect];
  441. } else {
  442. // Someone could have interrupted us while
  443. // fetching the token, marking the
  444. // connection as Disconnected
  445. if (self->connectionState ==
  446. ConnectionStateGettingToken) {
  447. FFLog(@"I-RDB034011",
  448. @"Successfully fetched token, "
  449. @"opening connection");
  450. [self
  451. openNetworkConnectionWithContext:
  452. context];
  453. } else {
  454. NSAssert(
  455. self->connectionState ==
  456. ConnectionStateDisconnected,
  457. @"Expected connection state "
  458. @"disconnected, but got %d",
  459. self->connectionState);
  460. FFLog(@"I-RDB034012",
  461. @"Not opening connection after "
  462. @"token refresh, because "
  463. @"connection was set to "
  464. @"disconnected.");
  465. }
  466. }
  467. } else {
  468. FFLog(@"I-RDB034013",
  469. @"Ignoring fetch token result, because "
  470. @"this was not the latest attempt.");
  471. }
  472. }];
  473. }];
  474. }
  475. }
  476. - (void)openNetworkConnectionWithContext:
  477. (FIRDatabaseConnectionContext *)context {
  478. NSAssert(self->connectionState == ConnectionStateGettingToken,
  479. @"Trying to open network connection while in wrong state: %d",
  480. self->connectionState);
  481. // TODO: Save entire context?
  482. self.authToken = context.authToken;
  483. self->connectionState = ConnectionStateConnecting;
  484. self.realtime = [[FConnection alloc] initWith:self.repoInfo
  485. andDispatchQueue:self.dispatchQueue
  486. googleAppID:self.config.googleAppID
  487. lastSessionID:self.lastSessionID
  488. appCheckToken:context.appCheckToken];
  489. self.realtime.delegate = self;
  490. [self.realtime open];
  491. }
  492. #if !TARGET_OS_WATCH
  493. static void reachabilityCallback(SCNetworkReachabilityRef ref,
  494. SCNetworkReachabilityFlags flags, void *info) {
  495. if (flags & kSCNetworkReachabilityFlagsReachable) {
  496. FFLog(@"I-RDB034014",
  497. @"Network became reachable. Trigger a connection attempt");
  498. FPersistentConnection *self = (__bridge FPersistentConnection *)info;
  499. // Reset reconnect delay
  500. [self.retryHelper signalSuccess];
  501. if (self->connectionState == ConnectionStateDisconnected) {
  502. [self tryScheduleReconnect];
  503. }
  504. } else {
  505. FFLog(@"I-RDB034015", @"Network is not reachable");
  506. }
  507. }
  508. #endif // !TARGET_OS_WATCH
  509. - (void)enteringForeground {
  510. dispatch_async(self.dispatchQueue, ^{
  511. // Reset reconnect delay
  512. [self.retryHelper signalSuccess];
  513. if (self->connectionState == ConnectionStateDisconnected) {
  514. [self tryScheduleReconnect];
  515. }
  516. });
  517. }
  518. - (void)setupNotifications {
  519. #if TARGET_OS_WATCH
  520. if (@available(watchOS 7.0, *)) {
  521. __weak FPersistentConnection *weakSelf = self;
  522. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  523. [center addObserverForName:WKApplicationWillEnterForegroundNotification
  524. object:nil
  525. queue:nil
  526. usingBlock:^(NSNotification *_Nonnull note) {
  527. [weakSelf enteringForeground];
  528. }];
  529. }
  530. #else
  531. NSString *const *foregroundConstant = (NSString *const *)dlsym(
  532. RTLD_DEFAULT, "UIApplicationWillEnterForegroundNotification");
  533. if (foregroundConstant) {
  534. [[NSNotificationCenter defaultCenter]
  535. addObserver:self
  536. selector:@selector(enteringForeground)
  537. name:*foregroundConstant
  538. object:nil];
  539. }
  540. // An empty address is interpreted a generic internet access
  541. struct sockaddr_in zeroAddress;
  542. bzero(&zeroAddress, sizeof(zeroAddress));
  543. zeroAddress.sin_len = sizeof(zeroAddress);
  544. zeroAddress.sin_family = AF_INET;
  545. reachability = SCNetworkReachabilityCreateWithAddress(
  546. kCFAllocatorDefault, (const struct sockaddr *)&zeroAddress);
  547. SCNetworkReachabilityContext ctx = {0, (__bridge void *)(self), NULL, NULL,
  548. NULL};
  549. if (SCNetworkReachabilitySetCallback(reachability, reachabilityCallback,
  550. &ctx)) {
  551. SCNetworkReachabilitySetDispatchQueue(reachability, self.dispatchQueue);
  552. } else {
  553. FFLog(@"I-RDB034016",
  554. @"Failed to set up network reachability monitoring");
  555. CFRelease(reachability);
  556. reachability = NULL;
  557. }
  558. #endif // !TARGET_OS_WATCH
  559. }
  560. - (void)sendAuthAndRestoreStateAfterComplete:(BOOL)restoreStateAfterComplete {
  561. NSAssert([self connected], @"Must be connected to send auth");
  562. NSAssert(self.authToken != nil,
  563. @"Can't send auth if there is no credential");
  564. NSDictionary *requestData = @{kFWPRequestCredential : self.authToken};
  565. [self sendAction:kFWPRequestActionAuth
  566. body:requestData
  567. sensitive:YES
  568. callback:^(NSDictionary *data) {
  569. self->connectionState = ConnectionStateConnected;
  570. NSString *status =
  571. [data objectForKey:kFWPResponseForActionStatus];
  572. id responseData = [data objectForKey:kFWPResponseForActionData];
  573. if (responseData == nil) {
  574. responseData = @"error";
  575. }
  576. BOOL statusOk =
  577. [status isEqualToString:kFWPResponseForActionStatusOk];
  578. if (statusOk) {
  579. if (restoreStateAfterComplete) {
  580. [self restoreState];
  581. }
  582. } else {
  583. self.authToken = nil;
  584. self.forceTokenRefreshes = YES;
  585. if ([status isEqualToString:@"expired_token"]) {
  586. FFLog(@"I-RDB034017", @"Authentication failed: %@ (%@)",
  587. status, responseData);
  588. } else {
  589. FFWarn(@"I-RDB034018", @"Authentication failed: %@ (%@)",
  590. status, responseData);
  591. }
  592. [self.realtime close];
  593. }
  594. }];
  595. }
  596. - (void)sendUnauth {
  597. [self sendAction:kFWPRequestActionUnauth
  598. body:@{}
  599. sensitive:NO
  600. callback:nil];
  601. }
  602. - (void)onAuthRevokedWithStatus:(NSString *)status
  603. andReason:(NSString *)reason {
  604. // This might be for an earlier token than we just recently sent. But since
  605. // we need to close the connection anyways, we can set it to null here and
  606. // we will refresh the token later on reconnect
  607. if ([status isEqualToString:@"expired_token"]) {
  608. FFLog(@"I-RDB034019", @"Auth token revoked: %@ (%@)", status, reason);
  609. } else {
  610. FFWarn(@"I-RDB034020", @"Auth token revoked: %@ (%@)", status, reason);
  611. }
  612. self.authToken = nil;
  613. self.forceTokenRefreshes = YES;
  614. // Try reconnecting on auth revocation
  615. [self.realtime close];
  616. }
  617. - (void)onListenRevoked:(FPath *)path {
  618. NSArray *queries = [self removeAllListensAtPath:path];
  619. for (FOutstandingQuery *query in queries) {
  620. query.onComplete(@"permission_denied");
  621. }
  622. }
  623. - (void)sendOnDisconnectAction:(NSString *)action
  624. forPath:(NSString *)pathString
  625. withData:(id)data
  626. andCallback:(fbt_void_nsstring_nsstring)callback {
  627. NSDictionary *request =
  628. @{kFWPRequestPath : pathString, kFWPRequestData : data};
  629. FFLog(@"I-RDB034021", @"onDisconnect %@: %@", action, request);
  630. [self sendAction:action
  631. body:request
  632. sensitive:NO
  633. callback:^(NSDictionary *data) {
  634. NSString *status =
  635. [data objectForKey:kFWPResponseForActionStatus];
  636. NSString *errorReason =
  637. [data objectForKey:kFWPResponseForActionData];
  638. callback(status, errorReason);
  639. }];
  640. }
  641. - (void)sendPut:(NSNumber *)index {
  642. NSAssert([self canSendWrites],
  643. @"sendPut called when not able to send writes");
  644. FOutstandingPut *put = self.outstandingPuts[index];
  645. assert(put != nil);
  646. fbt_void_nsstring_nsstring onComplete = put.onCompleteBlock;
  647. // Do not async this block; copying the block insinde sendAction: doesn't
  648. // happen in time (or something) so coredumps
  649. put.sent = YES;
  650. [self sendAction:put.action
  651. body:put.request
  652. sensitive:NO
  653. callback:^(NSDictionary *data) {
  654. FOutstandingPut *currentPut = self.outstandingPuts[index];
  655. if (currentPut == put) {
  656. [self.outstandingPuts removeObjectForKey:index];
  657. if (onComplete != nil) {
  658. NSString *status =
  659. [data objectForKey:kFWPResponseForActionStatus];
  660. NSString *errorReason =
  661. [data objectForKey:kFWPResponseForActionData];
  662. if (self.unackedListensCount == 0) {
  663. onComplete(status, errorReason);
  664. } else {
  665. FTupleCallbackStatus *putToAck =
  666. [[FTupleCallbackStatus alloc] init];
  667. putToAck.block = onComplete;
  668. putToAck.status = status;
  669. putToAck.errorReason = errorReason;
  670. [self.putsToAck addObject:putToAck];
  671. }
  672. }
  673. } else {
  674. FFLog(@"I-RDB034022",
  675. @"Ignoring on complete for put %@ because it was "
  676. @"already removed",
  677. index);
  678. }
  679. }];
  680. }
  681. - (void)sendGet:(NSNumber *)index {
  682. NSAssert([self canSendReads],
  683. @"sendGet called when not able to send reads");
  684. FOutstandingGet *get = self.outstandingGets[index];
  685. NSAssert(get != nil, @"sendGet found no outstanding get at index %@",
  686. index);
  687. if ([get sent]) {
  688. return;
  689. }
  690. get.sent = YES;
  691. [self sendAction:kFWPRequestActionGet
  692. body:get.request
  693. sensitive:NO
  694. callback:^(NSDictionary *data) {
  695. FOutstandingGet *currentGet = self.outstandingGets[index];
  696. if (currentGet == get) {
  697. [self.outstandingGets removeObjectForKey:index];
  698. NSString *status =
  699. [data objectForKey:kFWPResponseForActionStatus];
  700. id resultData = [data objectForKey:kFWPResponseForActionData];
  701. if (resultData == (id)[NSNull null]) {
  702. resultData = nil;
  703. }
  704. if ([status isEqualToString:kFWPResponseForActionStatusOk]) {
  705. get.onCompleteBlock(status, resultData, nil);
  706. return;
  707. }
  708. get.onCompleteBlock(status, nil, resultData);
  709. } else {
  710. FFLog(@"I-RDB034045",
  711. @"Ignoring on complete for get %@ because it was "
  712. @"already removed",
  713. index);
  714. }
  715. }];
  716. }
  717. - (void)sendUnlisten:(FPath *)path
  718. queryParams:(FQueryParams *)queryParams
  719. tagId:(NSNumber *)tagId {
  720. FFLog(@"I-RDB034023", @"Unlisten on %@ for %@", path, queryParams);
  721. NSMutableDictionary *request = [NSMutableDictionary
  722. dictionaryWithObjectsAndKeys:[path toString], kFWPRequestPath, nil];
  723. if (tagId != nil) {
  724. [request setObject:queryParams.wireProtocolParams
  725. forKey:kFWPRequestQueries];
  726. [request setObject:tagId forKey:kFWPRequestTag];
  727. }
  728. [self sendAction:kFWPRequestActionTaggedUnlisten
  729. body:request
  730. sensitive:NO
  731. callback:nil];
  732. }
  733. - (void)putInternal:(id)data
  734. forAction:(NSString *)action
  735. forPath:(NSString *)pathString
  736. withHash:(NSString *)hash
  737. withCallback:(fbt_void_nsstring_nsstring)onComplete {
  738. NSMutableDictionary *request = [NSMutableDictionary
  739. dictionaryWithObjectsAndKeys:pathString, kFWPRequestPath, data,
  740. kFWPRequestData, nil];
  741. if (hash) {
  742. [request setObject:hash forKey:kFWPRequestHash];
  743. }
  744. FOutstandingPut *put = [[FOutstandingPut alloc] init];
  745. put.action = action;
  746. put.request = request;
  747. put.onCompleteBlock = onComplete;
  748. put.sent = NO;
  749. NSNumber *index = [self.putCounter getAndIncrement];
  750. self.outstandingPuts[index] = put;
  751. if ([self canSendWrites]) {
  752. FFLog(@"I-RDB034024", @"Was connected, and added as index: %@", index);
  753. [self sendPut:index];
  754. } else {
  755. FFLog(@"I-RDB034025",
  756. @"Wasn't connected or writes paused, so added to outstanding "
  757. @"puts only. Path: %@",
  758. pathString);
  759. }
  760. }
  761. - (void)getDataAtPath:(NSString *)pathString
  762. withParams:(NSDictionary *)queryWireProtocolParams
  763. withCallback:(fbt_void_nsstring_id_nsstring)onComplete {
  764. NSMutableDictionary *request = [NSMutableDictionary
  765. dictionaryWithObjectsAndKeys:pathString, kFWPRequestPath,
  766. queryWireProtocolParams,
  767. kFWPRequestQueries, nil];
  768. FOutstandingGet *get = [[FOutstandingGet alloc] init];
  769. get.request = request;
  770. get.onCompleteBlock = onComplete;
  771. get.sent = NO;
  772. NSNumber *index = [self.getCounter getAndIncrement];
  773. self.outstandingGets[index] = get;
  774. if (![self connected]) {
  775. dispatch_after(
  776. dispatch_time(DISPATCH_TIME_NOW,
  777. kPersistentConnectionGetConnectTimeout),
  778. self.dispatchQueue, ^{
  779. FOutstandingGet *currGet = self.outstandingGets[index];
  780. if ([currGet sent] || currGet == nil) {
  781. return;
  782. }
  783. FFLog(@"I-RDB034045",
  784. @"get %@ timed out waiting for a connection", index);
  785. currGet.sent = YES;
  786. currGet.onCompleteBlock(kFWPResponseForActionStatusFailed, nil,
  787. kPersistentConnectionOffline);
  788. [self.outstandingGets removeObjectForKey:index];
  789. });
  790. return;
  791. }
  792. if ([self canSendReads]) {
  793. FFLog(@"I-RDB034024", @"Sending get: %@", index);
  794. [self sendGet:index];
  795. }
  796. }
  797. - (void)sendListen:(FOutstandingQuery *)listenSpec {
  798. FQuerySpec *query = listenSpec.query;
  799. FFLog(@"I-RDB034026", @"Listen for %@", query);
  800. NSMutableDictionary *request =
  801. [NSMutableDictionary dictionaryWithObject:[query.path toString]
  802. forKey:kFWPRequestPath];
  803. // Only bother to send query if it's non-default
  804. if (listenSpec.tagId != nil) {
  805. [request setObject:[query.params wireProtocolParams]
  806. forKey:kFWPRequestQueries];
  807. [request setObject:listenSpec.tagId forKey:kFWPRequestTag];
  808. }
  809. [request setObject:[listenSpec.syncTreeHash simpleHash]
  810. forKey:kFWPRequestHash];
  811. if ([listenSpec.syncTreeHash includeCompoundHash]) {
  812. FCompoundHash *compoundHash = [listenSpec.syncTreeHash compoundHash];
  813. NSMutableArray *posts = [NSMutableArray array];
  814. for (FPath *path in compoundHash.posts) {
  815. [posts addObject:path.wireFormat];
  816. }
  817. request[kFWPRequestCompoundHash] = @{
  818. kFWPRequestCompoundHashHashes : compoundHash.hashes,
  819. kFWPRequestCompoundHashPaths : posts
  820. };
  821. }
  822. fbt_void_nsdictionary onResponse = ^(NSDictionary *response) {
  823. FFLog(@"I-RDB034027", @"Listen response %@", response);
  824. // warn in any case, even if the listener was removed
  825. [self warnOnListenWarningsForQuery:query
  826. payload:response[kFWPResponseForActionData]];
  827. FOutstandingQuery *currentListenSpec = self.listens[query];
  828. // only trigger actions if the listen hasn't been removed (and maybe
  829. // readded)
  830. if (currentListenSpec == listenSpec) {
  831. NSString *status = [response objectForKey:kFWPRequestStatus];
  832. if (![status isEqualToString:@"ok"]) {
  833. [self removeListen:query];
  834. }
  835. if (listenSpec.onComplete) {
  836. listenSpec.onComplete(status);
  837. }
  838. }
  839. self.unackedListensCount--;
  840. NSAssert(self.unackedListensCount >= 0,
  841. @"unackedListensCount decremented to be negative.");
  842. if (self.unackedListensCount == 0) {
  843. [self ackPuts];
  844. }
  845. };
  846. [self sendAction:kFWPRequestActionTaggedListen
  847. body:request
  848. sensitive:NO
  849. callback:onResponse];
  850. self.unackedListensCount++;
  851. }
  852. - (void)warnOnListenWarningsForQuery:(FQuerySpec *)query payload:(id)payload {
  853. if (payload != nil && [payload isKindOfClass:[NSDictionary class]]) {
  854. NSDictionary *payloadDict = payload;
  855. id warnings = payloadDict[kFWPResponseDataWarnings];
  856. if (warnings != nil && [warnings isKindOfClass:[NSArray class]]) {
  857. NSArray *warningsArr = warnings;
  858. if ([warningsArr containsObject:@"no_index"]) {
  859. NSString *indexSpec = [NSString
  860. stringWithFormat:@"\".indexOn\": \"%@\"",
  861. [query.params.index queryDefinition]];
  862. NSString *indexPath = [query.path description];
  863. FFWarn(@"I-RDB034028",
  864. @"Using an unspecified index. Your data will be "
  865. @"downloaded and filtered on the client. "
  866. "Consider adding %@ at %@ to your security rules for "
  867. "better performance",
  868. indexSpec, indexPath);
  869. }
  870. }
  871. }
  872. }
  873. - (int)getNextRequestNumber {
  874. return [[self.requestNumber getAndIncrement] intValue];
  875. }
  876. - (void)sendAction:(NSString *)action
  877. body:(NSDictionary *)message
  878. sensitive:(BOOL)sensitive
  879. callback:(void (^)(NSDictionary *data))onMessage {
  880. // Hold onto the onMessage callback for this request before firing it off
  881. NSNumber *rn = [NSNumber numberWithInt:[self getNextRequestNumber]];
  882. NSDictionary *msg = [NSDictionary
  883. dictionaryWithObjectsAndKeys:rn, kFWPRequestNumber, action,
  884. kFWPRequestAction, message,
  885. kFWPRequestPayloadBody, nil];
  886. [self.realtime sendRequest:msg sensitive:sensitive];
  887. if (onMessage) {
  888. // Debug message without a callback; bump the rn, but don't hold onto
  889. // the cb
  890. [self.requestCBHash setObject:[onMessage copy] forKey:rn];
  891. }
  892. }
  893. - (void)cancelSentTransactions {
  894. NSMutableDictionary<NSNumber *, FOutstandingPut *>
  895. *cancelledOutstandingPuts = [[NSMutableDictionary alloc] init];
  896. for (NSNumber *index in self.outstandingPuts) {
  897. FOutstandingPut *put = self.outstandingPuts[index];
  898. if (put.request[kFWPRequestHash] && put.sent) {
  899. // This is a sent transaction put.
  900. cancelledOutstandingPuts[index] = put;
  901. }
  902. }
  903. [cancelledOutstandingPuts
  904. enumerateKeysAndObjectsUsingBlock:^(
  905. NSNumber *index, FOutstandingPut *outstandingPut, BOOL *stop) {
  906. // `onCompleteBlock:` may invoke `rerunTransactionsForPath:` and
  907. // enqueue new writes. We defer calling it until we have finished
  908. // enumerating all existing writes.
  909. outstandingPut.onCompleteBlock(
  910. kFTransactionDisconnect,
  911. @"Client was disconnected while running a transaction");
  912. [self.outstandingPuts removeObjectForKey:index];
  913. }];
  914. }
  915. - (void)onDataPushWithAction:(NSString *)action andBody:(NSDictionary *)body {
  916. FFLog(@"I-RDB034029", @"handleServerMessage: %@, %@", action, body);
  917. id<FPersistentConnectionDelegate> delegate = self.delegate;
  918. if ([action isEqualToString:kFWPAsyncServerDataUpdate] ||
  919. [action isEqualToString:kFWPAsyncServerDataMerge]) {
  920. BOOL isMerge = [action isEqualToString:kFWPAsyncServerDataMerge];
  921. if ([body objectForKey:kFWPAsyncServerDataUpdateBodyPath] &&
  922. [body objectForKey:kFWPAsyncServerDataUpdateBodyData]) {
  923. NSString *path =
  924. [body objectForKey:kFWPAsyncServerDataUpdateBodyPath];
  925. id payloadData =
  926. [body objectForKey:kFWPAsyncServerDataUpdateBodyData];
  927. if (isMerge && [payloadData isKindOfClass:[NSDictionary class]] &&
  928. [payloadData count] == 0) {
  929. // ignore empty merge
  930. } else {
  931. [delegate
  932. onDataUpdate:self
  933. forPath:path
  934. message:payloadData
  935. isMerge:isMerge
  936. tagId:[body objectForKey:
  937. kFWPAsyncServerDataUpdateBodyTag]];
  938. }
  939. } else {
  940. FFLog(
  941. @"I-RDB034030",
  942. @"Malformed data response from server missing path or data: %@",
  943. body);
  944. }
  945. } else if ([action isEqualToString:kFWPAsyncServerDataRangeMerge]) {
  946. NSString *path = body[kFWPAsyncServerDataUpdateBodyPath];
  947. NSArray *ranges = body[kFWPAsyncServerDataUpdateBodyData];
  948. NSNumber *tag = body[kFWPAsyncServerDataUpdateBodyTag];
  949. NSMutableArray *rangeMerges = [NSMutableArray array];
  950. for (NSDictionary *range in ranges) {
  951. NSString *startString = range[kFWPAsyncServerDataUpdateStartPath];
  952. NSString *endString = range[kFWPAsyncServerDataUpdateEndPath];
  953. id updateData = range[kFWPAsyncServerDataUpdateRangeMerge];
  954. id<FNode> updates = [FSnapshotUtilities nodeFrom:updateData];
  955. FPath *start = (startString != nil)
  956. ? [[FPath alloc] initWith:startString]
  957. : nil;
  958. FPath *end =
  959. (endString != nil) ? [[FPath alloc] initWith:endString] : nil;
  960. FRangeMerge *merge = [[FRangeMerge alloc] initWithStart:start
  961. end:end
  962. updates:updates];
  963. [rangeMerges addObject:merge];
  964. }
  965. [delegate onRangeMerge:rangeMerges forPath:path tagId:tag];
  966. } else if ([action isEqualToString:kFWPAsyncServerAuthRevoked]) {
  967. NSString *status = [body objectForKey:kFWPResponseForActionStatus];
  968. NSString *reason = [body objectForKey:kFWPResponseForActionData];
  969. [self onAuthRevokedWithStatus:status andReason:reason];
  970. } else if ([action isEqualToString:kFWPASyncServerListenCancelled]) {
  971. NSString *pathString =
  972. [body objectForKey:kFWPAsyncServerDataUpdateBodyPath];
  973. [self onListenRevoked:[[FPath alloc] initWith:pathString]];
  974. } else if ([action isEqualToString:kFWPAsyncServerSecurityDebug]) {
  975. NSString *msg = [body objectForKey:@"msg"];
  976. if (msg != nil) {
  977. NSArray *msgs = [msg componentsSeparatedByString:@"\n"];
  978. for (NSString *m in msgs) {
  979. FFWarn(@"I-RDB034031", @"%@", m);
  980. }
  981. }
  982. } else {
  983. // TODO: revoke listens, auth, security debug
  984. FFLog(@"I-RDB034032", @"Unsupported action from server: %@", action);
  985. }
  986. }
  987. - (void)restoreAuth {
  988. FFLog(@"I-RDB034033", @"Calling restore state");
  989. NSAssert(self->connectionState == ConnectionStateConnecting,
  990. @"Wanted to restore auth, but was in wrong state: %d",
  991. self->connectionState);
  992. if (self.authToken == nil) {
  993. FFLog(@"I-RDB034034", @"Not restoring auth because token is nil");
  994. self->connectionState = ConnectionStateConnected;
  995. [self restoreState];
  996. } else {
  997. FFLog(@"I-RDB034035", @"Restoring auth");
  998. self->connectionState = ConnectionStateAuthenticating;
  999. [self sendAuthAndRestoreStateAfterComplete:YES];
  1000. }
  1001. }
  1002. - (void)restoreState {
  1003. NSAssert(self->connectionState == ConnectionStateConnected,
  1004. @"Should be connected if we're restoring state, but we are: %d",
  1005. self->connectionState);
  1006. [self.listens enumerateKeysAndObjectsUsingBlock:^(
  1007. FQuerySpec *query, FOutstandingQuery *outstandingListen,
  1008. BOOL *stop) {
  1009. FFLog(@"I-RDB034036", @"Restoring listen for %@", query);
  1010. [self sendListen:outstandingListen];
  1011. }];
  1012. NSArray *putKeys = [[self.outstandingPuts allKeys]
  1013. sortedArrayUsingSelector:@selector(compare:)];
  1014. for (int i = 0; i < [putKeys count]; i++) {
  1015. if ([self.outstandingPuts objectForKey:[putKeys objectAtIndex:i]] !=
  1016. nil) {
  1017. FFLog(@"I-RDB034037", @"Restoring put: %d", i);
  1018. [self sendPut:[putKeys objectAtIndex:i]];
  1019. } else {
  1020. FFLog(@"I-RDB034038", @"Restoring put: skipped nil: %d", i);
  1021. }
  1022. }
  1023. NSArray *getKeys = [[self.outstandingGets allKeys]
  1024. sortedArrayUsingSelector:@selector(compare:)];
  1025. for (int i = 0; i < [getKeys count]; i++) {
  1026. if ([self.outstandingGets objectForKey:[getKeys objectAtIndex:i]] !=
  1027. nil) {
  1028. FFLog(@"I-RDB034037", @"Restoring get: %d", i);
  1029. [self sendGet:[getKeys objectAtIndex:i]];
  1030. } else {
  1031. FFLog(@"I-RDB034038", @"Restoring get: skipped nil: %d", i);
  1032. }
  1033. }
  1034. for (FTupleOnDisconnect *tuple in self.onDisconnectQueue) {
  1035. [self sendOnDisconnectAction:tuple.action
  1036. forPath:tuple.pathString
  1037. withData:tuple.data
  1038. andCallback:tuple.onComplete];
  1039. }
  1040. [self.onDisconnectQueue removeAllObjects];
  1041. }
  1042. - (NSArray *)removeListen:(FQuerySpec *)query {
  1043. NSAssert(query.isDefault || !query.loadsAllData,
  1044. @"removeListen called for non-default but complete query");
  1045. FOutstandingQuery *outstanding = self.listens[query];
  1046. if (!outstanding) {
  1047. FFLog(@"I-RDB034039",
  1048. @"Trying to remove listener for query %@ but no listener exists",
  1049. query);
  1050. return @[];
  1051. } else {
  1052. [self.listens removeObjectForKey:query];
  1053. return @[ outstanding ];
  1054. }
  1055. }
  1056. - (NSArray *)removeAllListensAtPath:(FPath *)path {
  1057. FFLog(@"I-RDB034040", @"Removing all listens at path %@", path);
  1058. NSMutableArray *removed = [NSMutableArray array];
  1059. NSMutableArray *toRemove = [NSMutableArray array];
  1060. [self.listens
  1061. enumerateKeysAndObjectsUsingBlock:^(
  1062. FQuerySpec *spec, FOutstandingQuery *outstanding, BOOL *stop) {
  1063. if ([spec.path isEqual:path]) {
  1064. [removed addObject:outstanding];
  1065. [toRemove addObject:spec];
  1066. }
  1067. }];
  1068. [self.listens removeObjectsForKeys:toRemove];
  1069. return removed;
  1070. }
  1071. - (void)purgeOutstandingWrites {
  1072. // We might have unacked puts in our queue that we need to ack now before we
  1073. // send out any cancels...
  1074. [self ackPuts];
  1075. // Cancel in order
  1076. NSArray *keys = [[self.outstandingPuts allKeys]
  1077. sortedArrayUsingSelector:@selector(compare:)];
  1078. for (NSNumber *key in keys) {
  1079. FOutstandingPut *put = self.outstandingPuts[key];
  1080. if (put.onCompleteBlock != nil) {
  1081. put.onCompleteBlock(kFErrorWriteCanceled, nil);
  1082. }
  1083. }
  1084. for (FTupleOnDisconnect *onDisconnect in self.onDisconnectQueue) {
  1085. if (onDisconnect.onComplete != nil) {
  1086. onDisconnect.onComplete(kFErrorWriteCanceled, nil);
  1087. }
  1088. }
  1089. [self.outstandingPuts removeAllObjects];
  1090. [self.onDisconnectQueue removeAllObjects];
  1091. }
  1092. - (void)ackPuts {
  1093. for (FTupleCallbackStatus *put in self.putsToAck) {
  1094. put.block(put.status, put.errorReason);
  1095. }
  1096. [self.putsToAck removeAllObjects];
  1097. }
  1098. - (void)handleTimestamp:(NSNumber *)timestamp {
  1099. FFLog(@"I-RDB034041", @"Handling timestamp: %@", timestamp);
  1100. double timestampDeltaMs = [timestamp doubleValue] -
  1101. ([[NSDate date] timeIntervalSince1970] * 1000);
  1102. [self.delegate onServerInfoUpdate:self
  1103. updates:@{
  1104. kDotInfoServerTimeOffset : [NSNumber
  1105. numberWithDouble:timestampDeltaMs]
  1106. }];
  1107. }
  1108. - (void)sendStats:(NSDictionary *)stats {
  1109. if ([stats count] > 0) {
  1110. NSDictionary *request = @{kFWPRequestCounters : stats};
  1111. [self sendAction:kFWPRequestActionStats
  1112. body:request
  1113. sensitive:NO
  1114. callback:^(NSDictionary *data) {
  1115. NSString *status =
  1116. [data objectForKey:kFWPResponseForActionStatus];
  1117. NSString *errorReason =
  1118. [data objectForKey:kFWPResponseForActionData];
  1119. BOOL statusOk =
  1120. [status isEqualToString:kFWPResponseForActionStatusOk];
  1121. if (!statusOk) {
  1122. FFLog(@"I-RDB034042", @"Failed to send stats: %@",
  1123. errorReason);
  1124. }
  1125. }];
  1126. } else {
  1127. FFLog(@"I-RDB034043", @"Not sending stats because stats are empty");
  1128. }
  1129. }
  1130. - (void)sendConnectStats {
  1131. NSMutableDictionary *stats = [NSMutableDictionary dictionary];
  1132. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_VISION
  1133. if (self.config.persistenceEnabled) {
  1134. stats[@"persistence.ios.enabled"] = @1;
  1135. }
  1136. #elif TARGET_OS_OSX
  1137. if (self.config.persistenceEnabled) {
  1138. stats[@"persistence.osx.enabled"] = @1;
  1139. }
  1140. #elif TARGET_OS_WATCH
  1141. if (self.config.persistenceEnabled) {
  1142. stats[@"persistence.watchos.enabled"] = @1;
  1143. }
  1144. #endif
  1145. NSString *sdkVersion =
  1146. [[FIRDatabase sdkVersion] stringByReplacingOccurrencesOfString:@"."
  1147. withString:@"-"];
  1148. NSString *sdkStatName =
  1149. [NSString stringWithFormat:@"sdk.objc.%@", sdkVersion];
  1150. stats[sdkStatName] = @1;
  1151. FFLog(@"I-RDB034044", @"Sending first connection stats");
  1152. [self sendStats:stats];
  1153. }
  1154. - (NSDictionary *)dumpListens {
  1155. return self.listens;
  1156. }
  1157. #pragma mark - App Check Token update
  1158. // TODO: Add tests!
  1159. - (void)refreshAppCheckToken:(NSString *)token {
  1160. if (![self connected]) {
  1161. // A fresh FAC token will be sent as a part of initial handshake.
  1162. return;
  1163. }
  1164. if (token.length == 0) {
  1165. // No token to send.
  1166. return;
  1167. }
  1168. // Send updated FAC token to the open connection.
  1169. [self sendAppCheckToken:token];
  1170. }
  1171. - (void)sendAppCheckToken:(NSString *)token {
  1172. NSDictionary *requestData = @{kFWPRequestAppCheckToken : token};
  1173. [self sendAction:kFWPRequestActionAppCheck
  1174. body:requestData
  1175. sensitive:YES
  1176. callback:^(NSDictionary *data) {
  1177. NSString *status =
  1178. [data objectForKey:kFWPResponseForActionStatus];
  1179. id responseData = [data objectForKey:kFWPResponseForActionData];
  1180. if (responseData == nil) {
  1181. responseData = @"Response data was empty.";
  1182. }
  1183. BOOL statusOk =
  1184. [status isEqualToString:kFWPResponseForActionStatusOk];
  1185. if (!statusOk) {
  1186. self.authToken = nil;
  1187. self.forceTokenRefreshes = YES;
  1188. if ([status isEqualToString:@"invalid_token"]) {
  1189. FFLog(@"I-RDB034045", @"App check failed: %@ (%@)",
  1190. status, responseData);
  1191. } else {
  1192. FFWarn(@"I-RDB034046", @"App check failed: %@ (%@)",
  1193. status, responseData);
  1194. }
  1195. [self.realtime close];
  1196. }
  1197. }];
  1198. }
  1199. @end