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