microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/debugger/appWorker.ts
316lines · 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 | }); | |
0864d702Ruslan Bikkinin7 years ago | 54 | // Prevent leaking process.versions from debugger process to |
| 55 | // worker because pure React Native doesn't do that and some packages as js-md5 rely on this behavior | |
| 56 | Object.defineProperty(process, "versions", { | |
| 57 | value: undefined | |
| 58 | }); | |
7daed3fcArtem Egorov8 years ago | 59 | |
| 60 | var vscodeHandlers = { | |
| 61 | 'vscode_reloadApp': function () { | |
| 62 | try { | |
| 63 | global.require('NativeModules').DevMenu.reload(); | |
| 64 | } catch (err) { | |
| 65 | // ignore | |
| 66 | } | |
| 67 | }, | |
| 68 | 'vscode_showDevMenu': function () { | |
| 69 | try { | |
| 70 | var DevMenu = global.require('NativeModules').DevMenu.show(); | |
| 71 | } catch (err) { | |
| 72 | // ignore | |
| 73 | } | |
| 74 | } | |
| 75 | }; | |
| 76 | | |
| 77 | process.on("message", function (message) { | |
| 78 | if (message.data && vscodeHandlers[message.data.method]) { | |
| 79 | vscodeHandlers[message.data.method](); | |
| 80 | } else if(onmessage) { | |
| 81 | onmessage(message); | |
| 82 | } | |
cc70057dVladimir Kotikov9 years ago | 83 | }); |
7daed3fcArtem Egorov8 years ago | 84 | |
cc70057dVladimir Kotikov9 years ago | 85 | var postMessage = function(message){ |
| 86 | process.send(message); | |
| 87 | }; | |
bb869343Serge Svekolnikov8 years ago | 88 | |
| 89 | if (!self.postMessage) { | |
| 90 | self.postMessage = postMessage; | |
| 91 | } | |
| 92 | | |
cc70057dVladimir Kotikov9 years ago | 93 | var importScripts = (function(){ |
| 94 | var fs=require('fs'), vm=require('vm'); | |
| 95 | return function(scriptUrl){ | |
| 96 | var scriptCode = fs.readFileSync(scriptUrl, "utf8"); | |
| 97 | vm.runInThisContext(scriptCode, {filename: scriptUrl}); | |
| 98 | }; | |
| 99 | })();`; | |
| 100 | | |
039239d1Vladimir Kotikov9 years ago | 101 | public static WORKER_DONE = `// Notify debugger that we're done with loading |
cc70057dVladimir Kotikov9 years ago | 102 | // and started listening for IPC messages |
| 103 | postMessage({workerLoaded:true});`; | |
| 104 | | |
bb869343Serge Svekolnikov8 years ago | 105 | public static FETCH_STUB = `(function(self) { |
| 106 | 'use strict'; | |
| 107 | | |
| 108 | if (self.fetch) { | |
| 109 | return | |
| 110 | } | |
| 111 | | |
| 112 | self.fetch = fetch; | |
| 113 | | |
| 114 | function fetch(url) { | |
| 115 | return new Promise((resolve, reject) => { | |
| 116 | var data = require("fs").readFileSync(url, 'utf8'); | |
| 117 | resolve( | |
| 118 | { | |
| 119 | text: function () { | |
| 120 | return data; | |
| 121 | } | |
| 122 | }); | |
| 123 | }); | |
| 124 | } | |
| 125 | })(global);`; | |
| 126 | | |
6eeec3c0Serge Svekolnikov8 years ago | 127 | private packagerAddress: string; |
e3ae4227digeff10 years ago | 128 | private packagerPort: number; |
4677921cdigeff10 years ago | 129 | private sourcesStoragePath: string; |
7daed3fcArtem Egorov8 years ago | 130 | private projectRootPath: string; |
6eeec3c0Serge Svekolnikov8 years ago | 131 | private packagerRemoteRoot?: string; |
| 132 | private packagerLocalRoot?: string; | |
ea8a5f88digeff10 years ago | 133 | private socketToApp: WebSocket; |
5c8365a6Artem Egorov8 years ago | 134 | private singleLifetimeWorker: IDebuggeeWorker | null; |
3b6023b2Jimmy Thomson10 years ago | 135 | private webSocketConstructor: (url: string) => WebSocket; |
| 136 | | |
7cc67271digeff10 years ago | 137 | private executionLimiter = new ExecutionsLimiter(); |
cc70057dVladimir Kotikov9 years ago | 138 | private nodeFileSystem = new NodeFileSystem(); |
| 139 | private scriptImporter: ScriptImporter; | |
7cc67271digeff10 years ago | 140 | |
6eeec3c0Serge Svekolnikov8 years ago | 141 | constructor( |
| 142 | attachRequestArguments: any, | |
| 143 | sourcesStoragePath: string, | |
| 144 | projectRootPath: string, | |
| 145 | { | |
| 146 | webSocketConstructor = (url: string) => new WebSocket(url), | |
| 147 | } = {}) { | |
e45838cbVladimir Kotikov9 years ago | 148 | super(); |
6eeec3c0Serge Svekolnikov8 years ago | 149 | this.packagerAddress = attachRequestArguments.address || "localhost"; |
| 150 | this.packagerPort = attachRequestArguments.port; | |
| 151 | this.packagerRemoteRoot = attachRequestArguments.remoteRoot; | |
| 152 | this.packagerLocalRoot = attachRequestArguments.localRoot; | |
4677921cdigeff10 years ago | 153 | this.sourcesStoragePath = sourcesStoragePath; |
7daed3fcArtem Egorov8 years ago | 154 | this.projectRootPath = projectRootPath; |
ea8a5f88digeff10 years ago | 155 | console.assert(!!this.sourcesStoragePath, "The sourcesStoragePath argument was null or empty"); |
3b6023b2Jimmy Thomson10 years ago | 156 | |
| 157 | this.webSocketConstructor = webSocketConstructor; | |
6eeec3c0Serge Svekolnikov8 years ago | 158 | this.scriptImporter = new ScriptImporter(this.packagerAddress, this.packagerPort, sourcesStoragePath, this.packagerRemoteRoot, this.packagerLocalRoot); |
4677921cdigeff10 years ago | 159 | } |
| 160 | | |
cc70057dVladimir Kotikov9 years ago | 161 | public start(retryAttempt: boolean = false): Q.Promise<any> { |
0a68f8dbArtem Egorov8 years ago | 162 | 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.`); |
| 163 | | |
6eeec3c0Serge Svekolnikov8 years ago | 164 | return ensurePackagerRunning(this.packagerAddress, this.packagerPort, errPackagerNotRunning) |
cc70057dVladimir Kotikov9 years ago | 165 | .then(() => { |
| 166 | // Don't fetch debugger worker on socket disconnect | |
| 167 | return retryAttempt ? Q.resolve<void>(void 0) : | |
| 168 | this.downloadAndPatchDebuggerWorker(); | |
| 169 | }) | |
| 170 | .then(() => this.createSocketToApp(retryAttempt)); | |
ff7dce65digeff10 years ago | 171 | } |
| 172 | | |
e45838cbVladimir Kotikov9 years ago | 173 | public stop() { |
| 174 | if (this.socketToApp) { | |
| 175 | this.socketToApp.removeAllListeners(); | |
| 176 | this.socketToApp.close(); | |
| 177 | } | |
| 178 | | |
| 179 | if (this.singleLifetimeWorker) { | |
| 180 | this.singleLifetimeWorker.stop(); | |
| 181 | } | |
| 182 | } | |
| 183 | | |
cc70057dVladimir Kotikov9 years ago | 184 | public downloadAndPatchDebuggerWorker(): Q.Promise<void> { |
| 185 | let scriptToRunPath = path.resolve(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILENAME); | |
a1324704Artem Egorov8 years ago | 186 | return this.scriptImporter.downloadDebuggerWorker(this.sourcesStoragePath, this.projectRootPath) |
cc70057dVladimir Kotikov9 years ago | 187 | .then(() => this.nodeFileSystem.readFile(scriptToRunPath, "utf8")) |
| 188 | .then((workerContent: string) => { | |
bb869343Serge Svekolnikov8 years ago | 189 | const isHaulProject = ReactNativeProjectHelper.isHaulProject(this.projectRootPath); |
cc70057dVladimir Kotikov9 years ago | 190 | // Add our customizations to debugger worker to get it working smoothly |
| 191 | // in Node env and polyfill WebWorkers API over Node's IPC. | |
bb869343Serge Svekolnikov8 years ago | 192 | const modifiedDebuggeeContent = [ |
| 193 | MultipleLifetimesAppWorker.WORKER_BOOTSTRAP, | |
| 194 | isHaulProject ? MultipleLifetimesAppWorker.FETCH_STUB : null, | |
| 195 | workerContent, | |
| 196 | MultipleLifetimesAppWorker.WORKER_DONE, | |
| 197 | ].join("\n"); | |
cc70057dVladimir Kotikov9 years ago | 198 | return this.nodeFileSystem.writeFile(scriptToRunPath, modifiedDebuggeeContent); |
| 199 | }); | |
| 200 | } | |
| 201 | | |
ff7dce65digeff10 years ago | 202 | private startNewWorkerLifetime(): Q.Promise<void> { |
6eeec3c0Serge Svekolnikov8 years ago | 203 | this.singleLifetimeWorker = new ForkedAppWorker(this.packagerAddress, this.packagerPort, this.sourcesStoragePath, this.projectRootPath, |
| 204 | (message) => { | |
| 205 | this.sendMessageToApp(message); | |
| 206 | }, | |
| 207 | this.packagerRemoteRoot, this.packagerLocalRoot); | |
0a68f8dbArtem Egorov8 years ago | 208 | logger.verbose("A new app worker lifetime was created."); |
e45838cbVladimir Kotikov9 years ago | 209 | return this.singleLifetimeWorker.start() |
cc70057dVladimir Kotikov9 years ago | 210 | .then(startedEvent => { |
| 211 | this.emit("connected", startedEvent); | |
| 212 | }); | |
4677921cdigeff10 years ago | 213 | } |
| 214 | | |
cc70057dVladimir Kotikov9 years ago | 215 | private createSocketToApp(retryAttempt: boolean = false): Q.Promise<void> { |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 216 | let deferred = Q.defer<void>(); |
6e731058Jimmy Thomson10 years ago | 217 | this.socketToApp = this.webSocketConstructor(this.debuggerProxyUrl()); |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 218 | this.socketToApp.on("open", () => { |
| 219 | this.onSocketOpened(); | |
| 220 | }); | |
299b0557Patricio Beltran10 years ago | 221 | this.socketToApp.on("close", |
| 222 | () => { | |
| 223 | this.executionLimiter.execute("onSocketClose.msg", /*limitInSeconds*/ 10, () => { | |
| 224 | /* | |
| 225 | * It is not the best idea to compare with the message, but this is the only thing React Native gives that is unique when | |
| 226 | * it closes the socket because it already has a connection to a debugger. | |
| 227 | * https://github.com/facebook/react-native/blob/588f01e9982775f0699c7bfd56623d4ed3949810/local-cli/server/util/webSocketProxy.js#L38 | |
| 228 | */ | |
6d5c8798Nikita Matrosov9 years ago | 229 | let msgKey = "_closeMessage"; |
| 230 | if (this.socketToApp[msgKey] === "Another debugger is already connected") { | |
299b0557Patricio Beltran10 years ago | 231 | deferred.reject(new RangeError("Another debugger is already connected to packager. Please close it before trying to debug with VSCode.")); |
| 232 | } | |
0a68f8dbArtem Egorov8 years ago | 233 | logger.log("Disconnected from the Proxy (Packager) to the React Native application. Retrying reconnection soon..."); |
299b0557Patricio Beltran10 years ago | 234 | }); |
| 235 | setTimeout(() => { | |
| 236 | this.start(true /* retryAttempt */); | |
| 237 | }, 100); | |
| 238 | }); | |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 239 | this.socketToApp.on("message", |
ea8a5f88digeff10 years ago | 240 | (message: any) => this.onMessage(message)); |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 241 | this.socketToApp.on("error", |
32cab018Meena Kunnathur Balakrishnan10 years ago | 242 | (error: Error) => { |
cc70057dVladimir Kotikov9 years ago | 243 | if (retryAttempt) { |
0a68f8dbArtem Egorov8 years ago | 244 | 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 | 245 | } |
| 246 | | |
32cab018Meena Kunnathur Balakrishnan10 years ago | 247 | deferred.reject(error); |
| 248 | }); | |
| 249 | | |
499fe4ebMeena Kunnathur Balakrishnan10 years ago | 250 | // In an attempt to catch failures in starting the packager on first attempt, |
| 251 | // wait for 300 ms before resolving the promise | |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 252 | Q.delay(300).done(() => deferred.resolve(void 0)); |
32cab018Meena Kunnathur Balakrishnan10 years ago | 253 | return deferred.promise; |
4677921cdigeff10 years ago | 254 | } |
| 255 | | |
| 256 | private debuggerProxyUrl() { | |
6eeec3c0Serge Svekolnikov8 years ago | 257 | return `ws://${this.packagerAddress}:${this.packagerPort}/debugger-proxy?role=debugger&name=vscode`; |
4677921cdigeff10 years ago | 258 | } |
| 259 | | |
ea8a5f88digeff10 years ago | 260 | private onSocketOpened() { |
7cc67271digeff10 years ago | 261 | this.executionLimiter.execute("onSocketOpened.msg", /*limitInSeconds*/ 10, () => |
0a68f8dbArtem Egorov8 years ago | 262 | logger.log("Established a connection with the Proxy (Packager) to the React Native application")); |
4677921cdigeff10 years ago | 263 | } |
| 264 | | |
9174feb7Vladimir Kotikov9 years ago | 265 | private killWorker() { |
| 266 | if (!this.singleLifetimeWorker) return; | |
| 267 | this.singleLifetimeWorker.stop(); | |
| 268 | this.singleLifetimeWorker = null; | |
| 269 | } | |
e7b314e8Vladimir Kotikov9 years ago | 270 | |
9174feb7Vladimir Kotikov9 years ago | 271 | private onMessage(message: string) { |
5d4d4de0digeff10 years ago | 272 | try { |
0a68f8dbArtem Egorov8 years ago | 273 | logger.verbose("From RN APP: " + message); |
ea8a5f88digeff10 years ago | 274 | let object = <RNAppMessage>JSON.parse(message); |
5d4d4de0digeff10 years ago | 275 | if (object.method === "prepareJSRuntime") { |
e7b314e8Vladimir Kotikov9 years ago | 276 | // In RN 0.40 Android runtime doesn't seem to be sending "$disconnected" event |
| 277 | // when user reloads an app, hence we need to try to kill it here either. | |
9174feb7Vladimir Kotikov9 years ago | 278 | this.killWorker(); |
5d4d4de0digeff10 years ago | 279 | // The MultipleLifetimesAppWorker will handle prepareJSRuntime aka create new lifetime |
| 280 | this.gotPrepareJSRuntime(object); | |
ff7dce65digeff10 years ago | 281 | } else if (object.method === "$disconnected") { |
| 282 | // We need to shutdown the current app worker, and create a new lifetime | |
9174feb7Vladimir Kotikov9 years ago | 283 | this.killWorker(); |
5d4d4de0digeff10 years ago | 284 | } else if (object.method) { |
| 285 | // All the other messages are handled by the single lifetime worker | |
5c8365a6Artem Egorov8 years ago | 286 | if (this.singleLifetimeWorker) { |
| 287 | this.singleLifetimeWorker.postMessage(object); | |
| 288 | } | |
5d4d4de0digeff10 years ago | 289 | } else { |
ea8a5f88digeff10 years ago | 290 | // 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 | 291 | logger.verbose("The react-native app sent a message without specifying a method: " + message); |
5d4d4de0digeff10 years ago | 292 | } |
| 293 | } catch (exception) { | |
ce591c62digeff10 years ago | 294 | printDebuggingError(`Failed to process message from the React Native app. Message:\n${message}`, exception); |
4677921cdigeff10 years ago | 295 | } |
| 296 | } | |
| 297 | | |
| 298 | private gotPrepareJSRuntime(message: any): void { | |
| 299 | // Create the sandbox, and replay that we finished processing the message | |
ff7dce65digeff10 years ago | 300 | this.startNewWorkerLifetime().done(() => { |
| 301 | this.sendMessageToApp({ replyID: parseInt(message.id, 10) }); | |
| 302 | }, error => printDebuggingError(`Failed to prepare the JavaScript runtime environment. Message:\n${message}`, error)); | |
4677921cdigeff10 years ago | 303 | } |
| 304 | | |
ff7dce65digeff10 years ago | 305 | private sendMessageToApp(message: any): void { |
5c8365a6Artem Egorov8 years ago | 306 | let stringified: string = ""; |
354c28a1digeff10 years ago | 307 | try { |
| 308 | stringified = JSON.stringify(message); | |
0a68f8dbArtem Egorov8 years ago | 309 | logger.verbose("To RN APP: " + stringified); |
354c28a1digeff10 years ago | 310 | this.socketToApp.send(stringified); |
| 311 | } catch (exception) { | |
| 312 | let messageToShow = stringified || ("" + message); // Try to show the stringified version, but show the toString if unavailable | |
ce591c62digeff10 years ago | 313 | printDebuggingError(`Failed to send message to the React Native app. Message:\n${messageToShow}`, exception); |
354c28a1digeff10 years ago | 314 | } |
4677921cdigeff10 years ago | 315 | } |
| 316 | } |