FConnection.m 7.4 KB

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