microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
dbfbebd91787effa9f8df87f8fc17707a5cb28cd

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/forkedAppWorker.ts

155lines · 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";
5c8365a6Artem Egorov8 years ago8import {ScriptImporter, DownloadedScript} from "./scriptImporter";
e45838cbVladimir Kotikov9 years ago9
0a68f8dbArtem Egorov8 years ago10import { logger } from "vscode-chrome-debug-core";
e45838cbVladimir Kotikov9 years ago11import { ErrorHelper } from "../common/error/errorHelper";
12import { IDebuggeeWorker, RNAppMessage } from "./appWorker";
7daed3fcArtem Egorov8 years ago13import { RemoteExtension } from "../common/remoteExtension";
1758f9a6Yuri Skorokhodov7 years ago14import { InternalErrorCode } from "../common/error/internalErrorCode";
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;
32protected debuggeeProcess: child_process.ChildProcess | null = null;
e45838cbVladimir Kotikov9 years ago33/** A deferred that we use to make sure that worker has been loaded completely defore start sending IPC messages */
6eeec3c0Serge Svekolnikov8 years ago34protected workerLoaded = Q.defer<void>();
5c8365a6Artem Egorov8 years ago35private bundleLoaded: Q.Deferred<void>;
7daed3fcArtem Egorov8 years ago36private remoteExtension: RemoteExtension;
e45838cbVladimir Kotikov9 years ago37
38constructor(
6eeec3c0Serge Svekolnikov8 years ago39private packagerAddress: string,
e45838cbVladimir Kotikov9 years ago40private packagerPort: number,
41private sourcesStoragePath: string,
7daed3fcArtem Egorov8 years ago42private projectRootPath: string,
6eeec3c0Serge Svekolnikov8 years ago43private postReplyToApp: (message: any) => void,
44private packagerRemoteRoot?: string,
45private packagerLocalRoot?: string
e45838cbVladimir Kotikov9 years ago46) {
6eeec3c0Serge Svekolnikov8 years ago47this.scriptImporter = new ScriptImporter(this.packagerAddress, this.packagerPort, this.sourcesStoragePath, this.packagerRemoteRoot, this.packagerLocalRoot);
7daed3fcArtem Egorov8 years ago48
49this.remoteExtension = RemoteExtension.atProjectRootPath(this.projectRootPath);
50
51this.remoteExtension.api.Debugger.onShowDevMenu(() => {
52this.postMessage({
53method: "vscode_showDevMenu",
54});
55});
56
57this.remoteExtension.api.Debugger.onReloadApp(() => {
58this.postMessage({
59method: "vscode_reloadApp",
60});
61});
e45838cbVladimir Kotikov9 years ago62}
63
64public stop() {
65if (this.debuggeeProcess) {
0a68f8dbArtem Egorov8 years ago66logger.verbose(`About to kill debuggee with pid ${this.debuggeeProcess.pid}`);
e45838cbVladimir Kotikov9 years ago67this.debuggeeProcess.kill();
68this.debuggeeProcess = null;
69}
70}
71
72public start(): Q.Promise<number> {
73let scriptToRunPath = path.resolve(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILENAME);
cc70057dVladimir Kotikov9 years ago74const port = Math.round(Math.random() * 40000 + 3000);
e45838cbVladimir Kotikov9 years ago75
cc70057dVladimir Kotikov9 years ago76// Note that we set --debug-brk flag to pause the process on the first line - this is
77// required for debug adapter to set the breakpoints BEFORE the debuggee has started.
78// The adapter will continue execution once it's done with breakpoints.
f533409bRuslan Bikkinin7 years ago79const nodeArgs = [`--inspect=${port}`, "--debug-brk", scriptToRunPath];
cc70057dVladimir Kotikov9 years ago80// Start child Node process in debugging mode
f533409bRuslan Bikkinin7 years ago81// Using fork instead of spawn causes breakage of piping between app worker and VS Code debug console, e.g. console.log() in application
82// wouldn't work. Please see https://github.com/Microsoft/vscode-react-native/issues/758
83this.debuggeeProcess = child_process.spawn("node", nodeArgs, {
84stdio: ["pipe", "pipe", "pipe", "ipc"],
85})
cc70057dVladimir Kotikov9 years ago86.on("message", (message: any) => {
87// 'workerLoaded' is a special message that indicates that worker is done with loading.
88// We need to wait for it before doing any IPC because process.send doesn't seems to care
6eeec3c0Serge Svekolnikov8 years ago89// about whether the message has been received or not and the first messages are often get
cc70057dVladimir Kotikov9 years ago90// discarded by spawned process
91if (message && message.workerLoaded) {
92this.workerLoaded.resolve(void 0);
93return;
94}
e45838cbVladimir Kotikov9 years ago95
cc70057dVladimir Kotikov9 years ago96this.postReplyToApp(message);
97})
98.on("error", (error: Error) => {
1758f9a6Yuri Skorokhodov7 years ago99printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.ReactNativeWorkerProcessThrownAnError), error);
e45838cbVladimir Kotikov9 years ago100});
cc70057dVladimir Kotikov9 years ago101
102// Resolve with port debugger server is listening on
103// This will be sent to subscribers of MLAppWorker in "connected" event
0a68f8dbArtem Egorov8 years ago104logger.verbose(`Spawned debuggee process with pid ${this.debuggeeProcess.pid} listening to ${port}`);
cc70057dVladimir Kotikov9 years ago105
106return Q.resolve(port);
e45838cbVladimir Kotikov9 years ago107}
108
6eeec3c0Serge Svekolnikov8 years ago109public postMessage(rnMessage: RNAppMessage): Q.Promise<RNAppMessage> {
e45838cbVladimir Kotikov9 years ago110// Before sending messages, make sure that the worker is loaded
6eeec3c0Serge Svekolnikov8 years ago111const promise = this.workerLoaded.promise
936b1ceaArtem Egorov8 years ago112.then(() => {
113if (rnMessage.method !== "executeApplicationScript") {
114// Before sending messages, make sure that the app script executed
115if (this.bundleLoaded) {
116return this.bundleLoaded.promise.then(() => {
117return rnMessage;
118});
119} else {
120return rnMessage;
121}
122} else {
123this.bundleLoaded = Q.defer<void>();
124// When packager asks worker to load bundle we download that bundle and
125// then set url field to point to that downloaded bundle, so the worker
126// will take our modified bundle
5c8365a6Artem Egorov8 years ago127if (rnMessage.url) {
6eeec3c0Serge Svekolnikov8 years ago128const packagerUrl = url.parse(rnMessage.url);
129packagerUrl.host = `${this.packagerAddress}:${this.packagerPort}`;
130rnMessage = {
131...rnMessage,
132url: url.format(packagerUrl),
133};
d124bf0eYuri Skorokhodov7 years ago134logger.verbose(`Packager requested runtime to load script from ${rnMessage.url}`);
979d7bfemax-mironov8 years ago135return this.scriptImporter.downloadAppScript(<string>rnMessage.url, this.projectRootPath)
5c8365a6Artem Egorov8 years ago136.then((downloadedScript: DownloadedScript) => {
137this.bundleLoaded.resolve(void 0);
138return Object.assign({}, rnMessage, { url: downloadedScript.filepath });
139});
140} else {
1758f9a6Yuri Skorokhodov7 years ago141throw ErrorHelper.getInternalError(InternalErrorCode.RNMessageWithMethodExecuteApplicationScriptDoesntHaveURLProperty);
5c8365a6Artem Egorov8 years ago142}
936b1ceaArtem Egorov8 years ago143}
6eeec3c0Serge Svekolnikov8 years ago144});
145promise.done(
5c8365a6Artem Egorov8 years ago146(message: RNAppMessage) => {
147if (this.debuggeeProcess) {
148this.debuggeeProcess.send({ data: message });
149}
150},
1758f9a6Yuri Skorokhodov7 years ago151(reason) => printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.CouldntImportScriptAt, rnMessage.url), reason));
6eeec3c0Serge Svekolnikov8 years ago152
153return promise;
e45838cbVladimir Kotikov9 years ago154}
155}