microsoft/vscode-react-native

Public

mirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
d55f3c22ee18a37c605867c8bf588451292bd24e

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/debugger/forkedAppWorker.ts

179lines · 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
4import * as path from "path";
5import * as url from "url";
6import * as cp from "child_process";
7import * as fs from "fs";
8import { ScriptImporter, DownloadedScript } from "./scriptImporter";
9import { logger } from "vscode-debugadapter";
10import { ErrorHelper } from "../common/error/errorHelper";
11import { IDebuggeeWorker, RNAppMessage } from "./appWorker";
12import { InternalErrorCode } from "../common/error/internalErrorCode";
13import { getLoggingDirectory } from "../extension/log/LogHelper";
14import { generateRandomPortNumber } from "../common/extensionHelper";
15
16function 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 */
29export class ForkedAppWorker implements IDebuggeeWorker {
30
31 protected scriptImporter: ScriptImporter;
32 protected debuggeeProcess: cp.ChildProcess | null = null;
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>;
36 private logWriteStream: fs.WriteStream;
37 private logDirectory: string | null;
38
39 constructor(
40 private packagerAddress: string,
41 private packagerPort: number,
42 private sourcesStoragePath: string,
43 private projectRootPath: string,
44 private postReplyToApp: (message: any) => void,
45 private packagerRemoteRoot?: string,
46 private packagerLocalRoot?: string
47 ) {
48 this.scriptImporter = new ScriptImporter(this.packagerAddress, this.packagerPort, this.sourcesStoragePath, this.packagerRemoteRoot, this.packagerLocalRoot);
49 }
50
51 public stop() {
52 if (this.debuggeeProcess) {
53 logger.verbose(`About to kill debuggee with pid ${this.debuggeeProcess.pid}`);
54 this.debuggeeProcess.kill();
55 this.debuggeeProcess = null;
56 }
57 }
58
59 public start(): Promise<number> {
60 let scriptToRunPath = path.resolve(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILENAME);
61 const port = generateRandomPortNumber();
62
63 // Note that we set --inspect-brk flag to pause the process on the first line - this is
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.
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];
69 // Start child Node process in debugging mode
70 // Using fork instead of spawn causes breakage of piping between app worker and VS Code debug console, e.g. console.log() in application
71 // wouldn't work. Please see https://github.com/microsoft/vscode-react-native/issues/758
72 this.debuggeeProcess = cp.spawn("node", nodeArgs, {
73 stdio: ["pipe", "pipe", "pipe", "ipc"],
74 })
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 }
85
86 this.postReplyToApp(message);
87 })
88 .on("error", (error: Error) => {
89 printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.ReactNativeWorkerProcessThrownAnError), error);
90 });
91
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
107 // Resolve with port debugger server is listening on
108 // This will be sent to subscribers of MLAppWorker in "connected" event
109 logger.verbose(`Spawned debuggee process with pid ${this.debuggeeProcess.pid} listening to ${port}`);
110
111 return Promise.resolve(port);
112 }
113
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();
123 }
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;
136 });
137 } else {
138 return rnMessage;
139 }
140 } else {
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 }
160 }
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));
169
170 return promise;
171 });
172 }
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 }
179}
180