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