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