FPersistentConnection.m 39 KB

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