microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/debugger/appWorker.ts
411lines · modeblame
9f036952Nisheet Jain10 years ago | 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT license. See LICENSE file in the project root for details. | |
| 3 | | |
cc70057dVladimir Kotikov9 years ago | 4 | import * as path from "path"; |
ea8a5f88digeff10 years ago | 5 | import * as WebSocket from "ws"; |
e45838cbVladimir Kotikov9 years ago | 6 | import { EventEmitter } from "events"; |
0a68f8dbArtem Egorov8 years ago | 7 | import { ensurePackagerRunning } from "../common/packagerStatus"; |
a4a7e387Meena Kunnathur Balakrishnan10 years ago | 8 | import {ErrorHelper} from "../common/error/errorHelper"; |
a6562589RedMickey6 years ago | 9 | import { logger } from "vscode-debugadapter"; |
7cc67271digeff10 years ago | 10 | import {ExecutionsLimiter} from "../common/executionsLimiter"; |
b05b5086Vladimir Kotikov9 years ago | 11 | import { ForkedAppWorker } from "./forkedAppWorker"; |
cc70057dVladimir Kotikov9 years ago | 12 | import { ScriptImporter } from "./scriptImporter"; |
bb869343Serge Svekolnikov8 years ago | 13 | import { ReactNativeProjectHelper } from "../common/reactNativeProjectHelper"; |
d124bf0eYuri Skorokhodov7 years ago | 14 | import * as nls from "vscode-nls"; |
| 15 | import { InternalErrorCode } from "../common/error/internalErrorCode"; | |
ce5e88eeYuri Skorokhodov5 years ago | 16 | import { FileSystem } from "../common/node/fileSystem"; |
| 17 | import { PromiseUtil } from "../common/node/promise"; | |
2d8af448Yuri Skorokhodov6 years ago | 18 | nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })(); |
d124bf0eYuri Skorokhodov7 years ago | 19 | const localize = nls.loadMessageBundle(); |
4677921cdigeff10 years ago | 20 | |
e45838cbVladimir Kotikov9 years ago | 21 | export interface RNAppMessage { |
ea8a5f88digeff10 years ago | 22 | method: string; |
e45838cbVladimir Kotikov9 years ago | 23 | url?: string; |
ea8a5f88digeff10 years ago | 24 | // These objects have also other properties but that we don't currently use |
| 25 | } | |
5d4d4de0digeff10 years ago | 26 | |
e45838cbVladimir Kotikov9 years ago | 27 | export interface IDebuggeeWorker { |
ce5e88eeYuri Skorokhodov5 years ago | 28 | start(): Promise<any>; |
e45838cbVladimir Kotikov9 years ago | 29 | stop(): void; |
| 30 | postMessage(message: RNAppMessage): void; | |
| 31 | } | |
| 32 | | |
1758f9a6Yuri Skorokhodov7 years ago | 33 | function printDebuggingError(error: Error, reason: any) { |
| 34 | const nestedError = ErrorHelper.getNestedError(error, InternalErrorCode.DebuggingWontWorkReloadJSAndReconnect, reason); | |
0a68f8dbArtem Egorov8 years ago | 35 | |
| 36 | logger.error(nestedError.message); | |
039239d1Vladimir Kotikov9 years ago | 37 | } |
| 38 | | |
| 39 | /** This class will create a SandboxedAppWorker that will run the RN App logic, and then create a socket | |
| 40 | * and send the RN App messages to the SandboxedAppWorker. The only RN App message that this class handles | |
| 41 | * is the prepareJSRuntime, which we reply to the RN App that the sandbox was created successfully. | |
| 42 | * When the socket closes, we'll create a new SandboxedAppWorker and a new socket pair and discard the old ones. | |
| 43 | */ | |
| 44 | | |
| 45 | export class MultipleLifetimesAppWorker extends EventEmitter { | |
| 46 | public static WORKER_BOOTSTRAP = ` | |
cc70057dVladimir Kotikov9 years ago | 47 | // Initialize some variables before react-native code would access them |
d64a6928Vladimir Kotikov9 years ago | 48 | var onmessage=null, self=global; |
cc70057dVladimir Kotikov9 years ago | 49 | // Cache Node's original require as __debug__.require |
d64a6928Vladimir Kotikov9 years ago | 50 | global.__debug__={require: require}; |
0864d702Ruslan Bikkinin7 years ago | 51 | // Prevent leaking process.versions from debugger process to |
| 52 | // worker because pure React Native doesn't do that and some packages as js-md5 rely on this behavior | |
| 53 | Object.defineProperty(process, "versions", { | |
| 54 | value: undefined | |
| 55 | }); | |
7daed3fcArtem Egorov8 years ago | 56 | |
4cf8fdf4Yuri Skorokhodov6 years ago | 57 | // TODO: Replace by url.fileURLToPath method when Node 10 LTS become deprecated |
| 58 | function fileUrlToPath(url) { | |
| 59 | if (process.platform === 'win32') { | |
| 60 | return url.toString().replace('file:///', ''); | |
| 61 | } else { | |
| 62 | return url.toString().replace('file://', ''); | |
| 63 | } | |
| 64 | } | |
| 65 | | |
2ecfbd20Yuri Skorokhodov7 years ago | 66 | function getNativeModules() { |
| 67 | var NativeModules; | |
| 68 | try { | |
| 69 | // This approach is for old RN versions | |
| 70 | NativeModules = global.require('NativeModules'); | |
| 71 | } catch (err) { | |
| 72 | // ignore error and try another way for more recent RN versions | |
| 73 | try { | |
| 74 | var nativeModuleId; | |
| 75 | var modules = global.__r.getModules(); | |
| 76 | var ids = Object.keys(modules); | |
| 77 | for (var i = 0; i < ids.length; i++) { | |
| 78 | if (modules[ids[i]].verboseName) { | |
| 79 | var packagePath = new String(modules[ids[i]].verboseName); | |
4cf8fdf4Yuri Skorokhodov6 years ago | 80 | if (packagePath.indexOf('react-native/Libraries/BatchedBridge/NativeModules.js') > 0) { |
2ecfbd20Yuri Skorokhodov7 years ago | 81 | nativeModuleId = parseInt(ids[i], 10); |
| 82 | break; | |
| 83 | } | |
| 84 | } | |
| 85 | } | |
| 86 | if (nativeModuleId) { | |
| 87 | NativeModules = global.__r(nativeModuleId); | |
| 88 | } | |
| 89 | } | |
| 90 | catch (err) { | |
| 91 | // suppress errors | |
| 92 | } | |
| 93 | } | |
| 94 | return NativeModules; | |
| 95 | } | |
| 96 | | |
| 97 | // Originally, this was made for iOS only | |
7daed3fcArtem Egorov8 years ago | 98 | var vscodeHandlers = { |
| 99 | 'vscode_reloadApp': function () { | |
2ecfbd20Yuri Skorokhodov7 years ago | 100 | var NativeModules = getNativeModules(); |
4dfc9ffdRedMickey5 years ago | 101 | if (NativeModules && NativeModules.DevMenu) { |
2ecfbd20Yuri Skorokhodov7 years ago | 102 | NativeModules.DevMenu.reload(); |
7daed3fcArtem Egorov8 years ago | 103 | } |
| 104 | }, | |
| 105 | 'vscode_showDevMenu': function () { | |
2ecfbd20Yuri Skorokhodov7 years ago | 106 | var NativeModules = getNativeModules(); |
4dfc9ffdRedMickey5 years ago | 107 | if (NativeModules && NativeModules.DevMenu) { |
2ecfbd20Yuri Skorokhodov7 years ago | 108 | NativeModules.DevMenu.show(); |
7daed3fcArtem Egorov8 years ago | 109 | } |
| 110 | } | |
| 111 | }; | |
| 112 | | |
| 113 | process.on("message", function (message) { | |
| 114 | if (message.data && vscodeHandlers[message.data.method]) { | |
| 115 | vscodeHandlers[message.data.method](); | |
| 116 | } else if(onmessage) { | |
| 117 | onmessage(message); | |
| 118 | } | |
cc70057dVladimir Kotikov9 years ago | 119 | }); |
7daed3fcArtem Egorov8 years ago | 120 | |
cc70057dVladimir Kotikov9 years ago | 121 | var postMessage = function(message){ |
| 122 | process.send(message); | |
| 123 | }; | |
bb869343Serge Svekolnikov8 years ago | 124 | |
| 125 | if (!self.postMessage) { | |
| 126 | self.postMessage = postMessage; | |
| 127 | } | |
| 128 | | |
cc70057dVladimir Kotikov9 years ago | 129 | var importScripts = (function(){ |
| 130 | var fs=require('fs'), vm=require('vm'); | |
| 131 | return function(scriptUrl){ | |
4cf8fdf4Yuri Skorokhodov6 years ago | 132 | scriptUrl = fileUrlToPath(scriptUrl); |
| 133 | var scriptCode = fs.readFileSync(scriptUrl, 'utf8'); | |
e67ace8aYuri Skorokhodov6 years ago | 134 | // Add a 'debugger;' statement to stop code execution |
| 135 | // to wait for the sourcemaps to be processed by the debug adapter | |
| 136 | vm.runInThisContext('debugger;' + scriptCode, {filename: scriptUrl}); | |
cc70057dVladimir Kotikov9 years ago | 137 | }; |
4cf8fdf4Yuri Skorokhodov6 years ago | 138 | })(); |
| 139 | `; | |
cc70057dVladimir Kotikov9 years ago | 140 | |
cf6dd6b9Yuri Skorokhodov7 years ago | 141 | public static CONSOLE_TRACE_PATCH = `// Worker is ran as nodejs process, so console.trace() writes to stderr and it leads to error in native app |
| 142 | // To avoid this console.trace() is overridden to print stacktrace via console.log() | |
| 143 | // Please, see Node JS implementation: https://github.com/nodejs/node/blob/master/lib/internal/console/constructor.js | |
| 144 | console.trace = (function() { | |
| 145 | return function() { | |
| 146 | try { | |
| 147 | var err = { | |
| 148 | name: 'Trace', | |
| 149 | message: require('util').format.apply(null, arguments) | |
| 150 | }; | |
| 151 | // Node uses 10, but usually it's not enough for RN app trace | |
| 152 | Error.stackTraceLimit = 30; | |
| 153 | Error.captureStackTrace(err, console.trace); | |
| 154 | console.log(err.stack); | |
| 155 | } catch (e) { | |
| 156 | console.error(e); | |
| 157 | } | |
| 158 | }; | |
4cf8fdf4Yuri Skorokhodov6 years ago | 159 | })(); |
| 160 | `; | |
cf6dd6b9Yuri Skorokhodov7 years ago | 161 | |
13a99427Yuri Skorokhodov6 years ago | 162 | public static PROCESS_TO_STRING_PATCH = `// As worker is ran in node, it breaks broadcast-channels package approach of identifying if it’s ran in node: |
| 163 | // https://github.com/pubkey/broadcast-channel/blob/master/src/util.js#L64 | |
| 164 | // To avoid it if process.toString() is called if will return empty string instead of [object process]. | |
| 165 | var nativeObjectToString = Object.prototype.toString; | |
| 166 | Object.prototype.toString = function() { | |
| 167 | if (this === process) { | |
| 168 | return ''; | |
| 169 | } else { | |
| 170 | return nativeObjectToString.call(this); | |
| 171 | } | |
f4e3ce39Yuri Skorokhodov6 years ago | 172 | }; |
13a99427Yuri Skorokhodov6 years ago | 173 | `; |
| 174 | | |
039239d1Vladimir Kotikov9 years ago | 175 | public static WORKER_DONE = `// Notify debugger that we're done with loading |
cc70057dVladimir Kotikov9 years ago | 176 | // and started listening for IPC messages |
| 177 | postMessage({workerLoaded:true});`; | |
| 178 | | |
bb869343Serge Svekolnikov8 years ago | 179 | public static FETCH_STUB = `(function(self) { |
4cf8fdf4Yuri Skorokhodov6 years ago | 180 | 'use strict'; |
bb869343Serge Svekolnikov8 years ago | 181 | |
4cf8fdf4Yuri Skorokhodov6 years ago | 182 | if (self.fetch) { |
| 183 | return; | |
| 184 | } | |
| 185 | | |
| 186 | self.fetch = fetch; | |
bb869343Serge Svekolnikov8 years ago | 187 | |
4cf8fdf4Yuri Skorokhodov6 years ago | 188 | function fetch(url) { |
| 189 | return new Promise((resolve, reject) => { | |
| 190 | var data = require('fs').readFileSync(fileUrlToPath(url), 'utf8'); | |
| 191 | resolve( | |
| 192 | { | |
| 193 | text: function () { | |
| 194 | return data; | |
| 195 | } | |
bb869343Serge Svekolnikov8 years ago | 196 | }); |
4cf8fdf4Yuri Skorokhodov6 years ago | 197 | }); |
| 198 | } | |
| 199 | })(global); | |
| 200 | `; | |
bb869343Serge Svekolnikov8 years ago | 201 | |
6eeec3c0Serge Svekolnikov8 years ago | 202 | private packagerAddress: string; |
e3ae4227digeff10 years ago | 203 | private packagerPort: number; |
4677921cdigeff10 years ago | 204 | private sourcesStoragePath: string; |
7daed3fcArtem Egorov8 years ago | 205 | private projectRootPath: string; |
6eeec3c0Serge Svekolnikov8 years ago | 206 | private packagerRemoteRoot?: string; |
| 207 | private packagerLocalRoot?: string; | |
cf911877Yuri Skorokhodov7 years ago | 208 | private debuggerWorkerUrlPath?: string; |
ea8a5f88digeff10 years ago | 209 | private socketToApp: WebSocket; |
5c8365a6Artem Egorov8 years ago | 210 | private singleLifetimeWorker: IDebuggeeWorker | null; |
3b6023b2Jimmy Thomson10 years ago | 211 | private webSocketConstructor: (url: string) => WebSocket; |
| 212 | | |
7cc67271digeff10 years ago | 213 | private executionLimiter = new ExecutionsLimiter(); |
ce5e88eeYuri Skorokhodov5 years ago | 214 | private nodeFileSystem = new FileSystem(); |
cc70057dVladimir Kotikov9 years ago | 215 | private scriptImporter: ScriptImporter; |
7cc67271digeff10 years ago | 216 | |
6eeec3c0Serge Svekolnikov8 years ago | 217 | constructor( |
| 218 | attachRequestArguments: any, | |
| 219 | sourcesStoragePath: string, | |
| 220 | projectRootPath: string, | |
| 221 | { | |
| 222 | webSocketConstructor = (url: string) => new WebSocket(url), | |
| 223 | } = {}) { | |
e45838cbVladimir Kotikov9 years ago | 224 | super(); |
6eeec3c0Serge Svekolnikov8 years ago | 225 | this.packagerAddress = attachRequestArguments.address || "localhost"; |
| 226 | this.packagerPort = attachRequestArguments.port; | |
| 227 | this.packagerRemoteRoot = attachRequestArguments.remoteRoot; | |
| 228 | this.packagerLocalRoot = attachRequestArguments.localRoot; | |
cf911877Yuri Skorokhodov7 years ago | 229 | this.debuggerWorkerUrlPath = attachRequestArguments.debuggerWorkerUrlPath; |
4677921cdigeff10 years ago | 230 | this.sourcesStoragePath = sourcesStoragePath; |
7daed3fcArtem Egorov8 years ago | 231 | this.projectRootPath = projectRootPath; |
1758f9a6Yuri Skorokhodov7 years ago | 232 | if (!this.sourcesStoragePath) |
| 233 | throw ErrorHelper.getInternalError(InternalErrorCode.SourcesStoragePathIsNullOrEmpty); | |
3b6023b2Jimmy Thomson10 years ago | 234 | this.webSocketConstructor = webSocketConstructor; |
6eeec3c0Serge Svekolnikov8 years ago | 235 | this.scriptImporter = new ScriptImporter(this.packagerAddress, this.packagerPort, sourcesStoragePath, this.packagerRemoteRoot, this.packagerLocalRoot); |
4677921cdigeff10 years ago | 236 | } |
| 237 | | |
ce5e88eeYuri Skorokhodov5 years ago | 238 | public start(retryAttempt: boolean = false): Promise<any> { |
d124bf0eYuri Skorokhodov7 years ago | 239 | const errPackagerNotRunning = ErrorHelper.getInternalError(InternalErrorCode.CannotAttachToPackagerCheckPackagerRunningOnPort, this.packagerPort); |
0a68f8dbArtem Egorov8 years ago | 240 | |
6eeec3c0Serge Svekolnikov8 years ago | 241 | return ensurePackagerRunning(this.packagerAddress, this.packagerPort, errPackagerNotRunning) |
cc70057dVladimir Kotikov9 years ago | 242 | .then(() => { |
| 243 | // Don't fetch debugger worker on socket disconnect | |
ce5e88eeYuri Skorokhodov5 years ago | 244 | return retryAttempt ? Promise.resolve() : |
cc70057dVladimir Kotikov9 years ago | 245 | this.downloadAndPatchDebuggerWorker(); |
| 246 | }) | |
| 247 | .then(() => this.createSocketToApp(retryAttempt)); | |
ff7dce65digeff10 years ago | 248 | } |
| 249 | | |
e45838cbVladimir Kotikov9 years ago | 250 | public stop() { |
| 251 | if (this.socketToApp) { | |
| 252 | this.socketToApp.removeAllListeners(); | |
| 253 | this.socketToApp.close(); | |
| 254 | } | |
| 255 | | |
| 256 | if (this.singleLifetimeWorker) { | |
| 257 | this.singleLifetimeWorker.stop(); | |
| 258 | } | |
| 259 | } | |
| 260 | | |
ce5e88eeYuri Skorokhodov5 years ago | 261 | public downloadAndPatchDebuggerWorker(): Promise<void> { |
cc70057dVladimir Kotikov9 years ago | 262 | let scriptToRunPath = path.resolve(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILENAME); |
cf911877Yuri Skorokhodov7 years ago | 263 | return this.scriptImporter.downloadDebuggerWorker(this.sourcesStoragePath, this.projectRootPath, this.debuggerWorkerUrlPath) |
cc70057dVladimir Kotikov9 years ago | 264 | .then(() => this.nodeFileSystem.readFile(scriptToRunPath, "utf8")) |
| 265 | .then((workerContent: string) => { | |
bb869343Serge Svekolnikov8 years ago | 266 | const isHaulProject = ReactNativeProjectHelper.isHaulProject(this.projectRootPath); |
cc70057dVladimir Kotikov9 years ago | 267 | // Add our customizations to debugger worker to get it working smoothly |
| 268 | // in Node env and polyfill WebWorkers API over Node's IPC. | |
bb869343Serge Svekolnikov8 years ago | 269 | const modifiedDebuggeeContent = [ |
| 270 | MultipleLifetimesAppWorker.WORKER_BOOTSTRAP, | |
cf6dd6b9Yuri Skorokhodov7 years ago | 271 | MultipleLifetimesAppWorker.CONSOLE_TRACE_PATCH, |
13a99427Yuri Skorokhodov6 years ago | 272 | MultipleLifetimesAppWorker.PROCESS_TO_STRING_PATCH, |
bb869343Serge Svekolnikov8 years ago | 273 | isHaulProject ? MultipleLifetimesAppWorker.FETCH_STUB : null, |
| 274 | workerContent, | |
| 275 | MultipleLifetimesAppWorker.WORKER_DONE, | |
| 276 | ].join("\n"); | |
cc70057dVladimir Kotikov9 years ago | 277 | return this.nodeFileSystem.writeFile(scriptToRunPath, modifiedDebuggeeContent); |
| 278 | }); | |
| 279 | } | |
| 280 | | |
7e74daf7Yuri Skorokhodov6 years ago | 281 | public showDevMenuCommand(): void { |
| 282 | if (this.singleLifetimeWorker) { | |
| 283 | this.singleLifetimeWorker.postMessage({ | |
| 284 | method: "vscode_showDevMenu", | |
| 285 | }); | |
| 286 | } | |
| 287 | } | |
| 288 | | |
| 289 | public reloadAppCommand(): void { | |
| 290 | if (this.singleLifetimeWorker) { | |
| 291 | this.singleLifetimeWorker.postMessage({ | |
| 292 | method: "vscode_reloadApp", | |
| 293 | }); | |
| 294 | } | |
| 295 | } | |
| 296 | | |
ce5e88eeYuri Skorokhodov5 years ago | 297 | private startNewWorkerLifetime(): Promise<void> { |
6eeec3c0Serge Svekolnikov8 years ago | 298 | this.singleLifetimeWorker = new ForkedAppWorker(this.packagerAddress, this.packagerPort, this.sourcesStoragePath, this.projectRootPath, |
| 299 | (message) => { | |
| 300 | this.sendMessageToApp(message); | |
| 301 | }, | |
| 302 | this.packagerRemoteRoot, this.packagerLocalRoot); | |
0a68f8dbArtem Egorov8 years ago | 303 | logger.verbose("A new app worker lifetime was created."); |
e45838cbVladimir Kotikov9 years ago | 304 | return this.singleLifetimeWorker.start() |
cc70057dVladimir Kotikov9 years ago | 305 | .then(startedEvent => { |
| 306 | this.emit("connected", startedEvent); | |
| 307 | }); | |
4677921cdigeff10 years ago | 308 | } |
| 309 | | |
ce5e88eeYuri Skorokhodov5 years ago | 310 | private createSocketToApp(retryAttempt: boolean = false): Promise<void> { |
| 311 | return new Promise((resolve, reject) => { | |
| 312 | this.socketToApp = this.webSocketConstructor(this.debuggerProxyUrl()); | |
| 313 | this.socketToApp.on("open", () => { | |
| 314 | this.onSocketOpened(); | |
299b0557Patricio Beltran10 years ago | 315 | }); |
ce5e88eeYuri Skorokhodov5 years ago | 316 | this.socketToApp.on("close", |
| 317 | () => { | |
| 318 | this.executionLimiter.execute("onSocketClose.msg", /*limitInSeconds*/ 10, () => { | |
| 319 | /* | |
| 320 | * It is not the best idea to compare with the message, but this is the only thing React Native gives that is unique when | |
| 321 | * it closes the socket because it already has a connection to a debugger. | |
| 322 | * https://github.com/facebook/react-native/blob/588f01e9982775f0699c7bfd56623d4ed3949810/local-cli/server/util/webSocketProxy.js#L38 | |
| 323 | */ | |
| 324 | let msgKey = "_closeMessage"; | |
| 325 | if (this.socketToApp[msgKey] === "Another debugger is already connected") { | |
| 326 | reject(ErrorHelper.getInternalError(InternalErrorCode.AnotherDebuggerConnectedToPackager)); | |
| 327 | } | |
| 328 | logger.log(localize("DisconnectedFromThePackagerToReactNative", "Disconnected from the Proxy (Packager) to the React Native application. Retrying reconnection soon...")); | |
| 329 | }); | |
| 330 | setTimeout(() => { | |
| 331 | this.start(true /* retryAttempt */); | |
| 332 | }, 100); | |
| 333 | }); | |
| 334 | this.socketToApp.on("message", | |
| 335 | (message: any) => this.onMessage(message)); | |
| 336 | this.socketToApp.on("error", | |
| 337 | (error: Error) => { | |
| 338 | if (retryAttempt) { | |
| 339 | printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.ReconnectionToPackagerFailedCheckForErrorsOrRestartReactNative), error); | |
| 340 | } | |
499fe4ebMeena Kunnathur Balakrishnan10 years ago | 341 | |
ce5e88eeYuri Skorokhodov5 years ago | 342 | reject(error); |
| 343 | }); | |
32cab018Meena Kunnathur Balakrishnan10 years ago | 344 | |
ce5e88eeYuri Skorokhodov5 years ago | 345 | // In an attempt to catch failures in starting the packager on first attempt, |
| 346 | // wait for 300 ms before resolving the promise | |
259c018fYuri Skorokhodov5 years ago | 347 | PromiseUtil.delay(300).then(() => resolve()); |
ce5e88eeYuri Skorokhodov5 years ago | 348 | }); |
4677921cdigeff10 years ago | 349 | } |
| 350 | | |
| 351 | private debuggerProxyUrl() { | |
6eeec3c0Serge Svekolnikov8 years ago | 352 | return `ws://${this.packagerAddress}:${this.packagerPort}/debugger-proxy?role=debugger&name=vscode`; |
4677921cdigeff10 years ago | 353 | } |
| 354 | | |
ea8a5f88digeff10 years ago | 355 | private onSocketOpened() { |
7cc67271digeff10 years ago | 356 | this.executionLimiter.execute("onSocketOpened.msg", /*limitInSeconds*/ 10, () => |
d124bf0eYuri Skorokhodov7 years ago | 357 | logger.log(localize("EstablishedConnectionWithPackagerToReactNativeApp", "Established a connection with the Proxy (Packager) to the React Native application"))); |
4677921cdigeff10 years ago | 358 | } |
| 359 | | |
9174feb7Vladimir Kotikov9 years ago | 360 | private killWorker() { |
| 361 | if (!this.singleLifetimeWorker) return; | |
| 362 | this.singleLifetimeWorker.stop(); | |
| 363 | this.singleLifetimeWorker = null; | |
| 364 | } | |
e7b314e8Vladimir Kotikov9 years ago | 365 | |
9174feb7Vladimir Kotikov9 years ago | 366 | private onMessage(message: string) { |
5d4d4de0digeff10 years ago | 367 | try { |
0a68f8dbArtem Egorov8 years ago | 368 | logger.verbose("From RN APP: " + message); |
ea8a5f88digeff10 years ago | 369 | let object = <RNAppMessage>JSON.parse(message); |
5d4d4de0digeff10 years ago | 370 | if (object.method === "prepareJSRuntime") { |
e7b314e8Vladimir Kotikov9 years ago | 371 | // In RN 0.40 Android runtime doesn't seem to be sending "$disconnected" event |
| 372 | // when user reloads an app, hence we need to try to kill it here either. | |
9174feb7Vladimir Kotikov9 years ago | 373 | this.killWorker(); |
5d4d4de0digeff10 years ago | 374 | // The MultipleLifetimesAppWorker will handle prepareJSRuntime aka create new lifetime |
| 375 | this.gotPrepareJSRuntime(object); | |
ff7dce65digeff10 years ago | 376 | } else if (object.method === "$disconnected") { |
| 377 | // We need to shutdown the current app worker, and create a new lifetime | |
9174feb7Vladimir Kotikov9 years ago | 378 | this.killWorker(); |
5d4d4de0digeff10 years ago | 379 | } else if (object.method) { |
| 380 | // All the other messages are handled by the single lifetime worker | |
5c8365a6Artem Egorov8 years ago | 381 | if (this.singleLifetimeWorker) { |
| 382 | this.singleLifetimeWorker.postMessage(object); | |
| 383 | } | |
5d4d4de0digeff10 years ago | 384 | } else { |
ea8a5f88digeff10 years ago | 385 | // Message doesn't have a method. Ignore it. This is an info message instead of warn because it's normal and expected |
d124bf0eYuri Skorokhodov7 years ago | 386 | logger.verbose(`The react-native app sent a message without specifying a method: ${message}`); |
5d4d4de0digeff10 years ago | 387 | } |
| 388 | } catch (exception) { | |
1758f9a6Yuri Skorokhodov7 years ago | 389 | printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.FailedToProcessMessageFromReactNativeApp, message), exception); |
4677921cdigeff10 years ago | 390 | } |
| 391 | } | |
| 392 | | |
| 393 | private gotPrepareJSRuntime(message: any): void { | |
| 394 | // Create the sandbox, and replay that we finished processing the message | |
ce5e88eeYuri Skorokhodov5 years ago | 395 | this.startNewWorkerLifetime().then(() => { |
ff7dce65digeff10 years ago | 396 | this.sendMessageToApp({ replyID: parseInt(message.id, 10) }); |
1758f9a6Yuri Skorokhodov7 years ago | 397 | }, error => printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.FailedToPrepareJSRuntimeEnvironment, message), error)); |
4677921cdigeff10 years ago | 398 | } |
| 399 | | |
ff7dce65digeff10 years ago | 400 | private sendMessageToApp(message: any): void { |
5c8365a6Artem Egorov8 years ago | 401 | let stringified: string = ""; |
354c28a1digeff10 years ago | 402 | try { |
| 403 | stringified = JSON.stringify(message); | |
d124bf0eYuri Skorokhodov7 years ago | 404 | logger.verbose(`To RN APP: ${stringified}`); |
354c28a1digeff10 years ago | 405 | this.socketToApp.send(stringified); |
| 406 | } catch (exception) { | |
| 407 | let messageToShow = stringified || ("" + message); // Try to show the stringified version, but show the toString if unavailable | |
1758f9a6Yuri Skorokhodov7 years ago | 408 | printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.FailedToSendMessageToTheReactNativeApp, messageToShow), exception); |
354c28a1digeff10 years ago | 409 | } |
4677921cdigeff10 years ago | 410 | } |
| 411 | } |