microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
gh-pages

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/forkedAppWorker.ts

182lines · 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 Q from "q";
5import * as path from "path";
6eeec3c0Serge Svekolnikov8 years ago6import * as url from "url";
e45838cbVladimir Kotikov9 years ago7import * as child_process from "child_process";
08722261Yuri Skorokhodov7 years ago8import * as fs from "fs";
5c8365a6Artem Egorov8 years ago9import {ScriptImporter, DownloadedScript} from "./scriptImporter";
e45838cbVladimir Kotikov9 years ago10
0a68f8dbArtem Egorov8 years ago11import { logger } from "vscode-chrome-debug-core";
e45838cbVladimir Kotikov9 years ago12import { ErrorHelper } from "../common/error/errorHelper";
13import { IDebuggeeWorker, RNAppMessage } from "./appWorker";
7daed3fcArtem Egorov8 years ago14import { RemoteExtension } from "../common/remoteExtension";
1758f9a6Yuri Skorokhodov7 years ago15import { InternalErrorCode } from "../common/error/internalErrorCode";
08722261Yuri Skorokhodov7 years ago16import { getLoggingDirectory } from "../extension/log/LogHelper";
e45838cbVladimir Kotikov9 years ago17
1758f9a6Yuri Skorokhodov7 years ago18function printDebuggingError(error: Error, reason: any) {
19const nestedError = ErrorHelper.getNestedError(error, InternalErrorCode.DebuggingWontWorkReloadJSAndReconnect, reason);
0a68f8dbArtem Egorov8 years ago20
21logger.error(nestedError.message);
e45838cbVladimir Kotikov9 years ago22}
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
6eeec3c0Serge Svekolnikov8 years ago33protected scriptImporter: ScriptImporter;
34protected debuggeeProcess: child_process.ChildProcess | null = null;
e45838cbVladimir Kotikov9 years ago35/** A deferred that we use to make sure that worker has been loaded completely defore start sending IPC messages */
6eeec3c0Serge Svekolnikov8 years ago36protected workerLoaded = Q.defer<void>();
5c8365a6Artem Egorov8 years ago37private bundleLoaded: Q.Deferred<void>;
7daed3fcArtem Egorov8 years ago38private remoteExtension: RemoteExtension;
08722261Yuri Skorokhodov7 years ago39private logWriteStream: fs.WriteStream;
40private logDirectory: string | null;
e45838cbVladimir Kotikov9 years ago41
42constructor(
6eeec3c0Serge Svekolnikov8 years ago43private packagerAddress: string,
e45838cbVladimir Kotikov9 years ago44private packagerPort: number,
45private sourcesStoragePath: string,
7daed3fcArtem Egorov8 years ago46private projectRootPath: string,
6eeec3c0Serge Svekolnikov8 years ago47private postReplyToApp: (message: any) => void,
48private packagerRemoteRoot?: string,
49private packagerLocalRoot?: string
e45838cbVladimir Kotikov9 years ago50) {
6eeec3c0Serge Svekolnikov8 years ago51this.scriptImporter = new ScriptImporter(this.packagerAddress, this.packagerPort, this.sourcesStoragePath, this.packagerRemoteRoot, this.packagerLocalRoot);
7daed3fcArtem Egorov8 years ago52
53this.remoteExtension = RemoteExtension.atProjectRootPath(this.projectRootPath);
54
55this.remoteExtension.api.Debugger.onShowDevMenu(() => {
56this.postMessage({
57method: "vscode_showDevMenu",
58});
59});
60
61this.remoteExtension.api.Debugger.onReloadApp(() => {
62this.postMessage({
63method: "vscode_reloadApp",
64});
65});
e45838cbVladimir Kotikov9 years ago66}
67
68public stop() {
69if (this.debuggeeProcess) {
0a68f8dbArtem Egorov8 years ago70logger.verbose(`About to kill debuggee with pid ${this.debuggeeProcess.pid}`);
e45838cbVladimir Kotikov9 years ago71this.debuggeeProcess.kill();
72this.debuggeeProcess = null;
73}
74}
75
76public start(): Q.Promise<number> {
77let scriptToRunPath = path.resolve(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILENAME);
cc70057dVladimir Kotikov9 years ago78const port = Math.round(Math.random() * 40000 + 3000);
e45838cbVladimir Kotikov9 years ago79
045132a1Yuri Skorokhodov7 years ago80// Note that we set --inspect-brk flag to pause the process on the first line - this is
cc70057dVladimir Kotikov9 years ago81// required for debug adapter to set the breakpoints BEFORE the debuggee has started.
82// The adapter will continue execution once it's done with breakpoints.
13a99427Yuri Skorokhodov6 years ago83// --no-deprecation flag disables deprecation warnings like "[DEP0005] DeprecationWarning: Buffer() is deprecated..." and so on that leads to errors in native app
84// https://nodejs.org/dist/latest-v7.x/docs/api/cli.html
85const nodeArgs = [`--inspect-brk=${port}`, "--no-deprecation", scriptToRunPath];
cc70057dVladimir Kotikov9 years ago86// Start child Node process in debugging mode
f533409bRuslan Bikkinin7 years ago87// Using fork instead of spawn causes breakage of piping between app worker and VS Code debug console, e.g. console.log() in application
88// wouldn't work. Please see https://github.com/Microsoft/vscode-react-native/issues/758
89this.debuggeeProcess = child_process.spawn("node", nodeArgs, {
90stdio: ["pipe", "pipe", "pipe", "ipc"],
91})
cc70057dVladimir Kotikov9 years ago92.on("message", (message: any) => {
93// 'workerLoaded' is a special message that indicates that worker is done with loading.
94// We need to wait for it before doing any IPC because process.send doesn't seems to care
6eeec3c0Serge Svekolnikov8 years ago95// about whether the message has been received or not and the first messages are often get
cc70057dVladimir Kotikov9 years ago96// discarded by spawned process
97if (message && message.workerLoaded) {
98this.workerLoaded.resolve(void 0);
99return;
100}
e45838cbVladimir Kotikov9 years ago101
cc70057dVladimir Kotikov9 years ago102this.postReplyToApp(message);
103})
104.on("error", (error: Error) => {
1758f9a6Yuri Skorokhodov7 years ago105printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.ReactNativeWorkerProcessThrownAnError), error);
e45838cbVladimir Kotikov9 years ago106});
cc70057dVladimir Kotikov9 years ago107
08722261Yuri Skorokhodov7 years ago108// If special env variables are defined, then write process outputs to file
109this.logDirectory = getLoggingDirectory();
110
111if (this.logDirectory) {
112this.logWriteStream = fs.createWriteStream(path.join(this.logDirectory, "nodeProcessLog.txt"));
113this.logWriteStream.on("error", err => {
114logger.error(`Error creating log file at path: ${this.logDirectory}. Error: ${err.toString()}\n`);
115});
116this.debuggeeProcess.stdout.pipe(this.logWriteStream);
117this.debuggeeProcess.stderr.pipe(this.logWriteStream);
118this.debuggeeProcess.on("close", () => {
119this.logWriteStream.end();
120});
121}
122
cc70057dVladimir Kotikov9 years ago123// Resolve with port debugger server is listening on
124// This will be sent to subscribers of MLAppWorker in "connected" event
0a68f8dbArtem Egorov8 years ago125logger.verbose(`Spawned debuggee process with pid ${this.debuggeeProcess.pid} listening to ${port}`);
cc70057dVladimir Kotikov9 years ago126
127return Q.resolve(port);
e45838cbVladimir Kotikov9 years ago128}
129
6eeec3c0Serge Svekolnikov8 years ago130public postMessage(rnMessage: RNAppMessage): Q.Promise<RNAppMessage> {
e45838cbVladimir Kotikov9 years ago131// Before sending messages, make sure that the worker is loaded
6eeec3c0Serge Svekolnikov8 years ago132const promise = this.workerLoaded.promise
936b1ceaArtem Egorov8 years ago133.then(() => {
134if (rnMessage.method !== "executeApplicationScript") {
135// Before sending messages, make sure that the app script executed
136if (this.bundleLoaded) {
137return this.bundleLoaded.promise.then(() => {
138return rnMessage;
139});
140} else {
141return rnMessage;
142}
143} else {
144this.bundleLoaded = Q.defer<void>();
145// When packager asks worker to load bundle we download that bundle and
146// then set url field to point to that downloaded bundle, so the worker
147// will take our modified bundle
5c8365a6Artem Egorov8 years ago148if (rnMessage.url) {
6eeec3c0Serge Svekolnikov8 years ago149const packagerUrl = url.parse(rnMessage.url);
150packagerUrl.host = `${this.packagerAddress}:${this.packagerPort}`;
151rnMessage = {
152...rnMessage,
153url: url.format(packagerUrl),
154};
d124bf0eYuri Skorokhodov7 years ago155logger.verbose(`Packager requested runtime to load script from ${rnMessage.url}`);
979d7bfemax-mironov8 years ago156return this.scriptImporter.downloadAppScript(<string>rnMessage.url, this.projectRootPath)
5c8365a6Artem Egorov8 years ago157.then((downloadedScript: DownloadedScript) => {
158this.bundleLoaded.resolve(void 0);
4cf8fdf4Yuri Skorokhodov6 years ago159return Object.assign({}, rnMessage, { url: `${this.pathToFileUrl(downloadedScript.filepath)}`});
5c8365a6Artem Egorov8 years ago160});
161} else {
1758f9a6Yuri Skorokhodov7 years ago162throw ErrorHelper.getInternalError(InternalErrorCode.RNMessageWithMethodExecuteApplicationScriptDoesntHaveURLProperty);
5c8365a6Artem Egorov8 years ago163}
936b1ceaArtem Egorov8 years ago164}
6eeec3c0Serge Svekolnikov8 years ago165});
166promise.done(
5c8365a6Artem Egorov8 years ago167(message: RNAppMessage) => {
168if (this.debuggeeProcess) {
169this.debuggeeProcess.send({ data: message });
170}
171},
1758f9a6Yuri Skorokhodov7 years ago172(reason) => printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.CouldntImportScriptAt, rnMessage.url), reason));
6eeec3c0Serge Svekolnikov8 years ago173
174return promise;
e45838cbVladimir Kotikov9 years ago175}
4cf8fdf4Yuri Skorokhodov6 years ago176
177// TODO: Replace by url.pathToFileURL method when Node 10 LTS become deprecated
178public pathToFileUrl(url: string) {
179const filePrefix = process.platform === "win32" ? "file:///" : "file://";
180return filePrefix + url;
181}
e45838cbVladimir Kotikov9 years ago182}