FConnection.m 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FirebaseDatabase/Sources/Realtime/FConnection.h"
  17. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  18. #import "FirebaseDatabase/Sources/Constants/FConstants.h"
  19. typedef enum {
  20. REALTIME_STATE_CONNECTING = 0,
  21. REALTIME_STATE_CONNECTED = 1,
  22. REALTIME_STATE_DISCONNECTED = 2,
  23. } FConnectionState;
  24. @interface FConnection () {
  25. FConnectionState state;
  26. }
  27. @property(nonatomic, strong) FWebSocketConnection *conn;
  28. @property(nonatomic, strong) FRepoInfo *repoInfo;
  29. @end
  30. #pragma mark -
  31. #pragma mark FConnection implementation
  32. @implementation FConnection
  33. @synthesize delegate;
  34. @synthesize conn;
  35. @synthesize repoInfo;
  36. #pragma mark -
  37. #pragma mark Initializers
  38. - (instancetype)initWith:(FRepoInfo *)aRepoInfo
  39. andDispatchQueue:(dispatch_queue_t)queue
  40. googleAppID:(NSString *)googleAppID
  41. lastSessionID:(NSString *)lastSessionID
  42. appCheckToken:(NSString *)appCheckToken {
  43. self = [super init];
  44. if (self) {
  45. state = REALTIME_STATE_CONNECTING;
  46. self.repoInfo = aRepoInfo;
  47. self.conn = [[FWebSocketConnection alloc] initWith:self.repoInfo
  48. andQueue:queue
  49. googleAppID:googleAppID
  50. lastSessionID:lastSessionID
  51. appCheckToken:appCheckToken];
  52. self.conn.delegate = self;
  53. }
  54. return self;
  55. }
  56. #pragma mark -
  57. #pragma mark Public method implementation
  58. - (void)open {
  59. FFLog(@"I-RDB082001", @"Calling open in FConnection");
  60. [self.conn open];
  61. }
  62. - (void)closeWithReason:(FDisconnectReason)reason {
  63. if (state != REALTIME_STATE_DISCONNECTED) {
  64. FFLog(@"I-RDB082002", @"Closing realtime connection.");
  65. state = REALTIME_STATE_DISCONNECTED;
  66. if (self.conn) {
  67. FFLog(@"I-RDB082003", @"Calling close again.");
  68. [self.conn close];
  69. self.conn = nil;
  70. }
  71. [self.delegate onDisconnect:self withReason:reason];
  72. }
  73. }
  74. - (void)close {
  75. [self closeWithReason:DISCONNECT_REASON_OTHER];
  76. }
  77. - (void)sendRequest:(NSDictionary *)dataMsg sensitive:(BOOL)sensitive {
  78. // since this came from the persistent connection, wrap it in a data message
  79. // envelope
  80. NSDictionary *msg = @{
  81. kFWPRequestType : kFWPRequestTypeData,
  82. kFWPRequestDataPayload : dataMsg
  83. };
  84. [self sendData:msg sensitive:sensitive];
  85. }
  86. #pragma mark -
  87. #pragma mark Helpers
  88. - (void)sendData:(NSDictionary *)data sensitive:(BOOL)sensitive {
  89. if (state != REALTIME_STATE_CONNECTED) {
  90. @throw [[NSException alloc]
  91. initWithName:@"InvalidConnectionState"
  92. reason:@"Tried to send data on an unconnected FConnection"
  93. userInfo:nil];
  94. } else {
  95. if (sensitive) {
  96. FFLog(@"I-RDB082004", @"Sending data (contents hidden)");
  97. } else {
  98. FFLog(@"I-RDB082005", @"Sending: %@", data);
  99. }
  100. [self.conn send:data];
  101. }
  102. }
  103. #pragma mark -
  104. #pragma mark FWebSocketConnectinDelegate implementation
  105. // Corresponds to onConnectionLost in JS
  106. - (void)onDisconnect:(FWebSocketConnection *)fwebSocket
  107. wasEverConnected:(BOOL)everConnected {
  108. self.conn = nil;
  109. if (!everConnected && state == REALTIME_STATE_CONNECTING) {
  110. FFLog(@"I-RDB082006", @"Realtime connection failed.");
  111. // Since we failed to connect at all, clear any cached entry for this
  112. // namespace in case the machine went away
  113. [self.repoInfo clearInternalHostCache];
  114. } else if (state == REALTIME_STATE_CONNECTED) {
  115. FFLog(@"I-RDB082007", @"Realtime connection lost.");
  116. }
  117. [self close];
  118. }
  119. // Corresponds to onMessageReceived in JS
  120. - (void)onMessage:(FWebSocketConnection *)fwebSocket
  121. withMessage:(NSDictionary *)message {
  122. NSString *rawMessageType =
  123. [message objectForKey:kFWPAsyncServerEnvelopeType];
  124. if (rawMessageType != nil) {
  125. if ([rawMessageType isEqualToString:kFWPAsyncServerDataMessage]) {
  126. [self onDataMessage:[message
  127. objectForKey:kFWPAsyncServerEnvelopeData]];
  128. } else if ([rawMessageType
  129. isEqualToString:kFWPAsyncServerControlMessage]) {
  130. [self onControl:[message objectForKey:kFWPAsyncServerEnvelopeData]];
  131. } else {
  132. FFLog(@"I-RDB082008", @"Unrecognized server packet type: %@",
  133. rawMessageType);
  134. }
  135. } else {
  136. FFLog(@"I-RDB082009", @"Unrecognized raw server packet received: %@",
  137. message);
  138. }
  139. }
  140. - (void)onDataMessage:(NSDictionary *)message {
  141. // we don't do anything with data messages, just kick them up a level
  142. FFLog(@"I-RDB082010", @"Got data message: %@", message);
  143. [self.delegate onDataMessage:self withMessage:message];
  144. }
  145. - (void)onControl:(NSDictionary *)message {
  146. FFLog(@"I-RDB082011", @"Got control message: %@", message);
  147. NSString *type = [message objectForKey:kFWPAsyncServerControlMessageType];
  148. if ([type isEqualToString:kFWPAsyncServerControlMessageShutdown]) {
  149. NSString *reason =
  150. [message objectForKey:kFWPAsyncServerControlMessageData];
  151. [self onConnectionShutdownWithReason:reason];
  152. } else if ([type isEqualToString:kFWPAsyncServerControlMessageReset]) {
  153. NSString *host =
  154. [message objectForKey:kFWPAsyncServerControlMessageData];
  155. [self onReset:host];
  156. } else if ([type isEqualToString:kFWPAsyncServerHello]) {
  157. NSDictionary *handshakeData =
  158. [message objectForKey:kFWPAsyncServerControlMessageData];
  159. [self onHandshake:handshakeData];
  160. } else {
  161. FFLog(@"I-RDB082012",
  162. @"Unknown control message returned from server: %@", message);
  163. }
  164. }
  165. - (void)onConnectionShutdownWithReason:(NSString *)reason {
  166. FFLog(@"I-RDB082013",
  167. @"Connection shutdown command received. Shutting down...");
  168. [self.delegate onKill:self withReason:reason];
  169. [self close];
  170. }
  171. - (void)onHandshake:(NSDictionary *)handshake {
  172. NSNumber *timestamp =
  173. [handshake objectForKey:kFWPAsyncServerHelloTimestamp];
  174. // NSString* version = [handshake
  175. // objectForKey:kFWPAsyncServerHelloVersion];
  176. NSString *host = [handshake objectForKey:kFWPAsyncServerHelloConnectedHost];
  177. NSString *sessionID = [handshake objectForKey:kFWPAsyncServerHelloSession];
  178. self.repoInfo.internalHost = host;
  179. if (state == REALTIME_STATE_CONNECTING) {
  180. [self.conn start];
  181. [self onConnection:self.conn readyAtTime:timestamp sessionID:sessionID];
  182. }
  183. }
  184. - (void)onConnection:(FWebSocketConnection *)conn
  185. readyAtTime:(NSNumber *)timestamp
  186. sessionID:(NSString *)sessionID {
  187. FFLog(@"I-RDB082014", @"Realtime connection established");
  188. state = REALTIME_STATE_CONNECTED;
  189. [self.delegate onReady:self atTime:timestamp sessionID:sessionID];
  190. }
  191. - (void)onReset:(NSString *)host {
  192. FFLog(
  193. @"I-RDB082015",
  194. @"Got a reset; killing connection to: %@; Updating internalHost to: %@",
  195. repoInfo.internalHost, host);
  196. self.repoInfo.internalHost = host;
  197. // Explicitly close the connection with SERVER_RESET so calling code knows
  198. // to reconnect immediately.
  199. [self closeWithReason:DISCONNECT_REASON_SERVER_RESET];
  200. }
  201. @end