microsoft/vscode-react-native

Public

mirrored from https://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
c73f53cb7e73b23ef50e6c58df7a845972d341cb

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/forkedAppWorker.ts

179lines · modeblame

e45838cbVladimir Kotikov9 years ago1// 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";
6eeec3c0Serge Svekolnikov8 years ago5import * as url from "url";
4f8669f9JiglioNero6 years ago6import * as cp from "child_process";
08722261Yuri Skorokhodov7 years ago7import * as fs from "fs";
ce5e88eeYuri Skorokhodov5 years ago8import { ScriptImporter, DownloadedScript } from "./scriptImporter";
a6562589RedMickey6 years ago9import { logger } from "vscode-debugadapter";
e45838cbVladimir Kotikov9 years ago10import { ErrorHelper } from "../common/error/errorHelper";
11import { IDebuggeeWorker, RNAppMessage } from "./appWorker";
1758f9a6Yuri Skorokhodov7 years ago12import { InternalErrorCode } from "../common/error/internalErrorCode";
08722261Yuri Skorokhodov7 years ago13import { getLoggingDirectory } from "../extension/log/LogHelper";
f872f4d5RedMickey6 years ago14import { generateRandomPortNumber } from "../common/extensionHelper";
e45838cbVladimir Kotikov9 years ago15
1758f9a6Yuri Skorokhodov7 years ago16function printDebuggingError(error: Error, reason: any) {
17const nestedError = ErrorHelper.getNestedError(error, InternalErrorCode.DebuggingWontWorkReloadJSAndReconnect, reason);
0a68f8dbArtem Egorov8 years ago18
19logger.error(nestedError.message);
e45838cbVladimir Kotikov9 years ago20}
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
6eeec3c0Serge Svekolnikov8 years ago31protected scriptImporter: ScriptImporter;
4f8669f9JiglioNero6 years ago32protected debuggeeProcess: cp.ChildProcess | null = null;
ce5e88eeYuri Skorokhodov5 years ago33/** A promise that we use to make sure that worker has been loaded completely before start sending IPC messages */
34protected workerLoaded: Promise<void>;
35private bundleLoaded: Promise<void>;
08722261Yuri Skorokhodov7 years ago36private logWriteStream: fs.WriteStream;
37private logDirectory: string | null;
e45838cbVladimir Kotikov9 years ago38
39constructor(
6eeec3c0Serge Svekolnikov8 years ago40private packagerAddress: string,
e45838cbVladimir Kotikov9 years ago41private packagerPort: number,
42private sourcesStoragePath: string,
7daed3fcArtem Egorov8 years ago43private projectRootPath: string,
6eeec3c0Serge Svekolnikov8 years ago44private postReplyToApp: (message: any) => void,
45private packagerRemoteRoot?: string,
46private packagerLocalRoot?: string
e45838cbVladimir Kotikov9 years ago47) {
6eeec3c0Serge Svekolnikov8 years ago48this.scriptImporter = new ScriptImporter(this.packagerAddress, this.packagerPort, this.sourcesStoragePath, this.packagerRemoteRoot, this.packagerLocalRoot);
e45838cbVladimir Kotikov9 years ago49}
50
51public stop() {
52if (this.debuggeeProcess) {
0a68f8dbArtem Egorov8 years ago53logger.verbose(`About to kill debuggee with pid ${this.debuggeeProcess.pid}`);
e45838cbVladimir Kotikov9 years ago54this.debuggeeProcess.kill();
55this.debuggeeProcess = null;
56}
57}
58
ce5e88eeYuri Skorokhodov5 years ago59public start(): Promise<number> {
e45838cbVladimir Kotikov9 years ago60let scriptToRunPath = path.resolve(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILENAME);
f872f4d5RedMickey6 years ago61const port = generateRandomPortNumber();
e45838cbVladimir Kotikov9 years ago62
045132a1Yuri Skorokhodov7 years ago63// Note that we set --inspect-brk flag to pause the process on the first line - this is
cc70057dVladimir Kotikov9 years ago64// 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 ago66// --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
68const nodeArgs = [`--inspect-brk=${port}`, "--no-deprecation", scriptToRunPath];
cc70057dVladimir Kotikov9 years ago69// Start child Node process in debugging mode
f533409bRuslan Bikkinin7 years ago70// 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 ago71// wouldn't work. Please see https://github.com/microsoft/vscode-react-native/issues/758
4f8669f9JiglioNero6 years ago72this.debuggeeProcess = cp.spawn("node", nodeArgs, {
f533409bRuslan Bikkinin7 years ago73stdio: ["pipe", "pipe", "pipe", "ipc"],
74})
ce5e88eeYuri Skorokhodov5 years ago75.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
81if (message && message.workerLoaded) {
82this.workerLoaded = Promise.resolve();
83return;
84}
e45838cbVladimir Kotikov9 years ago85
ce5e88eeYuri Skorokhodov5 years ago86this.postReplyToApp(message);
87})
88.on("error", (error: Error) => {
89printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.ReactNativeWorkerProcessThrownAnError), error);
90});
cc70057dVladimir Kotikov9 years ago91
08722261Yuri Skorokhodov7 years ago92// If special env variables are defined, then write process outputs to file
93this.logDirectory = getLoggingDirectory();
94
95if (this.logDirectory) {
96this.logWriteStream = fs.createWriteStream(path.join(this.logDirectory, "nodeProcessLog.txt"));
97this.logWriteStream.on("error", err => {
98logger.error(`Error creating log file at path: ${this.logDirectory}. Error: ${err.toString()}\n`);
99});
100this.debuggeeProcess.stdout.pipe(this.logWriteStream);
101this.debuggeeProcess.stderr.pipe(this.logWriteStream);
102this.debuggeeProcess.on("close", () => {
103this.logWriteStream.end();
104});
105}
106
cc70057dVladimir Kotikov9 years ago107// Resolve with port debugger server is listening on
108// This will be sent to subscribers of MLAppWorker in "connected" event
0a68f8dbArtem Egorov8 years ago109logger.verbose(`Spawned debuggee process with pid ${this.debuggeeProcess.pid} listening to ${port}`);
cc70057dVladimir Kotikov9 years ago110
ce5e88eeYuri Skorokhodov5 years ago111return Promise.resolve(port);
e45838cbVladimir Kotikov9 years ago112}
113
ce5e88eeYuri Skorokhodov5 years ago114public postMessage(rnMessage: RNAppMessage): Promise<RNAppMessage> {
115return new Promise((resolve) => {
116if (this.workerLoaded) {
117resolve();
118} else {
119const checkWorkerLoaded = setInterval(() => {
120if (this.workerLoaded) {
121clearInterval(checkWorkerLoaded);
122resolve();
936b1ceaArtem Egorov9 years ago123}
ce5e88eeYuri Skorokhodov5 years ago124}, 1000);
125}
126
127}).then(() => {
128// Before sending messages, make sure that the worker is loaded
129const promise = this.workerLoaded
130.then(() => {
131if (rnMessage.method !== "executeApplicationScript") {
132// Before sending messages, make sure that the app script executed
133if (this.bundleLoaded) {
134return this.bundleLoaded.then(() => {
135return rnMessage;
5c8365a6Artem Egorov8 years ago136});
ce5e88eeYuri Skorokhodov5 years ago137} else {
138return rnMessage;
139}
5c8365a6Artem Egorov8 years ago140} else {
ce5e88eeYuri Skorokhodov5 years ago141// 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
144if (rnMessage.url) {
145const packagerUrl = url.parse(rnMessage.url);
146packagerUrl.host = `${this.packagerAddress}:${this.packagerPort}`;
147rnMessage = {
148...rnMessage,
149url: url.format(packagerUrl),
150};
151logger.verbose(`Packager requested runtime to load script from ${rnMessage.url}`);
152return this.scriptImporter.downloadAppScript(<string>rnMessage.url, this.projectRootPath)
153.then((downloadedScript: DownloadedScript) => {
154this.bundleLoaded = Promise.resolve();
155return Object.assign({}, rnMessage, { url: `${this.pathToFileUrl(downloadedScript.filepath)}` });
156});
157} else {
158throw ErrorHelper.getInternalError(InternalErrorCode.RNMessageWithMethodExecuteApplicationScriptDoesntHaveURLProperty);
159}
5c8365a6Artem Egorov8 years ago160}
ce5e88eeYuri Skorokhodov5 years ago161});
162promise.then(
163(message: RNAppMessage) => {
164if (this.debuggeeProcess) {
165this.debuggeeProcess.send({ data: message });
166}
167},
168(reason) => printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.CouldntImportScriptAt, rnMessage.url), reason));
6eeec3c0Serge Svekolnikov8 years ago169
ce5e88eeYuri Skorokhodov5 years ago170return promise;
171});
e45838cbVladimir Kotikov9 years ago172}
4cf8fdf4Yuri Skorokhodov6 years ago173
174// TODO: Replace by url.pathToFileURL method when Node 10 LTS become deprecated
175public pathToFileUrl(url: string) {
176const filePrefix = process.platform === "win32" ? "file:///" : "file://";
177return filePrefix + url;
178}
e45838cbVladimir Kotikov9 years ago179}