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