microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
4c757eeb398e0299d0e9cd9bc95b68dd2f87a06e

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/forkedAppWorker.ts

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