FPersistentConnection.m 48 KB

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