| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260 |
- /*
- * Copyright 2017 Google
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- #import <Foundation/Foundation.h>
- #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
- #import "FirebaseDatabase/Sources/Api/FIRDatabaseConfig.h"
- #import "FirebaseDatabase/Sources/Constants/FConstants.h"
- #import "FirebaseDatabase/Sources/Core/FCompoundHash.h"
- #import "FirebaseDatabase/Sources/Core/FPersistentConnection.h"
- #import "FirebaseDatabase/Sources/Core/FQueryParams.h"
- #import "FirebaseDatabase/Sources/Core/FQuerySpec.h"
- #import "FirebaseDatabase/Sources/Core/FRangeMerge.h"
- #import "FirebaseDatabase/Sources/Core/FSyncTree.h"
- #import "FirebaseDatabase/Sources/Core/Utilities/FIRRetryHelper.h"
- #import "FirebaseDatabase/Sources/FIRDatabaseConfig_Private.h"
- #import "FirebaseDatabase/Sources/FIndex.h"
- #import "FirebaseDatabase/Sources/Login/FIRDatabaseConnectionContextProvider.h"
- #import "FirebaseDatabase/Sources/Public/FirebaseDatabase/FIRDatabaseReference.h"
- #import "FirebaseDatabase/Sources/Snapshot/FSnapshotUtilities.h"
- #import "FirebaseDatabase/Sources/Utilities/FAtomicNumber.h"
- #import "FirebaseDatabase/Sources/Utilities/FUtilities.h"
- #import "FirebaseDatabase/Sources/Utilities/Tuples/FTupleCallbackStatus.h"
- #import "FirebaseDatabase/Sources/Utilities/Tuples/FTupleOnDisconnect.h"
- #if !TARGET_OS_WATCH
- #import <SystemConfiguration/SystemConfiguration.h>
- #endif // !TARGET_OS_WATCH
- #import <dlfcn.h>
- #import <netinet/in.h>
- @interface FOutstandingQuery : NSObject
- @property(nonatomic, strong) FQuerySpec *query;
- @property(nonatomic, strong) NSNumber *tagId;
- @property(nonatomic, strong) id<FSyncTreeHash> syncTreeHash;
- @property(nonatomic, copy) fbt_void_nsstring onComplete;
- @end
- @implementation FOutstandingQuery
- @end
- @interface FOutstandingPut : NSObject
- @property(nonatomic, strong) NSString *action;
- @property(nonatomic, strong) NSDictionary *request;
- @property(nonatomic, copy) fbt_void_nsstring_nsstring onCompleteBlock;
- @property(nonatomic) BOOL sent;
- @end
- @implementation FOutstandingPut
- @end
- @interface FOutstandingGet : NSObject
- @property(nonatomic, strong) NSDictionary *request;
- @property(nonatomic, copy) fbt_void_nsstring_id_nsstring onCompleteBlock;
- @property(nonatomic) BOOL sent;
- @end
- @implementation FOutstandingGet
- @end
- typedef enum {
- ConnectionStateDisconnected,
- ConnectionStateGettingToken,
- ConnectionStateConnecting,
- ConnectionStateAuthenticating,
- ConnectionStateConnected
- } ConnectionState;
- @interface FPersistentConnection () {
- ConnectionState connectionState;
- BOOL firstConnection;
- NSTimeInterval reconnectDelay;
- NSTimeInterval lastConnectionAttemptTime;
- NSTimeInterval lastConnectionEstablishedTime;
- #if !TARGET_OS_WATCH
- SCNetworkReachabilityRef reachability;
- #endif // !TARGET_OS_WATCH
- }
- - (int)getNextRequestNumber;
- - (void)onDataPushWithAction:(NSString *)action andBody:(NSDictionary *)body;
- - (void)handleTimestamp:(NSNumber *)timestamp;
- - (void)sendOnDisconnectAction:(NSString *)action
- forPath:(NSString *)pathString
- withData:(id)data
- andCallback:(fbt_void_nsstring_nsstring)callback;
- @property(nonatomic, strong) FConnection *realtime;
- @property(nonatomic, strong) NSMutableDictionary *listens;
- @property(nonatomic, strong) NSMutableDictionary *outstandingPuts;
- @property(nonatomic, strong) NSMutableDictionary *outstandingGets;
- @property(nonatomic, strong) NSMutableArray *onDisconnectQueue;
- @property(nonatomic, strong) FRepoInfo *repoInfo;
- @property(nonatomic, strong) FAtomicNumber *putCounter;
- @property(nonatomic, strong) FAtomicNumber *getCounter;
- @property(nonatomic, strong) FAtomicNumber *requestNumber;
- @property(nonatomic, strong) NSMutableDictionary *requestCBHash;
- @property(nonatomic, strong) FIRDatabaseConfig *config;
- @property(nonatomic) NSUInteger unackedListensCount;
- @property(nonatomic, strong) NSMutableArray *putsToAck;
- @property(nonatomic, strong) dispatch_queue_t dispatchQueue;
- @property(nonatomic, strong) NSString *lastSessionID;
- @property(nonatomic, strong) NSMutableSet *interruptReasons;
- @property(nonatomic, strong) FIRRetryHelper *retryHelper;
- @property(nonatomic, strong) id<FIRDatabaseConnectionContextProvider>
- contextProvider;
- @property(nonatomic, strong) NSString *authToken;
- @property(nonatomic) BOOL forceTokenRefreshes;
- @property(nonatomic) NSUInteger currentFetchTokenAttempt;
- @end
- @implementation FPersistentConnection
- - (id)initWithRepoInfo:(FRepoInfo *)repoInfo
- dispatchQueue:(dispatch_queue_t)dispatchQueue
- config:(FIRDatabaseConfig *)config {
- self = [super init];
- if (self) {
- self->_config = config;
- self->_repoInfo = repoInfo;
- self->_dispatchQueue = dispatchQueue;
- self->_contextProvider = config.contextProvider;
- NSAssert(self->_contextProvider != nil,
- @"Expected auth token provider");
- self.interruptReasons = [NSMutableSet set];
- self.listens = [[NSMutableDictionary alloc] init];
- self.outstandingPuts = [[NSMutableDictionary alloc] init];
- self.outstandingGets = [[NSMutableDictionary alloc] init];
- self.onDisconnectQueue = [[NSMutableArray alloc] init];
- self.putCounter = [[FAtomicNumber alloc] init];
- self.getCounter = [[FAtomicNumber alloc] init];
- self.requestNumber = [[FAtomicNumber alloc] init];
- self.requestCBHash = [[NSMutableDictionary alloc] init];
- self.unackedListensCount = 0;
- self.putsToAck = [NSMutableArray array];
- connectionState = ConnectionStateDisconnected;
- firstConnection = YES;
- reconnectDelay = kPersistentConnReconnectMinDelay;
- self->_retryHelper = [[FIRRetryHelper alloc]
- initWithDispatchQueue:dispatchQueue
- minRetryDelayAfterFailure:kPersistentConnReconnectMinDelay
- maxRetryDelay:kPersistentConnReconnectMaxDelay
- retryExponent:kPersistentConnReconnectMultiplier
- jitterFactor:0.7];
- // Make sure we don't actually connect until open is called
- [self interruptForReason:kFInterruptReasonWaitingForOpen];
- }
- // nb: The reason establishConnection isn't called here like the JS version
- // is because callers need to set the delegate first. The ctor can be
- // modified to accept the delegate but that deviates from normal ios
- // conventions. After the delegate has been set, the caller is responsible
- // for calling establishConnection:
- return self;
- }
- - (void)dealloc {
- #if !TARGET_OS_WATCH
- if (reachability) {
- // Unschedule the notifications
- SCNetworkReachabilitySetDispatchQueue(reachability, NULL);
- CFRelease(reachability);
- }
- #endif // !TARGET_OS_WATCH
- }
- #pragma mark -
- #pragma mark Public methods
- - (void)open {
- [self resumeForReason:kFInterruptReasonWaitingForOpen];
- }
- /**
- * Note that the listens dictionary has a type of Map[String (pathString),
- * Map[FQueryParams, FOutstandingQuery]]
- *
- * This means, for each path we care about, there are sets of queryParams that
- * correspond to an FOutstandingQuery object. There can be multiple sets at a
- * path since we overlap listens for a short time while adding or removing a
- * query from a location in the tree.
- */
- - (void)listen:(FQuerySpec *)query
- tagId:(NSNumber *)tagId
- hash:(id<FSyncTreeHash>)hash
- onComplete:(fbt_void_nsstring)onComplete {
- FFLog(@"I-RDB034001", @"Listen called for %@", query);
- NSAssert(self.listens[query] == nil,
- @"listen() called twice for the same query");
- NSAssert(query.isDefault || !query.loadsAllData,
- @"listen called for non-default but complete query");
- FOutstandingQuery *outstanding = [[FOutstandingQuery alloc] init];
- outstanding.query = query;
- outstanding.tagId = tagId;
- outstanding.syncTreeHash = hash;
- outstanding.onComplete = onComplete;
- [self.listens setObject:outstanding forKey:query];
- if ([self connected]) {
- [self sendListen:outstanding];
- }
- }
- - (void)putData:(id)data
- forPath:(NSString *)pathString
- withHash:(NSString *)hash
- withCallback:(fbt_void_nsstring_nsstring)onComplete {
- [self putInternal:data
- forAction:kFWPRequestActionPut
- forPath:pathString
- withHash:hash
- withCallback:onComplete];
- }
- - (void)mergeData:(id)data
- forPath:(NSString *)pathString
- withCallback:(fbt_void_nsstring_nsstring)onComplete {
- [self putInternal:data
- forAction:kFWPRequestActionMerge
- forPath:pathString
- withHash:nil
- withCallback:onComplete];
- }
- - (void)onDisconnectPutData:(id)data
- forPath:(FPath *)path
- withCallback:(fbt_void_nsstring_nsstring)callback {
- if ([self canSendWrites]) {
- [self sendOnDisconnectAction:kFWPRequestActionDisconnectPut
- forPath:[path description]
- withData:data
- andCallback:callback];
- } else {
- FTupleOnDisconnect *tuple = [[FTupleOnDisconnect alloc] init];
- tuple.pathString = [path description];
- tuple.action = kFWPRequestActionDisconnectPut;
- tuple.data = data;
- tuple.onComplete = callback;
- [self.onDisconnectQueue addObject:tuple];
- }
- }
- - (void)onDisconnectMergeData:(id)data
- forPath:(FPath *)path
- withCallback:(fbt_void_nsstring_nsstring)callback {
- if ([self canSendWrites]) {
- [self sendOnDisconnectAction:kFWPRequestActionDisconnectMerge
- forPath:[path description]
- withData:data
- andCallback:callback];
- } else {
- FTupleOnDisconnect *tuple = [[FTupleOnDisconnect alloc] init];
- tuple.pathString = [path description];
- tuple.action = kFWPRequestActionDisconnectMerge;
- tuple.data = data;
- tuple.onComplete = callback;
- [self.onDisconnectQueue addObject:tuple];
- }
- }
- - (void)onDisconnectCancelPath:(FPath *)path
- withCallback:(fbt_void_nsstring_nsstring)callback {
- if ([self canSendWrites]) {
- [self sendOnDisconnectAction:kFWPRequestActionDisconnectCancel
- forPath:[path description]
- withData:[NSNull null]
- andCallback:callback];
- } else {
- FTupleOnDisconnect *tuple = [[FTupleOnDisconnect alloc] init];
- tuple.pathString = [path description];
- tuple.action = kFWPRequestActionDisconnectCancel;
- tuple.data = [NSNull null];
- tuple.onComplete = callback;
- [self.onDisconnectQueue addObject:tuple];
- }
- }
- - (void)unlisten:(FQuerySpec *)query tagId:(NSNumber *)tagId {
- FPath *path = query.path;
- FFLog(@"I-RDB034002", @"Unlistening for %@", query);
- NSArray *outstanding = [self removeListen:query];
- if (outstanding.count > 0 && [self connected]) {
- [self sendUnlisten:path queryParams:query.params tagId:tagId];
- }
- }
- - (void)refreshAuthToken:(NSString *)token {
- self.authToken = token;
- if ([self connected]) {
- if (token != nil) {
- [self sendAuthAndRestoreStateAfterComplete:NO];
- } else {
- [self sendUnauth];
- }
- }
- }
- #pragma mark -
- #pragma mark Connection status
- - (BOOL)connected {
- return self->connectionState == ConnectionStateAuthenticating ||
- self->connectionState == ConnectionStateConnected;
- }
- - (BOOL)canSendWrites {
- return self->connectionState == ConnectionStateConnected;
- }
- - (BOOL)canSendReads {
- return self->connectionState == ConnectionStateConnected;
- }
- #pragma mark -
- #pragma mark FConnection delegate methods
- - (void)onReady:(FConnection *)fconnection
- atTime:(NSNumber *)timestamp
- sessionID:(NSString *)sessionID {
- FFLog(@"I-RDB034003", @"On ready");
- lastConnectionEstablishedTime = [[NSDate date] timeIntervalSince1970];
- [self handleTimestamp:timestamp];
- if (firstConnection) {
- [self sendConnectStats];
- }
- [self restoreAuth];
- firstConnection = NO;
- self.lastSessionID = sessionID;
- dispatch_async(self.dispatchQueue, ^{
- [self.delegate onConnect:self];
- });
- }
- - (void)onDataMessage:(FConnection *)fconnection
- withMessage:(NSDictionary *)message {
- if (message[kFWPRequestNumber] != nil) {
- // this is a response to a request we sent
- NSNumber *rn = [NSNumber
- numberWithInt:[[message objectForKey:kFWPRequestNumber] intValue]];
- if ([self.requestCBHash objectForKey:rn]) {
- void (^callback)(NSDictionary *) =
- [self.requestCBHash objectForKey:rn];
- [self.requestCBHash removeObjectForKey:rn];
- if (callback) {
- // dispatch_async(self.dispatchQueue, ^{
- callback([message objectForKey:kFWPResponseForRNData]);
- //});
- }
- }
- } else if (message[kFWPRequestError] != nil) {
- NSString *error = [message objectForKey:kFWPRequestError];
- @throw [[NSException alloc] initWithName:@"FirebaseDatabaseServerError"
- reason:error
- userInfo:nil];
- } else if (message[kFWPAsyncServerAction] != nil) {
- // this is a server push of some sort
- NSString *action = [message objectForKey:kFWPAsyncServerAction];
- NSDictionary *body = [message objectForKey:kFWPAsyncServerPayloadBody];
- [self onDataPushWithAction:action andBody:body];
- }
- }
- - (void)onDisconnect:(FConnection *)fconnection
- withReason:(FDisconnectReason)reason {
- FFLog(@"I-RDB034004", @"Got on disconnect due to %s",
- (reason == DISCONNECT_REASON_SERVER_RESET) ? "server_reset"
- : "other");
- connectionState = ConnectionStateDisconnected;
- // Drop the realtime connection
- self.realtime = nil;
- [self cancelSentTransactions];
- [self.requestCBHash removeAllObjects];
- self.unackedListensCount = 0;
- if ([self shouldReconnect]) {
- NSTimeInterval timeSinceLastConnectSucceeded =
- [[NSDate date] timeIntervalSince1970] -
- lastConnectionEstablishedTime;
- BOOL lastConnectionWasSuccessful;
- if (lastConnectionEstablishedTime > 0) {
- lastConnectionWasSuccessful =
- timeSinceLastConnectSucceeded >
- kPersistentConnSuccessfulConnectionEstablishedDelay;
- } else {
- lastConnectionWasSuccessful = NO;
- }
- if (reason == DISCONNECT_REASON_SERVER_RESET ||
- lastConnectionWasSuccessful) {
- [self.retryHelper signalSuccess];
- }
- [self tryScheduleReconnect];
- }
- lastConnectionEstablishedTime = 0;
- [self.delegate onDisconnect:self];
- }
- - (void)onKill:(FConnection *)fconnection withReason:(NSString *)reason {
- FFWarn(@"I-RDB034005",
- @"Firebase Database connection was forcefully killed by the server. "
- @" Will not attempt reconnect. Reason: %@",
- reason);
- [self interruptForReason:kFInterruptReasonServerKill];
- }
- #pragma mark -
- #pragma mark Connection handling methods
- - (void)interruptForReason:(NSString *)reason {
- FFLog(@"I-RDB034006", @"Connection interrupted for: %@", reason);
- [self.interruptReasons addObject:reason];
- if (self.realtime) {
- // Will call onDisconnect and set the connection state to Disconnected
- [self.realtime close];
- self.realtime = nil;
- } else {
- [self.retryHelper cancel];
- self->connectionState = ConnectionStateDisconnected;
- }
- // Reset timeouts
- [self.retryHelper signalSuccess];
- }
- - (void)resumeForReason:(NSString *)reason {
- FFLog(@"I-RDB034007", @"Connection no longer interrupted for: %@", reason);
- [self.interruptReasons removeObject:reason];
- if ([self shouldReconnect] &&
- connectionState == ConnectionStateDisconnected) {
- [self tryScheduleReconnect];
- }
- }
- - (BOOL)shouldReconnect {
- return self.interruptReasons.count == 0;
- }
- - (BOOL)isInterruptedForReason:(NSString *)reason {
- return [self.interruptReasons containsObject:reason];
- }
- #pragma mark -
- #pragma mark Private methods
- - (void)tryScheduleReconnect {
- if ([self shouldReconnect]) {
- NSAssert(self->connectionState == ConnectionStateDisconnected,
- @"Not in disconnected state: %d", self->connectionState);
- BOOL forceRefresh = self.forceTokenRefreshes;
- self.forceTokenRefreshes = NO;
- FFLog(@"I-RDB034008", @"Scheduling connection attempt");
- [self.retryHelper retry:^{
- FFLog(@"I-RDB034009", @"Trying to fetch auth token");
- NSAssert(self->connectionState == ConnectionStateDisconnected,
- @"Not in disconnected state: %d", self->connectionState);
- self->connectionState = ConnectionStateGettingToken;
- self.currentFetchTokenAttempt++;
- NSUInteger thisFetchTokenAttempt = self.currentFetchTokenAttempt;
- [self.contextProvider
- fetchContextForcingRefresh:forceRefresh
- withCallback:^(
- FIRDatabaseConnectionContext *context,
- NSError *error) {
- if (thisFetchTokenAttempt ==
- self.currentFetchTokenAttempt) {
- if (error != nil) {
- self->connectionState =
- ConnectionStateDisconnected;
- FFLog(@"I-RDB034010",
- @"Error fetching token: %@", error);
- [self tryScheduleReconnect];
- } else {
- // Someone could have interrupted us while
- // fetching the token, marking the
- // connection as Disconnected
- if (self->connectionState ==
- ConnectionStateGettingToken) {
- FFLog(@"I-RDB034011",
- @"Successfully fetched token, "
- @"opening connection");
- [self
- openNetworkConnectionWithContext:
- context];
- } else {
- NSAssert(
- self->connectionState ==
- ConnectionStateDisconnected,
- @"Expected connection state "
- @"disconnected, but got %d",
- self->connectionState);
- FFLog(@"I-RDB034012",
- @"Not opening connection after "
- @"token refresh, because "
- @"connection was set to "
- @"disconnected.");
- }
- }
- } else {
- FFLog(@"I-RDB034013",
- @"Ignoring fetch token result, because "
- @"this was not the latest attempt.");
- }
- }];
- }];
- }
- }
- - (void)openNetworkConnectionWithContext:
- (FIRDatabaseConnectionContext *)context {
- NSAssert(self->connectionState == ConnectionStateGettingToken,
- @"Trying to open network connection while in wrong state: %d",
- self->connectionState);
- // TODO: Save entire context?
- self.authToken = context.authToken;
- self->connectionState = ConnectionStateConnecting;
- self.realtime = [[FConnection alloc] initWith:self.repoInfo
- andDispatchQueue:self.dispatchQueue
- googleAppID:self.config.googleAppID
- lastSessionID:self.lastSessionID
- appCheckToken:context.appCheckToken];
- self.realtime.delegate = self;
- [self.realtime open];
- }
- - (void)sendAuthAndRestoreStateAfterComplete:(BOOL)restoreStateAfterComplete {
- NSAssert([self connected], @"Must be connected to send auth");
- NSAssert(self.authToken != nil,
- @"Can't send auth if there is no credential");
- NSDictionary *requestData = @{kFWPRequestCredential : self.authToken};
- [self sendAction:kFWPRequestActionAuth
- body:requestData
- sensitive:YES
- callback:^(NSDictionary *data) {
- self->connectionState = ConnectionStateConnected;
- NSString *status =
- [data objectForKey:kFWPResponseForActionStatus];
- id responseData = [data objectForKey:kFWPResponseForActionData];
- if (responseData == nil) {
- responseData = @"error";
- }
- BOOL statusOk =
- [status isEqualToString:kFWPResponseForActionStatusOk];
- if (statusOk) {
- if (restoreStateAfterComplete) {
- [self restoreState];
- }
- } else {
- self.authToken = nil;
- self.forceTokenRefreshes = YES;
- if ([status isEqualToString:@"expired_token"]) {
- FFLog(@"I-RDB034017", @"Authentication failed: %@ (%@)",
- status, responseData);
- } else {
- FFWarn(@"I-RDB034018", @"Authentication failed: %@ (%@)",
- status, responseData);
- }
- [self.realtime close];
- }
- }];
- }
- - (void)sendUnauth {
- [self sendAction:kFWPRequestActionUnauth
- body:@{}
- sensitive:NO
- callback:nil];
- }
- - (void)onAuthRevokedWithStatus:(NSString *)status
- andReason:(NSString *)reason {
- // This might be for an earlier token than we just recently sent. But since
- // we need to close the connection anyways, we can set it to null here and
- // we will refresh the token later on reconnect
- if ([status isEqualToString:@"expired_token"]) {
- FFLog(@"I-RDB034019", @"Auth token revoked: %@ (%@)", status, reason);
- } else {
- FFWarn(@"I-RDB034020", @"Auth token revoked: %@ (%@)", status, reason);
- }
- self.authToken = nil;
- self.forceTokenRefreshes = YES;
- // Try reconnecting on auth revocation
- [self.realtime close];
- }
- - (void)onListenRevoked:(FPath *)path {
- NSArray *queries = [self removeAllListensAtPath:path];
- for (FOutstandingQuery *query in queries) {
- query.onComplete(@"permission_denied");
- }
- }
- - (void)sendOnDisconnectAction:(NSString *)action
- forPath:(NSString *)pathString
- withData:(id)data
- andCallback:(fbt_void_nsstring_nsstring)callback {
- NSDictionary *request =
- @{kFWPRequestPath : pathString, kFWPRequestData : data};
- FFLog(@"I-RDB034021", @"onDisconnect %@: %@", action, request);
- [self sendAction:action
- body:request
- sensitive:NO
- callback:^(NSDictionary *data) {
- NSString *status =
- [data objectForKey:kFWPResponseForActionStatus];
- NSString *errorReason =
- [data objectForKey:kFWPResponseForActionData];
- callback(status, errorReason);
- }];
- }
- - (void)sendPut:(NSNumber *)index {
- NSAssert([self canSendWrites],
- @"sendPut called when not able to send writes");
- FOutstandingPut *put = self.outstandingPuts[index];
- assert(put != nil);
- fbt_void_nsstring_nsstring onComplete = put.onCompleteBlock;
- // Do not async this block; copying the block insinde sendAction: doesn't
- // happen in time (or something) so coredumps
- put.sent = YES;
- [self sendAction:put.action
- body:put.request
- sensitive:NO
- callback:^(NSDictionary *data) {
- FOutstandingPut *currentPut = self.outstandingPuts[index];
- if (currentPut == put) {
- [self.outstandingPuts removeObjectForKey:index];
- if (onComplete != nil) {
- NSString *status =
- [data objectForKey:kFWPResponseForActionStatus];
- NSString *errorReason =
- [data objectForKey:kFWPResponseForActionData];
- if (self.unackedListensCount == 0) {
- onComplete(status, errorReason);
- } else {
- FTupleCallbackStatus *putToAck =
- [[FTupleCallbackStatus alloc] init];
- putToAck.block = onComplete;
- putToAck.status = status;
- putToAck.errorReason = errorReason;
- [self.putsToAck addObject:putToAck];
- }
- }
- } else {
- FFLog(@"I-RDB034022",
- @"Ignoring on complete for put %@ because it was "
- @"already removed",
- index);
- }
- }];
- }
- - (void)sendGet:(NSNumber *)index {
- NSAssert([self canSendReads],
- @"sendGet called when not able to send reads");
- FOutstandingGet *get = self.outstandingGets[index];
- NSAssert(get != nil, @"sendGet found no outstanding get at index %@",
- index);
- if ([get sent]) {
- return;
- }
- get.sent = YES;
- [self sendAction:kFWPRequestActionGet
- body:get.request
- sensitive:NO
- callback:^(NSDictionary *data) {
- FOutstandingGet *currentGet = self.outstandingGets[index];
- if (currentGet == get) {
- [self.outstandingGets removeObjectForKey:index];
- NSString *status =
- [data objectForKey:kFWPResponseForActionStatus];
- id resultData = [data objectForKey:kFWPResponseForActionData];
- if (resultData == (id)[NSNull null]) {
- resultData = nil;
- }
- if ([status isEqualToString:kFWPResponseForActionStatusOk]) {
- get.onCompleteBlock(status, resultData, nil);
- return;
- }
- get.onCompleteBlock(status, nil, resultData);
- } else {
- FFLog(@"I-RDB034045",
- @"Ignoring on complete for get %@ because it was "
- @"already removed",
- index);
- }
- }];
- }
- - (void)sendUnlisten:(FPath *)path
- queryParams:(FQueryParams *)queryParams
- tagId:(NSNumber *)tagId {
- FFLog(@"I-RDB034023", @"Unlisten on %@ for %@", path, queryParams);
- NSMutableDictionary *request = [NSMutableDictionary
- dictionaryWithObjectsAndKeys:[path toString], kFWPRequestPath, nil];
- if (tagId != nil) {
- [request setObject:queryParams.wireProtocolParams
- forKey:kFWPRequestQueries];
- [request setObject:tagId forKey:kFWPRequestTag];
- }
- [self sendAction:kFWPRequestActionTaggedUnlisten
- body:request
- sensitive:NO
- callback:nil];
- }
- - (void)putInternal:(id)data
- forAction:(NSString *)action
- forPath:(NSString *)pathString
- withHash:(NSString *)hash
- withCallback:(fbt_void_nsstring_nsstring)onComplete {
- NSMutableDictionary *request = [NSMutableDictionary
- dictionaryWithObjectsAndKeys:pathString, kFWPRequestPath, data,
- kFWPRequestData, nil];
- if (hash) {
- [request setObject:hash forKey:kFWPRequestHash];
- }
- FOutstandingPut *put = [[FOutstandingPut alloc] init];
- put.action = action;
- put.request = request;
- put.onCompleteBlock = onComplete;
- put.sent = NO;
- NSNumber *index = [self.putCounter getAndIncrement];
- self.outstandingPuts[index] = put;
- if ([self canSendWrites]) {
- FFLog(@"I-RDB034024", @"Was connected, and added as index: %@", index);
- [self sendPut:index];
- } else {
- FFLog(@"I-RDB034025",
- @"Wasn't connected or writes paused, so added to outstanding "
- @"puts only. Path: %@",
- pathString);
- }
- }
- - (void)getDataAtPath:(NSString *)pathString
- withParams:(NSDictionary *)queryWireProtocolParams
- withCallback:(fbt_void_nsstring_id_nsstring)onComplete {
- NSMutableDictionary *request = [NSMutableDictionary
- dictionaryWithObjectsAndKeys:pathString, kFWPRequestPath,
- queryWireProtocolParams,
- kFWPRequestQueries, nil];
- FOutstandingGet *get = [[FOutstandingGet alloc] init];
- get.request = request;
- get.onCompleteBlock = onComplete;
- get.sent = NO;
- NSNumber *index = [self.getCounter getAndIncrement];
- self.outstandingGets[index] = get;
- if (![self connected]) {
- dispatch_after(
- dispatch_time(DISPATCH_TIME_NOW,
- kPersistentConnectionGetConnectTimeout),
- self.dispatchQueue, ^{
- FOutstandingGet *currGet = self.outstandingGets[index];
- if ([currGet sent] || currGet == nil) {
- return;
- }
- FFLog(@"I-RDB034045",
- @"get %@ timed out waiting for a connection", index);
- currGet.sent = YES;
- currGet.onCompleteBlock(kFWPResponseForActionStatusFailed, nil,
- kPersistentConnectionOffline);
- [self.outstandingGets removeObjectForKey:index];
- });
- return;
- }
- if ([self canSendReads]) {
- FFLog(@"I-RDB034024", @"Sending get: %@", index);
- [self sendGet:index];
- }
- }
- - (void)sendListen:(FOutstandingQuery *)listenSpec {
- FQuerySpec *query = listenSpec.query;
- FFLog(@"I-RDB034026", @"Listen for %@", query);
- NSMutableDictionary *request =
- [NSMutableDictionary dictionaryWithObject:[query.path toString]
- forKey:kFWPRequestPath];
- // Only bother to send query if it's non-default
- if (listenSpec.tagId != nil) {
- [request setObject:[query.params wireProtocolParams]
- forKey:kFWPRequestQueries];
- [request setObject:listenSpec.tagId forKey:kFWPRequestTag];
- }
- [request setObject:[listenSpec.syncTreeHash simpleHash]
- forKey:kFWPRequestHash];
- if ([listenSpec.syncTreeHash includeCompoundHash]) {
- FCompoundHash *compoundHash = [listenSpec.syncTreeHash compoundHash];
- NSMutableArray *posts = [NSMutableArray array];
- for (FPath *path in compoundHash.posts) {
- [posts addObject:path.wireFormat];
- }
- request[kFWPRequestCompoundHash] = @{
- kFWPRequestCompoundHashHashes : compoundHash.hashes,
- kFWPRequestCompoundHashPaths : posts
- };
- }
- fbt_void_nsdictionary onResponse = ^(NSDictionary *response) {
- FFLog(@"I-RDB034027", @"Listen response %@", response);
- // warn in any case, even if the listener was removed
- [self warnOnListenWarningsForQuery:query
- payload:response[kFWPResponseForActionData]];
- FOutstandingQuery *currentListenSpec = self.listens[query];
- // only trigger actions if the listen hasn't been removed (and maybe
- // readded)
- if (currentListenSpec == listenSpec) {
- NSString *status = [response objectForKey:kFWPRequestStatus];
- if (![status isEqualToString:@"ok"]) {
- [self removeListen:query];
- }
- if (listenSpec.onComplete) {
- listenSpec.onComplete(status);
- }
- }
- self.unackedListensCount--;
- NSAssert(self.unackedListensCount >= 0,
- @"unackedListensCount decremented to be negative.");
- if (self.unackedListensCount == 0) {
- [self ackPuts];
- }
- };
- [self sendAction:kFWPRequestActionTaggedListen
- body:request
- sensitive:NO
- callback:onResponse];
- self.unackedListensCount++;
- }
- - (void)warnOnListenWarningsForQuery:(FQuerySpec *)query payload:(id)payload {
- if (payload != nil && [payload isKindOfClass:[NSDictionary class]]) {
- NSDictionary *payloadDict = payload;
- id warnings = payloadDict[kFWPResponseDataWarnings];
- if (warnings != nil && [warnings isKindOfClass:[NSArray class]]) {
- NSArray *warningsArr = warnings;
- if ([warningsArr containsObject:@"no_index"]) {
- NSString *indexSpec = [NSString
- stringWithFormat:@"\".indexOn\": \"%@\"",
- [query.params.index queryDefinition]];
- NSString *indexPath = [query.path description];
- FFWarn(@"I-RDB034028",
- @"Using an unspecified index. Your data will be "
- @"downloaded and filtered on the client. "
- "Consider adding %@ at %@ to your security rules for "
- "better performance",
- indexSpec, indexPath);
- }
- }
- }
- }
- - (int)getNextRequestNumber {
- return [[self.requestNumber getAndIncrement] intValue];
- }
- - (void)sendAction:(NSString *)action
- body:(NSDictionary *)message
- sensitive:(BOOL)sensitive
- callback:(void (^)(NSDictionary *data))onMessage {
- // Hold onto the onMessage callback for this request before firing it off
- NSNumber *rn = [NSNumber numberWithInt:[self getNextRequestNumber]];
- NSDictionary *msg = [NSDictionary
- dictionaryWithObjectsAndKeys:rn, kFWPRequestNumber, action,
- kFWPRequestAction, message,
- kFWPRequestPayloadBody, nil];
- [self.realtime sendRequest:msg sensitive:sensitive];
- if (onMessage) {
- // Debug message without a callback; bump the rn, but don't hold onto
- // the cb
- [self.requestCBHash setObject:[onMessage copy] forKey:rn];
- }
- }
- - (void)cancelSentTransactions {
- NSMutableDictionary<NSNumber *, FOutstandingPut *>
- *cancelledOutstandingPuts = [[NSMutableDictionary alloc] init];
- for (NSNumber *index in self.outstandingPuts) {
- FOutstandingPut *put = self.outstandingPuts[index];
- if (put.request[kFWPRequestHash] && put.sent) {
- // This is a sent transaction put.
- cancelledOutstandingPuts[index] = put;
- }
- }
- [cancelledOutstandingPuts
- enumerateKeysAndObjectsUsingBlock:^(
- NSNumber *index, FOutstandingPut *outstandingPut, BOOL *stop) {
- // `onCompleteBlock:` may invoke `rerunTransactionsForPath:` and
- // enqueue new writes. We defer calling it until we have finished
- // enumerating all existing writes.
- outstandingPut.onCompleteBlock(
- kFTransactionDisconnect,
- @"Client was disconnected while running a transaction");
- [self.outstandingPuts removeObjectForKey:index];
- }];
- }
- - (void)onDataPushWithAction:(NSString *)action andBody:(NSDictionary *)body {
- FFLog(@"I-RDB034029", @"handleServerMessage: %@, %@", action, body);
- id<FPersistentConnectionDelegate> delegate = self.delegate;
- if ([action isEqualToString:kFWPAsyncServerDataUpdate] ||
- [action isEqualToString:kFWPAsyncServerDataMerge]) {
- BOOL isMerge = [action isEqualToString:kFWPAsyncServerDataMerge];
- if ([body objectForKey:kFWPAsyncServerDataUpdateBodyPath] &&
- [body objectForKey:kFWPAsyncServerDataUpdateBodyData]) {
- NSString *path =
- [body objectForKey:kFWPAsyncServerDataUpdateBodyPath];
- id payloadData =
- [body objectForKey:kFWPAsyncServerDataUpdateBodyData];
- if (isMerge && [payloadData isKindOfClass:[NSDictionary class]] &&
- [payloadData count] == 0) {
- // ignore empty merge
- } else {
- [delegate
- onDataUpdate:self
- forPath:path
- message:payloadData
- isMerge:isMerge
- tagId:[body objectForKey:
- kFWPAsyncServerDataUpdateBodyTag]];
- }
- } else {
- FFLog(
- @"I-RDB034030",
- @"Malformed data response from server missing path or data: %@",
- body);
- }
- } else if ([action isEqualToString:kFWPAsyncServerDataRangeMerge]) {
- NSString *path = body[kFWPAsyncServerDataUpdateBodyPath];
- NSArray *ranges = body[kFWPAsyncServerDataUpdateBodyData];
- NSNumber *tag = body[kFWPAsyncServerDataUpdateBodyTag];
- NSMutableArray *rangeMerges = [NSMutableArray array];
- for (NSDictionary *range in ranges) {
- NSString *startString = range[kFWPAsyncServerDataUpdateStartPath];
- NSString *endString = range[kFWPAsyncServerDataUpdateEndPath];
- id updateData = range[kFWPAsyncServerDataUpdateRangeMerge];
- id<FNode> updates = [FSnapshotUtilities nodeFrom:updateData];
- FPath *start = (startString != nil)
- ? [[FPath alloc] initWith:startString]
- : nil;
- FPath *end =
- (endString != nil) ? [[FPath alloc] initWith:endString] : nil;
- FRangeMerge *merge = [[FRangeMerge alloc] initWithStart:start
- end:end
- updates:updates];
- [rangeMerges addObject:merge];
- }
- [delegate onRangeMerge:rangeMerges forPath:path tagId:tag];
- } else if ([action isEqualToString:kFWPAsyncServerAuthRevoked]) {
- NSString *status = [body objectForKey:kFWPResponseForActionStatus];
- NSString *reason = [body objectForKey:kFWPResponseForActionData];
- [self onAuthRevokedWithStatus:status andReason:reason];
- } else if ([action isEqualToString:kFWPASyncServerListenCancelled]) {
- NSString *pathString =
- [body objectForKey:kFWPAsyncServerDataUpdateBodyPath];
- [self onListenRevoked:[[FPath alloc] initWith:pathString]];
- } else if ([action isEqualToString:kFWPAsyncServerSecurityDebug]) {
- NSString *msg = [body objectForKey:@"msg"];
- if (msg != nil) {
- NSArray *msgs = [msg componentsSeparatedByString:@"\n"];
- for (NSString *m in msgs) {
- FFWarn(@"I-RDB034031", @"%@", m);
- }
- }
- } else {
- // TODO: revoke listens, auth, security debug
- FFLog(@"I-RDB034032", @"Unsupported action from server: %@", action);
- }
- }
- - (void)restoreAuth {
- FFLog(@"I-RDB034033", @"Calling restore state");
- NSAssert(self->connectionState == ConnectionStateConnecting,
- @"Wanted to restore auth, but was in wrong state: %d",
- self->connectionState);
- if (self.authToken == nil) {
- FFLog(@"I-RDB034034", @"Not restoring auth because token is nil");
- self->connectionState = ConnectionStateConnected;
- [self restoreState];
- } else {
- FFLog(@"I-RDB034035", @"Restoring auth");
- self->connectionState = ConnectionStateAuthenticating;
- [self sendAuthAndRestoreStateAfterComplete:YES];
- }
- }
- - (void)restoreState {
- NSAssert(self->connectionState == ConnectionStateConnected,
- @"Should be connected if we're restoring state, but we are: %d",
- self->connectionState);
- [self.listens enumerateKeysAndObjectsUsingBlock:^(
- FQuerySpec *query, FOutstandingQuery *outstandingListen,
- BOOL *stop) {
- FFLog(@"I-RDB034036", @"Restoring listen for %@", query);
- [self sendListen:outstandingListen];
- }];
- NSArray *putKeys = [[self.outstandingPuts allKeys]
- sortedArrayUsingSelector:@selector(compare:)];
- for (int i = 0; i < [putKeys count]; i++) {
- if ([self.outstandingPuts objectForKey:[putKeys objectAtIndex:i]] !=
- nil) {
- FFLog(@"I-RDB034037", @"Restoring put: %d", i);
- [self sendPut:[putKeys objectAtIndex:i]];
- } else {
- FFLog(@"I-RDB034038", @"Restoring put: skipped nil: %d", i);
- }
- }
- NSArray *getKeys = [[self.outstandingGets allKeys]
- sortedArrayUsingSelector:@selector(compare:)];
- for (int i = 0; i < [getKeys count]; i++) {
- if ([self.outstandingGets objectForKey:[getKeys objectAtIndex:i]] !=
- nil) {
- FFLog(@"I-RDB034037", @"Restoring get: %d", i);
- [self sendGet:[getKeys objectAtIndex:i]];
- } else {
- FFLog(@"I-RDB034038", @"Restoring get: skipped nil: %d", i);
- }
- }
- for (FTupleOnDisconnect *tuple in self.onDisconnectQueue) {
- [self sendOnDisconnectAction:tuple.action
- forPath:tuple.pathString
- withData:tuple.data
- andCallback:tuple.onComplete];
- }
- [self.onDisconnectQueue removeAllObjects];
- }
- - (NSArray *)removeListen:(FQuerySpec *)query {
- NSAssert(query.isDefault || !query.loadsAllData,
- @"removeListen called for non-default but complete query");
- FOutstandingQuery *outstanding = self.listens[query];
- if (!outstanding) {
- FFLog(@"I-RDB034039",
- @"Trying to remove listener for query %@ but no listener exists",
- query);
- return @[];
- } else {
- [self.listens removeObjectForKey:query];
- return @[ outstanding ];
- }
- }
- - (NSArray *)removeAllListensAtPath:(FPath *)path {
- FFLog(@"I-RDB034040", @"Removing all listens at path %@", path);
- NSMutableArray *removed = [NSMutableArray array];
- NSMutableArray *toRemove = [NSMutableArray array];
- [self.listens
- enumerateKeysAndObjectsUsingBlock:^(
- FQuerySpec *spec, FOutstandingQuery *outstanding, BOOL *stop) {
- if ([spec.path isEqual:path]) {
- [removed addObject:outstanding];
- [toRemove addObject:spec];
- }
- }];
- [self.listens removeObjectsForKeys:toRemove];
- return removed;
- }
- - (void)purgeOutstandingWrites {
- // We might have unacked puts in our queue that we need to ack now before we
- // send out any cancels...
- [self ackPuts];
- // Cancel in order
- NSArray *keys = [[self.outstandingPuts allKeys]
- sortedArrayUsingSelector:@selector(compare:)];
- for (NSNumber *key in keys) {
- FOutstandingPut *put = self.outstandingPuts[key];
- if (put.onCompleteBlock != nil) {
- put.onCompleteBlock(kFErrorWriteCanceled, nil);
- }
- }
- for (FTupleOnDisconnect *onDisconnect in self.onDisconnectQueue) {
- if (onDisconnect.onComplete != nil) {
- onDisconnect.onComplete(kFErrorWriteCanceled, nil);
- }
- }
- [self.outstandingPuts removeAllObjects];
- [self.onDisconnectQueue removeAllObjects];
- }
- - (void)ackPuts {
- for (FTupleCallbackStatus *put in self.putsToAck) {
- put.block(put.status, put.errorReason);
- }
- [self.putsToAck removeAllObjects];
- }
- - (void)handleTimestamp:(NSNumber *)timestamp {
- FFLog(@"I-RDB034041", @"Handling timestamp: %@", timestamp);
- double timestampDeltaMs = [timestamp doubleValue] -
- ([[NSDate date] timeIntervalSince1970] * 1000);
- [self.delegate onServerInfoUpdate:self
- updates:@{
- kDotInfoServerTimeOffset : [NSNumber
- numberWithDouble:timestampDeltaMs]
- }];
- }
- - (void)sendStats:(NSDictionary *)stats {
- if ([stats count] > 0) {
- NSDictionary *request = @{kFWPRequestCounters : stats};
- [self sendAction:kFWPRequestActionStats
- body:request
- sensitive:NO
- callback:^(NSDictionary *data) {
- NSString *status =
- [data objectForKey:kFWPResponseForActionStatus];
- NSString *errorReason =
- [data objectForKey:kFWPResponseForActionData];
- BOOL statusOk =
- [status isEqualToString:kFWPResponseForActionStatusOk];
- if (!statusOk) {
- FFLog(@"I-RDB034042", @"Failed to send stats: %@",
- errorReason);
- }
- }];
- } else {
- FFLog(@"I-RDB034043", @"Not sending stats because stats are empty");
- }
- }
- - (void)sendConnectStats {
- NSMutableDictionary *stats = [NSMutableDictionary dictionary];
- #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_VISION
- if (self.config.persistenceEnabled) {
- stats[@"persistence.ios.enabled"] = @1;
- }
- #elif TARGET_OS_OSX
- if (self.config.persistenceEnabled) {
- stats[@"persistence.osx.enabled"] = @1;
- }
- #elif TARGET_OS_WATCH
- if (self.config.persistenceEnabled) {
- stats[@"persistence.watchos.enabled"] = @1;
- }
- #endif
- NSString *sdkVersion =
- [[FIRDatabase sdkVersion] stringByReplacingOccurrencesOfString:@"."
- withString:@"-"];
- NSString *sdkStatName =
- [NSString stringWithFormat:@"sdk.objc.%@", sdkVersion];
- stats[sdkStatName] = @1;
- FFLog(@"I-RDB034044", @"Sending first connection stats");
- [self sendStats:stats];
- }
- - (NSDictionary *)dumpListens {
- return self.listens;
- }
- #pragma mark - App Check Token update
- // TODO: Add tests!
- - (void)refreshAppCheckToken:(NSString *)token {
- if (![self connected]) {
- // A fresh FAC token will be sent as a part of initial handshake.
- return;
- }
- if (token.length == 0) {
- // No token to send.
- return;
- }
- // Send updated FAC token to the open connection.
- [self sendAppCheckToken:token];
- }
- - (void)sendAppCheckToken:(NSString *)token {
- NSDictionary *requestData = @{kFWPRequestAppCheckToken : token};
- [self sendAction:kFWPRequestActionAppCheck
- body:requestData
- sensitive:YES
- callback:^(NSDictionary *data) {
- NSString *status =
- [data objectForKey:kFWPResponseForActionStatus];
- id responseData = [data objectForKey:kFWPResponseForActionData];
- if (responseData == nil) {
- responseData = @"Response data was empty.";
- }
- BOOL statusOk =
- [status isEqualToString:kFWPResponseForActionStatusOk];
- if (!statusOk) {
- self.authToken = nil;
- self.forceTokenRefreshes = YES;
- if ([status isEqualToString:@"invalid_token"]) {
- FFLog(@"I-RDB034045", @"App check failed: %@ (%@)",
- status, responseData);
- } else {
- FFWarn(@"I-RDB034046", @"App check failed: %@ (%@)",
- status, responseData);
- }
- [self.realtime close];
- }
- }];
- }
- @end
|