FConnection.m 7.1 KB

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