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