FPersistentConnection.m 51 KB

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