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