FPersistentConnection.m 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  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/FIRLogger.h>
  18. #import <SystemConfiguration/SystemConfiguration.h>
  19. #import <netinet/in.h>
  20. #import <dlfcn.h>
  21. #import "FIRDatabaseReference.h"
  22. #import "FPersistentConnection.h"
  23. #import "FConstants.h"
  24. #import "FAtomicNumber.h"
  25. #import "FQueryParams.h"
  26. #import "FTupleOnDisconnect.h"
  27. #import "FTupleCallbackStatus.h"
  28. #import "FQuerySpec.h"
  29. #import "FIndex.h"
  30. #import "FIRDatabaseConfig.h"
  31. #import "FIRDatabaseConfig_Private.h"
  32. #import "FSnapshotUtilities.h"
  33. #import "FRangeMerge.h"
  34. #import "FCompoundHash.h"
  35. #import "FSyncTree.h"
  36. #import "FIRRetryHelper.h"
  37. #import "FAuthTokenProvider.h"
  38. #import "FUtilities.h"
  39. @interface FOutstandingQuery : NSObject
  40. @property (nonatomic, strong) FQuerySpec* query;
  41. @property (nonatomic, strong) NSNumber *tagId;
  42. @property (nonatomic, strong) id<FSyncTreeHash> syncTreeHash;
  43. @property (nonatomic, copy) fbt_void_nsstring onComplete;
  44. @end
  45. @implementation FOutstandingQuery
  46. @end
  47. @interface FOutstandingPut : NSObject
  48. @property (nonatomic, strong) NSString *action;
  49. @property (nonatomic, strong) NSDictionary *request;
  50. @property (nonatomic, copy) fbt_void_nsstring_nsstring onCompleteBlock;
  51. @property (nonatomic) BOOL sent;
  52. @end
  53. @implementation FOutstandingPut
  54. @end
  55. typedef enum {
  56. ConnectionStateDisconnected,
  57. ConnectionStateGettingToken,
  58. ConnectionStateConnecting,
  59. ConnectionStateAuthenticating,
  60. ConnectionStateConnected
  61. } ConnectionState;
  62. @interface FPersistentConnection () {
  63. ConnectionState connectionState;
  64. BOOL firstConnection;
  65. NSTimeInterval reconnectDelay;
  66. NSTimeInterval lastConnectionAttemptTime;
  67. NSTimeInterval lastConnectionEstablishedTime;
  68. SCNetworkReachabilityRef reachability;
  69. }
  70. - (int) getNextRequestNumber;
  71. - (void) onDataPushWithAction:(NSString *)action andBody:(NSDictionary *)body;
  72. - (void) handleTimestamp:(NSNumber *)timestamp;
  73. - (void) sendOnDisconnectAction:(NSString *)action forPath:(NSString *)pathString withData:(id)data andCallback:(fbt_void_nsstring_nsstring)callback;
  74. @property (nonatomic, strong) FConnection* realtime;
  75. @property (nonatomic, strong) NSMutableDictionary* listens;
  76. @property (nonatomic, strong) NSMutableDictionary* outstandingPuts;
  77. @property (nonatomic, strong) NSMutableArray* onDisconnectQueue;
  78. @property (nonatomic, strong) FRepoInfo* repoInfo;
  79. @property (nonatomic, strong) FAtomicNumber* putCounter;
  80. @property (nonatomic, strong) FAtomicNumber* requestNumber;
  81. @property (nonatomic, strong) NSMutableDictionary* requestCBHash;
  82. @property (nonatomic, strong) FIRDatabaseConfig *config;
  83. @property (nonatomic) NSUInteger unackedListensCount;
  84. @property (nonatomic, strong) NSMutableArray *putsToAck;
  85. @property (nonatomic, strong) dispatch_queue_t dispatchQueue;
  86. @property (nonatomic, strong) NSString* lastSessionID;
  87. @property (nonatomic, strong) NSMutableSet *interruptReasons;
  88. @property (nonatomic, strong) FIRRetryHelper *retryHelper;
  89. @property (nonatomic, strong) id<FAuthTokenProvider> authTokenProvider;
  90. @property (nonatomic, strong) NSString *authToken;
  91. @property (nonatomic) BOOL forceAuthTokenRefresh;
  92. @property (nonatomic) NSUInteger currentFetchTokenAttempt;
  93. @end
  94. @implementation FPersistentConnection
  95. - (id)initWithRepoInfo:(FRepoInfo *)repoInfo dispatchQueue:(dispatch_queue_t)dispatchQueue config:(FIRDatabaseConfig *)config {
  96. self = [super init];
  97. if (self) {
  98. self->_config = config;
  99. self->_repoInfo = repoInfo;
  100. self->_dispatchQueue = dispatchQueue;
  101. self->_authTokenProvider = config.authTokenProvider;
  102. NSAssert(self->_authTokenProvider != nil, @"Expected auth token provider");
  103. self.interruptReasons = [NSMutableSet set];
  104. self.listens = [[NSMutableDictionary alloc] init];
  105. self.outstandingPuts = [[NSMutableDictionary alloc] init];
  106. self.onDisconnectQueue = [[NSMutableArray alloc] init];
  107. self.putCounter = [[FAtomicNumber alloc] init];
  108. self.requestNumber = [[FAtomicNumber alloc] init];
  109. self.requestCBHash = [[NSMutableDictionary alloc] init];
  110. self.unackedListensCount = 0;
  111. self.putsToAck = [NSMutableArray array];
  112. connectionState = ConnectionStateDisconnected;
  113. firstConnection = YES;
  114. reconnectDelay = kPersistentConnReconnectMinDelay;
  115. self->_retryHelper = [[FIRRetryHelper alloc] initWithDispatchQueue:dispatchQueue
  116. minRetryDelayAfterFailure:kPersistentConnReconnectMinDelay
  117. maxRetryDelay:kPersistentConnReconnectMaxDelay
  118. retryExponent:kPersistentConnReconnectMultiplier
  119. jitterFactor:0.7];
  120. [self setupNotifications];
  121. // Make sure we don't actually connect until open is called
  122. [self interruptForReason:kFInterruptReasonWaitingForOpen];
  123. }
  124. // nb: The reason establishConnection isn't called here like the JS version is because
  125. // callers need to set the delegate first. The ctor can be modified to accept the delegate
  126. // but that deviates from normal ios conventions. After the delegate has been set, the caller
  127. // is responsible for calling establishConnection:
  128. return self;
  129. }
  130. - (void) dealloc {
  131. if (reachability) {
  132. // Unschedule the notifications
  133. SCNetworkReachabilitySetDispatchQueue(reachability, NULL);
  134. CFRelease(reachability);
  135. }
  136. }
  137. #pragma mark -
  138. #pragma mark Public methods
  139. - (void) open {
  140. [self resumeForReason:kFInterruptReasonWaitingForOpen];
  141. }
  142. /**
  143. * Note that the listens dictionary has a type of Map[String (pathString), Map[FQueryParams, FOutstandingQuery]]
  144. *
  145. * This means, for each path we care about, there are sets of queryParams that correspond to an FOutstandingQuery object.
  146. * There can be multiple sets at a path since we overlap listens for a short time while adding or removing a query from a
  147. * location in the tree.
  148. */
  149. - (void) listen:(FQuerySpec *)query
  150. tagId:(NSNumber *)tagId
  151. hash:(id<FSyncTreeHash>)hash
  152. onComplete:(fbt_void_nsstring)onComplete {
  153. FFLog(@"I-RDB034001", @"Listen called for %@", query);
  154. NSAssert(self.listens[query] == nil, @"listen() called twice for the same query");
  155. NSAssert(query.isDefault || !query.loadsAllData, @"listen called for non-default but complete query");
  156. FOutstandingQuery* outstanding = [[FOutstandingQuery alloc] init];
  157. outstanding.query = query;
  158. outstanding.tagId = tagId;
  159. outstanding.syncTreeHash = hash;
  160. outstanding.onComplete = onComplete;
  161. [self.listens setObject:outstanding forKey:query];
  162. if ([self connected]) {
  163. [self sendListen:outstanding];
  164. }
  165. }
  166. - (void) putData:(id)data forPath:(NSString *)pathString withHash:(NSString *)hash withCallback:(fbt_void_nsstring_nsstring)onComplete {
  167. [self putInternal:data forAction:kFWPRequestActionPut forPath:pathString withHash:hash withCallback:onComplete];
  168. }
  169. - (void) mergeData:(id)data forPath:(NSString *)pathString withCallback:(fbt_void_nsstring_nsstring)onComplete {
  170. [self putInternal:data forAction:kFWPRequestActionMerge forPath:pathString withHash:nil withCallback:onComplete];
  171. }
  172. - (void) onDisconnectPutData:(id)data forPath:(FPath *)path withCallback:(fbt_void_nsstring_nsstring)callback {
  173. if ([self canSendWrites]) {
  174. [self sendOnDisconnectAction:kFWPRequestActionDisconnectPut forPath:[path description] withData:data andCallback:callback];
  175. } else {
  176. FTupleOnDisconnect* tuple = [[FTupleOnDisconnect alloc] init];
  177. tuple.pathString = [path description];
  178. tuple.action = kFWPRequestActionDisconnectPut;
  179. tuple.data = data;
  180. tuple.onComplete = callback;
  181. [self.onDisconnectQueue addObject:tuple];
  182. }
  183. }
  184. - (void) onDisconnectMergeData:(id)data forPath:(FPath *)path withCallback:(fbt_void_nsstring_nsstring)callback {
  185. if ([self canSendWrites]) {
  186. [self sendOnDisconnectAction:kFWPRequestActionDisconnectMerge forPath:[path description] withData:data andCallback:callback];
  187. } else {
  188. FTupleOnDisconnect* tuple = [[FTupleOnDisconnect alloc] init];
  189. tuple.pathString = [path description];
  190. tuple.action = kFWPRequestActionDisconnectMerge;
  191. tuple.data = data;
  192. tuple.onComplete = callback;
  193. [self.onDisconnectQueue addObject:tuple];
  194. }
  195. }
  196. - (void) onDisconnectCancelPath:(FPath *)path withCallback:(fbt_void_nsstring_nsstring)callback {
  197. if ([self canSendWrites]) {
  198. [self sendOnDisconnectAction:kFWPRequestActionDisconnectCancel forPath:[path description] withData:[NSNull null] andCallback:callback];
  199. } else {
  200. FTupleOnDisconnect* tuple = [[FTupleOnDisconnect alloc] init];
  201. tuple.pathString = [path description];
  202. tuple.action = kFWPRequestActionDisconnectCancel;
  203. tuple.data = [NSNull null];
  204. tuple.onComplete = callback;
  205. [self.onDisconnectQueue addObject:tuple];
  206. }
  207. }
  208. - (void) unlisten:(FQuerySpec *)query tagId:(NSNumber *)tagId {
  209. FPath *path = query.path;
  210. FFLog(@"I-RDB034002", @"Unlistening for %@", query);
  211. NSArray *outstanding = [self removeListen:query];
  212. if (outstanding.count > 0 && [self connected]) {
  213. [self sendUnlisten:path queryParams:query.params tagId:tagId];
  214. }
  215. }
  216. - (void) refreshAuthToken:(NSString *)token {
  217. self.authToken = token;
  218. if ([self connected]) {
  219. if (token != nil) {
  220. [self sendAuthAndRestoreStateAfterComplete:NO];
  221. } else {
  222. [self sendUnauth];
  223. }
  224. }
  225. }
  226. #pragma mark -
  227. #pragma mark Connection status
  228. - (BOOL)connected {
  229. return self->connectionState == ConnectionStateAuthenticating || self->connectionState == ConnectionStateConnected;
  230. }
  231. - (BOOL)canSendWrites {
  232. return self->connectionState == ConnectionStateConnected;
  233. }
  234. #pragma mark -
  235. #pragma mark FConnection delegate methods
  236. - (void)onReady:(FConnection *)fconnection atTime:(NSNumber *)timestamp sessionID:(NSString *)sessionID {
  237. FFLog(@"I-RDB034003", @"On ready");
  238. lastConnectionEstablishedTime = [[NSDate date] timeIntervalSince1970];
  239. [self handleTimestamp:timestamp];
  240. if (firstConnection) {
  241. [self sendConnectStats];
  242. }
  243. [self restoreAuth];
  244. firstConnection = NO;
  245. self.lastSessionID = sessionID;
  246. dispatch_async(self.dispatchQueue, ^{
  247. [self.delegate onConnect:self];
  248. });
  249. }
  250. - (void)onDataMessage:(FConnection *)fconnection withMessage:(NSDictionary *)message {
  251. if (message[kFWPRequestNumber] != nil) {
  252. // this is a response to a request we sent
  253. NSNumber* rn = [NSNumber numberWithInt:[[message objectForKey:kFWPRequestNumber] intValue]];
  254. if ([self.requestCBHash objectForKey:rn]) {
  255. void (^callback)(NSDictionary*) = [self.requestCBHash objectForKey:rn];
  256. [self.requestCBHash removeObjectForKey:rn];
  257. if (callback) {
  258. //dispatch_async(self.dispatchQueue, ^{
  259. callback([message objectForKey:kFWPResponseForRNData]);
  260. //});
  261. }
  262. }
  263. } else if (message[kFWPRequestError] != nil) {
  264. NSString* error = [message objectForKey:kFWPRequestError];
  265. @throw [[NSException alloc] initWithName:@"FirebaseDatabaseServerError" reason:error userInfo:nil];
  266. } else if (message[kFWPAsyncServerAction] != nil) {
  267. // this is a server push of some sort
  268. NSString* action = [message objectForKey:kFWPAsyncServerAction];
  269. NSDictionary* body = [message objectForKey:kFWPAsyncServerPayloadBody];
  270. [self onDataPushWithAction:action andBody:body];
  271. }
  272. }
  273. - (void)onDisconnect:(FConnection *)fconnection withReason:(FDisconnectReason)reason {
  274. FFLog(@"I-RDB034004", @"Got on disconnect due to %s", (reason == DISCONNECT_REASON_SERVER_RESET) ? "server_reset" : "other");
  275. connectionState = ConnectionStateDisconnected;
  276. // Drop the realtime connection
  277. self.realtime = nil;
  278. [self cancelSentTransactions];
  279. [self.requestCBHash removeAllObjects];
  280. self.unackedListensCount = 0;
  281. if ([self shouldReconnect]) {
  282. NSTimeInterval timeSinceLastConnectSucceeded = [[NSDate date] timeIntervalSince1970] - lastConnectionEstablishedTime;
  283. BOOL lastConnectionWasSuccessful;
  284. if (lastConnectionEstablishedTime > 0) {
  285. lastConnectionWasSuccessful = timeSinceLastConnectSucceeded > kPersistentConnSuccessfulConnectionEstablishedDelay;
  286. } else {
  287. lastConnectionWasSuccessful = NO;
  288. }
  289. if (reason == DISCONNECT_REASON_SERVER_RESET || lastConnectionWasSuccessful) {
  290. [self.retryHelper signalSuccess];
  291. }
  292. [self tryScheduleReconnect];
  293. }
  294. lastConnectionEstablishedTime = 0;
  295. [self.delegate onDisconnect:self];
  296. }
  297. - (void)onKill:(FConnection *)fconnection withReason:(NSString *)reason {
  298. FFWarn(@"I-RDB034005", @"Firebase Database connection was forcefully killed by the server. Will not attempt reconnect. Reason: %@", reason);
  299. [self interruptForReason:kFInterruptReasonServerKill];
  300. }
  301. #pragma mark -
  302. #pragma mark Connection handling methods
  303. - (void) interruptForReason:(NSString *)reason {
  304. FFLog(@"I-RDB034006", @"Connection interrupted for: %@", reason);
  305. [self.interruptReasons addObject:reason];
  306. if (self.realtime) {
  307. // Will call onDisconnect and set the connection state to Disconnected
  308. [self.realtime close];
  309. self.realtime = nil;
  310. } else {
  311. [self.retryHelper cancel];
  312. self->connectionState = ConnectionStateDisconnected;
  313. }
  314. // Reset timeouts
  315. [self.retryHelper signalSuccess];
  316. }
  317. - (void) resumeForReason:(NSString *)reason {
  318. FFLog(@"I-RDB034007", @"Connection no longer interrupted for: %@", reason);
  319. [self.interruptReasons removeObject:reason];
  320. if ([self shouldReconnect] && connectionState == ConnectionStateDisconnected) {
  321. [self tryScheduleReconnect];
  322. }
  323. }
  324. - (BOOL) shouldReconnect {
  325. return self.interruptReasons.count == 0;
  326. }
  327. - (BOOL) isInterruptedForReason:(NSString *)reason {
  328. return [self.interruptReasons containsObject:reason];
  329. }
  330. #pragma mark -
  331. #pragma mark Private methods
  332. - (void) tryScheduleReconnect {
  333. if ([self shouldReconnect]) {
  334. NSAssert(self->connectionState == ConnectionStateDisconnected,
  335. @"Not in disconnected state: %d", self->connectionState);
  336. BOOL forceRefresh = self.forceAuthTokenRefresh;
  337. self.forceAuthTokenRefresh = NO;
  338. FFLog(@"I-RDB034008", @"Scheduling connection attempt");
  339. [self.retryHelper retry:^{
  340. FFLog(@"I-RDB034009", @"Trying to fetch auth token");
  341. NSAssert(self->connectionState == ConnectionStateDisconnected,
  342. @"Not in disconnected state: %d", self->connectionState);
  343. self->connectionState = ConnectionStateGettingToken;
  344. self.currentFetchTokenAttempt++;
  345. NSUInteger thisFetchTokenAttempt = self.currentFetchTokenAttempt;
  346. [self.authTokenProvider fetchTokenForcingRefresh:forceRefresh withCallback:^(NSString *token, NSError *error) {
  347. if (thisFetchTokenAttempt == self.currentFetchTokenAttempt) {
  348. if (error != nil) {
  349. self->connectionState = ConnectionStateDisconnected;
  350. FFLog(@"I-RDB034010", @"Error fetching token: %@", error);
  351. [self tryScheduleReconnect];
  352. } else {
  353. // Someone could have interrupted us while fetching the token,
  354. // marking the connection as Disconnected
  355. if (self->connectionState == ConnectionStateGettingToken) {
  356. FFLog(@"I-RDB034011", @"Successfully fetched token, opening connection");
  357. [self openNetworkConnectionWithToken:token];
  358. } else {
  359. NSAssert(self->connectionState == ConnectionStateDisconnected,
  360. @"Expected connection state disconnected, but got %d", self->connectionState);
  361. FFLog(@"I-RDB034012", @"Not opening connection after token refresh, because connection was set to disconnected.");
  362. }
  363. }
  364. } else {
  365. FFLog(@"I-RDB034013", @"Ignoring fetch token result, because this was not the latest attempt.");
  366. }
  367. }];
  368. }];
  369. }
  370. }
  371. - (void) openNetworkConnectionWithToken:(NSString *)token {
  372. NSAssert(self->connectionState == ConnectionStateGettingToken,
  373. @"Trying to open network connection while in wrong state: %d", self->connectionState);
  374. self.authToken = token;
  375. self->connectionState = ConnectionStateConnecting;
  376. self.realtime = [[FConnection alloc] initWith:self.repoInfo
  377. andDispatchQueue:self.dispatchQueue
  378. lastSessionID:self.lastSessionID];
  379. self.realtime.delegate = self;
  380. [self.realtime open];
  381. }
  382. static void reachabilityCallback(SCNetworkReachabilityRef ref, SCNetworkReachabilityFlags flags, void* info) {
  383. if (flags & kSCNetworkReachabilityFlagsReachable) {
  384. FFLog(@"I-RDB034014", @"Network became reachable. Trigger a connection attempt");
  385. FPersistentConnection* self = (__bridge FPersistentConnection *)info;
  386. // Reset reconnect delay
  387. [self.retryHelper signalSuccess];
  388. if (self->connectionState == ConnectionStateDisconnected) {
  389. [self tryScheduleReconnect];
  390. }
  391. } else {
  392. FFLog(@"I-RDB034015", @"Network is not reachable");
  393. }
  394. }
  395. - (void) enteringForeground {
  396. dispatch_async(self.dispatchQueue, ^{
  397. // Reset reconnect delay
  398. [self.retryHelper signalSuccess];
  399. if (self->connectionState == ConnectionStateDisconnected) {
  400. [self tryScheduleReconnect];
  401. }
  402. });
  403. }
  404. - (void) setupNotifications {
  405. NSString * const* foregroundConstant = (NSString * const *) dlsym(RTLD_DEFAULT, "UIApplicationWillEnterForegroundNotification");
  406. if (foregroundConstant) {
  407. [[NSNotificationCenter defaultCenter] addObserver:self
  408. selector:@selector(enteringForeground)
  409. name:*foregroundConstant
  410. object:nil];
  411. }
  412. // An empty address is interpreted a generic internet access
  413. struct sockaddr_in zeroAddress;
  414. bzero(&zeroAddress, sizeof(zeroAddress));
  415. zeroAddress.sin_len = sizeof(zeroAddress);
  416. zeroAddress.sin_family = AF_INET;
  417. reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)&zeroAddress);
  418. SCNetworkReachabilityContext ctx = {0, (__bridge void *)(self), NULL, NULL, NULL};
  419. if (SCNetworkReachabilitySetCallback(reachability, reachabilityCallback, &ctx)) {
  420. SCNetworkReachabilitySetDispatchQueue(reachability, self.dispatchQueue);
  421. } else {
  422. FFLog(@"I-RDB034016", @"Failed to set up network reachability monitoring");
  423. CFRelease(reachability);
  424. reachability = NULL;
  425. }
  426. }
  427. - (void) sendAuthAndRestoreStateAfterComplete:(BOOL)restoreStateAfterComplete {
  428. NSAssert([self connected], @"Must be connected to send auth");
  429. NSAssert(self.authToken != nil, @"Can't send auth if there is no credential");
  430. NSDictionary* requestData = @{kFWPRequestCredential: self.authToken};
  431. [self sendAction:kFWPRequestActionAuth body:requestData sensitive:YES callback:^(NSDictionary *data) {
  432. self->connectionState = ConnectionStateConnected;
  433. NSString* status = [data objectForKey:kFWPResponseForActionStatus];
  434. id responseData = [data objectForKey:kFWPResponseForActionData];
  435. if (responseData == nil) {
  436. responseData = @"error";
  437. }
  438. BOOL statusOk = [status isEqualToString:kFWPResponseForActionStatusOk];
  439. if (statusOk) {
  440. if (restoreStateAfterComplete) {
  441. [self restoreState];
  442. }
  443. } else {
  444. self.authToken = nil;
  445. self.forceAuthTokenRefresh = YES;
  446. if ([status isEqualToString:@"expired_token"]) {
  447. FFLog(@"I-RDB034017", @"Authentication failed: %@ (%@)", status, responseData);
  448. } else {
  449. FFWarn(@"I-RDB034018", @"Authentication failed: %@ (%@)", status, responseData);
  450. }
  451. [self.realtime close];
  452. }
  453. }];
  454. }
  455. - (void) sendUnauth {
  456. [self sendAction:kFWPRequestActionUnauth body:@{} sensitive:NO callback:nil];
  457. }
  458. - (void) onAuthRevokedWithStatus:(NSString *)status andReason:(NSString *)reason {
  459. // This might be for an earlier token than we just recently sent. But since we need to close the connection anyways,
  460. // we can set it to null here and we will refresh the token later on reconnect
  461. if ([status isEqualToString:@"expired_token"]) {
  462. FFLog(@"I-RDB034019", @"Auth token revoked: %@ (%@)", status, reason);
  463. } else {
  464. FFWarn(@"I-RDB034020", @"Auth token revoked: %@ (%@)", status, reason);
  465. }
  466. self.authToken = nil;
  467. self.forceAuthTokenRefresh = YES;
  468. // Try reconnecting on auth revocation
  469. [self.realtime close];
  470. }
  471. - (void) onListenRevoked:(FPath *)path {
  472. NSArray *queries = [self removeAllListensAtPath:path];
  473. for (FOutstandingQuery* query in queries) {
  474. query.onComplete(@"permission_denied");
  475. }
  476. }
  477. - (void) sendOnDisconnectAction:(NSString *)action forPath:(NSString *)pathString withData:(id)data andCallback:(fbt_void_nsstring_nsstring)callback {
  478. NSDictionary* request = @{kFWPRequestPath: pathString, kFWPRequestData: data};
  479. FFLog(@"I-RDB034021", @"onDisconnect %@: %@", action, request);
  480. [self sendAction:action
  481. body:request
  482. sensitive:NO
  483. callback:^(NSDictionary *data) {
  484. NSString* status = [data objectForKey:kFWPResponseForActionStatus];
  485. NSString* errorReason = [data objectForKey:kFWPResponseForActionData];
  486. callback(status, errorReason);
  487. }];
  488. }
  489. - (void) sendPut:(NSNumber *) index {
  490. NSAssert([self canSendWrites], @"sendPut called when not able to send writes");
  491. FOutstandingPut* put = self.outstandingPuts[index];
  492. assert(put != nil);
  493. fbt_void_nsstring_nsstring onComplete = put.onCompleteBlock;
  494. // Do not async this block; copying the block insinde sendAction: doesn't happen in time (or something) so coredumps
  495. put.sent = YES;
  496. [self sendAction:put.action
  497. body:put.request
  498. sensitive:NO
  499. callback:^(NSDictionary* data) {
  500. FOutstandingPut *currentPut = self.outstandingPuts[index];
  501. if (currentPut == put) {
  502. [self.outstandingPuts removeObjectForKey:index];
  503. if (onComplete != nil) {
  504. NSString *status = [data objectForKey:kFWPResponseForActionStatus];
  505. NSString *errorReason = [data objectForKey:kFWPResponseForActionData];
  506. if (self.unackedListensCount == 0) {
  507. onComplete(status, errorReason);
  508. } else {
  509. FTupleCallbackStatus *putToAck = [[FTupleCallbackStatus alloc] init];
  510. putToAck.block = onComplete;
  511. putToAck.status = status;
  512. putToAck.errorReason = errorReason;
  513. [self.putsToAck addObject:putToAck];
  514. }
  515. }
  516. } else {
  517. FFLog(@"I-RDB034022", @"Ignoring on complete for put %@ because it was already removed", index);
  518. }
  519. }];
  520. }
  521. - (void) sendUnlisten:(FPath *)path queryParams:(FQueryParams *)queryParams tagId:(NSNumber *)tagId {
  522. FFLog(@"I-RDB034023", @"Unlisten on %@ for %@", path, queryParams);
  523. NSMutableDictionary* request = [NSMutableDictionary dictionaryWithObjectsAndKeys:[path toString], kFWPRequestPath, nil];
  524. if (tagId) {
  525. [request setObject:queryParams.wireProtocolParams forKey:kFWPRequestQueries];
  526. [request setObject:tagId forKey:kFWPRequestTag];
  527. }
  528. [self sendAction:kFWPRequestActionTaggedUnlisten
  529. body:request
  530. sensitive:NO
  531. callback:nil];
  532. }
  533. - (void) putInternal:(id)data forAction:(NSString *)action forPath:(NSString *)pathString withHash:(NSString *)hash withCallback:(fbt_void_nsstring_nsstring)onComplete {
  534. NSMutableDictionary *request = [NSMutableDictionary dictionaryWithObjectsAndKeys:
  535. pathString, kFWPRequestPath,
  536. data, kFWPRequestData, nil];
  537. if(hash) {
  538. [request setObject:hash forKey:kFWPRequestHash];
  539. }
  540. FOutstandingPut *put = [[FOutstandingPut alloc] init];
  541. put.action = action;
  542. put.request = request;
  543. put.onCompleteBlock = onComplete;
  544. put.sent = NO;
  545. NSNumber* index = [self.putCounter getAndIncrement];
  546. self.outstandingPuts[index] = put;
  547. if ([self canSendWrites]) {
  548. FFLog(@"I-RDB034024", @"Was connected, and added as index: %@", index);
  549. [self sendPut:index];
  550. }
  551. else {
  552. FFLog(@"I-RDB034025", @"Wasn't connected or writes paused, so added to outstanding puts only. Path: %@", pathString);
  553. }
  554. }
  555. - (void) sendListen:(FOutstandingQuery *)listenSpec {
  556. FQuerySpec *query = listenSpec.query;
  557. FFLog(@"I-RDB034026", @"Listen for %@", query);
  558. NSMutableDictionary *request = [NSMutableDictionary dictionaryWithObject:[query.path toString] forKey:kFWPRequestPath];
  559. // Only bother to send query if it's non-default
  560. if (listenSpec.tagId != nil) {
  561. [request setObject:[query.params wireProtocolParams] forKey:kFWPRequestQueries];
  562. [request setObject:listenSpec.tagId forKey:kFWPRequestTag];
  563. }
  564. [request setObject:[listenSpec.syncTreeHash simpleHash] forKey:kFWPRequestHash];
  565. if ([listenSpec.syncTreeHash includeCompoundHash]) {
  566. FCompoundHash *compoundHash = [listenSpec.syncTreeHash compoundHash];
  567. NSMutableArray *posts = [NSMutableArray array];
  568. for (FPath *path in compoundHash.posts) {
  569. [posts addObject:path.wireFormat];
  570. }
  571. request[kFWPRequestCompoundHash] = @{ kFWPRequestCompoundHashHashes: compoundHash.hashes,
  572. kFWPRequestCompoundHashPaths: posts };
  573. }
  574. fbt_void_nsdictionary onResponse = ^(NSDictionary *response) {
  575. FFLog(@"I-RDB034027", @"Listen response %@", response);
  576. // warn in any case, even if the listener was removed
  577. [self warnOnListenWarningsForQuery:query payload:response[kFWPResponseForActionData]];
  578. FOutstandingQuery *currentListenSpec = self.listens[query];
  579. // only trigger actions if the listen hasn't been removed (and maybe readded)
  580. if (currentListenSpec == listenSpec) {
  581. NSString *status = [response objectForKey:kFWPRequestStatus];
  582. if (![status isEqualToString:@"ok"]) {
  583. [self removeListen:query];
  584. }
  585. if (listenSpec.onComplete) {
  586. listenSpec.onComplete(status);
  587. }
  588. }
  589. self.unackedListensCount--;
  590. NSAssert(self.unackedListensCount >= 0, @"unackedListensCount decremented to be negative.");
  591. if (self.unackedListensCount == 0) {
  592. [self ackPuts];
  593. }
  594. };
  595. [self sendAction:kFWPRequestActionTaggedListen
  596. body:request
  597. sensitive:NO
  598. callback:onResponse];
  599. self.unackedListensCount++;
  600. }
  601. - (void) warnOnListenWarningsForQuery:(FQuerySpec *)query payload:(id)payload {
  602. if (payload != nil && [payload isKindOfClass:[NSDictionary class]]) {
  603. NSDictionary *payloadDict = payload;
  604. id warnings = payloadDict[kFWPResponseDataWarnings];
  605. if (warnings != nil && [warnings isKindOfClass:[NSArray class]]) {
  606. NSArray *warningsArr = warnings;
  607. if ([warningsArr containsObject:@"no_index"]) {
  608. NSString *indexSpec = [NSString stringWithFormat:@"\".indexOn\": \"%@\"", [query.params.index queryDefinition]];
  609. NSString *indexPath = [query.path description];
  610. FFWarn(@"I-RDB034028", @"Using an unspecified index. Your data will be downloaded and filtered on the client. "
  611. "Consider adding %@ at %@ to your security rules for better performance", indexSpec, indexPath);
  612. }
  613. }
  614. }
  615. }
  616. - (int) getNextRequestNumber {
  617. return [[self.requestNumber getAndIncrement] intValue];
  618. }
  619. - (void)sendAction:(NSString *)action
  620. body:(NSDictionary *)message
  621. sensitive:(BOOL)sensitive
  622. callback:(void (^)(NSDictionary* data))onMessage {
  623. // Hold onto the onMessage callback for this request before firing it off
  624. NSNumber* rn = [NSNumber numberWithInt:[self getNextRequestNumber]];
  625. NSDictionary* msg = [NSDictionary dictionaryWithObjectsAndKeys:
  626. rn, kFWPRequestNumber,
  627. action, kFWPRequestAction,
  628. message, kFWPRequestPayloadBody,
  629. nil];
  630. [self.realtime sendRequest:msg sensitive:sensitive];
  631. if (onMessage) {
  632. // Debug message without a callback; bump the rn, but don't hold onto the cb
  633. [self.requestCBHash setObject:[onMessage copy] forKey:rn];
  634. }
  635. }
  636. - (void) cancelSentTransactions {
  637. NSMutableArray* toPrune = [[NSMutableArray alloc] init];
  638. for (NSNumber* index in self.outstandingPuts) {
  639. FOutstandingPut* put = self.outstandingPuts[index];
  640. if (put.request[kFWPRequestHash] && put.sent) {
  641. // This is a sent transaction put
  642. put.onCompleteBlock(kFTransactionDisconnect, @"Client was disconnected while running a transaction");
  643. [toPrune addObject:index];
  644. }
  645. }
  646. for (NSNumber* index in toPrune) {
  647. [self.outstandingPuts removeObjectForKey:index];
  648. }
  649. }
  650. - (void) onDataPushWithAction:(NSString *)action andBody:(NSDictionary *)body {
  651. FFLog(@"I-RDB034029", @"handleServerMessage: %@, %@", action, body);
  652. id<FPersistentConnectionDelegate> delegate = self.delegate;
  653. if ([action isEqualToString:kFWPAsyncServerDataUpdate] || [action isEqualToString:kFWPAsyncServerDataMerge]) {
  654. BOOL isMerge = [action isEqualToString:kFWPAsyncServerDataMerge];
  655. if ([body objectForKey:kFWPAsyncServerDataUpdateBodyPath] && [body objectForKey:kFWPAsyncServerDataUpdateBodyData]) {
  656. NSString* path = [body objectForKey:kFWPAsyncServerDataUpdateBodyPath];
  657. id payloadData = [body objectForKey:kFWPAsyncServerDataUpdateBodyData];
  658. if (isMerge && [payloadData isKindOfClass:[NSDictionary class]] && [payloadData count] == 0) {
  659. // ignore empty merge
  660. } else {
  661. [delegate onDataUpdate:self forPath:path message:payloadData isMerge:isMerge tagId:[body objectForKey:kFWPAsyncServerDataUpdateBodyTag]];
  662. }
  663. }
  664. else {
  665. FFLog(@"I-RDB034030", @"Malformed data response from server missing path or data: %@", body);
  666. }
  667. } else if ([action isEqualToString:kFWPAsyncServerDataRangeMerge]) {
  668. NSString *path = body[kFWPAsyncServerDataUpdateBodyPath];
  669. NSArray *ranges = body[kFWPAsyncServerDataUpdateBodyData];
  670. NSNumber *tag = body[kFWPAsyncServerDataUpdateBodyTag];
  671. NSMutableArray *rangeMerges = [NSMutableArray array];
  672. for (NSDictionary *range in ranges) {
  673. NSString *startString = range[kFWPAsyncServerDataUpdateStartPath];
  674. NSString *endString = range[kFWPAsyncServerDataUpdateEndPath];
  675. id updateData = range[kFWPAsyncServerDataUpdateRangeMerge];
  676. id<FNode> updates = [FSnapshotUtilities nodeFrom:updateData];
  677. FPath *start = (startString != nil) ? [[FPath alloc] initWith:startString] : nil;
  678. FPath *end = (endString != nil) ? [[FPath alloc] initWith:endString] : nil;
  679. FRangeMerge *merge = [[FRangeMerge alloc] initWithStart:start end:end updates:updates];
  680. [rangeMerges addObject:merge];
  681. }
  682. [delegate onRangeMerge:rangeMerges forPath:path tagId:tag];
  683. } else if ([action isEqualToString:kFWPAsyncServerAuthRevoked]) {
  684. NSString* status = [body objectForKey:kFWPResponseForActionStatus];
  685. NSString* reason = [body objectForKey:kFWPResponseForActionData];
  686. [self onAuthRevokedWithStatus:status andReason:reason];
  687. } else if ([action isEqualToString:kFWPASyncServerListenCancelled]) {
  688. NSString* pathString = [body objectForKey:kFWPAsyncServerDataUpdateBodyPath];
  689. [self onListenRevoked:[[FPath alloc] initWith:pathString]];
  690. } else if ([action isEqualToString:kFWPAsyncServerSecurityDebug]) {
  691. NSString* msg = [body objectForKey:@"msg"];
  692. if (msg != nil) {
  693. NSArray *msgs = [msg componentsSeparatedByString:@"\n"];
  694. for (NSString* m in msgs) {
  695. FFWarn(@"I-RDB034031", @"%@", m);
  696. }
  697. }
  698. } else {
  699. // TODO: revoke listens, auth, security debug
  700. FFLog(@"I-RDB034032", @"Unsupported action from server: %@", action);
  701. }
  702. }
  703. - (void) restoreAuth {
  704. FFLog(@"I-RDB034033", @"Calling restore state");
  705. NSAssert(self->connectionState == ConnectionStateConnecting,
  706. @"Wanted to restore auth, but was in wrong state: %d", self->connectionState);
  707. if (self.authToken == nil) {
  708. FFLog(@"I-RDB034034", @"Not restoring auth because token is nil");
  709. self->connectionState = ConnectionStateConnected;
  710. [self restoreState];
  711. } else {
  712. FFLog(@"I-RDB034035", @"Restoring auth");
  713. self->connectionState = ConnectionStateAuthenticating;
  714. [self sendAuthAndRestoreStateAfterComplete:YES];
  715. }
  716. }
  717. - (void) restoreState {
  718. NSAssert(self->connectionState == ConnectionStateConnected,
  719. @"Should be connected if we're restoring state, but we are: %d", self->connectionState);
  720. [self.listens enumerateKeysAndObjectsUsingBlock:^(FQuerySpec *query, FOutstandingQuery *outstandingListen, BOOL *stop) {
  721. FFLog(@"I-RDB034036", @"Restoring listen for %@", query);
  722. [self sendListen:outstandingListen];
  723. }];
  724. NSArray* keys = [[self.outstandingPuts allKeys] sortedArrayUsingSelector:@selector(compare:)];
  725. for(int i = 0; i < [keys count]; i++) {
  726. if([self.outstandingPuts objectForKey:[keys objectAtIndex:i]] != nil) {
  727. FFLog(@"I-RDB034037", @"Restoring put: %d", i);
  728. [self sendPut:[keys objectAtIndex:i]];
  729. }
  730. else {
  731. FFLog(@"I-RDB034038", @"Restoring put: skipped nil: %d", i);
  732. }
  733. }
  734. for (FTupleOnDisconnect* tuple in self.onDisconnectQueue) {
  735. [self sendOnDisconnectAction:tuple.action forPath:tuple.pathString withData:tuple.data andCallback:tuple.onComplete];
  736. }
  737. [self.onDisconnectQueue removeAllObjects];
  738. }
  739. - (NSArray *) removeListen:(FQuerySpec *)query {
  740. NSAssert(query.isDefault || !query.loadsAllData, @"removeListen called for non-default but complete query");
  741. FOutstandingQuery* outstanding = self.listens[query];
  742. if (!outstanding) {
  743. FFLog(@"I-RDB034039", @"Trying to remove listener for query %@ but no listener exists", query);
  744. return @[];
  745. } else {
  746. [self.listens removeObjectForKey:query];
  747. return @[outstanding];
  748. }
  749. }
  750. - (NSArray *) removeAllListensAtPath:(FPath *)path {
  751. FFLog(@"I-RDB034040", @"Removing all listens at path %@", path);
  752. NSMutableArray *removed = [NSMutableArray array];
  753. NSMutableArray *toRemove = [NSMutableArray array];
  754. [self.listens enumerateKeysAndObjectsUsingBlock:^(FQuerySpec *spec, FOutstandingQuery *outstanding, BOOL *stop) {
  755. if ([spec.path isEqual:path]) {
  756. [removed addObject:outstanding];
  757. [toRemove addObject:spec];
  758. }
  759. }];
  760. [self.listens removeObjectsForKeys:toRemove];
  761. return removed;
  762. }
  763. - (void) purgeOutstandingWrites {
  764. // We might have unacked puts in our queue that we need to ack now before we send out any cancels...
  765. [self ackPuts];
  766. // Cancel in order
  767. NSArray* keys = [[self.outstandingPuts allKeys] sortedArrayUsingSelector:@selector(compare:)];
  768. for (NSNumber *key in keys) {
  769. FOutstandingPut *put = self.outstandingPuts[key];
  770. if (put.onCompleteBlock != nil) {
  771. put.onCompleteBlock(kFErrorWriteCanceled, nil);
  772. }
  773. }
  774. for (FTupleOnDisconnect *onDisconnect in self.onDisconnectQueue) {
  775. if (onDisconnect.onComplete != nil) {
  776. onDisconnect.onComplete(kFErrorWriteCanceled, nil);
  777. }
  778. }
  779. [self.outstandingPuts removeAllObjects];
  780. [self.onDisconnectQueue removeAllObjects];
  781. }
  782. - (void) ackPuts {
  783. for (FTupleCallbackStatus *put in self.putsToAck) {
  784. put.block(put.status, put.errorReason);
  785. }
  786. [self.putsToAck removeAllObjects];
  787. }
  788. - (void) handleTimestamp:(NSNumber *)timestamp {
  789. FFLog(@"I-RDB034041", @"Handling timestamp: %@", timestamp);
  790. double timestampDeltaMs = [timestamp doubleValue] - ([[NSDate date] timeIntervalSince1970] * 1000);
  791. [self.delegate onServerInfoUpdate:self updates:@{kDotInfoServerTimeOffset: [NSNumber numberWithDouble:timestampDeltaMs]}];
  792. }
  793. - (void) sendStats:(NSDictionary *)stats {
  794. if ([stats count] > 0) {
  795. NSDictionary *request = @{ kFWPRequestCounters: stats };
  796. [self sendAction:kFWPRequestActionStats body:request sensitive:NO callback:^(NSDictionary *data) {
  797. NSString* status = [data objectForKey:kFWPResponseForActionStatus];
  798. NSString* errorReason = [data objectForKey:kFWPResponseForActionData];
  799. BOOL statusOk = [status isEqualToString:kFWPResponseForActionStatusOk];
  800. if (!statusOk) {
  801. FFLog(@"I-RDB034042", @"Failed to send stats: %@", errorReason);
  802. }
  803. }];
  804. } else {
  805. FFLog(@"I-RDB034043", @"Not sending stats because stats are empty");
  806. }
  807. }
  808. - (void) sendConnectStats {
  809. NSMutableDictionary *stats = [NSMutableDictionary dictionary];
  810. #if TARGET_OS_IOS || TARGET_OS_TV
  811. if (self.config.persistenceEnabled) {
  812. stats[@"persistence.ios.enabled"] = @1;
  813. }
  814. #elif TARGET_OS_OSX
  815. if (self.config.persistenceEnabled) {
  816. stats[@"persistence.osx.enabled"] = @1;
  817. }
  818. #endif
  819. NSString *sdkVersion = [[FIRDatabase sdkVersion] stringByReplacingOccurrencesOfString:@"." withString:@"-"];
  820. NSString *sdkStatName = [NSString stringWithFormat:@"sdk.objc.%@", sdkVersion];
  821. stats[sdkStatName] = @1;
  822. FFLog(@"I-RDB034044", @"Sending first connection stats");
  823. [self sendStats:stats];
  824. }
  825. - (NSDictionary *) dumpListens {
  826. return self.listens;
  827. }
  828. @end