microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/debugger/forkedAppWorker.ts
182lines · modeblame
e45838cbVladimir Kotikov9 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 | | |
| 4 | import * as Q from "q"; | |
| 5 | import * as path from "path"; | |
6eeec3c0Serge Svekolnikov8 years ago | 6 | import * as url from "url"; |
90d15117JiglioNero6 years ago | 7 | import * as cp from "child_process"; |
08722261Yuri Skorokhodov7 years ago | 8 | import * as fs from "fs"; |
5c8365a6Artem Egorov8 years ago | 9 | import {ScriptImporter, DownloadedScript} from "./scriptImporter"; |
e45838cbVladimir Kotikov9 years ago | 10 | |
0a68f8dbArtem Egorov8 years ago | 11 | import { logger } from "vscode-chrome-debug-core"; |
e45838cbVladimir Kotikov9 years ago | 12 | import { ErrorHelper } from "../common/error/errorHelper"; |
| 13 | import { IDebuggeeWorker, RNAppMessage } from "./appWorker"; | |
7daed3fcArtem Egorov8 years ago | 14 | import { RemoteExtension } from "../common/remoteExtension"; |
1758f9a6Yuri Skorokhodov7 years ago | 15 | import { InternalErrorCode } from "../common/error/internalErrorCode"; |
08722261Yuri Skorokhodov7 years ago | 16 | import { getLoggingDirectory } from "../extension/log/LogHelper"; |
e45838cbVladimir Kotikov9 years ago | 17 | |
1758f9a6Yuri Skorokhodov7 years ago | 18 | function printDebuggingError(error: Error, reason: any) { |
| 19 | const nestedError = ErrorHelper.getNestedError(error, InternalErrorCode.DebuggingWontWorkReloadJSAndReconnect, reason); | |
0a68f8dbArtem Egorov8 years ago | 20 | |
| 21 | logger.error(nestedError.message); | |
e45838cbVladimir Kotikov9 years ago | 22 | } |
| 23 | | |
| 24 | /** This class will run the RN App logic inside a forked Node process. The framework to run the logic is provided by the file | |
| 25 | * debuggerWorker.js (designed to run on a WebWorker). We add a couple of tweaks (mostly to polyfill WebWorker API) to that | |
| 26 | * file and load it inside of a process. | |
| 27 | * On this side we listen to IPC messages and either respond to them or redirect them to packager via MultipleLifetimeAppWorker's | |
| 28 | * instance. We also intercept packager's signal to load the bundle's code and mutate the message with path to file we've downloaded | |
| 29 | * to let importScripts function take this file. | |
| 30 | */ | |
| 31 | export class ForkedAppWorker implements IDebuggeeWorker { | |
| 32 | | |
6eeec3c0Serge Svekolnikov8 years ago | 33 | protected scriptImporter: ScriptImporter; |
90d15117JiglioNero6 years ago | 34 | protected debuggeeProcess: cp.ChildProcess | null = null; |
e45838cbVladimir Kotikov9 years ago | 35 | /** A deferred that we use to make sure that worker has been loaded completely defore start sending IPC messages */ |
6eeec3c0Serge Svekolnikov8 years ago | 36 | protected workerLoaded = Q.defer<void>(); |
5c8365a6Artem Egorov8 years ago | 37 | private bundleLoaded: Q.Deferred<void>; |
7daed3fcArtem Egorov8 years ago | 38 | private remoteExtension: RemoteExtension; |
08722261Yuri Skorokhodov7 years ago | 39 | private logWriteStream: fs.WriteStream; |
| 40 | private logDirectory: string | null; | |
e45838cbVladimir Kotikov9 years ago | 41 | |
| 42 | constructor( | |
6eeec3c0Serge Svekolnikov8 years ago | 43 | private packagerAddress: string, |
e45838cbVladimir Kotikov9 years ago | 44 | private packagerPort: number, |
| 45 | private sourcesStoragePath: string, | |
7daed3fcArtem Egorov8 years ago | 46 | private projectRootPath: string, |
6eeec3c0Serge Svekolnikov8 years ago | 47 | private postReplyToApp: (message: any) => void, |
| 48 | private packagerRemoteRoot?: string, | |
| 49 | private packagerLocalRoot?: string | |
e45838cbVladimir Kotikov9 years ago | 50 | ) { |
6eeec3c0Serge Svekolnikov8 years ago | 51 | this.scriptImporter = new ScriptImporter(this.packagerAddress, this.packagerPort, this.sourcesStoragePath, this.packagerRemoteRoot, this.packagerLocalRoot); |
7daed3fcArtem Egorov8 years ago | 52 | |
| 53 | this.remoteExtension = RemoteExtension.atProjectRootPath(this.projectRootPath); | |
| 54 | | |
| 55 | this.remoteExtension.api.Debugger.onShowDevMenu(() => { | |
| 56 | this.postMessage({ | |
| 57 | method: "vscode_showDevMenu", | |
| 58 | }); | |
| 59 | }); | |
| 60 | | |
| 61 | this.remoteExtension.api.Debugger.onReloadApp(() => { | |
| 62 | this.postMessage({ | |
| 63 | method: "vscode_reloadApp", | |
| 64 | }); | |
| 65 | }); | |
e45838cbVladimir Kotikov9 years ago | 66 | } |
| 67 | | |
| 68 | public stop() { | |
| 69 | if (this.debuggeeProcess) { | |
0a68f8dbArtem Egorov8 years ago | 70 | logger.verbose(`About to kill debuggee with pid ${this.debuggeeProcess.pid}`); |
e45838cbVladimir Kotikov9 years ago | 71 | this.debuggeeProcess.kill(); |
| 72 | this.debuggeeProcess = null; | |
| 73 | } | |
| 74 | } | |
| 75 | | |
| 76 | public start(): Q.Promise<number> { | |
| 77 | let scriptToRunPath = path.resolve(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILENAME); | |
cc70057dVladimir Kotikov9 years ago | 78 | const port = Math.round(Math.random() * 40000 + 3000); |
e45838cbVladimir Kotikov9 years ago | 79 | |
045132a1Yuri Skorokhodov7 years ago | 80 | // Note that we set --inspect-brk flag to pause the process on the first line - this is |
cc70057dVladimir Kotikov9 years ago | 81 | // required for debug adapter to set the breakpoints BEFORE the debuggee has started. |
| 82 | // The adapter will continue execution once it's done with breakpoints. | |
13a99427Yuri Skorokhodov6 years ago | 83 | // --no-deprecation flag disables deprecation warnings like "[DEP0005] DeprecationWarning: Buffer() is deprecated..." and so on that leads to errors in native app |
| 84 | // https://nodejs.org/dist/latest-v7.x/docs/api/cli.html | |
| 85 | const nodeArgs = [`--inspect-brk=${port}`, "--no-deprecation", scriptToRunPath]; | |
cc70057dVladimir Kotikov9 years ago | 86 | // Start child Node process in debugging mode |
f533409bRuslan Bikkinin7 years ago | 87 | // Using fork instead of spawn causes breakage of piping between app worker and VS Code debug console, e.g. console.log() in application |
f6fb2d2aFrieder Bluemle5 years ago | 88 | // wouldn't work. Please see https://github.com/microsoft/vscode-react-native/issues/758 |
90d15117JiglioNero6 years ago | 89 | this.debuggeeProcess = cp.spawn("node", nodeArgs, { |
f533409bRuslan Bikkinin7 years ago | 90 | stdio: ["pipe", "pipe", "pipe", "ipc"], |
| 91 | }) | |
cc70057dVladimir Kotikov9 years ago | 92 | .on("message", (message: any) => { |
| 93 | // 'workerLoaded' is a special message that indicates that worker is done with loading. | |
| 94 | // We need to wait for it before doing any IPC because process.send doesn't seems to care | |
6eeec3c0Serge Svekolnikov8 years ago | 95 | // about whether the message has been received or not and the first messages are often get |
cc70057dVladimir Kotikov9 years ago | 96 | // discarded by spawned process |
| 97 | if (message && message.workerLoaded) { | |
| 98 | this.workerLoaded.resolve(void 0); | |
| 99 | return; | |
| 100 | } | |
e45838cbVladimir Kotikov9 years ago | 101 | |
cc70057dVladimir Kotikov9 years ago | 102 | this.postReplyToApp(message); |
| 103 | }) | |
| 104 | .on("error", (error: Error) => { | |
1758f9a6Yuri Skorokhodov7 years ago | 105 | printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.ReactNativeWorkerProcessThrownAnError), error); |
e45838cbVladimir Kotikov9 years ago | 106 | }); |
cc70057dVladimir Kotikov9 years ago | 107 | |
08722261Yuri Skorokhodov7 years ago | 108 | // If special env variables are defined, then write process outputs to file |
| 109 | this.logDirectory = getLoggingDirectory(); | |
| 110 | | |
| 111 | if (this.logDirectory) { | |
| 112 | this.logWriteStream = fs.createWriteStream(path.join(this.logDirectory, "nodeProcessLog.txt")); | |
| 113 | this.logWriteStream.on("error", err => { | |
| 114 | logger.error(`Error creating log file at path: ${this.logDirectory}. Error: ${err.toString()}\n`); | |
| 115 | }); | |
| 116 | this.debuggeeProcess.stdout.pipe(this.logWriteStream); | |
| 117 | this.debuggeeProcess.stderr.pipe(this.logWriteStream); | |
| 118 | this.debuggeeProcess.on("close", () => { | |
| 119 | this.logWriteStream.end(); | |
| 120 | }); | |
| 121 | } | |
| 122 | | |
cc70057dVladimir Kotikov9 years ago | 123 | // Resolve with port debugger server is listening on |
| 124 | // This will be sent to subscribers of MLAppWorker in "connected" event | |
0a68f8dbArtem Egorov8 years ago | 125 | logger.verbose(`Spawned debuggee process with pid ${this.debuggeeProcess.pid} listening to ${port}`); |
cc70057dVladimir Kotikov9 years ago | 126 | |
| 127 | return Q.resolve(port); | |
e45838cbVladimir Kotikov9 years ago | 128 | } |
| 129 | | |
6eeec3c0Serge Svekolnikov8 years ago | 130 | public postMessage(rnMessage: RNAppMessage): Q.Promise<RNAppMessage> { |
e45838cbVladimir Kotikov9 years ago | 131 | // Before sending messages, make sure that the worker is loaded |
6eeec3c0Serge Svekolnikov8 years ago | 132 | const promise = this.workerLoaded.promise |
936b1ceaArtem Egorov8 years ago | 133 | .then(() => { |
| 134 | if (rnMessage.method !== "executeApplicationScript") { | |
| 135 | // Before sending messages, make sure that the app script executed | |
| 136 | if (this.bundleLoaded) { | |
| 137 | return this.bundleLoaded.promise.then(() => { | |
| 138 | return rnMessage; | |
| 139 | }); | |
| 140 | } else { | |
| 141 | return rnMessage; | |
| 142 | } | |
| 143 | } else { | |
| 144 | this.bundleLoaded = Q.defer<void>(); | |
| 145 | // When packager asks worker to load bundle we download that bundle and | |
| 146 | // then set url field to point to that downloaded bundle, so the worker | |
| 147 | // will take our modified bundle | |
5c8365a6Artem Egorov8 years ago | 148 | if (rnMessage.url) { |
6eeec3c0Serge Svekolnikov8 years ago | 149 | const packagerUrl = url.parse(rnMessage.url); |
| 150 | packagerUrl.host = `${this.packagerAddress}:${this.packagerPort}`; | |
| 151 | rnMessage = { | |
| 152 | ...rnMessage, | |
| 153 | url: url.format(packagerUrl), | |
| 154 | }; | |
d124bf0eYuri Skorokhodov7 years ago | 155 | logger.verbose(`Packager requested runtime to load script from ${rnMessage.url}`); |
979d7bfemax-mironov8 years ago | 156 | return this.scriptImporter.downloadAppScript(<string>rnMessage.url, this.projectRootPath) |
5c8365a6Artem Egorov8 years ago | 157 | .then((downloadedScript: DownloadedScript) => { |
| 158 | this.bundleLoaded.resolve(void 0); | |
4cf8fdf4Yuri Skorokhodov6 years ago | 159 | return Object.assign({}, rnMessage, { url: `${this.pathToFileUrl(downloadedScript.filepath)}`}); |
5c8365a6Artem Egorov8 years ago | 160 | }); |
| 161 | } else { | |
1758f9a6Yuri Skorokhodov7 years ago | 162 | throw ErrorHelper.getInternalError(InternalErrorCode.RNMessageWithMethodExecuteApplicationScriptDoesntHaveURLProperty); |
5c8365a6Artem Egorov8 years ago | 163 | } |
936b1ceaArtem Egorov8 years ago | 164 | } |
6eeec3c0Serge Svekolnikov8 years ago | 165 | }); |
| 166 | promise.done( | |
5c8365a6Artem Egorov8 years ago | 167 | (message: RNAppMessage) => { |
| 168 | if (this.debuggeeProcess) { | |
| 169 | this.debuggeeProcess.send({ data: message }); | |
| 170 | } | |
| 171 | }, | |
1758f9a6Yuri Skorokhodov7 years ago | 172 | (reason) => printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.CouldntImportScriptAt, rnMessage.url), reason)); |
6eeec3c0Serge Svekolnikov8 years ago | 173 | |
| 174 | return promise; | |
e45838cbVladimir Kotikov9 years ago | 175 | } |
4cf8fdf4Yuri Skorokhodov6 years ago | 176 | |
| 177 | // TODO: Replace by url.pathToFileURL method when Node 10 LTS become deprecated | |
| 178 | public pathToFileUrl(url: string) { | |
| 179 | const filePrefix = process.platform === "win32" ? "file:///" : "file://"; | |
| 180 | return filePrefix + url; | |
| 181 | } | |
e45838cbVladimir Kotikov9 years ago | 182 | } |