microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/debugger/appWorker.ts
311lines · 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 | | |
4677921cdigeff10 years ago | 4 | import * as Q from "q"; |
cc70057dVladimir Kotikov9 years ago | 5 | import * as path from "path"; |
ea8a5f88digeff10 years ago | 6 | import * as WebSocket from "ws"; |
e45838cbVladimir Kotikov9 years ago | 7 | import { EventEmitter } from "events"; |
0a68f8dbArtem Egorov8 years ago | 8 | import { ensurePackagerRunning } from "../common/packagerStatus"; |
a4a7e387Meena Kunnathur Balakrishnan10 years ago | 9 | import {ErrorHelper} from "../common/error/errorHelper"; |
0a68f8dbArtem Egorov8 years ago | 10 | import { logger } from "vscode-chrome-debug-core"; |
7cc67271digeff10 years ago | 11 | import {ExecutionsLimiter} from "../common/executionsLimiter"; |
cc70057dVladimir Kotikov9 years ago | 12 | import { FileSystem as NodeFileSystem} from "../common/node/fileSystem"; |
b05b5086Vladimir Kotikov9 years ago | 13 | import { ForkedAppWorker } from "./forkedAppWorker"; |
cc70057dVladimir Kotikov9 years ago | 14 | import { ScriptImporter } from "./scriptImporter"; |
bb869343Serge Svekolnikov8 years ago | 15 | import { ReactNativeProjectHelper } from "../common/reactNativeProjectHelper"; |
4677921cdigeff10 years ago | 16 | |
e45838cbVladimir Kotikov9 years ago | 17 | export interface RNAppMessage { |
ea8a5f88digeff10 years ago | 18 | method: string; |
e45838cbVladimir Kotikov9 years ago | 19 | url?: string; |
ea8a5f88digeff10 years ago | 20 | // These objects have also other properties but that we don't currently use |
| 21 | } | |
5d4d4de0digeff10 years ago | 22 | |
e45838cbVladimir Kotikov9 years ago | 23 | export interface IDebuggeeWorker { |
| 24 | start(): Q.Promise<any>; | |
| 25 | stop(): void; | |
| 26 | postMessage(message: RNAppMessage): void; | |
| 27 | } | |
| 28 | | |
039239d1Vladimir Kotikov9 years ago | 29 | function printDebuggingError(message: string, reason: any) { |
0a68f8dbArtem Egorov8 years ago | 30 | const nestedError = ErrorHelper.getNestedWarning(reason, `${message}. Debugging won't work: Try reloading the JS from inside the app, or Reconnect the VS Code debugger`); |
| 31 | | |
| 32 | logger.error(nestedError.message); | |
039239d1Vladimir Kotikov9 years ago | 33 | } |
| 34 | | |
| 35 | /** This class will create a SandboxedAppWorker that will run the RN App logic, and then create a socket | |
| 36 | * and send the RN App messages to the SandboxedAppWorker. The only RN App message that this class handles | |
| 37 | * is the prepareJSRuntime, which we reply to the RN App that the sandbox was created successfully. | |
| 38 | * When the socket closes, we'll create a new SandboxedAppWorker and a new socket pair and discard the old ones. | |
| 39 | */ | |
| 40 | | |
| 41 | export class MultipleLifetimesAppWorker extends EventEmitter { | |
| 42 | public static WORKER_BOOTSTRAP = ` | |
cc70057dVladimir Kotikov9 years ago | 43 | // Initialize some variables before react-native code would access them |
d64a6928Vladimir Kotikov9 years ago | 44 | var onmessage=null, self=global; |
cc70057dVladimir Kotikov9 years ago | 45 | // Cache Node's original require as __debug__.require |
d64a6928Vladimir Kotikov9 years ago | 46 | global.__debug__={require: require}; |
| 47 | // avoid Node's GLOBAL deprecation warning | |
| 48 | Object.defineProperty(global, "GLOBAL", { | |
| 49 | configurable: true, | |
| 50 | writable: true, | |
| 51 | enumerable: true, | |
| 52 | value: global | |
| 53 | }); | |
7daed3fcArtem Egorov8 years ago | 54 | |
| 55 | var vscodeHandlers = { | |
| 56 | 'vscode_reloadApp': function () { | |
| 57 | try { | |
| 58 | global.require('NativeModules').DevMenu.reload(); | |
| 59 | } catch (err) { | |
| 60 | // ignore | |
| 61 | } | |
| 62 | }, | |
| 63 | 'vscode_showDevMenu': function () { | |
| 64 | try { | |
| 65 | var DevMenu = global.require('NativeModules').DevMenu.show(); | |
| 66 | } catch (err) { | |
| 67 | // ignore | |
| 68 | } | |
| 69 | } | |
| 70 | }; | |
| 71 | | |
| 72 | process.on("message", function (message) { | |
| 73 | if (message.data && vscodeHandlers[message.data.method]) { | |
| 74 | vscodeHandlers[message.data.method](); | |
| 75 | } else if(onmessage) { | |
| 76 | onmessage(message); | |
| 77 | } | |
cc70057dVladimir Kotikov9 years ago | 78 | }); |
7daed3fcArtem Egorov8 years ago | 79 | |
cc70057dVladimir Kotikov9 years ago | 80 | var postMessage = function(message){ |
| 81 | process.send(message); | |
| 82 | }; | |
bb869343Serge Svekolnikov8 years ago | 83 | |
| 84 | if (!self.postMessage) { | |
| 85 | self.postMessage = postMessage; | |
| 86 | } | |
| 87 | | |
cc70057dVladimir Kotikov9 years ago | 88 | var importScripts = (function(){ |
| 89 | var fs=require('fs'), vm=require('vm'); | |
| 90 | return function(scriptUrl){ | |
| 91 | var scriptCode = fs.readFileSync(scriptUrl, "utf8"); | |
| 92 | vm.runInThisContext(scriptCode, {filename: scriptUrl}); | |
| 93 | }; | |
| 94 | })();`; | |
| 95 | | |
039239d1Vladimir Kotikov9 years ago | 96 | public static WORKER_DONE = `// Notify debugger that we're done with loading |
cc70057dVladimir Kotikov9 years ago | 97 | // and started listening for IPC messages |
| 98 | postMessage({workerLoaded:true});`; | |
| 99 | | |
bb869343Serge Svekolnikov8 years ago | 100 | public static FETCH_STUB = `(function(self) { |
| 101 | 'use strict'; | |
| 102 | | |
| 103 | if (self.fetch) { | |
| 104 | return | |
| 105 | } | |
| 106 | | |
| 107 | self.fetch = fetch; | |
| 108 | | |
| 109 | function fetch(url) { | |
| 110 | return new Promise((resolve, reject) => { | |
| 111 | var data = require("fs").readFileSync(url, 'utf8'); | |
| 112 | resolve( | |
| 113 | { | |
| 114 | text: function () { | |
| 115 | return data; | |
| 116 | } | |
| 117 | }); | |
| 118 | }); | |
| 119 | } | |
| 120 | })(global);`; | |
| 121 | | |
6eeec3c0Serge Svekolnikov8 years ago | 122 | private packagerAddress: string; |
e3ae4227digeff10 years ago | 123 | private packagerPort: number; |
4677921cdigeff10 years ago | 124 | private sourcesStoragePath: string; |
7daed3fcArtem Egorov8 years ago | 125 | private projectRootPath: string; |
6eeec3c0Serge Svekolnikov8 years ago | 126 | private packagerRemoteRoot?: string; |
| 127 | private packagerLocalRoot?: string; | |
ea8a5f88digeff10 years ago | 128 | private socketToApp: WebSocket; |
5c8365a6Artem Egorov8 years ago | 129 | private singleLifetimeWorker: IDebuggeeWorker | null; |
3b6023b2Jimmy Thomson10 years ago | 130 | private webSocketConstructor: (url: string) => WebSocket; |
| 131 | | |
7cc67271digeff10 years ago | 132 | private executionLimiter = new ExecutionsLimiter(); |
cc70057dVladimir Kotikov9 years ago | 133 | private nodeFileSystem = new NodeFileSystem(); |
| 134 | private scriptImporter: ScriptImporter; | |
7cc67271digeff10 years ago | 135 | |
6eeec3c0Serge Svekolnikov8 years ago | 136 | constructor( |
| 137 | attachRequestArguments: any, | |
| 138 | sourcesStoragePath: string, | |
| 139 | projectRootPath: string, | |
| 140 | { | |
| 141 | webSocketConstructor = (url: string) => new WebSocket(url), | |
| 142 | } = {}) { | |
e45838cbVladimir Kotikov9 years ago | 143 | super(); |
6eeec3c0Serge Svekolnikov8 years ago | 144 | this.packagerAddress = attachRequestArguments.address || "localhost"; |
| 145 | this.packagerPort = attachRequestArguments.port; | |
| 146 | this.packagerRemoteRoot = attachRequestArguments.remoteRoot; | |
| 147 | this.packagerLocalRoot = attachRequestArguments.localRoot; | |
4677921cdigeff10 years ago | 148 | this.sourcesStoragePath = sourcesStoragePath; |
7daed3fcArtem Egorov8 years ago | 149 | this.projectRootPath = projectRootPath; |
ea8a5f88digeff10 years ago | 150 | console.assert(!!this.sourcesStoragePath, "The sourcesStoragePath argument was null or empty"); |
3b6023b2Jimmy Thomson10 years ago | 151 | |
| 152 | this.webSocketConstructor = webSocketConstructor; | |
6eeec3c0Serge Svekolnikov8 years ago | 153 | this.scriptImporter = new ScriptImporter(this.packagerAddress, this.packagerPort, sourcesStoragePath, this.packagerRemoteRoot, this.packagerLocalRoot); |
4677921cdigeff10 years ago | 154 | } |
| 155 | | |
cc70057dVladimir Kotikov9 years ago | 156 | public start(retryAttempt: boolean = false): Q.Promise<any> { |
0a68f8dbArtem Egorov8 years ago | 157 | const errPackagerNotRunning = new Error(`Cannot attach to packager. Are you sure there is a packager and it is running in the port ${this.packagerPort}? If your packager is configured to run in another port make sure to add that to the setting.json.`); |
| 158 | | |
6eeec3c0Serge Svekolnikov8 years ago | 159 | return ensurePackagerRunning(this.packagerAddress, this.packagerPort, errPackagerNotRunning) |
cc70057dVladimir Kotikov9 years ago | 160 | .then(() => { |
| 161 | // Don't fetch debugger worker on socket disconnect | |
| 162 | return retryAttempt ? Q.resolve<void>(void 0) : | |
| 163 | this.downloadAndPatchDebuggerWorker(); | |
| 164 | }) | |
| 165 | .then(() => this.createSocketToApp(retryAttempt)); | |
ff7dce65digeff10 years ago | 166 | } |
| 167 | | |
e45838cbVladimir Kotikov9 years ago | 168 | public stop() { |
| 169 | if (this.socketToApp) { | |
| 170 | this.socketToApp.removeAllListeners(); | |
| 171 | this.socketToApp.close(); | |
| 172 | } | |
| 173 | | |
| 174 | if (this.singleLifetimeWorker) { | |
| 175 | this.singleLifetimeWorker.stop(); | |
| 176 | } | |
| 177 | } | |
| 178 | | |
cc70057dVladimir Kotikov9 years ago | 179 | public downloadAndPatchDebuggerWorker(): Q.Promise<void> { |
| 180 | let scriptToRunPath = path.resolve(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILENAME); | |
a1324704Artem Egorov8 years ago | 181 | return this.scriptImporter.downloadDebuggerWorker(this.sourcesStoragePath, this.projectRootPath) |
cc70057dVladimir Kotikov9 years ago | 182 | .then(() => this.nodeFileSystem.readFile(scriptToRunPath, "utf8")) |
| 183 | .then((workerContent: string) => { | |
bb869343Serge Svekolnikov8 years ago | 184 | const isHaulProject = ReactNativeProjectHelper.isHaulProject(this.projectRootPath); |
cc70057dVladimir Kotikov9 years ago | 185 | // Add our customizations to debugger worker to get it working smoothly |
| 186 | // in Node env and polyfill WebWorkers API over Node's IPC. | |
bb869343Serge Svekolnikov8 years ago | 187 | const modifiedDebuggeeContent = [ |
| 188 | MultipleLifetimesAppWorker.WORKER_BOOTSTRAP, | |
| 189 | isHaulProject ? MultipleLifetimesAppWorker.FETCH_STUB : null, | |
| 190 | workerContent, | |
| 191 | MultipleLifetimesAppWorker.WORKER_DONE, | |
| 192 | ].join("\n"); | |
cc70057dVladimir Kotikov9 years ago | 193 | return this.nodeFileSystem.writeFile(scriptToRunPath, modifiedDebuggeeContent); |
| 194 | }); | |
| 195 | } | |
| 196 | | |
ff7dce65digeff10 years ago | 197 | private startNewWorkerLifetime(): Q.Promise<void> { |
6eeec3c0Serge Svekolnikov8 years ago | 198 | this.singleLifetimeWorker = new ForkedAppWorker(this.packagerAddress, this.packagerPort, this.sourcesStoragePath, this.projectRootPath, |
| 199 | (message) => { | |
| 200 | this.sendMessageToApp(message); | |
| 201 | }, | |
| 202 | this.packagerRemoteRoot, this.packagerLocalRoot); | |
0a68f8dbArtem Egorov8 years ago | 203 | logger.verbose("A new app worker lifetime was created."); |
e45838cbVladimir Kotikov9 years ago | 204 | return this.singleLifetimeWorker.start() |
cc70057dVladimir Kotikov9 years ago | 205 | .then(startedEvent => { |
| 206 | this.emit("connected", startedEvent); | |
| 207 | }); | |
4677921cdigeff10 years ago | 208 | } |
| 209 | | |
cc70057dVladimir Kotikov9 years ago | 210 | private createSocketToApp(retryAttempt: boolean = false): Q.Promise<void> { |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 211 | let deferred = Q.defer<void>(); |
6e731058Jimmy Thomson10 years ago | 212 | this.socketToApp = this.webSocketConstructor(this.debuggerProxyUrl()); |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 213 | this.socketToApp.on("open", () => { |
| 214 | this.onSocketOpened(); | |
| 215 | }); | |
299b0557Patricio Beltran10 years ago | 216 | this.socketToApp.on("close", |
| 217 | () => { | |
| 218 | this.executionLimiter.execute("onSocketClose.msg", /*limitInSeconds*/ 10, () => { | |
| 219 | /* | |
| 220 | * It is not the best idea to compare with the message, but this is the only thing React Native gives that is unique when | |
| 221 | * it closes the socket because it already has a connection to a debugger. | |
| 222 | * https://github.com/facebook/react-native/blob/588f01e9982775f0699c7bfd56623d4ed3949810/local-cli/server/util/webSocketProxy.js#L38 | |
| 223 | */ | |
6d5c8798Nikita Matrosov9 years ago | 224 | let msgKey = "_closeMessage"; |
| 225 | if (this.socketToApp[msgKey] === "Another debugger is already connected") { | |
299b0557Patricio Beltran10 years ago | 226 | deferred.reject(new RangeError("Another debugger is already connected to packager. Please close it before trying to debug with VSCode.")); |
| 227 | } | |
0a68f8dbArtem Egorov8 years ago | 228 | logger.log("Disconnected from the Proxy (Packager) to the React Native application. Retrying reconnection soon..."); |
299b0557Patricio Beltran10 years ago | 229 | }); |
| 230 | setTimeout(() => { | |
| 231 | this.start(true /* retryAttempt */); | |
| 232 | }, 100); | |
| 233 | }); | |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 234 | this.socketToApp.on("message", |
ea8a5f88digeff10 years ago | 235 | (message: any) => this.onMessage(message)); |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 236 | this.socketToApp.on("error", |
32cab018Meena Kunnathur Balakrishnan10 years ago | 237 | (error: Error) => { |
cc70057dVladimir Kotikov9 years ago | 238 | if (retryAttempt) { |
0a68f8dbArtem Egorov8 years ago | 239 | printDebuggingError("Reconnection to the proxy (Packager) failed. Please check the output window for Packager errors, if any. If failure persists, please restart the React Native debugger.", error); |
499fe4ebMeena Kunnathur Balakrishnan10 years ago | 240 | } |
| 241 | | |
32cab018Meena Kunnathur Balakrishnan10 years ago | 242 | deferred.reject(error); |
| 243 | }); | |
| 244 | | |
499fe4ebMeena Kunnathur Balakrishnan10 years ago | 245 | // In an attempt to catch failures in starting the packager on first attempt, |
| 246 | // wait for 300 ms before resolving the promise | |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 247 | Q.delay(300).done(() => deferred.resolve(void 0)); |
32cab018Meena Kunnathur Balakrishnan10 years ago | 248 | return deferred.promise; |
4677921cdigeff10 years ago | 249 | } |
| 250 | | |
| 251 | private debuggerProxyUrl() { | |
6eeec3c0Serge Svekolnikov8 years ago | 252 | return `ws://${this.packagerAddress}:${this.packagerPort}/debugger-proxy?role=debugger&name=vscode`; |
4677921cdigeff10 years ago | 253 | } |
| 254 | | |
ea8a5f88digeff10 years ago | 255 | private onSocketOpened() { |
7cc67271digeff10 years ago | 256 | this.executionLimiter.execute("onSocketOpened.msg", /*limitInSeconds*/ 10, () => |
0a68f8dbArtem Egorov8 years ago | 257 | logger.log("Established a connection with the Proxy (Packager) to the React Native application")); |
4677921cdigeff10 years ago | 258 | } |
| 259 | | |
9174feb7Vladimir Kotikov9 years ago | 260 | private killWorker() { |
| 261 | if (!this.singleLifetimeWorker) return; | |
| 262 | this.singleLifetimeWorker.stop(); | |
| 263 | this.singleLifetimeWorker = null; | |
| 264 | } | |
e7b314e8Vladimir Kotikov9 years ago | 265 | |
9174feb7Vladimir Kotikov9 years ago | 266 | private onMessage(message: string) { |
5d4d4de0digeff10 years ago | 267 | try { |
0a68f8dbArtem Egorov8 years ago | 268 | logger.verbose("From RN APP: " + message); |
ea8a5f88digeff10 years ago | 269 | let object = <RNAppMessage>JSON.parse(message); |
5d4d4de0digeff10 years ago | 270 | if (object.method === "prepareJSRuntime") { |
e7b314e8Vladimir Kotikov9 years ago | 271 | // In RN 0.40 Android runtime doesn't seem to be sending "$disconnected" event |
| 272 | // when user reloads an app, hence we need to try to kill it here either. | |
9174feb7Vladimir Kotikov9 years ago | 273 | this.killWorker(); |
5d4d4de0digeff10 years ago | 274 | // The MultipleLifetimesAppWorker will handle prepareJSRuntime aka create new lifetime |
| 275 | this.gotPrepareJSRuntime(object); | |
ff7dce65digeff10 years ago | 276 | } else if (object.method === "$disconnected") { |
| 277 | // We need to shutdown the current app worker, and create a new lifetime | |
9174feb7Vladimir Kotikov9 years ago | 278 | this.killWorker(); |
5d4d4de0digeff10 years ago | 279 | } else if (object.method) { |
| 280 | // All the other messages are handled by the single lifetime worker | |
5c8365a6Artem Egorov8 years ago | 281 | if (this.singleLifetimeWorker) { |
| 282 | this.singleLifetimeWorker.postMessage(object); | |
| 283 | } | |
5d4d4de0digeff10 years ago | 284 | } else { |
ea8a5f88digeff10 years ago | 285 | // Message doesn't have a method. Ignore it. This is an info message instead of warn because it's normal and expected |
0a68f8dbArtem Egorov8 years ago | 286 | logger.verbose("The react-native app sent a message without specifying a method: " + message); |
5d4d4de0digeff10 years ago | 287 | } |
| 288 | } catch (exception) { | |
ce591c62digeff10 years ago | 289 | printDebuggingError(`Failed to process message from the React Native app. Message:\n${message}`, exception); |
4677921cdigeff10 years ago | 290 | } |
| 291 | } | |
| 292 | | |
| 293 | private gotPrepareJSRuntime(message: any): void { | |
| 294 | // Create the sandbox, and replay that we finished processing the message | |
ff7dce65digeff10 years ago | 295 | this.startNewWorkerLifetime().done(() => { |
| 296 | this.sendMessageToApp({ replyID: parseInt(message.id, 10) }); | |
| 297 | }, error => printDebuggingError(`Failed to prepare the JavaScript runtime environment. Message:\n${message}`, error)); | |
4677921cdigeff10 years ago | 298 | } |
| 299 | | |
ff7dce65digeff10 years ago | 300 | private sendMessageToApp(message: any): void { |
5c8365a6Artem Egorov8 years ago | 301 | let stringified: string = ""; |
354c28a1digeff10 years ago | 302 | try { |
| 303 | stringified = JSON.stringify(message); | |
0a68f8dbArtem Egorov8 years ago | 304 | logger.verbose("To RN APP: " + stringified); |
354c28a1digeff10 years ago | 305 | this.socketToApp.send(stringified); |
| 306 | } catch (exception) { | |
| 307 | let messageToShow = stringified || ("" + message); // Try to show the stringified version, but show the toString if unavailable | |
ce591c62digeff10 years ago | 308 | printDebuggingError(`Failed to send message to the React Native app. Message:\n${messageToShow}`, exception); |
354c28a1digeff10 years ago | 309 | } |
4677921cdigeff10 years ago | 310 | } |
| 311 | } |