microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
2c19da7f131d11b4265a94fe25139194a565116e

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/forkedAppWorker.ts

166lines · 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 Q from "q";
5import * as path from "path";
6import * as url from "url";
7import * as child_process from "child_process";
8import * as fs from "fs";
9import {ScriptImporter, DownloadedScript} from "./scriptImporter";
10import { logger } from "vscode-debugadapter";
11import { ErrorHelper } from "../common/error/errorHelper";
12import { IDebuggeeWorker, RNAppMessage } from "./appWorker";
13import { InternalErrorCode } from "../common/error/internalErrorCode";
14import { getLoggingDirectory } from "../extension/log/LogHelper";
15import { generateRandomPortNumber } from "../common/extensionHelper";
16
17function printDebuggingError(error: Error, reason: any) {
18 const nestedError = ErrorHelper.getNestedError(error, InternalErrorCode.DebuggingWontWorkReloadJSAndReconnect, reason);
19
20 logger.error(nestedError.message);
21}
22
23/** This class will run the RN App logic inside a forked Node process. The framework to run the logic is provided by the file
24 * debuggerWorker.js (designed to run on a WebWorker). We add a couple of tweaks (mostly to polyfill WebWorker API) to that
25 * file and load it inside of a process.
26 * On this side we listen to IPC messages and either respond to them or redirect them to packager via MultipleLifetimeAppWorker's
27 * instance. We also intercept packager's signal to load the bundle's code and mutate the message with path to file we've downloaded
28 * to let importScripts function take this file.
29 */
30export class ForkedAppWorker implements IDebuggeeWorker {
31
32 protected scriptImporter: ScriptImporter;
33 protected debuggeeProcess: child_process.ChildProcess | null = null;
34 /** A deferred that we use to make sure that worker has been loaded completely defore start sending IPC messages */
35 protected workerLoaded = Q.defer<void>();
36 private bundleLoaded: Q.Deferred<void>;
37 private logWriteStream: fs.WriteStream;
38 private logDirectory: string | null;
39
40 constructor(
41 private packagerAddress: string,
42 private packagerPort: number,
43 private sourcesStoragePath: string,
44 private projectRootPath: string,
45 private postReplyToApp: (message: any) => void,
46 private packagerRemoteRoot?: string,
47 private packagerLocalRoot?: string
48 ) {
49 this.scriptImporter = new ScriptImporter(this.packagerAddress, this.packagerPort, this.sourcesStoragePath, this.packagerRemoteRoot, this.packagerLocalRoot);
50 }
51
52 public stop() {
53 if (this.debuggeeProcess) {
54 logger.verbose(`About to kill debuggee with pid ${this.debuggeeProcess.pid}`);
55 this.debuggeeProcess.kill();
56 this.debuggeeProcess = null;
57 }
58 }
59
60 public start(): Q.Promise<number> {
61 let scriptToRunPath = path.resolve(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILENAME);
62 const port = generateRandomPortNumber();
63
64 // Note that we set --inspect-brk flag to pause the process on the first line - this is
65 // required for debug adapter to set the breakpoints BEFORE the debuggee has started.
66 // The adapter will continue execution once it's done with breakpoints.
67 // --no-deprecation flag disables deprecation warnings like "[DEP0005] DeprecationWarning: Buffer() is deprecated..." and so on that leads to errors in native app
68 // https://nodejs.org/dist/latest-v7.x/docs/api/cli.html
69 const nodeArgs = [`--inspect-brk=${port}`, "--no-deprecation", scriptToRunPath];
70 // Start child Node process in debugging mode
71 // Using fork instead of spawn causes breakage of piping between app worker and VS Code debug console, e.g. console.log() in application
72 // wouldn't work. Please see https://github.com/Microsoft/vscode-react-native/issues/758
73 this.debuggeeProcess = child_process.spawn("node", nodeArgs, {
74 stdio: ["pipe", "pipe", "pipe", "ipc"],
75 })
76 .on("message", (message: any) => {
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.resolve(void 0);
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 Q.resolve(port);
112 }
113
114 public postMessage(rnMessage: RNAppMessage): Q.Promise<RNAppMessage> {
115 // Before sending messages, make sure that the worker is loaded
116 const promise = this.workerLoaded.promise
117 .then(() => {
118 if (rnMessage.method !== "executeApplicationScript") {
119 // Before sending messages, make sure that the app script executed
120 if (this.bundleLoaded) {
121 return this.bundleLoaded.promise.then(() => {
122 return rnMessage;
123 });
124 } else {
125 return rnMessage;
126 }
127 } else {
128 this.bundleLoaded = Q.defer<void>();
129 // When packager asks worker to load bundle we download that bundle and
130 // then set url field to point to that downloaded bundle, so the worker
131 // will take our modified bundle
132 if (rnMessage.url) {
133 const packagerUrl = url.parse(rnMessage.url);
134 packagerUrl.host = `${this.packagerAddress}:${this.packagerPort}`;
135 rnMessage = {
136 ...rnMessage,
137 url: url.format(packagerUrl),
138 };
139 logger.verbose(`Packager requested runtime to load script from ${rnMessage.url}`);
140 return this.scriptImporter.downloadAppScript(<string>rnMessage.url, this.projectRootPath)
141 .then((downloadedScript: DownloadedScript) => {
142 this.bundleLoaded.resolve(void 0);
143 return Object.assign({}, rnMessage, { url: `${this.pathToFileUrl(downloadedScript.filepath)}`});
144 });
145 } else {
146 throw ErrorHelper.getInternalError(InternalErrorCode.RNMessageWithMethodExecuteApplicationScriptDoesntHaveURLProperty);
147 }
148 }
149 });
150 promise.done(
151 (message: RNAppMessage) => {
152 if (this.debuggeeProcess) {
153 this.debuggeeProcess.send({ data: message });
154 }
155 },
156 (reason) => printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.CouldntImportScriptAt, rnMessage.url), reason));
157
158 return promise;
159 }
160
161 // TODO: Replace by url.pathToFileURL method when Node 10 LTS become deprecated
162 public pathToFileUrl(url: string) {
163 const filePrefix = process.platform === "win32" ? "file:///" : "file://";
164 return filePrefix + url;
165 }
166}
167