microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
efbe1ba61ca71887b3fa9a2d1ae3afb9a78cb87e

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/appWorker.ts

319lines · 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 WebSocket from "ws";
7import { EventEmitter } from "events";
8import { ensurePackagerRunning } from "../common/packagerStatus";
9import {ErrorHelper} from "../common/error/errorHelper";
10import { logger } from "vscode-chrome-debug-core";
11import {ExecutionsLimiter} from "../common/executionsLimiter";
12import { FileSystem as NodeFileSystem} from "../common/node/fileSystem";
13import { ForkedAppWorker } from "./forkedAppWorker";
14import { ScriptImporter } from "./scriptImporter";
15import { ReactNativeProjectHelper } from "../common/reactNativeProjectHelper";
16import * as nls from "vscode-nls";
17import { InternalErrorCode } from "../common/error/internalErrorCode";
18const localize = nls.loadMessageBundle();
19
20export interface RNAppMessage {
21 method: string;
22 url?: string;
23 // These objects have also other properties but that we don't currently use
24}
25
26export interface IDebuggeeWorker {
27 start(): Q.Promise<any>;
28 stop(): void;
29 postMessage(message: RNAppMessage): void;
30}
31
32function printDebuggingError(error: Error, reason: any) {
33 const nestedError = ErrorHelper.getNestedError(error, InternalErrorCode.DebuggingWontWorkReloadJSAndReconnect, reason);
34
35 logger.error(nestedError.message);
36}
37
38 /** This class will create a SandboxedAppWorker that will run the RN App logic, and then create a socket
39 * and send the RN App messages to the SandboxedAppWorker. The only RN App message that this class handles
40 * is the prepareJSRuntime, which we reply to the RN App that the sandbox was created successfully.
41 * When the socket closes, we'll create a new SandboxedAppWorker and a new socket pair and discard the old ones.
42 */
43
44export class MultipleLifetimesAppWorker extends EventEmitter {
45 public static WORKER_BOOTSTRAP = `
46// Initialize some variables before react-native code would access them
47var onmessage=null, self=global;
48// Cache Node's original require as __debug__.require
49global.__debug__={require: require};
50// avoid Node's GLOBAL deprecation warning
51Object.defineProperty(global, "GLOBAL", {
52 configurable: true,
53 writable: true,
54 enumerable: true,
55 value: global
56});
57// Prevent leaking process.versions from debugger process to
58// worker because pure React Native doesn't do that and some packages as js-md5 rely on this behavior
59Object.defineProperty(process, "versions", {
60 value: undefined
61});
62
63var vscodeHandlers = {
64 'vscode_reloadApp': function () {
65 try {
66 global.require('NativeModules').DevMenu.reload();
67 } catch (err) {
68 // ignore
69 }
70 },
71 'vscode_showDevMenu': function () {
72 try {
73 var DevMenu = global.require('NativeModules').DevMenu.show();
74 } catch (err) {
75 // ignore
76 }
77 }
78};
79
80process.on("message", function (message) {
81 if (message.data && vscodeHandlers[message.data.method]) {
82 vscodeHandlers[message.data.method]();
83 } else if(onmessage) {
84 onmessage(message);
85 }
86});
87
88var postMessage = function(message){
89 process.send(message);
90};
91
92if (!self.postMessage) {
93 self.postMessage = postMessage;
94}
95
96var importScripts = (function(){
97 var fs=require('fs'), vm=require('vm');
98 return function(scriptUrl){
99 var scriptCode = fs.readFileSync(scriptUrl, "utf8");
100 vm.runInThisContext(scriptCode, {filename: scriptUrl});
101 };
102})();`;
103
104 public static WORKER_DONE = `// Notify debugger that we're done with loading
105// and started listening for IPC messages
106postMessage({workerLoaded:true});`;
107
108 public static FETCH_STUB = `(function(self) {
109 'use strict';
110
111 if (self.fetch) {
112 return
113 }
114
115 self.fetch = fetch;
116
117 function fetch(url) {
118 return new Promise((resolve, reject) => {
119 var data = require("fs").readFileSync(url, 'utf8');
120 resolve(
121 {
122 text: function () {
123 return data;
124 }
125 });
126 });
127 }
128 })(global);`;
129
130 private packagerAddress: string;
131 private packagerPort: number;
132 private sourcesStoragePath: string;
133 private projectRootPath: string;
134 private packagerRemoteRoot?: string;
135 private packagerLocalRoot?: string;
136 private socketToApp: WebSocket;
137 private singleLifetimeWorker: IDebuggeeWorker | null;
138 private webSocketConstructor: (url: string) => WebSocket;
139
140 private executionLimiter = new ExecutionsLimiter();
141 private nodeFileSystem = new NodeFileSystem();
142 private scriptImporter: ScriptImporter;
143
144 constructor(
145 attachRequestArguments: any,
146 sourcesStoragePath: string,
147 projectRootPath: string,
148 {
149 webSocketConstructor = (url: string) => new WebSocket(url),
150 } = {}) {
151 super();
152 this.packagerAddress = attachRequestArguments.address || "localhost";
153 this.packagerPort = attachRequestArguments.port;
154 this.packagerRemoteRoot = attachRequestArguments.remoteRoot;
155 this.packagerLocalRoot = attachRequestArguments.localRoot;
156 this.sourcesStoragePath = sourcesStoragePath;
157 this.projectRootPath = projectRootPath;
158 if (!this.sourcesStoragePath)
159 throw ErrorHelper.getInternalError(InternalErrorCode.SourcesStoragePathIsNullOrEmpty);
160 this.webSocketConstructor = webSocketConstructor;
161 this.scriptImporter = new ScriptImporter(this.packagerAddress, this.packagerPort, sourcesStoragePath, this.packagerRemoteRoot, this.packagerLocalRoot);
162 }
163
164 public start(retryAttempt: boolean = false): Q.Promise<any> {
165 const errPackagerNotRunning = ErrorHelper.getInternalError(InternalErrorCode.CannotAttachToPackagerCheckPackagerRunningOnPort, this.packagerPort);
166
167 return ensurePackagerRunning(this.packagerAddress, this.packagerPort, errPackagerNotRunning)
168 .then(() => {
169 // Don't fetch debugger worker on socket disconnect
170 return retryAttempt ? Q.resolve<void>(void 0) :
171 this.downloadAndPatchDebuggerWorker();
172 })
173 .then(() => this.createSocketToApp(retryAttempt));
174 }
175
176 public stop() {
177 if (this.socketToApp) {
178 this.socketToApp.removeAllListeners();
179 this.socketToApp.close();
180 }
181
182 if (this.singleLifetimeWorker) {
183 this.singleLifetimeWorker.stop();
184 }
185 }
186
187 public downloadAndPatchDebuggerWorker(): Q.Promise<void> {
188 let scriptToRunPath = path.resolve(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILENAME);
189 return this.scriptImporter.downloadDebuggerWorker(this.sourcesStoragePath, this.projectRootPath)
190 .then(() => this.nodeFileSystem.readFile(scriptToRunPath, "utf8"))
191 .then((workerContent: string) => {
192 const isHaulProject = ReactNativeProjectHelper.isHaulProject(this.projectRootPath);
193 // Add our customizations to debugger worker to get it working smoothly
194 // in Node env and polyfill WebWorkers API over Node's IPC.
195 const modifiedDebuggeeContent = [
196 MultipleLifetimesAppWorker.WORKER_BOOTSTRAP,
197 isHaulProject ? MultipleLifetimesAppWorker.FETCH_STUB : null,
198 workerContent,
199 MultipleLifetimesAppWorker.WORKER_DONE,
200 ].join("\n");
201 return this.nodeFileSystem.writeFile(scriptToRunPath, modifiedDebuggeeContent);
202 });
203 }
204
205 private startNewWorkerLifetime(): Q.Promise<void> {
206 this.singleLifetimeWorker = new ForkedAppWorker(this.packagerAddress, this.packagerPort, this.sourcesStoragePath, this.projectRootPath,
207 (message) => {
208 this.sendMessageToApp(message);
209 },
210 this.packagerRemoteRoot, this.packagerLocalRoot);
211 logger.verbose("A new app worker lifetime was created.");
212 return this.singleLifetimeWorker.start()
213 .then(startedEvent => {
214 this.emit("connected", startedEvent);
215 });
216 }
217
218 private createSocketToApp(retryAttempt: boolean = false): Q.Promise<void> {
219 let deferred = Q.defer<void>();
220 this.socketToApp = this.webSocketConstructor(this.debuggerProxyUrl());
221 this.socketToApp.on("open", () => {
222 this.onSocketOpened();
223 });
224 this.socketToApp.on("close",
225 () => {
226 this.executionLimiter.execute("onSocketClose.msg", /*limitInSeconds*/ 10, () => {
227 /*
228 * It is not the best idea to compare with the message, but this is the only thing React Native gives that is unique when
229 * it closes the socket because it already has a connection to a debugger.
230 * https://github.com/facebook/react-native/blob/588f01e9982775f0699c7bfd56623d4ed3949810/local-cli/server/util/webSocketProxy.js#L38
231 */
232 let msgKey = "_closeMessage";
233 if (this.socketToApp[msgKey] === "Another debugger is already connected") {
234 deferred.reject(ErrorHelper.getInternalError(InternalErrorCode.AnotherDebuggerConnectedToPackager));
235 }
236 logger.log(localize("DisconnectedFromThePackagerToReactNative", "Disconnected from the Proxy (Packager) to the React Native application. Retrying reconnection soon..."));
237 });
238 setTimeout(() => {
239 this.start(true /* retryAttempt */);
240 }, 100);
241 });
242 this.socketToApp.on("message",
243 (message: any) => this.onMessage(message));
244 this.socketToApp.on("error",
245 (error: Error) => {
246 if (retryAttempt) {
247 printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.ReconnectionToPackagerFailedCheckForErrorsOrRestartReactNative), error);
248 }
249
250 deferred.reject(error);
251 });
252
253 // In an attempt to catch failures in starting the packager on first attempt,
254 // wait for 300 ms before resolving the promise
255 Q.delay(300).done(() => deferred.resolve(void 0));
256 return deferred.promise;
257 }
258
259 private debuggerProxyUrl() {
260 return `ws://${this.packagerAddress}:${this.packagerPort}/debugger-proxy?role=debugger&name=vscode`;
261 }
262
263 private onSocketOpened() {
264 this.executionLimiter.execute("onSocketOpened.msg", /*limitInSeconds*/ 10, () =>
265 logger.log(localize("EstablishedConnectionWithPackagerToReactNativeApp", "Established a connection with the Proxy (Packager) to the React Native application")));
266 }
267
268 private killWorker() {
269 if (!this.singleLifetimeWorker) return;
270 this.singleLifetimeWorker.stop();
271 this.singleLifetimeWorker = null;
272 }
273
274 private onMessage(message: string) {
275 try {
276 logger.verbose("From RN APP: " + message);
277 let object = <RNAppMessage>JSON.parse(message);
278 if (object.method === "prepareJSRuntime") {
279 // In RN 0.40 Android runtime doesn't seem to be sending "$disconnected" event
280 // when user reloads an app, hence we need to try to kill it here either.
281 this.killWorker();
282 // The MultipleLifetimesAppWorker will handle prepareJSRuntime aka create new lifetime
283 this.gotPrepareJSRuntime(object);
284 } else if (object.method === "$disconnected") {
285 // We need to shutdown the current app worker, and create a new lifetime
286 this.killWorker();
287 } else if (object.method) {
288 // All the other messages are handled by the single lifetime worker
289 if (this.singleLifetimeWorker) {
290 this.singleLifetimeWorker.postMessage(object);
291 }
292 } else {
293 // Message doesn't have a method. Ignore it. This is an info message instead of warn because it's normal and expected
294 logger.verbose(`The react-native app sent a message without specifying a method: ${message}`);
295 }
296 } catch (exception) {
297 printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.FailedToProcessMessageFromReactNativeApp, message), exception);
298 }
299 }
300
301 private gotPrepareJSRuntime(message: any): void {
302 // Create the sandbox, and replay that we finished processing the message
303 this.startNewWorkerLifetime().done(() => {
304 this.sendMessageToApp({ replyID: parseInt(message.id, 10) });
305 }, error => printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.FailedToPrepareJSRuntimeEnvironment, message), error));
306 }
307
308 private sendMessageToApp(message: any): void {
309 let stringified: string = "";
310 try {
311 stringified = JSON.stringify(message);
312 logger.verbose(`To RN APP: ${stringified}`);
313 this.socketToApp.send(stringified);
314 } catch (exception) {
315 let messageToShow = stringified || ("" + message); // Try to show the stringified version, but show the toString if unavailable
316 printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.FailedToSendMessageToTheReactNativeApp, messageToShow), exception);
317 }
318 }
319}
320