FPersistentConnection.m 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  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. - (void)enteringForeground {
  493. dispatch_async(self.dispatchQueue, ^{
  494. // Reset reconnect delay
  495. [self.retryHelper signalSuccess];
  496. if (self->connectionState == ConnectionStateDisconnected) {
  497. [self tryScheduleReconnect];
  498. }
  499. });
  500. }
  501. - (void)setupNotifications {
  502. #if TARGET_OS_WATCH
  503. __weak FPersistentConnection *weakSelf = self;
  504. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  505. [center addObserverForName:WKApplicationWillEnterForegroundNotification
  506. object:nil
  507. queue:nil
  508. usingBlock:^(NSNotification *_Nonnull note) {
  509. [weakSelf enteringForeground];
  510. }];
  511. #endif // TARGET_OS_WATCH
  512. }
  513. - (void)sendAuthAndRestoreStateAfterComplete:(BOOL)restoreStateAfterComplete {
  514. NSAssert([self connected], @"Must be connected to send auth");
  515. NSAssert(self.authToken != nil,
  516. @"Can't send auth if there is no credential");
  517. NSDictionary *requestData = @{kFWPRequestCredential : self.authToken};
  518. [self sendAction:kFWPRequestActionAuth
  519. body:requestData
  520. sensitive:YES
  521. callback:^(NSDictionary *data) {
  522. self->connectionState = ConnectionStateConnected;
  523. NSString *status =
  524. [data objectForKey:kFWPResponseForActionStatus];
  525. id responseData = [data objectForKey:kFWPResponseForActionData];
  526. if (responseData == nil) {
  527. responseData = @"error";
  528. }
  529. BOOL statusOk =
  530. [status isEqualToString:kFWPResponseForActionStatusOk];
  531. if (statusOk) {
  532. if (restoreStateAfterComplete) {
  533. [self restoreState];
  534. }
  535. } else {
  536. self.authToken = nil;
  537. self.forceTokenRefreshes = YES;
  538. if ([status isEqualToString:@"expired_token"]) {
  539. FFLog(@"I-RDB034017", @"Authentication failed: %@ (%@)",
  540. status, responseData);
  541. } else {
  542. FFWarn(@"I-RDB034018", @"Authentication failed: %@ (%@)",
  543. status, responseData);
  544. }
  545. [self.realtime close];
  546. }
  547. }];
  548. }
  549. - (void)sendUnauth {
  550. [self sendAction:kFWPRequestActionUnauth
  551. body:@{}
  552. sensitive:NO
  553. callback:nil];
  554. }
  555. - (void)onAuthRevokedWithStatus:(NSString *)status
  556. andReason:(NSString *)reason {
  557. // This might be for an earlier token than we just recently sent. But since
  558. // we need to close the connection anyways, we can set it to null here and
  559. // we will refresh the token later on reconnect
  560. if ([status isEqualToString:@"expired_token"]) {
  561. FFLog(@"I-RDB034019", @"Auth token revoked: %@ (%@)", status, reason);
  562. } else {
  563. FFWarn(@"I-RDB034020", @"Auth token revoked: %@ (%@)", status, reason);
  564. }
  565. self.authToken = nil;
  566. self.forceTokenRefreshes = YES;
  567. // Try reconnecting on auth revocation
  568. [self.realtime close];
  569. }
  570. - (void)onListenRevoked:(FPath *)path {
  571. NSArray *queries = [self removeAllListensAtPath:path];
  572. for (FOutstandingQuery *query in queries) {
  573. query.onComplete(@"permission_denied");
  574. }
  575. }
  576. - (void)sendOnDisconnectAction:(NSString *)action
  577. forPath:(NSString *)pathString
  578. withData:(id)data
  579. andCallback:(fbt_void_nsstring_nsstring)callback {
  580. NSDictionary *request =
  581. @{kFWPRequestPath : pathString, kFWPRequestData : data};
  582. FFLog(@"I-RDB034021", @"onDisconnect %@: %@", action, request);
  583. [self sendAction:action
  584. body:request
  585. sensitive:NO
  586. callback:^(NSDictionary *data) {
  587. NSString *status =
  588. [data objectForKey:kFWPResponseForActionStatus];
  589. NSString *errorReason =
  590. [data objectForKey:kFWPResponseForActionData];
  591. callback(status, errorReason);
  592. }];
  593. }
  594. - (void)sendPut:(NSNumber *)index {
  595. NSAssert([self canSendWrites],
  596. @"sendPut called when not able to send writes");
  597. FOutstandingPut *put = self.outstandingPuts[index];
  598. assert(put != nil);
  599. fbt_void_nsstring_nsstring onComplete = put.onCompleteBlock;
  600. // Do not async this block; copying the block insinde sendAction: doesn't
  601. // happen in time (or something) so coredumps
  602. put.sent = YES;
  603. [self sendAction:put.action
  604. body:put.request
  605. sensitive:NO
  606. callback:^(NSDictionary *data) {
  607. FOutstandingPut *currentPut = self.outstandingPuts[index];
  608. if (currentPut == put) {
  609. [self.outstandingPuts removeObjectForKey:index];
  610. if (onComplete != nil) {
  611. NSString *status =
  612. [data objectForKey:kFWPResponseForActionStatus];
  613. NSString *errorReason =
  614. [data objectForKey:kFWPResponseForActionData];
  615. if (self.unackedListensCount == 0) {
  616. onComplete(status, errorReason);
  617. } else {
  618. FTupleCallbackStatus *putToAck =
  619. [[FTupleCallbackStatus alloc] init];
  620. putToAck.block = onComplete;
  621. putToAck.status = status;
  622. putToAck.errorReason = errorReason;
  623. [self.putsToAck addObject:putToAck];
  624. }
  625. }
  626. } else {
  627. FFLog(@"I-RDB034022",
  628. @"Ignoring on complete for put %@ because it was "
  629. @"already removed",
  630. index);
  631. }
  632. }];
  633. }
  634. - (void)sendGet:(NSNumber *)index {
  635. NSAssert([self canSendReads],
  636. @"sendGet called when not able to send reads");
  637. FOutstandingGet *get = self.outstandingGets[index];
  638. NSAssert(get != nil, @"sendGet found no outstanding get at index %@",
  639. index);
  640. if ([get sent]) {
  641. return;
  642. }
  643. get.sent = YES;
  644. [self sendAction:kFWPRequestActionGet
  645. body:get.request
  646. sensitive:NO
  647. callback:^(NSDictionary *data) {
  648. FOutstandingGet *currentGet = self.outstandingGets[index];
  649. if (currentGet == get) {
  650. [self.outstandingGets removeObjectForKey:index];
  651. NSString *status =
  652. [data objectForKey:kFWPResponseForActionStatus];
  653. id resultData = [data objectForKey:kFWPResponseForActionData];
  654. if (resultData == (id)[NSNull null]) {
  655. resultData = nil;
  656. }
  657. if ([status isEqualToString:kFWPResponseForActionStatusOk]) {
  658. get.onCompleteBlock(status, resultData, nil);
  659. return;
  660. }
  661. get.onCompleteBlock(status, nil, resultData);
  662. } else {
  663. FFLog(@"I-RDB034045",
  664. @"Ignoring on complete for get %@ because it was "
  665. @"already removed",
  666. index);
  667. }
  668. }];
  669. }
  670. - (void)sendUnlisten:(FPath *)path
  671. queryParams:(FQueryParams *)queryParams
  672. tagId:(NSNumber *)tagId {
  673. FFLog(@"I-RDB034023", @"Unlisten on %@ for %@", path, queryParams);
  674. NSMutableDictionary *request = [NSMutableDictionary
  675. dictionaryWithObjectsAndKeys:[path toString], kFWPRequestPath, nil];
  676. if (tagId != nil) {
  677. [request setObject:queryParams.wireProtocolParams
  678. forKey:kFWPRequestQueries];
  679. [request setObject:tagId forKey:kFWPRequestTag];
  680. }
  681. [self sendAction:kFWPRequestActionTaggedUnlisten
  682. body:request
  683. sensitive:NO
  684. callback:nil];
  685. }
  686. - (void)putInternal:(id)data
  687. forAction:(NSString *)action
  688. forPath:(NSString *)pathString
  689. withHash:(NSString *)hash
  690. withCallback:(fbt_void_nsstring_nsstring)onComplete {
  691. NSMutableDictionary *request = [NSMutableDictionary
  692. dictionaryWithObjectsAndKeys:pathString, kFWPRequestPath, data,
  693. kFWPRequestData, nil];
  694. if (hash) {
  695. [request setObject:hash forKey:kFWPRequestHash];
  696. }
  697. FOutstandingPut *put = [[FOutstandingPut alloc] init];
  698. put.action = action;
  699. put.request = request;
  700. put.onCompleteBlock = onComplete;
  701. put.sent = NO;
  702. NSNumber *index = [self.putCounter getAndIncrement];
  703. self.outstandingPuts[index] = put;
  704. if ([self canSendWrites]) {
  705. FFLog(@"I-RDB034024", @"Was connected, and added as index: %@", index);
  706. [self sendPut:index];
  707. } else {
  708. FFLog(@"I-RDB034025",
  709. @"Wasn't connected or writes paused, so added to outstanding "
  710. @"puts only. Path: %@",
  711. pathString);
  712. }
  713. }
  714. - (void)getDataAtPath:(NSString *)pathString
  715. withParams:(NSDictionary *)queryWireProtocolParams
  716. withCallback:(fbt_void_nsstring_id_nsstring)onComplete {
  717. NSMutableDictionary *request = [NSMutableDictionary
  718. dictionaryWithObjectsAndKeys:pathString, kFWPRequestPath,
  719. queryWireProtocolParams,
  720. kFWPRequestQueries, nil];
  721. FOutstandingGet *get = [[FOutstandingGet alloc] init];
  722. get.request = request;
  723. get.onCompleteBlock = onComplete;
  724. get.sent = NO;
  725. NSNumber *index = [self.getCounter getAndIncrement];
  726. self.outstandingGets[index] = get;
  727. if (![self connected]) {
  728. dispatch_after(
  729. dispatch_time(DISPATCH_TIME_NOW,
  730. kPersistentConnectionGetConnectTimeout),
  731. self.dispatchQueue, ^{
  732. FOutstandingGet *currGet = self.outstandingGets[index];
  733. if ([currGet sent] || currGet == nil) {
  734. return;
  735. }
  736. FFLog(@"I-RDB034045",
  737. @"get %@ timed out waiting for a connection", index);
  738. currGet.sent = YES;
  739. currGet.onCompleteBlock(kFWPResponseForActionStatusFailed, nil,
  740. kPersistentConnectionOffline);
  741. [self.outstandingGets removeObjectForKey:index];
  742. });
  743. return;
  744. }
  745. if ([self canSendReads]) {
  746. FFLog(@"I-RDB034024", @"Sending get: %@", index);
  747. [self sendGet:index];
  748. }
  749. }
  750. - (void)sendListen:(FOutstandingQuery *)listenSpec {
  751. FQuerySpec *query = listenSpec.query;
  752. FFLog(@"I-RDB034026", @"Listen for %@", query);
  753. NSMutableDictionary *request =
  754. [NSMutableDictionary dictionaryWithObject:[query.path toString]
  755. forKey:kFWPRequestPath];
  756. // Only bother to send query if it's non-default
  757. if (listenSpec.tagId != nil) {
  758. [request setObject:[query.params wireProtocolParams]
  759. forKey:kFWPRequestQueries];
  760. [request setObject:listenSpec.tagId forKey:kFWPRequestTag];
  761. }
  762. [request setObject:[listenSpec.syncTreeHash simpleHash]
  763. forKey:kFWPRequestHash];
  764. if ([listenSpec.syncTreeHash includeCompoundHash]) {
  765. FCompoundHash *compoundHash = [listenSpec.syncTreeHash compoundHash];
  766. NSMutableArray *posts = [NSMutableArray array];
  767. for (FPath *path in compoundHash.posts) {
  768. [posts addObject:path.wireFormat];
  769. }
  770. request[kFWPRequestCompoundHash] = @{
  771. kFWPRequestCompoundHashHashes : compoundHash.hashes,
  772. kFWPRequestCompoundHashPaths : posts
  773. };
  774. }
  775. fbt_void_nsdictionary onResponse = ^(NSDictionary *response) {
  776. FFLog(@"I-RDB034027", @"Listen response %@", response);
  777. // warn in any case, even if the listener was removed
  778. [self warnOnListenWarningsForQuery:query
  779. payload:response[kFWPResponseForActionData]];
  780. FOutstandingQuery *currentListenSpec = self.listens[query];
  781. // only trigger actions if the listen hasn't been removed (and maybe
  782. // readded)
  783. if (currentListenSpec == listenSpec) {
  784. NSString *status = [response objectForKey:kFWPRequestStatus];
  785. if (![status isEqualToString:@"ok"]) {
  786. [self removeListen:query];
  787. }
  788. if (listenSpec.onComplete) {
  789. listenSpec.onComplete(status);
  790. }
  791. }
  792. self.unackedListensCount--;
  793. NSAssert(self.unackedListensCount >= 0,
  794. @"unackedListensCount decremented to be negative.");
  795. if (self.unackedListensCount == 0) {
  796. [self ackPuts];
  797. }
  798. };
  799. [self sendAction:kFWPRequestActionTaggedListen
  800. body:request
  801. sensitive:NO
  802. callback:onResponse];
  803. self.unackedListensCount++;
  804. }
  805. - (void)warnOnListenWarningsForQuery:(FQuerySpec *)query payload:(id)payload {
  806. if (payload != nil && [payload isKindOfClass:[NSDictionary class]]) {
  807. NSDictionary *payloadDict = payload;
  808. id warnings = payloadDict[kFWPResponseDataWarnings];
  809. if (warnings != nil && [warnings isKindOfClass:[NSArray class]]) {
  810. NSArray *warningsArr = warnings;
  811. if ([warningsArr containsObject:@"no_index"]) {
  812. NSString *indexSpec = [NSString
  813. stringWithFormat:@"\".indexOn\": \"%@\"",
  814. [query.params.index queryDefinition]];
  815. NSString *indexPath = [query.path description];
  816. FFWarn(@"I-RDB034028",
  817. @"Using an unspecified index. Your data will be "
  818. @"downloaded and filtered on the client. "
  819. "Consider adding %@ at %@ to your security rules for "
  820. "better performance",
  821. indexSpec, indexPath);
  822. }
  823. }
  824. }
  825. }
  826. - (int)getNextRequestNumber {
  827. return [[self.requestNumber getAndIncrement] intValue];
  828. }
  829. - (void)sendAction:(NSString *)action
  830. body:(NSDictionary *)message
  831. sensitive:(BOOL)sensitive
  832. callback:(void (^)(NSDictionary *data))onMessage {
  833. // Hold onto the onMessage callback for this request before firing it off
  834. NSNumber *rn = [NSNumber numberWithInt:[self getNextRequestNumber]];
  835. NSDictionary *msg = [NSDictionary
  836. dictionaryWithObjectsAndKeys:rn, kFWPRequestNumber, action,
  837. kFWPRequestAction, message,
  838. kFWPRequestPayloadBody, nil];
  839. [self.realtime sendRequest:msg sensitive:sensitive];
  840. if (onMessage) {
  841. // Debug message without a callback; bump the rn, but don't hold onto
  842. // the cb
  843. [self.requestCBHash setObject:[onMessage copy] forKey:rn];
  844. }
  845. }
  846. - (void)cancelSentTransactions {
  847. NSMutableDictionary<NSNumber *, FOutstandingPut *>
  848. *cancelledOutstandingPuts = [[NSMutableDictionary alloc] init];
  849. for (NSNumber *index in self.outstandingPuts) {
  850. FOutstandingPut *put = self.outstandingPuts[index];
  851. if (put.request[kFWPRequestHash] && put.sent) {
  852. // This is a sent transaction put.
  853. cancelledOutstandingPuts[index] = put;
  854. }
  855. }
  856. [cancelledOutstandingPuts
  857. enumerateKeysAndObjectsUsingBlock:^(
  858. NSNumber *index, FOutstandingPut *outstandingPut, BOOL *stop) {
  859. // `onCompleteBlock:` may invoke `rerunTransactionsForPath:` and
  860. // enqueue new writes. We defer calling it until we have finished
  861. // enumerating all existing writes.
  862. outstandingPut.onCompleteBlock(
  863. kFTransactionDisconnect,
  864. @"Client was disconnected while running a transaction");
  865. [self.outstandingPuts removeObjectForKey:index];
  866. }];
  867. }
  868. - (void)onDataPushWithAction:(NSString *)action andBody:(NSDictionary *)body {
  869. FFLog(@"I-RDB034029", @"handleServerMessage: %@, %@", action, body);
  870. id<FPersistentConnectionDelegate> delegate = self.delegate;
  871. if ([action isEqualToString:kFWPAsyncServerDataUpdate] ||
  872. [action isEqualToString:kFWPAsyncServerDataMerge]) {
  873. BOOL isMerge = [action isEqualToString:kFWPAsyncServerDataMerge];
  874. if ([body objectForKey:kFWPAsyncServerDataUpdateBodyPath] &&
  875. [body objectForKey:kFWPAsyncServerDataUpdateBodyData]) {
  876. NSString *path =
  877. [body objectForKey:kFWPAsyncServerDataUpdateBodyPath];
  878. id payloadData =
  879. [body objectForKey:kFWPAsyncServerDataUpdateBodyData];
  880. if (isMerge && [payloadData isKindOfClass:[NSDictionary class]] &&
  881. [payloadData count] == 0) {
  882. // ignore empty merge
  883. } else {
  884. [delegate
  885. onDataUpdate:self
  886. forPath:path
  887. message:payloadData
  888. isMerge:isMerge
  889. tagId:[body objectForKey:
  890. kFWPAsyncServerDataUpdateBodyTag]];
  891. }
  892. } else {
  893. FFLog(
  894. @"I-RDB034030",
  895. @"Malformed data response from server missing path or data: %@",
  896. body);
  897. }
  898. } else if ([action isEqualToString:kFWPAsyncServerDataRangeMerge]) {
  899. NSString *path = body[kFWPAsyncServerDataUpdateBodyPath];
  900. NSArray *ranges = body[kFWPAsyncServerDataUpdateBodyData];
  901. NSNumber *tag = body[kFWPAsyncServerDataUpdateBodyTag];
  902. NSMutableArray *rangeMerges = [NSMutableArray array];
  903. for (NSDictionary *range in ranges) {
  904. NSString *startString = range[kFWPAsyncServerDataUpdateStartPath];
  905. NSString *endString = range[kFWPAsyncServerDataUpdateEndPath];
  906. id updateData = range[kFWPAsyncServerDataUpdateRangeMerge];
  907. id<FNode> updates = [FSnapshotUtilities nodeFrom:updateData];
  908. FPath *start = (startString != nil)
  909. ? [[FPath alloc] initWith:startString]
  910. : nil;
  911. FPath *end =
  912. (endString != nil) ? [[FPath alloc] initWith:endString] : nil;
  913. FRangeMerge *merge = [[FRangeMerge alloc] initWithStart:start
  914. end:end
  915. updates:updates];
  916. [rangeMerges addObject:merge];
  917. }
  918. [delegate onRangeMerge:rangeMerges forPath:path tagId:tag];
  919. } else if ([action isEqualToString:kFWPAsyncServerAuthRevoked]) {
  920. NSString *status = [body objectForKey:kFWPResponseForActionStatus];
  921. NSString *reason = [body objectForKey:kFWPResponseForActionData];
  922. [self onAuthRevokedWithStatus:status andReason:reason];
  923. } else if ([action isEqualToString:kFWPASyncServerListenCancelled]) {
  924. NSString *pathString =
  925. [body objectForKey:kFWPAsyncServerDataUpdateBodyPath];
  926. [self onListenRevoked:[[FPath alloc] initWith:pathString]];
  927. } else if ([action isEqualToString:kFWPAsyncServerSecurityDebug]) {
  928. NSString *msg = [body objectForKey:@"msg"];
  929. if (msg != nil) {
  930. NSArray *msgs = [msg componentsSeparatedByString:@"\n"];
  931. for (NSString *m in msgs) {
  932. FFWarn(@"I-RDB034031", @"%@", m);
  933. }
  934. }
  935. } else {
  936. // TODO: revoke listens, auth, security debug
  937. FFLog(@"I-RDB034032", @"Unsupported action from server: %@", action);
  938. }
  939. }
  940. - (void)restoreAuth {
  941. FFLog(@"I-RDB034033", @"Calling restore state");
  942. NSAssert(self->connectionState == ConnectionStateConnecting,
  943. @"Wanted to restore auth, but was in wrong state: %d",
  944. self->connectionState);
  945. if (self.authToken == nil) {
  946. FFLog(@"I-RDB034034", @"Not restoring auth because token is nil");
  947. self->connectionState = ConnectionStateConnected;
  948. [self restoreState];
  949. } else {
  950. FFLog(@"I-RDB034035", @"Restoring auth");
  951. self->connectionState = ConnectionStateAuthenticating;
  952. [self sendAuthAndRestoreStateAfterComplete:YES];
  953. }
  954. }
  955. - (void)restoreState {
  956. NSAssert(self->connectionState == ConnectionStateConnected,
  957. @"Should be connected if we're restoring state, but we are: %d",
  958. self->connectionState);
  959. [self.listens enumerateKeysAndObjectsUsingBlock:^(
  960. FQuerySpec *query, FOutstandingQuery *outstandingListen,
  961. BOOL *stop) {
  962. FFLog(@"I-RDB034036", @"Restoring listen for %@", query);
  963. [self sendListen:outstandingListen];
  964. }];
  965. NSArray *putKeys = [[self.outstandingPuts allKeys]
  966. sortedArrayUsingSelector:@selector(compare:)];
  967. for (int i = 0; i < [putKeys count]; i++) {
  968. if ([self.outstandingPuts objectForKey:[putKeys objectAtIndex:i]] !=
  969. nil) {
  970. FFLog(@"I-RDB034037", @"Restoring put: %d", i);
  971. [self sendPut:[putKeys objectAtIndex:i]];
  972. } else {
  973. FFLog(@"I-RDB034038", @"Restoring put: skipped nil: %d", i);
  974. }
  975. }
  976. NSArray *getKeys = [[self.outstandingGets allKeys]
  977. sortedArrayUsingSelector:@selector(compare:)];
  978. for (int i = 0; i < [getKeys count]; i++) {
  979. if ([self.outstandingGets objectForKey:[getKeys objectAtIndex:i]] !=
  980. nil) {
  981. FFLog(@"I-RDB034037", @"Restoring get: %d", i);
  982. [self sendGet:[getKeys objectAtIndex:i]];
  983. } else {
  984. FFLog(@"I-RDB034038", @"Restoring get: skipped nil: %d", i);
  985. }
  986. }
  987. for (FTupleOnDisconnect *tuple in self.onDisconnectQueue) {
  988. [self sendOnDisconnectAction:tuple.action
  989. forPath:tuple.pathString
  990. withData:tuple.data
  991. andCallback:tuple.onComplete];
  992. }
  993. [self.onDisconnectQueue removeAllObjects];
  994. }
  995. - (NSArray *)removeListen:(FQuerySpec *)query {
  996. NSAssert(query.isDefault || !query.loadsAllData,
  997. @"removeListen called for non-default but complete query");
  998. FOutstandingQuery *outstanding = self.listens[query];
  999. if (!outstanding) {
  1000. FFLog(@"I-RDB034039",
  1001. @"Trying to remove listener for query %@ but no listener exists",
  1002. query);
  1003. return @[];
  1004. } else {
  1005. [self.listens removeObjectForKey:query];
  1006. return @[ outstanding ];
  1007. }
  1008. }
  1009. - (NSArray *)removeAllListensAtPath:(FPath *)path {
  1010. FFLog(@"I-RDB034040", @"Removing all listens at path %@", path);
  1011. NSMutableArray *removed = [NSMutableArray array];
  1012. NSMutableArray *toRemove = [NSMutableArray array];
  1013. [self.listens
  1014. enumerateKeysAndObjectsUsingBlock:^(
  1015. FQuerySpec *spec, FOutstandingQuery *outstanding, BOOL *stop) {
  1016. if ([spec.path isEqual:path]) {
  1017. [removed addObject:outstanding];
  1018. [toRemove addObject:spec];
  1019. }
  1020. }];
  1021. [self.listens removeObjectsForKeys:toRemove];
  1022. return removed;
  1023. }
  1024. - (void)purgeOutstandingWrites {
  1025. // We might have unacked puts in our queue that we need to ack now before we
  1026. // send out any cancels...
  1027. [self ackPuts];
  1028. // Cancel in order
  1029. NSArray *keys = [[self.outstandingPuts allKeys]
  1030. sortedArrayUsingSelector:@selector(compare:)];
  1031. for (NSNumber *key in keys) {
  1032. FOutstandingPut *put = self.outstandingPuts[key];
  1033. if (put.onCompleteBlock != nil) {
  1034. put.onCompleteBlock(kFErrorWriteCanceled, nil);
  1035. }
  1036. }
  1037. for (FTupleOnDisconnect *onDisconnect in self.onDisconnectQueue) {
  1038. if (onDisconnect.onComplete != nil) {
  1039. onDisconnect.onComplete(kFErrorWriteCanceled, nil);
  1040. }
  1041. }
  1042. [self.outstandingPuts removeAllObjects];
  1043. [self.onDisconnectQueue removeAllObjects];
  1044. }
  1045. - (void)ackPuts {
  1046. for (FTupleCallbackStatus *put in self.putsToAck) {
  1047. put.block(put.status, put.errorReason);
  1048. }
  1049. [self.putsToAck removeAllObjects];
  1050. }
  1051. - (void)handleTimestamp:(NSNumber *)timestamp {
  1052. FFLog(@"I-RDB034041", @"Handling timestamp: %@", timestamp);
  1053. double timestampDeltaMs = [timestamp doubleValue] -
  1054. ([[NSDate date] timeIntervalSince1970] * 1000);
  1055. [self.delegate onServerInfoUpdate:self
  1056. updates:@{
  1057. kDotInfoServerTimeOffset : [NSNumber
  1058. numberWithDouble:timestampDeltaMs]
  1059. }];
  1060. }
  1061. - (void)sendStats:(NSDictionary *)stats {
  1062. if ([stats count] > 0) {
  1063. NSDictionary *request = @{kFWPRequestCounters : stats};
  1064. [self sendAction:kFWPRequestActionStats
  1065. body:request
  1066. sensitive:NO
  1067. callback:^(NSDictionary *data) {
  1068. NSString *status =
  1069. [data objectForKey:kFWPResponseForActionStatus];
  1070. NSString *errorReason =
  1071. [data objectForKey:kFWPResponseForActionData];
  1072. BOOL statusOk =
  1073. [status isEqualToString:kFWPResponseForActionStatusOk];
  1074. if (!statusOk) {
  1075. FFLog(@"I-RDB034042", @"Failed to send stats: %@",
  1076. errorReason);
  1077. }
  1078. }];
  1079. } else {
  1080. FFLog(@"I-RDB034043", @"Not sending stats because stats are empty");
  1081. }
  1082. }
  1083. - (void)sendConnectStats {
  1084. NSMutableDictionary *stats = [NSMutableDictionary dictionary];
  1085. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_VISION
  1086. if (self.config.persistenceEnabled) {
  1087. stats[@"persistence.ios.enabled"] = @1;
  1088. }
  1089. #elif TARGET_OS_OSX
  1090. if (self.config.persistenceEnabled) {
  1091. stats[@"persistence.osx.enabled"] = @1;
  1092. }
  1093. #elif TARGET_OS_WATCH
  1094. if (self.config.persistenceEnabled) {
  1095. stats[@"persistence.watchos.enabled"] = @1;
  1096. }
  1097. #endif
  1098. NSString *sdkVersion =
  1099. [[FIRDatabase sdkVersion] stringByReplacingOccurrencesOfString:@"."
  1100. withString:@"-"];
  1101. NSString *sdkStatName =
  1102. [NSString stringWithFormat:@"sdk.objc.%@", sdkVersion];
  1103. stats[sdkStatName] = @1;
  1104. FFLog(@"I-RDB034044", @"Sending first connection stats");
  1105. [self sendStats:stats];
  1106. }
  1107. - (NSDictionary *)dumpListens {
  1108. return self.listens;
  1109. }
  1110. #pragma mark - App Check Token update
  1111. // TODO: Add tests!
  1112. - (void)refreshAppCheckToken:(NSString *)token {
  1113. if (![self connected]) {
  1114. // A fresh FAC token will be sent as a part of initial handshake.
  1115. return;
  1116. }
  1117. if (token.length == 0) {
  1118. // No token to send.
  1119. return;
  1120. }
  1121. // Send updated FAC token to the open connection.
  1122. [self sendAppCheckToken:token];
  1123. }
  1124. - (void)sendAppCheckToken:(NSString *)token {
  1125. NSDictionary *requestData = @{kFWPRequestAppCheckToken : token};
  1126. [self sendAction:kFWPRequestActionAppCheck
  1127. body:requestData
  1128. sensitive:YES
  1129. callback:^(NSDictionary *data) {
  1130. NSString *status =
  1131. [data objectForKey:kFWPResponseForActionStatus];
  1132. id responseData = [data objectForKey:kFWPResponseForActionData];
  1133. if (responseData == nil) {
  1134. responseData = @"Response data was empty.";
  1135. }
  1136. BOOL statusOk =
  1137. [status isEqualToString:kFWPResponseForActionStatusOk];
  1138. if (!statusOk) {
  1139. self.authToken = nil;
  1140. self.forceTokenRefreshes = YES;
  1141. if ([status isEqualToString:@"invalid_token"]) {
  1142. FFLog(@"I-RDB034045", @"App check failed: %@ (%@)",
  1143. status, responseData);
  1144. } else {
  1145. FFWarn(@"I-RDB034046", @"App check failed: %@ (%@)",
  1146. status, responseData);
  1147. }
  1148. [self.realtime close];
  1149. }
  1150. }];
  1151. }
  1152. @end