microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
0.3.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/appWorker.ts

235lines · 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 {Packager} from "../common/packager";
9import {ErrorHelper} from "../common/error/errorHelper";
10import {Log} from "../common/log/log";
11import {LogLevel} from "../common/log/logHelper";
12import {ExecutionsLimiter} from "../common/executionsLimiter";
13import { FileSystem as NodeFileSystem} from "../common/node/fileSystem";
14import { ForkedAppWorker } from "./forkedAppWorker";
15import { ScriptImporter } from "./scriptImporter";
16
17export interface RNAppMessage {
18 method: string;
19 url?: string;
20 // These objects have also other properties but that we don't currently use
21}
22
23export interface IDebuggeeWorker {
24 start(): Q.Promise<any>;
25 stop(): void;
26 postMessage(message: RNAppMessage): void;
27}
28
29function printDebuggingError(message: string, reason: any) {
30 Log.logWarning(ErrorHelper.getNestedWarning(reason, `${message}. Debugging won't work: Try reloading the JS from inside the app, or Reconnect the VS Code debugger`));
31}
32
33 /** This class will create a SandboxedAppWorker that will run the RN App logic, and then create a socket
34 * and send the RN App messages to the SandboxedAppWorker. The only RN App message that this class handles
35 * is the prepareJSRuntime, which we reply to the RN App that the sandbox was created successfully.
36 * When the socket closes, we'll create a new SandboxedAppWorker and a new socket pair and discard the old ones.
37 */
38
39export class MultipleLifetimesAppWorker extends EventEmitter {
40 public static WORKER_BOOTSTRAP = `
41// Initialize some variables before react-native code would access them
42// and also avoid Node's GLOBAL deprecation warning
43var onmessage=null, self=global.GLOBAL=global;
44// Cache Node's original require as __debug__.require
45var __debug__={require: require};
46process.on("message", function(message){
47 if (onmessage) onmessage(message);
48});
49var postMessage = function(message){
50 process.send(message);
51};
52var importScripts = (function(){
53 var fs=require('fs'), vm=require('vm');
54 return function(scriptUrl){
55 var scriptCode = fs.readFileSync(scriptUrl, "utf8");
56 vm.runInThisContext(scriptCode, {filename: scriptUrl});
57 };
58})();`;
59
60 public static WORKER_DONE = `// Notify debugger that we're done with loading
61// and started listening for IPC messages
62postMessage({workerLoaded:true});`;
63
64 private packagerPort: number;
65 private sourcesStoragePath: string;
66 private socketToApp: WebSocket;
67 private singleLifetimeWorker: IDebuggeeWorker;
68 private webSocketConstructor: (url: string) => WebSocket;
69
70 private executionLimiter = new ExecutionsLimiter();
71 private nodeFileSystem = new NodeFileSystem();
72 private scriptImporter: ScriptImporter;
73
74 constructor(packagerPort: number, sourcesStoragePath: string, {
75 webSocketConstructor = (url: string) => new WebSocket(url),
76 } = {}) {
77 super();
78 this.packagerPort = packagerPort;
79 this.sourcesStoragePath = sourcesStoragePath;
80 console.assert(!!this.sourcesStoragePath, "The sourcesStoragePath argument was null or empty");
81
82 this.webSocketConstructor = webSocketConstructor;
83 this.scriptImporter = new ScriptImporter(packagerPort, sourcesStoragePath);
84 }
85
86 public start(retryAttempt: boolean = false): Q.Promise<any> {
87 return Packager.isPackagerRunning(Packager.getHostForPort(this.packagerPort))
88 .then(running => {
89 if (!running) {
90 throw new Error(`Cannot attach to packager. Are you sure there is a packager and it is running in the port ${this.packagerPort}? If your packager is configured to run in another port make sure to add that to the setting.json.`);
91 }
92 })
93 .then(() => {
94 // Don't fetch debugger worker on socket disconnect
95 return retryAttempt ? Q.resolve<void>(void 0) :
96 this.downloadAndPatchDebuggerWorker();
97 })
98 .then(() => this.createSocketToApp(retryAttempt));
99 }
100
101 public stop() {
102 if (this.socketToApp) {
103 this.socketToApp.removeAllListeners();
104 this.socketToApp.close();
105 }
106
107 if (this.singleLifetimeWorker) {
108 this.singleLifetimeWorker.stop();
109 }
110 }
111
112 public downloadAndPatchDebuggerWorker(): Q.Promise<void> {
113 let scriptToRunPath = path.resolve(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILENAME);
114 return this.scriptImporter.downloadDebuggerWorker(this.sourcesStoragePath)
115 .then(() => this.nodeFileSystem.readFile(scriptToRunPath, "utf8"))
116 .then((workerContent: string) => {
117 // Add our customizations to debugger worker to get it working smoothly
118 // in Node env and polyfill WebWorkers API over Node's IPC.
119 const modifiedDebuggeeContent = [MultipleLifetimesAppWorker.WORKER_BOOTSTRAP,
120 workerContent, MultipleLifetimesAppWorker.WORKER_DONE].join("\n");
121 return this.nodeFileSystem.writeFile(scriptToRunPath, modifiedDebuggeeContent);
122 });
123 }
124
125 private startNewWorkerLifetime(): Q.Promise<void> {
126 this.singleLifetimeWorker = new ForkedAppWorker(this.packagerPort, this.sourcesStoragePath, (message) => {
127 this.sendMessageToApp(message);
128 });
129 Log.logInternalMessage(LogLevel.Info, "A new app worker lifetime was created.");
130 return this.singleLifetimeWorker.start()
131 .then(startedEvent => {
132 this.emit("connected", startedEvent);
133 });
134 }
135
136 private createSocketToApp(retryAttempt: boolean = false): Q.Promise<void> {
137 let deferred = Q.defer<void>();
138 this.socketToApp = this.webSocketConstructor(this.debuggerProxyUrl());
139 this.socketToApp.on("open", () => {
140 this.onSocketOpened();
141 });
142 this.socketToApp.on("close",
143 () => {
144 this.executionLimiter.execute("onSocketClose.msg", /*limitInSeconds*/ 10, () => {
145 /*
146 * It is not the best idea to compare with the message, but this is the only thing React Native gives that is unique when
147 * it closes the socket because it already has a connection to a debugger.
148 * https://github.com/facebook/react-native/blob/588f01e9982775f0699c7bfd56623d4ed3949810/local-cli/server/util/webSocketProxy.js#L38
149 */
150 if (this.socketToApp._closeMessage === "Another debugger is already connected") {
151 deferred.reject(new RangeError("Another debugger is already connected to packager. Please close it before trying to debug with VSCode."));
152 }
153 Log.logMessage("Disconnected from the Proxy (Packager) to the React Native application. Retrying reconnection soon...");
154 });
155 setTimeout(() => {
156 this.start(true /* retryAttempt */);
157 }, 100);
158 });
159 this.socketToApp.on("message",
160 (message: any) => this.onMessage(message));
161 this.socketToApp.on("error",
162 (error: Error) => {
163 if (retryAttempt) {
164 Log.logWarning(ErrorHelper.getNestedWarning(error,
165 "Reconnection to the proxy (Packager) failed. Please check the output window for Packager errors, if any. If failure persists, please restart the React Native debugger."));
166 }
167
168 deferred.reject(error);
169 });
170
171 // In an attempt to catch failures in starting the packager on first attempt,
172 // wait for 300 ms before resolving the promise
173 Q.delay(300).done(() => deferred.resolve(void 0));
174 return deferred.promise;
175 }
176
177 private debuggerProxyUrl() {
178 return `ws://${Packager.getHostForPort(this.packagerPort)}/debugger-proxy?role=debugger&name=vscode`;
179 }
180
181 private onSocketOpened() {
182 this.executionLimiter.execute("onSocketOpened.msg", /*limitInSeconds*/ 10, () =>
183 Log.logMessage("Established a connection with the Proxy (Packager) to the React Native application"));
184 }
185
186 private killWorker() {
187 if (!this.singleLifetimeWorker) return;
188 this.singleLifetimeWorker.stop();
189 this.singleLifetimeWorker = null;
190 }
191
192 private onMessage(message: string) {
193 try {
194 Log.logInternalMessage(LogLevel.Trace, "From RN APP: " + message);
195 let object = <RNAppMessage>JSON.parse(message);
196 if (object.method === "prepareJSRuntime") {
197 // In RN 0.40 Android runtime doesn't seem to be sending "$disconnected" event
198 // when user reloads an app, hence we need to try to kill it here either.
199 this.killWorker();
200 // The MultipleLifetimesAppWorker will handle prepareJSRuntime aka create new lifetime
201 this.gotPrepareJSRuntime(object);
202 } else if (object.method === "$disconnected") {
203 // We need to shutdown the current app worker, and create a new lifetime
204 this.killWorker();
205 } else if (object.method) {
206 // All the other messages are handled by the single lifetime worker
207 this.singleLifetimeWorker.postMessage(object);
208 } else {
209 // Message doesn't have a method. Ignore it. This is an info message instead of warn because it's normal and expected
210 Log.logInternalMessage(LogLevel.Info, "The react-native app sent a message without specifying a method: " + message);
211 }
212 } catch (exception) {
213 printDebuggingError(`Failed to process message from the React Native app. Message:\n${message}`, exception);
214 }
215 }
216
217 private gotPrepareJSRuntime(message: any): void {
218 // Create the sandbox, and replay that we finished processing the message
219 this.startNewWorkerLifetime().done(() => {
220 this.sendMessageToApp({ replyID: parseInt(message.id, 10) });
221 }, error => printDebuggingError(`Failed to prepare the JavaScript runtime environment. Message:\n${message}`, error));
222 }
223
224 private sendMessageToApp(message: any): void {
225 let stringified: string = null;
226 try {
227 stringified = JSON.stringify(message);
228 Log.logInternalMessage(LogLevel.Trace, "To RN APP: " + stringified);
229 this.socketToApp.send(stringified);
230 } catch (exception) {
231 let messageToShow = stringified || ("" + message); // Try to show the stringified version, but show the toString if unavailable
232 printDebuggingError(`Failed to send message to the React Native app. Message:\n${messageToShow}`, exception);
233 }
234 }
235}
236