FPersistentConnection.m 49 KB

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