microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/debugger/appWorker.ts
234lines · 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"; |
| 10 | import {Log, LogLevel} from "../common/log"; | |
| 11 | import {Node} from "../common/node/node"; | |
4677921cdigeff10 years ago | 12 | |
| 13 | import Module = require("module"); | |
| 14 | | |
| 15 | // This file is a replacement of: https://github.com/facebook/react-native/blob/8d397b4cbc05ad801cfafb421cee39bcfe89711d/local-cli/server/util/debugger.html for Node.JS | |
| 16 | | |
| 17 | interface DebuggerWorkerSandbox { | |
| 18 | __filename: string; | |
| 19 | __dirname: string; | |
| 20 | self: DebuggerWorkerSandbox; | |
ea8a5f88digeff10 years ago | 21 | console: typeof console; |
| 22 | require: (id: string) => any; | |
4677921cdigeff10 years ago | 23 | importScripts: (url: string) => void; |
| 24 | postMessage: (object: any) => void; | |
ea8a5f88digeff10 years ago | 25 | onmessage: (object: RNAppMessage) => void; |
| 26 | postMessageArgument: RNAppMessage; // We use this argument to pass messages to the worker | |
4677921cdigeff10 years ago | 27 | } |
| 28 | | |
ea8a5f88digeff10 years ago | 29 | interface RNAppMessage { |
| 30 | method: string; | |
| 31 | // These objects have also other properties but that we don't currently use | |
| 32 | } | |
5d4d4de0digeff10 years ago | 33 | |
ce591c62digeff10 years ago | 34 | function printDebuggingError(message: string, reason: any) { |
10873e11digeff10 years ago | 35 | Log.logWarning(`${message}. Debugging won't work: Try reloading the JS from inside the app, or Reconnect the VS Code debugger`, reason); |
5d4d4de0digeff10 years ago | 36 | } |
| 37 | | |
4677921cdigeff10 years ago | 38 | export class SandboxedAppWorker { |
ea8a5f88digeff10 years ago | 39 | /** This class will run the RN App logic inside a sandbox. The framework to run the logic is provided by the file |
| 40 | * debuggerWorker.js (designed to run on a WebWorker). We load that file inside a sandbox, and then we use the | |
| 41 | * PROCESS_MESSAGE_INSIDE_SANDBOX script to execute the logic to respond to a message inside the sandbox. | |
| 42 | * The code inside the debuggerWorker.js will call the global function postMessage to send a reply back to the app, | |
| 43 | * so we define our custom function there, so we can handle the message. We also provide our own importScript function | |
| 44 | * to download any script used by debuggerWorker.js | |
| 45 | */ | |
4677921cdigeff10 years ago | 46 | private sourcesStoragePath: string; |
5547a16fJimmy Thomson10 years ago | 47 | private debugAdapterPort: number; |
4677921cdigeff10 years ago | 48 | private postReplyToApp: (message: any) => void; |
| 49 | | |
| 50 | private sandbox: DebuggerWorkerSandbox; | |
| 51 | private sandboxContext: vm.Context; | |
ea8a5f88digeff10 years ago | 52 | private scriptToReceiveMessageInSandbox: vm.Script; |
4677921cdigeff10 years ago | 53 | |
5d4d4de0digeff10 years ago | 54 | private pendingScriptImport = Q(void 0); |
4677921cdigeff10 years ago | 55 | |
ea8a5f88digeff10 years ago | 56 | private static PROCESS_MESSAGE_INSIDE_SANDBOX = "onmessage({ data: postMessageArgument });"; |
| 57 | | |
5547a16fJimmy Thomson10 years ago | 58 | constructor(sourcesStoragePath: string, debugAdapterPort: number, postReplyToApp: (message: any) => void) { |
4677921cdigeff10 years ago | 59 | this.sourcesStoragePath = sourcesStoragePath; |
2570720bJimmy Thomson10 years ago | 60 | this.debugAdapterPort = debugAdapterPort; |
4677921cdigeff10 years ago | 61 | this.postReplyToApp = postReplyToApp; |
ea8a5f88digeff10 years ago | 62 | this.scriptToReceiveMessageInSandbox = new vm.Script(SandboxedAppWorker.PROCESS_MESSAGE_INSIDE_SANDBOX); |
4677921cdigeff10 years ago | 63 | } |
| 64 | | |
5d4d4de0digeff10 years ago | 65 | public start(): Q.Promise<void> { |
2743f19cdlebu10 years ago | 66 | let scriptToRunPath = require.resolve(path.join(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILE_BASENAME)); |
4677921cdigeff10 years ago | 67 | this.initializeSandboxAndContext(scriptToRunPath); |
5d4d4de0digeff10 years ago | 68 | return this.readFileContents(scriptToRunPath).then(fileContents => |
| 69 | // On a debugger worker the onmessage variable already exist. We need to declare it before the | |
| 70 | // javascript file can assign it. We do it in the first line without a new line to not break | |
| 71 | // the debugging experience of debugging debuggerWorker.js itself (as part of the extension) | |
| 72 | this.runInSandbox(scriptToRunPath, "var onmessage = null; " + fileContents)); | |
4677921cdigeff10 years ago | 73 | } |
| 74 | | |
ea8a5f88digeff10 years ago | 75 | public postMessage(object: RNAppMessage): void { |
| 76 | this.sandbox.postMessageArgument = object; | |
| 77 | this.scriptToReceiveMessageInSandbox.runInContext(this.sandboxContext); | |
4677921cdigeff10 years ago | 78 | } |
| 79 | | |
| 80 | private initializeSandboxAndContext(scriptToRunPath: string): void { | |
| 81 | let scriptToRunModule = new Module(scriptToRunPath); | |
| 82 | | |
| 83 | this.sandbox = { | |
| 84 | __filename: scriptToRunPath, | |
| 85 | __dirname: path.dirname(scriptToRunPath), | |
| 86 | self: null, | |
| 87 | console: console, | |
| 88 | require: (filePath: string) => scriptToRunModule.require(filePath), // Give the sandbox access to require("<filePath>"); | |
| 89 | importScripts: (url: string) => this.importScripts(url), // Import script like using <script/> | |
| 90 | postMessage: (object: any) => this.gotResponseFromDebuggerWorker(object), // Post message back to the UI thread | |
ea8a5f88digeff10 years ago | 91 | onmessage: null, |
| 92 | postMessageArgument: null | |
4677921cdigeff10 years ago | 93 | }; |
| 94 | this.sandbox.self = this.sandbox; | |
| 95 | | |
| 96 | this.sandboxContext = vm.createContext(this.sandbox); | |
| 97 | } | |
| 98 | | |
b3a793eeNisheet Jain10 years ago | 99 | private runInSandbox(filename: string, fileContents?: string): Q.Promise<void> { |
| 100 | let fileContentsPromise = fileContents | |
| 101 | ? Q(fileContents) | |
| 102 | : this.readFileContents(filename); | |
| 103 | | |
| 104 | return fileContentsPromise.then(contents => { | |
| 105 | vm.runInContext(contents, this.sandboxContext, filename); | |
| 106 | }); | |
| 107 | } | |
| 108 | | |
| 109 | private readFileContents(filename: string) { | |
| 110 | return new Node.FileSystem().readFile(filename).then(contents => contents.toString()); | |
| 111 | } | |
| 112 | | |
4677921cdigeff10 years ago | 113 | private importScripts(url: string): void { |
5d4d4de0digeff10 years ago | 114 | /* The debuggerWorker.js executes this code: |
| 115 | importScripts(message.url); | |
| 116 | sendReply(); | |
| 117 | | |
| 118 | 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 | |
| 119 | actually send the reply back to the application until after importScripts has finished executing. We use | |
| 120 | this.pendingScriptImport to make the gotResponseFromDebuggerWorker() method hold the reply back, until've finished importing | |
| 121 | and running the script */ | |
4677921cdigeff10 years ago | 122 | let defer = Q.defer<{}>(); |
5d4d4de0digeff10 years ago | 123 | this.pendingScriptImport = defer.promise; |
4677921cdigeff10 years ago | 124 | |
| 125 | // The next line converts to any due to the incorrect typing on node.d.ts of vm.runInThisContext | |
2743f19cdlebu10 years ago | 126 | new ScriptImporter(this.sourcesStoragePath).downloadAppScript(url, this.debugAdapterPort) |
4677921cdigeff10 years ago | 127 | .then(downloadedScript => |
| 128 | this.runInSandbox(downloadedScript.filepath, downloadedScript.contents)) | |
5d4d4de0digeff10 years ago | 129 | .done(() => { |
9d7db611digeff10 years ago | 130 | // Now we let the reply to the app proceed |
| 131 | defer.resolve({}); | |
| 132 | }, reason => { | |
ce591c62digeff10 years ago | 133 | printDebuggingError(`Couldn't import script at <${url}>`, reason); |
9d7db611digeff10 years ago | 134 | }); |
4677921cdigeff10 years ago | 135 | } |
| 136 | | |
| 137 | private gotResponseFromDebuggerWorker(object: any): void { | |
5d4d4de0digeff10 years ago | 138 | // We might need to hold the response until a script is imported. See comments on this.importScripts() |
| 139 | this.pendingScriptImport.done(() => | |
10873e11digeff10 years ago | 140 | this.postReplyToApp(object), reason => { |
ce591c62digeff10 years ago | 141 | printDebuggingError("Unexpected internal error while processing a message from the RN App.", reason); |
10873e11digeff10 years ago | 142 | }); |
4677921cdigeff10 years ago | 143 | } |
| 144 | } | |
| 145 | | |
| 146 | export class MultipleLifetimesAppWorker { | |
ea8a5f88digeff10 years ago | 147 | /** This class will create a SandboxedAppWorker that will run the RN App logic, and then create a socket |
| 148 | * and send the RN App messages to the SandboxedAppWorker. The only RN App message that this class handles | |
| 149 | * is the prepareJSRuntime, which we reply to the RN App that the sandbox was created succesfully. | |
| 150 | * When the socket closes, we'll create a new SandboxedAppWorker and a new socket pair and discard the old ones. | |
| 151 | */ | |
4677921cdigeff10 years ago | 152 | private sourcesStoragePath: string; |
5547a16fJimmy Thomson10 years ago | 153 | private debugAdapterPort: number; |
ea8a5f88digeff10 years ago | 154 | private socketToApp: WebSocket; |
4677921cdigeff10 years ago | 155 | private singleLifetimeWorker: SandboxedAppWorker; |
| 156 | | |
5547a16fJimmy Thomson10 years ago | 157 | constructor(sourcesStoragePath: string, debugAdapterPort: number) { |
4677921cdigeff10 years ago | 158 | this.sourcesStoragePath = sourcesStoragePath; |
5547a16fJimmy Thomson10 years ago | 159 | this.debugAdapterPort = debugAdapterPort; |
ea8a5f88digeff10 years ago | 160 | console.assert(!!this.sourcesStoragePath, "The sourcesStoragePath argument was null or empty"); |
4677921cdigeff10 years ago | 161 | } |
| 162 | | |
5d4d4de0digeff10 years ago | 163 | public start(): Q.Promise<void> { |
5547a16fJimmy Thomson10 years ago | 164 | this.singleLifetimeWorker = new SandboxedAppWorker(this.sourcesStoragePath, this.debugAdapterPort, (message) => { |
5d4d4de0digeff10 years ago | 165 | this.sendMessageToApp(message); |
| 166 | }); | |
| 167 | return this.singleLifetimeWorker.start().then(() => { | |
| 168 | this.socketToApp = this.createSocketToApp(); | |
| 169 | }); | |
4677921cdigeff10 years ago | 170 | } |
| 171 | | |
| 172 | private createSocketToApp() { | |
| 173 | let socketToApp = new WebSocket(this.debuggerProxyUrl()); | |
ea8a5f88digeff10 years ago | 174 | socketToApp.on("open", () => |
| 175 | this.onSocketOpened()); | |
| 176 | socketToApp.on("close", () => | |
| 177 | this.onSocketClose()); | |
| 178 | socketToApp.on("message", | |
| 179 | (message: any) => this.onMessage(message)); | |
| 180 | socketToApp.on("error", | |
ce591c62digeff10 years ago | 181 | (error: Error) => printDebuggingError("An error ocurred while using the socket to communicate with the React Native app", error)); |
4677921cdigeff10 years ago | 182 | return socketToApp; |
| 183 | } | |
| 184 | | |
| 185 | private debuggerProxyUrl() { | |
f158bbd1Atticus White10 years ago | 186 | return `ws://${Packager.HOST}/debugger-proxy?role=debugger&name=vscode`; |
4677921cdigeff10 years ago | 187 | } |
| 188 | | |
ea8a5f88digeff10 years ago | 189 | private onSocketOpened() { |
4677921cdigeff10 years ago | 190 | Log.logMessage("Established a connection with the Proxy (Packager) to the React Native application"); |
| 191 | } | |
| 192 | | |
ea8a5f88digeff10 years ago | 193 | private onSocketClose() { |
5d4d4de0digeff10 years ago | 194 | // TODO: Add some logic to not print this message that often, we'll spam the user |
4677921cdigeff10 years ago | 195 | Log.logMessage("Disconnected from the Proxy (Packager) to the React Native application. Retrying reconnection soon..."); |
5d4d4de0digeff10 years ago | 196 | setTimeout(() => this.start(), 100); |
4677921cdigeff10 years ago | 197 | } |
| 198 | | |
ea8a5f88digeff10 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") { |
| 204 | // The MultipleLifetimesAppWorker will handle prepareJSRuntime aka create new lifetime | |
| 205 | this.gotPrepareJSRuntime(object); | |
| 206 | } else if (object.method) { | |
| 207 | // All the other messages are handled by the single lifetime worker | |
| 208 | this.singleLifetimeWorker.postMessage(object); | |
| 209 | } else { | |
ea8a5f88digeff10 years ago | 210 | // Message doesn't have a method. Ignore it. This is an info message instead of warn because it's normal and expected |
| 211 | Log.logInternalMessage(LogLevel.Info, "The react-native app sent a message without specifying a method: " + message); | |
5d4d4de0digeff10 years ago | 212 | } |
| 213 | } catch (exception) { | |
ce591c62digeff10 years ago | 214 | printDebuggingError(`Failed to process message from the React Native app. Message:\n${message}`, exception); |
4677921cdigeff10 years ago | 215 | } |
| 216 | } | |
| 217 | | |
| 218 | private gotPrepareJSRuntime(message: any): void { | |
| 219 | // Create the sandbox, and replay that we finished processing the message | |
| 220 | this.sendMessageToApp({ replyID: parseInt(message.id, 10) }); | |
| 221 | } | |
| 222 | | |
| 223 | private sendMessageToApp(message: any) { | |
354c28a1digeff10 years ago | 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 | |
ce591c62digeff10 years ago | 231 | printDebuggingError(`Failed to send message to the React Native app. Message:\n${messageToShow}`, exception); |
354c28a1digeff10 years ago | 232 | } |
4677921cdigeff10 years ago | 233 | } |
| 234 | } |