FConnection.m 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. - (id)initWith:(FRepoInfo *)aRepoInfo
  39. andDispatchQueue:(dispatch_queue_t)queue
  40. googleAppID:googleAppID
  41. lastSessionID:(NSString *)lastSessionID {
  42. self = [super init];
  43. if (self) {
  44. state = REALTIME_STATE_CONNECTING;
  45. self.repoInfo = aRepoInfo;
  46. self.conn = [[FWebSocketConnection alloc] initWith:self.repoInfo
  47. andQueue:queue
  48. googleAppID:googleAppID
  49. lastSessionID:lastSessionID];
  50. self.conn.delegate = self;
  51. }
  52. return self;
  53. }
  54. #pragma mark -
  55. #pragma mark Public method implementation
  56. - (void)open {
  57. FFLog(@"I-RDB082001", @"Calling open in FConnection");
  58. [self.conn open];
  59. }
  60. - (void)closeWithReason:(FDisconnectReason)reason {
  61. if (state != REALTIME_STATE_DISCONNECTED) {
  62. FFLog(@"I-RDB082002", @"Closing realtime connection.");
  63. state = REALTIME_STATE_DISCONNECTED;
  64. if (self.conn) {
  65. FFLog(@"I-RDB082003", @"Calling close again.");
  66. [self.conn close];
  67. self.conn = nil;
  68. }
  69. [self.delegate onDisconnect:self withReason:reason];
  70. }
  71. }
  72. - (void)close {
  73. [self closeWithReason:DISCONNECT_REASON_OTHER];
  74. }
  75. - (void)sendRequest:(NSDictionary *)dataMsg sensitive:(BOOL)sensitive {
  76. // since this came from the persistent connection, wrap it in a data message
  77. // envelope
  78. NSDictionary *msg = @{
  79. kFWPRequestType : kFWPRequestTypeData,
  80. kFWPRequestDataPayload : dataMsg
  81. };
  82. [self sendData:msg sensitive:sensitive];
  83. }
  84. #pragma mark -
  85. #pragma mark Helpers
  86. - (void)sendData:(NSDictionary *)data sensitive:(BOOL)sensitive {
  87. if (state != REALTIME_STATE_CONNECTED) {
  88. @throw [[NSException alloc]
  89. initWithName:@"InvalidConnectionState"
  90. reason:@"Tried to send data on an unconnected FConnection"
  91. userInfo:nil];
  92. } else {
  93. if (sensitive) {
  94. FFLog(@"I-RDB082004", @"Sending data (contents hidden)");
  95. } else {
  96. FFLog(@"I-RDB082005", @"Sending: %@", data);
  97. }
  98. [self.conn send:data];
  99. }
  100. }
  101. #pragma mark -
  102. #pragma mark FWebSocketConnectinDelegate implementation
  103. // Corresponds to onConnectionLost in JS
  104. - (void)onDisconnect:(FWebSocketConnection *)fwebSocket
  105. wasEverConnected:(BOOL)everConnected {
  106. self.conn = nil;
  107. if (!everConnected && state == REALTIME_STATE_CONNECTING) {
  108. FFLog(@"I-RDB082006", @"Realtime connection failed.");
  109. // Since we failed to connect at all, clear any cached entry for this
  110. // namespace in case the machine went away
  111. [self.repoInfo clearInternalHostCache];
  112. } else if (state == REALTIME_STATE_CONNECTED) {
  113. FFLog(@"I-RDB082007", @"Realtime connection lost.");
  114. }
  115. [self close];
  116. }
  117. // Corresponds to onMessageReceived in JS
  118. - (void)onMessage:(FWebSocketConnection *)fwebSocket
  119. withMessage:(NSDictionary *)message {
  120. NSString *rawMessageType =
  121. [message objectForKey:kFWPAsyncServerEnvelopeType];
  122. if (rawMessageType != nil) {
  123. if ([rawMessageType isEqualToString:kFWPAsyncServerDataMessage]) {
  124. [self onDataMessage:[message
  125. objectForKey:kFWPAsyncServerEnvelopeData]];
  126. } else if ([rawMessageType
  127. isEqualToString:kFWPAsyncServerControlMessage]) {
  128. [self onControl:[message objectForKey:kFWPAsyncServerEnvelopeData]];
  129. } else {
  130. FFLog(@"I-RDB082008", @"Unrecognized server packet type: %@",
  131. rawMessageType);
  132. }
  133. } else {
  134. FFLog(@"I-RDB082009", @"Unrecognized raw server packet received: %@",
  135. message);
  136. }
  137. }
  138. - (void)onDataMessage:(NSDictionary *)message {
  139. // we don't do anything with data messages, just kick them up a level
  140. FFLog(@"I-RDB082010", @"Got data message: %@", message);
  141. [self.delegate onDataMessage:self withMessage:message];
  142. }
  143. - (void)onControl:(NSDictionary *)message {
  144. FFLog(@"I-RDB082011", @"Got control message: %@", message);
  145. NSString *type = [message objectForKey:kFWPAsyncServerControlMessageType];
  146. if ([type isEqualToString:kFWPAsyncServerControlMessageShutdown]) {
  147. NSString *reason =
  148. [message objectForKey:kFWPAsyncServerControlMessageData];
  149. [self onConnectionShutdownWithReason:reason];
  150. } else if ([type isEqualToString:kFWPAsyncServerControlMessageReset]) {
  151. NSString *host =
  152. [message objectForKey:kFWPAsyncServerControlMessageData];
  153. [self onReset:host];
  154. } else if ([type isEqualToString:kFWPAsyncServerHello]) {
  155. NSDictionary *handshakeData =
  156. [message objectForKey:kFWPAsyncServerControlMessageData];
  157. [self onHandshake:handshakeData];
  158. } else {
  159. FFLog(@"I-RDB082012",
  160. @"Unknown control message returned from server: %@", message);
  161. }
  162. }
  163. - (void)onConnectionShutdownWithReason:(NSString *)reason {
  164. FFLog(@"I-RDB082013",
  165. @"Connection shutdown command received. Shutting down...");
  166. [self.delegate onKill:self withReason:reason];
  167. [self close];
  168. }
  169. - (void)onHandshake:(NSDictionary *)handshake {
  170. NSNumber *timestamp =
  171. [handshake objectForKey:kFWPAsyncServerHelloTimestamp];
  172. // NSString* version = [handshake
  173. // objectForKey:kFWPAsyncServerHelloVersion];
  174. NSString *host = [handshake objectForKey:kFWPAsyncServerHelloConnectedHost];
  175. NSString *sessionID = [handshake objectForKey:kFWPAsyncServerHelloSession];
  176. self.repoInfo.internalHost = host;
  177. if (state == REALTIME_STATE_CONNECTING) {
  178. [self.conn start];
  179. [self onConnection:self.conn readyAtTime:timestamp sessionID:sessionID];
  180. }
  181. }
  182. - (void)onConnection:(FWebSocketConnection *)conn
  183. readyAtTime:(NSNumber *)timestamp
  184. sessionID:(NSString *)sessionID {
  185. FFLog(@"I-RDB082014", @"Realtime connection established");
  186. state = REALTIME_STATE_CONNECTED;
  187. [self.delegate onReady:self atTime:timestamp sessionID:sessionID];
  188. }
  189. - (void)onReset:(NSString *)host {
  190. FFLog(
  191. @"I-RDB082015",
  192. @"Got a reset; killing connection to: %@; Updating internalHost to: %@",
  193. repoInfo.internalHost, host);
  194. self.repoInfo.internalHost = host;
  195. // Explicitly close the connection with SERVER_RESET so calling code knows
  196. // to reconnect immediately.
  197. [self closeWithReason:DISCONNECT_REASON_SERVER_RESET];
  198. }
  199. @end