microsoft/vscode-react-native
Publicmirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable
src/debugger/forkedAppWorker.ts
154lines · 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 url from "url"; |
| 7 | import * as child_process from "child_process"; |
| 8 | import {ScriptImporter, DownloadedScript} from "./scriptImporter"; |
| 9 | |
| 10 | import { logger } from "vscode-chrome-debug-core"; |
| 11 | import { ErrorHelper } from "../common/error/errorHelper"; |
| 12 | import { IDebuggeeWorker, RNAppMessage } from "./appWorker"; |
| 13 | import { RemoteExtension } from "../common/remoteExtension"; |
| 14 | |
| 15 | function printDebuggingError(message: string, reason: any) { |
| 16 | const nestedError = ErrorHelper.getNestedWarning(reason, `${message}. Debugging won't work: Try reloading the JS from inside the app, or Reconnect the VS Code debugger`); |
| 17 | |
| 18 | logger.error(nestedError.message); |
| 19 | } |
| 20 | |
| 21 | /** This class will run the RN App logic inside a forked Node process. The framework to run the logic is provided by the file |
| 22 | * debuggerWorker.js (designed to run on a WebWorker). We add a couple of tweaks (mostly to polyfill WebWorker API) to that |
| 23 | * file and load it inside of a process. |
| 24 | * On this side we listen to IPC messages and either respond to them or redirect them to packager via MultipleLifetimeAppWorker's |
| 25 | * instance. We also intercept packager's signal to load the bundle's code and mutate the message with path to file we've downloaded |
| 26 | * to let importScripts function take this file. |
| 27 | */ |
| 28 | export class ForkedAppWorker implements IDebuggeeWorker { |
| 29 | |
| 30 | protected scriptImporter: ScriptImporter; |
| 31 | protected debuggeeProcess: child_process.ChildProcess | null = null; |
| 32 | /** A deferred that we use to make sure that worker has been loaded completely defore start sending IPC messages */ |
| 33 | protected workerLoaded = Q.defer<void>(); |
| 34 | private bundleLoaded: Q.Deferred<void>; |
| 35 | private remoteExtension: RemoteExtension; |
| 36 | |
| 37 | constructor( |
| 38 | private packagerAddress: string, |
| 39 | private packagerPort: number, |
| 40 | private sourcesStoragePath: string, |
| 41 | private projectRootPath: string, |
| 42 | private postReplyToApp: (message: any) => void, |
| 43 | private packagerRemoteRoot?: string, |
| 44 | private packagerLocalRoot?: string |
| 45 | ) { |
| 46 | this.scriptImporter = new ScriptImporter(this.packagerAddress, this.packagerPort, this.sourcesStoragePath, this.packagerRemoteRoot, this.packagerLocalRoot); |
| 47 | |
| 48 | this.remoteExtension = RemoteExtension.atProjectRootPath(this.projectRootPath); |
| 49 | |
| 50 | this.remoteExtension.api.Debugger.onShowDevMenu(() => { |
| 51 | this.postMessage({ |
| 52 | method: "vscode_showDevMenu", |
| 53 | }); |
| 54 | }); |
| 55 | |
| 56 | this.remoteExtension.api.Debugger.onReloadApp(() => { |
| 57 | this.postMessage({ |
| 58 | method: "vscode_reloadApp", |
| 59 | }); |
| 60 | }); |
| 61 | } |
| 62 | |
| 63 | public stop() { |
| 64 | if (this.debuggeeProcess) { |
| 65 | logger.verbose(`About to kill debuggee with pid ${this.debuggeeProcess.pid}`); |
| 66 | this.debuggeeProcess.kill(); |
| 67 | this.debuggeeProcess = null; |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | public start(): Q.Promise<number> { |
| 72 | let scriptToRunPath = path.resolve(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILENAME); |
| 73 | const port = Math.round(Math.random() * 40000 + 3000); |
| 74 | |
| 75 | // Note that we set --debug-brk flag to pause the process on the first line - this is |
| 76 | // required for debug adapter to set the breakpoints BEFORE the debuggee has started. |
| 77 | // The adapter will continue execution once it's done with breakpoints. |
| 78 | const nodeArgs = [`--inspect=${port}`, "--debug-brk", scriptToRunPath]; |
| 79 | // Start child Node process in debugging mode |
| 80 | // Using fork instead of spawn causes breakage of piping between app worker and VS Code debug console, e.g. console.log() in application |
| 81 | // wouldn't work. Please see https://github.com/Microsoft/vscode-react-native/issues/758 |
| 82 | this.debuggeeProcess = child_process.spawn("node", nodeArgs, { |
| 83 | stdio: ["pipe", "pipe", "pipe", "ipc"], |
| 84 | }) |
| 85 | .on("message", (message: any) => { |
| 86 | // 'workerLoaded' is a special message that indicates that worker is done with loading. |
| 87 | // We need to wait for it before doing any IPC because process.send doesn't seems to care |
| 88 | // about whether the message has been received or not and the first messages are often get |
| 89 | // discarded by spawned process |
| 90 | if (message && message.workerLoaded) { |
| 91 | this.workerLoaded.resolve(void 0); |
| 92 | return; |
| 93 | } |
| 94 | |
| 95 | this.postReplyToApp(message); |
| 96 | }) |
| 97 | .on("error", (error: Error) => { |
| 98 | printDebuggingError("React Native worker process thrown an error", error); |
| 99 | }); |
| 100 | |
| 101 | // Resolve with port debugger server is listening on |
| 102 | // This will be sent to subscribers of MLAppWorker in "connected" event |
| 103 | logger.verbose(`Spawned debuggee process with pid ${this.debuggeeProcess.pid} listening to ${port}`); |
| 104 | |
| 105 | return Q.resolve(port); |
| 106 | } |
| 107 | |
| 108 | public postMessage(rnMessage: RNAppMessage): Q.Promise<RNAppMessage> { |
| 109 | // Before sending messages, make sure that the worker is loaded |
| 110 | const promise = this.workerLoaded.promise |
| 111 | .then(() => { |
| 112 | if (rnMessage.method !== "executeApplicationScript") { |
| 113 | // Before sending messages, make sure that the app script executed |
| 114 | if (this.bundleLoaded) { |
| 115 | return this.bundleLoaded.promise.then(() => { |
| 116 | return rnMessage; |
| 117 | }); |
| 118 | } else { |
| 119 | return rnMessage; |
| 120 | } |
| 121 | } else { |
| 122 | this.bundleLoaded = Q.defer<void>(); |
| 123 | // When packager asks worker to load bundle we download that bundle and |
| 124 | // then set url field to point to that downloaded bundle, so the worker |
| 125 | // will take our modified bundle |
| 126 | if (rnMessage.url) { |
| 127 | const packagerUrl = url.parse(rnMessage.url); |
| 128 | packagerUrl.host = `${this.packagerAddress}:${this.packagerPort}`; |
| 129 | rnMessage = { |
| 130 | ...rnMessage, |
| 131 | url: url.format(packagerUrl), |
| 132 | }; |
| 133 | logger.verbose("Packager requested runtime to load script from " + rnMessage.url); |
| 134 | return this.scriptImporter.downloadAppScript(<string>rnMessage.url, this.projectRootPath) |
| 135 | .then((downloadedScript: DownloadedScript) => { |
| 136 | this.bundleLoaded.resolve(void 0); |
| 137 | return Object.assign({}, rnMessage, { url: downloadedScript.filepath }); |
| 138 | }); |
| 139 | } else { |
| 140 | throw Error("RNMessage with method 'executeApplicationScript' doesn't have 'url' property"); |
| 141 | } |
| 142 | } |
| 143 | }); |
| 144 | promise.done( |
| 145 | (message: RNAppMessage) => { |
| 146 | if (this.debuggeeProcess) { |
| 147 | this.debuggeeProcess.send({ data: message }); |
| 148 | } |
| 149 | }, |
| 150 | (reason) => printDebuggingError(`Couldn't import script at <${rnMessage.url}>`, reason)); |
| 151 | |
| 152 | return promise; |
| 153 | } |
| 154 | } |
| 155 | |