RCTInspectorPackagerConnection.m
9.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
#import "RCTInspectorPackagerConnection.h"
#if RCT_DEV
#import "RCTDefines.h"
#import "RCTInspector.h"
#import "RCTLog.h"
#import "RCTSRWebSocket.h"
#import "RCTUtils.h"
// This is a port of the Android impl, at
// ReactAndroid/src/main/java/com/facebook/react/devsupport/InspectorPackagerConnection.java
// please keep consistent :)
const int RECONNECT_DELAY_MS = 2000;
@implementation RCTBundleStatus
@end
@interface RCTInspectorPackagerConnection () <RCTSRWebSocketDelegate> {
NSURL *_url;
NSMutableDictionary<NSString *, RCTInspectorLocalConnection *> *_inspectorConnections;
RCTSRWebSocket *_webSocket;
dispatch_queue_t _jsQueue;
BOOL _closed;
BOOL _suppressConnectionErrors;
RCTBundleStatusProvider _bundleStatusProvider;
}
@end
@interface RCTInspectorRemoteConnection () {
__weak RCTInspectorPackagerConnection *_owningPackagerConnection;
NSString *_pageId;
}
- (instancetype)initWithPackagerConnection:(RCTInspectorPackagerConnection *)owningPackagerConnection
pageId:(NSString *)pageId;
@end
static NSDictionary<NSString *, id> *makePageIdPayload(NSString *pageId)
{
return @{ @"pageId": pageId };
}
@implementation RCTInspectorPackagerConnection
RCT_NOT_IMPLEMENTED(- (instancetype)init)
- (instancetype)initWithURL:(NSURL *)url
{
if (self = [super init]) {
_url = url;
_inspectorConnections = [NSMutableDictionary new];
_jsQueue = dispatch_queue_create("com.facebook.react.WebSocketExecutor", DISPATCH_QUEUE_SERIAL);
}
return self;
}
- (void)setBundleStatusProvider:(RCTBundleStatusProvider)bundleStatusProvider
{
_bundleStatusProvider = bundleStatusProvider;
}
- (void)handleProxyMessage:(NSDictionary<NSString *, id> *)message
{
NSString *event = message[@"event"];
NSDictionary *payload = message[@"payload"];
if ([@"getPages" isEqualToString:event]) {
[self sendEvent:event payload:[self pages]];
} else if ([@"wrappedEvent" isEqualToString:event]) {
[self handleWrappedEvent:payload];
} else if ([@"connect" isEqualToString:event]) {
[self handleConnect:payload];
} else if ([@"disconnect" isEqualToString:event]) {
[self handleDisconnect:payload];
} else {
RCTLogError(@"Unknown event: %@", event);
}
}
- (void)sendEventToAllConnections:(NSString *)event
{
for (NSString *pageId in _inspectorConnections) {
[_inspectorConnections[pageId] sendMessage:event];
}
}
- (void)closeAllConnections
{
for (NSString *pageId in _inspectorConnections){
[[_inspectorConnections objectForKey:pageId] disconnect];
}
[_inspectorConnections removeAllObjects];
}
- (void)handleConnect:(NSDictionary *)payload
{
NSString *pageId = payload[@"pageId"];
if (_inspectorConnections[pageId]) {
[_inspectorConnections removeObjectForKey:pageId];
RCTLogError(@"Already connected: %@", pageId);
return;
}
RCTInspectorRemoteConnection *remoteConnection =
[[RCTInspectorRemoteConnection alloc] initWithPackagerConnection:self
pageId:pageId];
RCTInspectorLocalConnection *inspectorConnection = [RCTInspector connectPage:[pageId integerValue]
forRemoteConnection:remoteConnection];
_inspectorConnections[pageId] = inspectorConnection;
}
- (void)handleDisconnect:(NSDictionary *)payload
{
NSString *pageId = payload[@"pageId"];
RCTInspectorLocalConnection *inspectorConnection = _inspectorConnections[pageId];
if (inspectorConnection) {
[self removeConnectionForPage:pageId];
[inspectorConnection disconnect];
}
}
- (void)removeConnectionForPage:(NSString *)pageId
{
[_inspectorConnections removeObjectForKey:pageId];
}
- (void)handleWrappedEvent:(NSDictionary *)payload
{
NSString *pageId = payload[@"pageId"];
NSString *wrappedEvent = payload[@"wrappedEvent"];
RCTInspectorLocalConnection *inspectorConnection = _inspectorConnections[pageId];
if (!inspectorConnection) {
RCTLogWarn(
@"Not connected to page: %@ , failed trying to handle event: %@",
pageId,
wrappedEvent);
return;
}
[inspectorConnection sendMessage:wrappedEvent];
}
- (NSArray *)pages
{
NSArray<RCTInspectorPage *> *pages = [RCTInspector pages];
NSMutableArray *array = [NSMutableArray arrayWithCapacity:pages.count];
RCTBundleStatusProvider statusProvider = _bundleStatusProvider;
RCTBundleStatus *bundleStatus = statusProvider == nil
? nil
: statusProvider();
for (RCTInspectorPage *page in pages) {
NSDictionary *jsonPage = @{
@"id": [@(page.id) stringValue],
@"title": page.title,
@"app": [[NSBundle mainBundle] bundleIdentifier],
@"isLastBundleDownloadSuccess": bundleStatus == nil
? [NSNull null]
: @(bundleStatus.isLastBundleDownloadSuccess),
@"bundleUpdateTimestamp": bundleStatus == nil
? [NSNull null]
: @((long)bundleStatus.bundleUpdateTimestamp * 1000),
};
[array addObject:jsonPage];
}
return array;
}
- (void)sendWrappedEvent:(NSString *)pageId
message:(NSString *)message
{
NSDictionary *payload = @{
@"pageId": pageId,
@"wrappedEvent": message,
};
[self sendEvent:@"wrappedEvent" payload:payload];
}
- (void)sendEvent:(NSString *)name payload:(id)payload
{
NSDictionary *jsonMessage = @{
@"event": name,
@"payload": payload,
};
[self sendToPackager:jsonMessage];
}
// analogous to InspectorPackagerConnection.Connection.onFailure(...)
- (void)webSocket:(RCTSRWebSocket *)webSocket didFailWithError:(NSError *)error
{
if (_webSocket) {
[self abort:@"Websocket exception"
withCause:error];
}
if (!_closed) {
[self reconnect];
}
}
// analogous to InspectorPackagerConnection.Connection.onMessage(...)
- (void)webSocket:(RCTSRWebSocket *)webSocket didReceiveMessage:(id)opaqueMessage
{
// warn but don't die on unrecognized messages
if (![opaqueMessage isKindOfClass:[NSString class]]) {
RCTLogWarn(@"Unrecognized inspector message, object is of type: %@", [opaqueMessage class]);
return;
}
NSString *messageText = opaqueMessage;
NSError *error = nil;
id parsedJSON = RCTJSONParse(messageText, &error);
if (error) {
RCTLogWarn(@"Unrecognized inspector message, string was not valid JSON: %@",
messageText);
return;
}
[self handleProxyMessage:parsedJSON];
}
// analogous to InspectorPackagerConnection.Connection.onClosed(...)
- (void)webSocket:(RCTSRWebSocket *)webSocket didCloseWithCode:(NSInteger)code
reason:(NSString *)reason
wasClean:(BOOL)wasClean
{
_webSocket = nil;
[self closeAllConnections];
if (!_closed) {
[self reconnect];
}
}
- (void)connect
{
if (_closed) {
RCTLogError(@"Illegal state: Can't connect after having previously been closed.");
return;
}
// The corresopnding android code has a lot of custom config options for
// timeouts, but it appears the iOS RCTSRWebSocket API doesn't have the same
// implemented options.
_webSocket = [[RCTSRWebSocket alloc] initWithURL:_url];
[_webSocket setDelegateDispatchQueue:_jsQueue];
_webSocket.delegate = self;
[_webSocket open];
}
- (void)reconnect
{
if (_closed) {
RCTLogError(@"Illegal state: Can't reconnect after having previously been closed.");
return;
}
if (_suppressConnectionErrors) {
RCTLogWarn(@"Couldn't connect to packager, will silently retry");
_suppressConnectionErrors = true;
}
__weak RCTInspectorPackagerConnection *weakSelf = self;
dispatch_after(
dispatch_time(DISPATCH_TIME_NOW, RECONNECT_DELAY_MS *NSEC_PER_MSEC),
dispatch_get_main_queue(), ^{
RCTInspectorPackagerConnection *strongSelf = weakSelf;
if (strongSelf && !strongSelf->_closed) {
[strongSelf connect];
}
});
}
- (void)closeQuietly
{
_closed = true;
[self disposeWebSocket];
}
- (void)sendToPackager:(NSDictionary *)messageObject
{
__weak RCTInspectorPackagerConnection *weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
RCTInspectorPackagerConnection *strongSelf = weakSelf;
if (strongSelf && !strongSelf->_closed) {
NSError *error;
NSString *messageText = RCTJSONStringify(messageObject, &error);
if (error) {
RCTLogWarn(@"Couldn't send event to packager: %@", error);
} else {
[strongSelf->_webSocket send:messageText];
}
}
});
}
- (void)abort:(NSString *)message
withCause:(NSError *)cause
{
// Don't log ECONNREFUSED at all; it's expected in cases where the server isn't listening.
if (![cause.domain isEqual:NSPOSIXErrorDomain] || cause.code != ECONNREFUSED) {
RCTLogInfo(@"Error occurred, shutting down websocket connection: %@ %@", message, cause);
}
[self closeAllConnections];
[self disposeWebSocket];
}
- (void)disposeWebSocket
{
if (_webSocket) {
[_webSocket closeWithCode:1000
reason:@"End of session"];
_webSocket.delegate = nil;
_webSocket = nil;
}
}
@end
@implementation RCTInspectorRemoteConnection
RCT_NOT_IMPLEMENTED(- (instancetype)init)
- (instancetype)initWithPackagerConnection:(RCTInspectorPackagerConnection *)owningPackagerConnection
pageId:(NSString *)pageId
{
if (self = [super init]) {
_owningPackagerConnection = owningPackagerConnection;
_pageId = pageId;
}
return self;
}
- (void)onMessage:(NSString *)message
{
[_owningPackagerConnection sendWrappedEvent:_pageId
message:message];
}
- (void)onDisconnect
{
RCTInspectorPackagerConnection *owningPackagerConnectionStrong = _owningPackagerConnection;
if (owningPackagerConnectionStrong) {
[owningPackagerConnectionStrong removeConnectionForPage:_pageId];
[owningPackagerConnectionStrong sendEvent:@"disconnect"
payload:makePageIdPayload(_pageId)];
}
}
@end
#endif