Files
firebase-ios-sdk/FirebaseDatabase/Sources/Core/FPersistentConnection.m
T
47e0a982fb App check and storage, functions and RTDB support (#7928)
* AppAttestation initial public API

* Run ./scripts/style.sh

* Copyright

* Cleanup

* Cleanup

* Get token forcing refresh method

* Formatting

* Forcing refresh samples

* Interop introduced

* Code samples for Interop

* Run  ./scripts/style.sh

* Cleanup

* TODOs and Copirights

* Fix build

* Supported iOS versions

* Remove unnecessary bridging header

* Run  ./scripts/style.sh

* [WIP] DeviceCheckAttestationProvider as a subspec

* cleanup

* Add memory attributes to readonly properties

* Move FIRDeviceCheckAttestationProvider.h to private headers

* TODO for `FirebaseAppAttestation/Core` name

* Remove memory attributes from FIRAppAttestationToken properties

* FIRAppAttestationTests.testSetAttestationProviderFactory introduced

* FIRAppAttestationToken initializer

* Basic FIRLibrary implementation and FIRAppAttestationProviderFactory ingestion.

* Fix

* FIRAppAttestationToken+Interop.h

* TODOs

* Tests: reset FIRApps

* GHA for App Attestation

* Run ./scripts/style.sh

* Style fixes.

* Run ./scripts/style.sh

* TODO

* Nullable initializer and type annpotations

* TODOs

* TODOs

* TODO

* Fix spec and allow warnings

* AppAttestation initial public API

* Run ./scripts/style.sh

* Copyright

* Cleanup

* Cleanup

* Get token forcing refresh method

* Formatting

* Forcing refresh samples

* Interop introduced

* Code samples for Interop

* Run  ./scripts/style.sh

* Cleanup

* TODOs and Copirights

* Fix build

* Supported iOS versions

* Remove unnecessary bridging header

* Run  ./scripts/style.sh

* [WIP] DeviceCheckAttestationProvider as a subspec

* cleanup

* Add memory attributes to readonly properties

* Move FIRDeviceCheckAttestationProvider.h to private headers

* TODO for `FirebaseAppAttestation/Core` name

* Remove memory attributes from FIRAppAttestationToken properties

* FIRAppAttestationTests.testSetAttestationProviderFactory introduced

* FIRAppAttestationToken initializer

* Basic FIRLibrary implementation and FIRAppAttestationProviderFactory ingestion.

* Fix

* FIRAppAttestationToken+Interop.h

* TODOs

* Tests: reset FIRApps

* Run ./scripts/style.sh

* Style fixes.

* Run ./scripts/style.sh

* TODO

* Nullable initializer and type annpotations

* TODOs

* TODOs

* TODO

* Revert FirestoreDecoder.swift formatting.

* Basic implementation of FIRDeviceCheckAttestationProvider and tests (#626)

* DeviceCheck attestation provider sceleton

* DeviceCheck attestation provider sceleton

* Basic FIRDeviceCheckAttestationProviderTests

* Run ./scripts/style.sh

* FIRAppAttestStorage implementation and tests (#627)

* FIRDeviceCheckAttestationProvider designated init

* FIRAppAttestStorage API and basic tests.

* FIRAppAttestStoredToken: NSSecureCoding implementation

* WIP Storage

* Add `accessGroup` param to `FIRAppAttestStorage`

* FIRAppAttestStorage implementation

* Use constants

* FIRAppAttestStorage API doc

* Coding style and typos.

* Code formatting

* Attestation Token caching (#630)

* Storage instance and looging

* AppAttestation caching

* Tests and cleanup

* Cleanup

* Rename App Attestation -> App Check (#631)

* Rename App Attestation -> App Check

* Run ./scripts/style.sh

* Update GHA

* Default Custom Provider (#633)

* AppCheck: remove not unnecessary public API (#634)

* AppCheck: remove not unnecessary public API

* Run ./scripts/style.sh

* AppCheck: DeviceCheck token server API (#635)

* Generic HTTP request handling

* [draft] AppCheck: device check HTTP API and simple tests

* Parse response

* Cleanup

* AppCheck: API errors and tests (#636)

* AppCheck errors

* API service tests and fixes

* Cleanup

* Run ./scripts/style.sh

* Naming

* AppCheck: Register device check provider factory as a default (#637)

* AppCheck errors

* API service tests and fixes

* Cleanup

* Run ./scripts/style.sh

* AppCheck: register FIRDeviceCheckProvider as a component

* Naming

* Registre device check provider factory as a default

* FIRDeviceCheckProvider tests

* AppCheck: API communication common for all providers moved to FIRAppCheckAPIService (#640)

* FIRAppCheckAPIService introduced

* Move URL seession stub to FIRURLSessionOCMockStub

* Run ./scripts/style.sh

* Move approximate date comparing to FIRDateTestUtils

* compose request in FIRAppCheckAPIService

* FIRAppCheckAPIServiceTests

* Use FIRAppCheckAPIService in FIRDeviceCheckProvider

* Cleanup

* DeviceCheck mock server integration and tests (#686)

* DeviceCheck mock server integration and tests

* TODO

* Update FIROptions.h import

* Temporary add FirebaseAppCheck to skip import validation

* TestUtilities moved to SharedTestUtilities

* FirebaseAppCheck.podspec:  TestUtilities->SharedTestUtilities

* SwiftPM: add OCMock dependency to SharedTestUtilities

* FIRURLSessionOCMockStub: #import "OCMock.h"

* App Check: Firebase 7 fixes (#715)

* AppCheck Firebase 7

* FirebaseCore repo-relative imports

* Fix FIRAppCheckStorage.m compilation

* Repo relative imports

* linebreak

* AppCheck: debug FAC token provider (#716)

* AppCheck Firebase 7

* FirebaseCore repo-relative imports

* Fix FIRAppCheckStorage.m compilation

* Repo relative imports

* linebreak

* Remove FIRAppCheckDefaultCustomProvider

* FIRAppCheckDebugProvider introduced

* FIRAppCheckDebugProviderTests

* style

* Print locally generated debug token to console

* Fix imports

* mullability and line breaks

* typo

* Comments

* TODO

* AppCheck: merge into single spec (package) (#717)

* Standard package folder structure

* Move interop header into AppCheck sources folder

* Combine public headers in the standard dir

* Private headers to internal

* Podspec

* Headers import udpdate

* style

* Fix header imports

* Enable check_imports.swift and fix imports

* AppCheck: server request adjustments (#718)

* Wrap DeviceCheck token into JSON

* AppChek - remove static_framework requirement

* WIP

* Update default base URL

* Set content-type header

* Check for empty response data

* Fix tests

* Style and formatting

* Podspec - revert wrong change and remove static_framework

* Assign error to error pointer safely.

* AppCheck: primitive test app (#719)

* Remove static_framework requirement

* WIP: FIRAppCheckTestApp introduced

* Delete .plist

* Copyright

* Remove empty test targets

* pod deintegrate

* Remove test targets from Podfile

* formatting

* Storage: integration with AppCheck (#720)

* Storage: add AppCheck interop dependency

* Inject AppCheck into FIRStorageTokenAuthorizer

* initial AppCheck integration

* Introduce AppCheck fake

* AppCheck fake implementation

* FIRStorageTokenAuthorizer tests and fixes

* @"Authorization" header constant

* Log AppCheck error.

* Cleanup

* FIRStorageTokenAuthorizerTests: helpers

* TODO

* Cleanup

* AppCheck: separate 2P and 3P API (#724)

* FIRAppCheckInterop: remove a convenience method.

* Rename: FIRAppCheckTokenInterop->FIRAppCheckTokenResultInterop

* FIRAppCheckTokenResult introduced

* Update FIRAppCheckTokenHandlerInterop,  FIRAppCheckTokenResultInterop and tests

* style

* Update token result

* Update storage integration

* Adjust check_imports.swift for test files

* Don't use internal AppCheck classes in Storage tests

* style

* Rename token to tokenResult in 2P API

* Add private Core headers to app check sources

* Fix storage log message code format

* token clarification comments in API docs

* Rename token->tokenResult

* AppCheck cleanup (#737)

* Fix public headers import

* Cleanup imported test utils

* FirebaseAppCheck podspec: revert git URL

* AppCheck: Debug token to AppCheck token exchange API (#739)

* GUL: make NSURLSession promise extension public

* Use NSURLSession+GULPromises to send requests

* style

* Move FIRAppCheckToken+APIResponse to Core dir

* rename

* FIRAppCheckDebugProviderAPIService introduced

* Move async token parsing API to FIRAppCheckToken extension

* Move token exchange response handling to FIRAppCheckAPIService. Tests WIP.

* Move API response parsing tests to FIRAppCheckAPIServiceTests

* FIRAppCheckDebugProviderAPIServiceTests

* Cleanup

* style

* App Check debug provider: integrate with exchange API (#743)

* Move FIROption validation to FIRAppCheckValidator

* FIRAppCheckDebugProvider token exchange and tests

* Fix FIRAppCheckDebugProviderFactoryTests

* style

* App Check test app debug provider fix (#747)

* App Check: minor touchups (#750)

* Update dummy token value

* Print local debug token to logs

* Require GoogleUtilities v7.2 and above

* Print debug token on init

* Don't print debug token again

* App Check: use prod environment (#751)

* App Check: use prod backend by default.

* Update token expiration threshold

* App Check SwiftPM support (#753)

* AppCheck SwiftPM package definition

* Promise header import fix

* OCMock header fix

* Fix fixture dependent tests

* Exclude Keychain dependent tests

* License

* ./scripts/style.sh

* Cleanup

* Format with proper SwiftFormat version

* `.process` resources.

* Swift tests target

* Cleanup and code formatting

* App Check: token auto-refresh (#754)

* FIRAppCheckTokenRefresher API defined

* FIRAppCheckTokenRefresher implementation draft

* [WIP] Token refresher integration

* Token refresher integration

* FIRAppCheckTests: token refresher tests

* FIRAppCheckTests: additional tests cases

* FIRAppCheckTimer introduced

* FIRAppCheckTokenRefresher: use FIRAppCheckTimer instead of the dispatch timer.

* FIRFakeTimer

* FIRAppCheckTokenRefresherTests testInitialRefresh

* FIRAppCheckTokenRefresherTests: testNextRefreshOnRefreshSuccess

* ./scripts/style.sh

* Exponential backoff

* Style and comments

* Move token refresh files to a separate folder

* FIRAppCheckTimerTests

* FIRAppCheck: use expicit class in init

* FIRAppCheckDebugProviderFactory Swift name

* FIRAppCheckTokenRefresher: Increment/decrement directly

* App Check fixes (#755)

* Fix backoff: no backoff for the initial request

* Use eager initialization

* FIRAppCheckTokenRefresher: don't refresh until handler set

* FIRAppCheckIntegrationTests: disable token refresher

* Fix testInitialRefresh test

* style

* FIRAppCheckIntegrationTests fix

* Temporary exclude App Check from platfrom logging (#756)

* App Check: send app check SDK version only in the header (#757)

* App Check: store FAC token per app ID (#758)

* App Check: store FAC token per app ID

* update podspec

* API docs

* FIRAppCheck initWithApp tests

* AppCheckCustomProvideApp (#760)

* Functions: App Check integration (#762)

* Functions: app check API added to FUNContextProvider

* FUNContextProviderTests

* FUNContextProvider app check support

* ./scripts/style.sh

* FIRFunctions: pass FAC token as HTTP header

* Fix SPM

* Fix Firebase-Package scheme bad merge

* Cleanup

* RTDB: pass FAC token to web socket (#763)

* RTDB: pass FAC token to web socket

* FIRAppCheckFake default init

* Rename FAuthTokenProvider to FIRDatabaseConnectionContext; integrate with App Check

* Pass App Check token in the HTTP header

* Rename

* Fix existing tests

* TODO

* ./scripts/style.sh

* Context provider: assume separate FAC token change listener

* FIRDatabaseConnectionContextProviderTests

* Remove unused files

* Copy NSMutableURLRequest

* Cleanup

* ./scripts/style.sh

* FIRDatabaseConnectionContextProvider: sync callback when no auth or app check

* Cleanup

* Rename "authToken" leftovers to "context"

* Fix renaming

* Pass missing headers to NSURLSessionWebSocketTask

* Cleanup

* add a name to TODO

* App Check: token update notifications (#764)

* AppCheck: token did change API and tests

* notification implementation and fixes

* Run ./scripts/style.sh

* Update comments

* RTDB: send app check token updates to keep connection open (#765)

* Pass AppCheck instance as an object into the the FAC token update notification

* FIRDatabaseConnectionContext: add FAC token change listener API

* formatting

* Send FAC token updates to open connection

* More informative empty response message

* refreshAppCheckToken fixes

* Remove assertion

* Don't modify state

* forceTokensRefresh -> forceTokenRefreshes

* Call listeners on [FIRDatabaseQuery sharedQueue]

* App Check API cleanup and docs (#766)

* AppCheck public API and docs cleanup

* More API docs

* Fix compilation errors

* typos and wording

* Make summary different from description (pod lib lint warning)

* port app check workflow changes from another branch

* pod lib lint: remove --allow-warnings

* App Check cleanup (#767)

* Cleanup debug code and outdated TODOs

* Fix FIRDeviceCheckProvider availablility for SPM

* Fix availability in tests

* Fix availability in tests

* Make sure os requirements are consistent for tests specs

* Migrate v1alpha URLs to v1beta

* Migrate v1alpha URLs to v1beta

* Run ./scripts/style.sh

* Functions tests: fix Xcode 11 warnings (#7931)

* Functions tests: fix Xcode 11 warnings

* style

* App Check: token auto-refresh opt-out API (#769)

* FIRAppCheckSettings introduced (WIP)

* FIRAppCheckSettingsTests

* Style

* Make FIRAppCheckSettings instance per-app.

* FIRAppCheckTokenRefresher: use FIRAppCheckSettings.isTokenAutoRefreshEnabled (WIP)

* Tests

* Add public instance getters

* Fix analyzer warnings

* Fix testspec OS versions

* FIRAppCheckTokenRefresher expiration date update; tests

* FIRAppCheck.isTokenAutoRefreshEnabled implementation and tests

* style

* FIRAppCheck: Use specific types for variables in the default init

* More precise comments

* missing symbol

* FIRAppCheckSettings: remove defensive conditions from init.

Co-authored-by: Nick Cooke <nickcooke@google.com>
Co-authored-by: Nick Cooke <36927374+ncooke3@users.noreply.github.com>
2021-04-21 21:01:11 -04:00

1335 lines
51 KiB
Objective-C

/*
* 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/Sources/Private/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 <WatchKit/WatchKit.h>
#else
#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];
[self setupNotifications];
// 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];
}
#if !TARGET_OS_WATCH
static void reachabilityCallback(SCNetworkReachabilityRef ref,
SCNetworkReachabilityFlags flags, void *info) {
if (flags & kSCNetworkReachabilityFlagsReachable) {
FFLog(@"I-RDB034014",
@"Network became reachable. Trigger a connection attempt");
FPersistentConnection *self = (__bridge FPersistentConnection *)info;
// Reset reconnect delay
[self.retryHelper signalSuccess];
if (self->connectionState == ConnectionStateDisconnected) {
[self tryScheduleReconnect];
}
} else {
FFLog(@"I-RDB034015", @"Network is not reachable");
}
}
#endif // !TARGET_OS_WATCH
- (void)enteringForeground {
dispatch_async(self.dispatchQueue, ^{
// Reset reconnect delay
[self.retryHelper signalSuccess];
if (self->connectionState == ConnectionStateDisconnected) {
[self tryScheduleReconnect];
}
});
}
- (void)setupNotifications {
#if TARGET_OS_WATCH
if (@available(watchOS 7.0, *)) {
__weak FPersistentConnection *weakSelf = self;
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserverForName:WKApplicationWillEnterForegroundNotification
object:nil
queue:nil
usingBlock:^(NSNotification *_Nonnull note) {
[weakSelf enteringForeground];
}];
}
#else
NSString *const *foregroundConstant = (NSString *const *)dlsym(
RTLD_DEFAULT, "UIApplicationWillEnterForegroundNotification");
if (foregroundConstant) {
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(enteringForeground)
name:*foregroundConstant
object:nil];
}
// An empty address is interpreted a generic internet access
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
reachability = SCNetworkReachabilityCreateWithAddress(
kCFAllocatorDefault, (const struct sockaddr *)&zeroAddress);
SCNetworkReachabilityContext ctx = {0, (__bridge void *)(self), NULL, NULL,
NULL};
if (SCNetworkReachabilitySetCallback(reachability, reachabilityCallback,
&ctx)) {
SCNetworkReachabilitySetDispatchQueue(reachability, self.dispatchQueue);
} else {
FFLog(@"I-RDB034016",
@"Failed to set up network reachability monitoring");
CFRelease(reachability);
reachability = NULL;
}
#endif // !TARGET_OS_WATCH
}
- (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
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 : self.authToken};
[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