microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
280c07463f45573fc0cd19fc2d2eb91eb3e828fd

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/extension/extensionServer.ts

261lines · 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 net from "net";
5import * as Q from "q";
6import * as vscode from "vscode";
7
8import * as em from "../common/extensionMessaging";
9import {Log} from "../common/log/log";
10import {LogLevel} from "../common/log/logHelper";
11import {Packager} from "../common/packager";
12import {PackagerStatus, PackagerStatusIndicator} from "./packagerStatusIndicator";
13import {LogCatMonitor} from "./android/logCatMonitor";
14import {FileSystem} from "../common/node/fileSystem";
15import {ConfigurationReader} from "../common/configurationReader";
16import {SettingsHelper} from "./settingsHelper";
17import {Telemetry} from "../common/telemetry";
18import {ExponentHelper} from "../common/exponent/exponentHelper";
19
20export class ExtensionServer implements vscode.Disposable {
21 private serverInstance: net.Server = null;
22 private messageHandlerDictionary: { [id: number]: ((...argArray: any[]) => Q.Promise<any>) } = {};
23 private reactNativePackager: Packager;
24 private reactNativePackageStatusIndicator: PackagerStatusIndicator;
25 private pipePath: string;
26 private logCatMonitor: LogCatMonitor = null;
27 private exponentHelper: ExponentHelper;
28
29 public constructor(projectRootPath: string, reactNativePackager: Packager, packagerStatusIndicator: PackagerStatusIndicator, exponentHelper: ExponentHelper) {
30
31 this.pipePath = new em.MessagingChannel(projectRootPath).getPath();
32 this.reactNativePackager = reactNativePackager;
33 this.reactNativePackageStatusIndicator = packagerStatusIndicator;
34 this.exponentHelper = exponentHelper;
35
36 /* register handlers for all messages */
37 this.messageHandlerDictionary[em.ExtensionMessage.START_PACKAGER] = this.startPackager;
38 this.messageHandlerDictionary[em.ExtensionMessage.STOP_PACKAGER] = this.stopPackager;
39 this.messageHandlerDictionary[em.ExtensionMessage.RESTART_PACKAGER] = this.restartPackager;
40 this.messageHandlerDictionary[em.ExtensionMessage.PREWARM_BUNDLE_CACHE] = this.prewarmBundleCache;
41 this.messageHandlerDictionary[em.ExtensionMessage.START_MONITORING_LOGCAT] = this.startMonitoringLogCat;
42 this.messageHandlerDictionary[em.ExtensionMessage.STOP_MONITORING_LOGCAT] = this.stopMonitoringLogCat;
43 this.messageHandlerDictionary[em.ExtensionMessage.GET_PACKAGER_PORT] = this.getPackagerPort;
44 this.messageHandlerDictionary[em.ExtensionMessage.SEND_TELEMETRY] = this.sendTelemetry;
45 this.messageHandlerDictionary[em.ExtensionMessage.OPEN_FILE_AT_LOCATION] = this.openFileAtLocation;
46 this.messageHandlerDictionary[em.ExtensionMessage.START_EXPONENT_PACKAGER] = this.startExponentPackager;
47 this.messageHandlerDictionary[em.ExtensionMessage.SHOW_INFORMATION_MESSAGE] = this.showInformationMessage;
48 }
49
50 /**
51 * Starts the server.
52 */
53 public setup(): Q.Promise<void> {
54
55 let deferred = Q.defer<void>();
56
57 let launchCallback = (error: any) => {
58 Log.logInternalMessage(LogLevel.Info, `Extension messaging server started at ${this.pipePath}.`);
59 if (error) {
60 deferred.reject(error);
61 } else {
62 deferred.resolve(null);
63 }
64 };
65
66 this.serverInstance = net.createServer(this.handleSocket.bind(this));
67 this.serverInstance.on("error", this.recoverServer.bind(this));
68 this.serverInstance.listen(this.pipePath, launchCallback);
69
70 return deferred.promise;
71 }
72
73 /**
74 * Stops the server.
75 */
76 public dispose(): void {
77 if (this.serverInstance) {
78 this.serverInstance.close();
79 this.serverInstance = null;
80 }
81
82 this.stopMonitoringLogCat();
83 }
84
85 /**
86 * Message handler for GET_PACKAGER_PORT.
87 */
88 private getPackagerPort(): Q.Promise<number> {
89 return Q(SettingsHelper.getPackagerPort());
90 }
91
92 /**
93 * Message handler for START_PACKAGER.
94 */
95 private startPackager(port?: any): Q.Promise<any> {
96 return this.exponentHelper.configureReactNativeEnvironment()
97 .then(() => {
98 const portToUse = ConfigurationReader.readIntWithDefaultSync(port, SettingsHelper.getPackagerPort());
99 return this.reactNativePackager.startAsReactNative(portToUse);
100 })
101 .then(() =>
102 this.reactNativePackageStatusIndicator.updatePackagerStatus(PackagerStatus.PACKAGER_STARTED));
103 }
104
105 /**
106 * Message handler for START_EXPONENT_PACKAGER.
107 */
108 private startExponentPackager(port?: any): Q.Promise<any> {
109 return this.exponentHelper.configureExponentEnvironment()
110 .then(() => {
111 const portToUse = ConfigurationReader.readIntWithDefaultSync(port, SettingsHelper.getPackagerPort());
112 return this.reactNativePackager.startAsExponent(portToUse);
113 })
114 .then(exponentUrl => {
115 this.reactNativePackageStatusIndicator.updatePackagerStatus(PackagerStatus.EXPONENT_PACKAGER_STARTED);
116 return exponentUrl;
117 });
118 }
119
120 /**
121 * Message handler for STOP_PACKAGER.
122 */
123 private stopPackager(): Q.Promise<any> {
124 return this.reactNativePackager.stop()
125 .then(() => this.reactNativePackageStatusIndicator.updatePackagerStatus(PackagerStatus.PACKAGER_STOPPED));
126 }
127
128 /**
129 * Message handler for RESTART_PACKAGER.
130 */
131 private restartPackager(port?: any): Q.Promise<any> {
132 const portToUse = ConfigurationReader.readIntWithDefaultSync(port, SettingsHelper.getPackagerPort());
133 return this.reactNativePackager.restart(portToUse)
134 .then(() =>
135 this.reactNativePackageStatusIndicator.updatePackagerStatus(PackagerStatus.PACKAGER_STARTED));
136 }
137
138 /**
139 * Message handler for PREWARM_BUNDLE_CACHE.
140 */
141 private prewarmBundleCache(platform: string): Q.Promise<any> {
142 return this.reactNativePackager.prewarmBundleCache(platform);
143 }
144
145 /**
146 * Message handler for START_MONITORING_LOGCAT.
147 */
148 private startMonitoringLogCat(deviceId: string, logCatArguments: string): Q.Promise<any> {
149 this.stopMonitoringLogCat(); // Stop previous logcat monitor if it's running
150
151 // this.logCatMonitor can be mutated, so we store it locally too
152 const logCatMonitor = this.logCatMonitor = new LogCatMonitor(deviceId, logCatArguments);
153 logCatMonitor.start() // The LogCat will continue running forever, so we don't wait for it
154 .catch(error =>
155 Log.logWarning("Error while monitoring LogCat", error))
156 .done();
157
158 return Q.resolve<void>(void 0);
159 }
160
161 /**
162 * Message handler for OPEN_FILE_AT_LOCATION
163 */
164 private openFileAtLocation(filename: string, lineNumber: number): Q.Promise<void> {
165 return Q(vscode.workspace.openTextDocument(vscode.Uri.file(filename)).then((document: vscode.TextDocument) => {
166 return vscode.window.showTextDocument(document).then((editor: vscode.TextEditor) => {
167 let range = editor.document.lineAt(lineNumber - 1).range;
168 editor.selection = new vscode.Selection(range.start, range.end);
169 editor.revealRange(range, vscode.TextEditorRevealType.InCenter);
170 });
171 }));
172 }
173
174 private stopMonitoringLogCat(): Q.Promise<void> {
175 if (this.logCatMonitor) {
176 this.logCatMonitor.dispose();
177 this.logCatMonitor = null;
178 }
179
180 return Q.resolve<void>(void 0);
181 }
182
183 /**
184 * Sends telemetry
185 */
186 private sendTelemetry(extensionId: string, extensionVersion: string, appInsightsKey: string, eventName: string, properties: {[key: string]: string}, measures: {[key: string]: number}): Q.Promise<any> {
187 Telemetry.sendExtensionTelemetry(extensionId, extensionVersion, appInsightsKey, eventName, properties, measures);
188 return Q.resolve({});
189 }
190
191 /**
192 * Extension message handler.
193 */
194 private handleExtensionMessage(messageWithArgs: em.MessageWithArguments): Q.Promise<any> {
195 let handler = this.messageHandlerDictionary[messageWithArgs.message];
196 if (handler) {
197 Log.logInternalMessage(LogLevel.Info, "Handling message: " + em.ExtensionMessage[messageWithArgs.message]);
198 return handler.apply(this, messageWithArgs.args);
199 } else {
200 return Q.reject("Invalid message: " + messageWithArgs.message);
201 }
202 }
203
204 /**
205 * Handles connections to the server.
206 */
207 private handleSocket(socket: net.Socket): void {
208 let handleError = (e: any) => {
209 Log.logError(e);
210 socket.end(em.ErrorMarker);
211 };
212
213 let dataCallback = (data: any) => {
214 try {
215 let messageWithArgs: em.MessageWithArguments = JSON.parse(data);
216 this.handleExtensionMessage(messageWithArgs)
217 .then(result => {
218 socket.end(JSON.stringify(result));
219 })
220 .catch((e) => { handleError(e); })
221 .done();
222 } catch (e) {
223 handleError(e);
224 }
225 };
226
227 socket.on("data", dataCallback);
228 };
229
230 /**
231 * Recovers the server in case the named socket we use already exists, but no other instance of VSCode is active.
232 */
233 private recoverServer(error: any): void {
234 let errorHandler = (e: any) => {
235 /* The named socket is not used. */
236 if (e.code === "ECONNREFUSED") {
237 new FileSystem().removePathRecursivelyAsync(this.pipePath)
238 .then(() => {
239 this.serverInstance.listen(this.pipePath);
240 })
241 .done();
242 }
243 };
244
245 /* The named socket already exists. */
246 if (error.code === "EADDRINUSE") {
247 let clientSocket = new net.Socket();
248 clientSocket.on("error", errorHandler);
249 clientSocket.connect(this.pipePath, function() {
250 clientSocket.end();
251 });
252 }
253 }
254
255 /**
256 * Message handler for SHOW_INFORMATION_MESSAGE
257 */
258 private showInformationMessage(message: string): Q.Promise<void> {
259 return Q(vscode.window.showInformationMessage(message)).then(() => {});
260 }
261}
262