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 vm from "vm"; |
| 5 | import * as Q from "q"; | |
| 6 | import * as path from "path"; | |
ea8a5f88digeff10 years ago | 7 | import * as WebSocket from "ws"; |
4677921cdigeff10 years ago | 8 | import {ScriptImporter} from "./scriptImporter"; |
b0061ac6Meena Kunnathur Balakrishnan10 years ago | 9 | import {Packager} from "../common/packager"; |
a4a7e387Meena Kunnathur Balakrishnan10 years ago | 10 | import {ErrorHelper} from "../common/error/errorHelper"; |
190e393cMeena Kunnathur Balakrishnan10 years ago | 11 | import {Log} from "../common/log/log"; |
| 12 | import {LogLevel} from "../common/log/logHelper"; | |
3b6023b2Jimmy Thomson10 years ago | 13 | import {FileSystem} from "../common/node/fileSystem"; |
7cc67271digeff10 years ago | 14 | import {ExecutionsLimiter} from "../common/executionsLimiter"; |
4677921cdigeff10 years ago | 15 | |
| 16 | import Module = require("module"); | |
| 17 | | |
| 18 | // This file is a replacement of: https://github.com/facebook/react-native/blob/8d397b4cbc05ad801cfafb421cee39bcfe89711d/local-cli/server/util/debugger.html for Node.JS | |
| 19 | interface DebuggerWorkerSandbox { | |
| 20 | __filename: string; | |
| 21 | __dirname: string; | |
| 22 | self: DebuggerWorkerSandbox; | |
ea8a5f88digeff10 years ago | 23 | console: typeof console; |
| 24 | require: (id: string) => any; | |
4677921cdigeff10 years ago | 25 | importScripts: (url: string) => void; |
| 26 | postMessage: (object: any) => void; | |
ea8a5f88digeff10 years ago | 27 | onmessage: (object: RNAppMessage) => void; |
| 28 | postMessageArgument: RNAppMessage; // We use this argument to pass messages to the worker | |
4677921cdigeff10 years ago | 29 | } |
| 30 | | |
ea8a5f88digeff10 years ago | 31 | interface RNAppMessage { |
| 32 | method: string; | |
| 33 | // These objects have also other properties but that we don't currently use | |
| 34 | } | |
5d4d4de0digeff10 years ago | 35 | |
ce591c62digeff10 years ago | 36 | function printDebuggingError(message: string, reason: any) { |
a4a7e387Meena Kunnathur Balakrishnan10 years ago | 37 | Log.logWarning(ErrorHelper.getNestedWarning(reason, `${message}. Debugging won't work: Try reloading the JS from inside the app, or Reconnect the VS Code debugger`)); |
5d4d4de0digeff10 years ago | 38 | } |
| 39 | | |
4677921cdigeff10 years ago | 40 | export class SandboxedAppWorker { |
ea8a5f88digeff10 years ago | 41 | /** This class will run the RN App logic inside a sandbox. The framework to run the logic is provided by the file |
| 42 | * debuggerWorker.js (designed to run on a WebWorker). We load that file inside a sandbox, and then we use the | |
| 43 | * PROCESS_MESSAGE_INSIDE_SANDBOX script to execute the logic to respond to a message inside the sandbox. | |
| 44 | * The code inside the debuggerWorker.js will call the global function postMessage to send a reply back to the app, | |
| 45 | * so we define our custom function there, so we can handle the message. We also provide our own importScript function | |
| 46 | * to download any script used by debuggerWorker.js | |
| 47 | */ | |
4677921cdigeff10 years ago | 48 | private sourcesStoragePath: string; |
5547a16fJimmy Thomson10 years ago | 49 | private debugAdapterPort: number; |
4677921cdigeff10 years ago | 50 | private postReplyToApp: (message: any) => void; |
| 51 | | |
| 52 | private sandbox: DebuggerWorkerSandbox; | |
| 53 | private sandboxContext: vm.Context; | |
ea8a5f88digeff10 years ago | 54 | private scriptToReceiveMessageInSandbox: vm.Script; |
4677921cdigeff10 years ago | 55 | |
5d4d4de0digeff10 years ago | 56 | private pendingScriptImport = Q(void 0); |
4677921cdigeff10 years ago | 57 | |
3b6023b2Jimmy Thomson10 years ago | 58 | private nodeFileSystem: FileSystem; |
| 59 | private scriptImporter: ScriptImporter; | |
| 60 | | |
ea8a5f88digeff10 years ago | 61 | private static PROCESS_MESSAGE_INSIDE_SANDBOX = "onmessage({ data: postMessageArgument });"; |
| 62 | | |
3b6023b2Jimmy Thomson10 years ago | 63 | constructor(sourcesStoragePath: string, debugAdapterPort: number, postReplyToApp: (message: any) => void, { |
| 64 | nodeFileSystem = new FileSystem(), | |
cdf34447digeff10 years ago | 65 | scriptImporter = new ScriptImporter(sourcesStoragePath), |
3b6023b2Jimmy Thomson10 years ago | 66 | } = {}) { |
4677921cdigeff10 years ago | 67 | this.sourcesStoragePath = sourcesStoragePath; |
2570720bJimmy Thomson10 years ago | 68 | this.debugAdapterPort = debugAdapterPort; |
4677921cdigeff10 years ago | 69 | this.postReplyToApp = postReplyToApp; |
ea8a5f88digeff10 years ago | 70 | this.scriptToReceiveMessageInSandbox = new vm.Script(SandboxedAppWorker.PROCESS_MESSAGE_INSIDE_SANDBOX); |
3b6023b2Jimmy Thomson10 years ago | 71 | |
| 72 | this.nodeFileSystem = nodeFileSystem; | |
| 73 | this.scriptImporter = scriptImporter; | |
4677921cdigeff10 years ago | 74 | } |
| 75 | | |
5d4d4de0digeff10 years ago | 76 | public start(): Q.Promise<void> { |
2743f19cdlebu10 years ago | 77 | let scriptToRunPath = require.resolve(path.join(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILE_BASENAME)); |
4677921cdigeff10 years ago | 78 | this.initializeSandboxAndContext(scriptToRunPath); |
5d4d4de0digeff10 years ago | 79 | return this.readFileContents(scriptToRunPath).then(fileContents => |
| 80 | // On a debugger worker the onmessage variable already exist. We need to declare it before the | |
| 81 | // javascript file can assign it. We do it in the first line without a new line to not break | |
| 82 | // the debugging experience of debugging debuggerWorker.js itself (as part of the extension) | |
| 83 | this.runInSandbox(scriptToRunPath, "var onmessage = null; " + fileContents)); | |
4677921cdigeff10 years ago | 84 | } |
| 85 | | |
ea8a5f88digeff10 years ago | 86 | public postMessage(object: RNAppMessage): void { |
| 87 | this.sandbox.postMessageArgument = object; | |
| 88 | this.scriptToReceiveMessageInSandbox.runInContext(this.sandboxContext); | |
4677921cdigeff10 years ago | 89 | } |
| 90 | | |
| 91 | private initializeSandboxAndContext(scriptToRunPath: string): void { | |
| 92 | let scriptToRunModule = new Module(scriptToRunPath); | |
| 93 | | |
| 94 | this.sandbox = { | |
| 95 | __filename: scriptToRunPath, | |
| 96 | __dirname: path.dirname(scriptToRunPath), | |
| 97 | self: null, | |
| 98 | console: console, | |
| 99 | require: (filePath: string) => scriptToRunModule.require(filePath), // Give the sandbox access to require("<filePath>"); | |
| 100 | importScripts: (url: string) => this.importScripts(url), // Import script like using <script/> | |
| 101 | postMessage: (object: any) => this.gotResponseFromDebuggerWorker(object), // Post message back to the UI thread | |
ea8a5f88digeff10 years ago | 102 | onmessage: null, |
cdf34447digeff10 years ago | 103 | postMessageArgument: null, |
4677921cdigeff10 years ago | 104 | }; |
| 105 | this.sandbox.self = this.sandbox; | |
| 106 | | |
| 107 | this.sandboxContext = vm.createContext(this.sandbox); | |
| 108 | } | |
| 109 | | |
b3a793eeNisheet Jain10 years ago | 110 | private runInSandbox(filename: string, fileContents?: string): Q.Promise<void> { |
| 111 | let fileContentsPromise = fileContents | |
| 112 | ? Q(fileContents) | |
| 113 | : this.readFileContents(filename); | |
| 114 | | |
| 115 | return fileContentsPromise.then(contents => { | |
| 116 | vm.runInContext(contents, this.sandboxContext, filename); | |
| 117 | }); | |
| 118 | } | |
| 119 | | |
| 120 | private readFileContents(filename: string) { | |
3b6023b2Jimmy Thomson10 years ago | 121 | return this.nodeFileSystem.readFile(filename).then(contents => contents.toString()); |
b3a793eeNisheet Jain10 years ago | 122 | } |
| 123 | | |
4677921cdigeff10 years ago | 124 | private importScripts(url: string): void { |
5d4d4de0digeff10 years ago | 125 | /* The debuggerWorker.js executes this code: |
| 126 | importScripts(message.url); | |
| 127 | sendReply(); | |
| 128 | | |
| 129 | In the original code importScripts is a sync call. In our code it's async, so we need to mess with sendReply() so we won't | |
| 130 | actually send the reply back to the application until after importScripts has finished executing. We use | |
| 131 | this.pendingScriptImport to make the gotResponseFromDebuggerWorker() method hold the reply back, until've finished importing | |
| 132 | and running the script */ | |
4677921cdigeff10 years ago | 133 | let defer = Q.defer<{}>(); |
5d4d4de0digeff10 years ago | 134 | this.pendingScriptImport = defer.promise; |
4677921cdigeff10 years ago | 135 | |
| 136 | // The next line converts to any due to the incorrect typing on node.d.ts of vm.runInThisContext | |
3b6023b2Jimmy Thomson10 years ago | 137 | this.scriptImporter.downloadAppScript(url, this.debugAdapterPort) |
4677921cdigeff10 years ago | 138 | .then(downloadedScript => |
| 139 | this.runInSandbox(downloadedScript.filepath, downloadedScript.contents)) | |
5d4d4de0digeff10 years ago | 140 | .done(() => { |
9d7db611digeff10 years ago | 141 | // Now we let the reply to the app proceed |
| 142 | defer.resolve({}); | |
| 143 | }, reason => { | |
ce591c62digeff10 years ago | 144 | printDebuggingError(`Couldn't import script at <${url}>`, reason); |
9d7db611digeff10 years ago | 145 | }); |
4677921cdigeff10 years ago | 146 | } |
| 147 | | |
| 148 | private gotResponseFromDebuggerWorker(object: any): void { | |
5d4d4de0digeff10 years ago | 149 | // We might need to hold the response until a script is imported. See comments on this.importScripts() |
| 150 | this.pendingScriptImport.done(() => | |
10873e11digeff10 years ago | 151 | this.postReplyToApp(object), reason => { |
ce591c62digeff10 years ago | 152 | printDebuggingError("Unexpected internal error while processing a message from the RN App.", reason); |
10873e11digeff10 years ago | 153 | }); |
4677921cdigeff10 years ago | 154 | } |
| 155 | } | |
| 156 | | |
| 157 | export class MultipleLifetimesAppWorker { | |
ea8a5f88digeff10 years ago | 158 | /** This class will create a SandboxedAppWorker that will run the RN App logic, and then create a socket |
| 159 | * and send the RN App messages to the SandboxedAppWorker. The only RN App message that this class handles | |
80002087Joshua Skelton10 years ago | 160 | * is the prepareJSRuntime, which we reply to the RN App that the sandbox was created successfully. |
ea8a5f88digeff10 years ago | 161 | * When the socket closes, we'll create a new SandboxedAppWorker and a new socket pair and discard the old ones. |
| 162 | */ | |
4677921cdigeff10 years ago | 163 | private sourcesStoragePath: string; |
5547a16fJimmy Thomson10 years ago | 164 | private debugAdapterPort: number; |
ea8a5f88digeff10 years ago | 165 | private socketToApp: WebSocket; |
4677921cdigeff10 years ago | 166 | private singleLifetimeWorker: SandboxedAppWorker; |
| 167 | | |
3b6023b2Jimmy Thomson10 years ago | 168 | private sandboxedAppConstructor: (storagePath: string, adapterPort: number, messageFunction: (message: any) => void) => SandboxedAppWorker; |
| 169 | private webSocketConstructor: (url: string) => WebSocket; | |
| 170 | | |
7cc67271digeff10 years ago | 171 | private executionLimiter = new ExecutionsLimiter(); |
| 172 | | |
3b6023b2Jimmy Thomson10 years ago | 173 | constructor(sourcesStoragePath: string, debugAdapterPort: number, { |
| 174 | sandboxedAppConstructor = (path: string, port: number, messageFunc: (message: any) => void) => new SandboxedAppWorker(path, port, messageFunc), | |
cdf34447digeff10 years ago | 175 | webSocketConstructor = (url: string) => new WebSocket(url), |
3b6023b2Jimmy Thomson10 years ago | 176 | } = {}) { |
4677921cdigeff10 years ago | 177 | this.sourcesStoragePath = sourcesStoragePath; |
5547a16fJimmy Thomson10 years ago | 178 | this.debugAdapterPort = debugAdapterPort; |
ea8a5f88digeff10 years ago | 179 | console.assert(!!this.sourcesStoragePath, "The sourcesStoragePath argument was null or empty"); |
3b6023b2Jimmy Thomson10 years ago | 180 | |
| 181 | this.sandboxedAppConstructor = sandboxedAppConstructor; | |
| 182 | this.webSocketConstructor = webSocketConstructor; | |
4677921cdigeff10 years ago | 183 | } |
| 184 | | |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 185 | public start(warnOnFailure: boolean = false): Q.Promise<any> { |
| 186 | return this.createSocketToApp(warnOnFailure); | |
ff7dce65digeff10 years ago | 187 | } |
| 188 | | |
| 189 | private startNewWorkerLifetime(): Q.Promise<void> { | |
3b6023b2Jimmy Thomson10 years ago | 190 | this.singleLifetimeWorker = this.sandboxedAppConstructor(this.sourcesStoragePath, this.debugAdapterPort, (message) => { |
5d4d4de0digeff10 years ago | 191 | this.sendMessageToApp(message); |
| 192 | }); | |
ff7dce65digeff10 years ago | 193 | Log.logInternalMessage(LogLevel.Info, "A new app worker lifetime was created."); |
| 194 | return this.singleLifetimeWorker.start(); | |
4677921cdigeff10 years ago | 195 | } |
| 196 | | |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 197 | private createSocketToApp(warnOnFailure: boolean = false): Q.Promise<void> { |
| 198 | let deferred = Q.defer<void>(); | |
6e731058Jimmy Thomson10 years ago | 199 | this.socketToApp = this.webSocketConstructor(this.debuggerProxyUrl()); |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 200 | this.socketToApp.on("open", () => { |
| 201 | this.onSocketOpened(); | |
| 202 | }); | |
| 203 | this.socketToApp.on("close", () => | |
ea8a5f88digeff10 years ago | 204 | this.onSocketClose()); |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 205 | this.socketToApp.on("message", |
ea8a5f88digeff10 years ago | 206 | (message: any) => this.onMessage(message)); |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 207 | this.socketToApp.on("error", |
32cab018Meena Kunnathur Balakrishnan10 years ago | 208 | (error: Error) => { |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 209 | if (warnOnFailure) { |
| 210 | Log.logWarning(ErrorHelper.getNestedWarning(error, | |
| 211 | "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 | 212 | } |
| 213 | | |
32cab018Meena Kunnathur Balakrishnan10 years ago | 214 | deferred.reject(error); |
| 215 | }); | |
| 216 | | |
499fe4ebMeena Kunnathur Balakrishnan10 years ago | 217 | // In an attempt to catch failures in starting the packager on first attempt, |
| 218 | // wait for 300 ms before resolving the promise | |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 219 | Q.delay(300).done(() => deferred.resolve(void 0)); |
32cab018Meena Kunnathur Balakrishnan10 years ago | 220 | return deferred.promise; |
4677921cdigeff10 years ago | 221 | } |
| 222 | | |
| 223 | private debuggerProxyUrl() { | |
f158bbd1Atticus White10 years ago | 224 | return `ws://${Packager.HOST}/debugger-proxy?role=debugger&name=vscode`; |
4677921cdigeff10 years ago | 225 | } |
| 226 | | |
ea8a5f88digeff10 years ago | 227 | private onSocketOpened() { |
7cc67271digeff10 years ago | 228 | this.executionLimiter.execute("onSocketOpened.msg", /*limitInSeconds*/ 10, () => |
| 229 | Log.logMessage("Established a connection with the Proxy (Packager) to the React Native application")); | |
4677921cdigeff10 years ago | 230 | } |
| 231 | | |
ea8a5f88digeff10 years ago | 232 | private onSocketClose() { |
7cc67271digeff10 years ago | 233 | this.executionLimiter.execute("onSocketClose.msg", /*limitInSeconds*/ 10, () => |
| 234 | Log.logMessage("Disconnected from the Proxy (Packager) to the React Native application. Retrying reconnection soon...")); | |
499fe4ebMeena Kunnathur Balakrishnan10 years ago | 235 | setTimeout(() => this.start(true /* retryAttempt */), 100); |
4677921cdigeff10 years ago | 236 | } |
| 237 | | |
ea8a5f88digeff10 years ago | 238 | private onMessage(message: string) { |
5d4d4de0digeff10 years ago | 239 | try { |
ea8a5f88digeff10 years ago | 240 | Log.logInternalMessage(LogLevel.Trace, "From RN APP: " + message); |
| 241 | let object = <RNAppMessage>JSON.parse(message); | |
5d4d4de0digeff10 years ago | 242 | if (object.method === "prepareJSRuntime") { |
| 243 | // The MultipleLifetimesAppWorker will handle prepareJSRuntime aka create new lifetime | |
| 244 | this.gotPrepareJSRuntime(object); | |
ff7dce65digeff10 years ago | 245 | } else if (object.method === "$disconnected") { |
| 246 | // We need to shutdown the current app worker, and create a new lifetime | |
| 247 | this.singleLifetimeWorker = null; | |
5d4d4de0digeff10 years ago | 248 | } else if (object.method) { |
| 249 | // All the other messages are handled by the single lifetime worker | |
| 250 | this.singleLifetimeWorker.postMessage(object); | |
| 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 |
| 253 | Log.logInternalMessage(LogLevel.Info, "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 { |
354c28a1digeff10 years ago | 268 | let stringified: string = null; |
| 269 | try { | |
| 270 | stringified = JSON.stringify(message); | |
| 271 | Log.logInternalMessage(LogLevel.Trace, "To RN APP: " + stringified); | |
| 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 | } |