microsoft/vscode-react-native
Publicmirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable
src/extension/extensionServer.ts
287lines · 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 | |
| 4 | import * as net from "net"; |
| 5 | import * as Q from "q"; |
| 6 | import * as vscode from "vscode"; |
| 7 | |
| 8 | import * as em from "../common/extensionMessaging"; |
| 9 | import {Log} from "../common/log/log"; |
| 10 | import {LogLevel} from "../common/log/logHelper"; |
| 11 | import {Packager, PackagerRunAs} from "../common/packager"; |
| 12 | import {PackagerStatus, PackagerStatusIndicator} from "./packagerStatusIndicator"; |
| 13 | import {LogCatMonitor} from "./android/logCatMonitor"; |
| 14 | import {FileSystem} from "../common/node/fileSystem"; |
| 15 | import {ConfigurationReader} from "../common/configurationReader"; |
| 16 | import {SettingsHelper} from "./settingsHelper"; |
| 17 | import {Telemetry} from "../common/telemetry"; |
| 18 | import {ExponentHelper} from "../common/exponent/exponentHelper"; |
| 19 | |
| 20 | export 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.reactNativePackager.isRunning().then((running) => { |
| 97 | if (running) { |
| 98 | if (this.reactNativePackager.getRunningAs() !== PackagerRunAs.REACT_NATIVE) { |
| 99 | return this.reactNativePackager.stop().then(() => |
| 100 | this.reactNativePackageStatusIndicator.updatePackagerStatus(PackagerStatus.PACKAGER_STOPPED) |
| 101 | ); |
| 102 | } |
| 103 | |
| 104 | Log.logMessage("Attaching to running React Native packager"); |
| 105 | } |
| 106 | }).then(() => |
| 107 | this.exponentHelper.configureReactNativeEnvironment() |
| 108 | ).then(() => { |
| 109 | const portToUse = ConfigurationReader.readIntWithDefaultSync(port, SettingsHelper.getPackagerPort()); |
| 110 | return this.reactNativePackager.startAsReactNative(portToUse); |
| 111 | }) |
| 112 | .then(() => |
| 113 | this.reactNativePackageStatusIndicator.updatePackagerStatus(PackagerStatus.PACKAGER_STARTED)); |
| 114 | } |
| 115 | |
| 116 | /** |
| 117 | * Message handler for START_EXPONENT_PACKAGER. |
| 118 | */ |
| 119 | private startExponentPackager(port?: any): Q.Promise<any> { |
| 120 | return this.reactNativePackager.isRunning().then((running) => { |
| 121 | if (running) { |
| 122 | if (this.reactNativePackager.getRunningAs() !== PackagerRunAs.EXPONENT) { |
| 123 | return this.reactNativePackager.stop().then(() => |
| 124 | this.reactNativePackageStatusIndicator.updatePackagerStatus(PackagerStatus.PACKAGER_STOPPED)); |
| 125 | } |
| 126 | |
| 127 | Log.logMessage("Attaching to running Exponent packager"); |
| 128 | } |
| 129 | }).then(() => |
| 130 | this.exponentHelper.configureExponentEnvironment() |
| 131 | ).then(() => |
| 132 | this.exponentHelper.loginToExponent( |
| 133 | (message, password) => { return Q(vscode.window.showInputBox({ placeHolder: message, password: password })); }, |
| 134 | (message) => { return Q(vscode.window.showInformationMessage(message)); } |
| 135 | )) |
| 136 | .then(() => { |
| 137 | const portToUse = ConfigurationReader.readIntWithDefaultSync(port, SettingsHelper.getPackagerPort()); |
| 138 | return this.reactNativePackager.startAsExponent(portToUse); |
| 139 | }) |
| 140 | .then(exponentUrl => { |
| 141 | this.reactNativePackageStatusIndicator.updatePackagerStatus(PackagerStatus.EXPONENT_PACKAGER_STARTED); |
| 142 | return exponentUrl; |
| 143 | }); |
| 144 | } |
| 145 | |
| 146 | /** |
| 147 | * Message handler for STOP_PACKAGER. |
| 148 | */ |
| 149 | private stopPackager(): Q.Promise<any> { |
| 150 | return this.reactNativePackager.stop() |
| 151 | .then(() => this.reactNativePackageStatusIndicator.updatePackagerStatus(PackagerStatus.PACKAGER_STOPPED)); |
| 152 | } |
| 153 | |
| 154 | /** |
| 155 | * Message handler for RESTART_PACKAGER. |
| 156 | */ |
| 157 | private restartPackager(port?: any): Q.Promise<any> { |
| 158 | const portToUse = ConfigurationReader.readIntWithDefaultSync(port, SettingsHelper.getPackagerPort()); |
| 159 | return this.reactNativePackager.restart(portToUse) |
| 160 | .then(() => |
| 161 | this.reactNativePackageStatusIndicator.updatePackagerStatus(PackagerStatus.PACKAGER_STARTED)); |
| 162 | } |
| 163 | |
| 164 | /** |
| 165 | * Message handler for PREWARM_BUNDLE_CACHE. |
| 166 | */ |
| 167 | private prewarmBundleCache(platform: string): Q.Promise<any> { |
| 168 | return this.reactNativePackager.prewarmBundleCache(platform); |
| 169 | } |
| 170 | |
| 171 | /** |
| 172 | * Message handler for START_MONITORING_LOGCAT. |
| 173 | */ |
| 174 | private startMonitoringLogCat(deviceId: string, logCatArguments: string): Q.Promise<any> { |
| 175 | this.stopMonitoringLogCat(); // Stop previous logcat monitor if it's running |
| 176 | |
| 177 | // this.logCatMonitor can be mutated, so we store it locally too |
| 178 | const logCatMonitor = this.logCatMonitor = new LogCatMonitor(deviceId, logCatArguments); |
| 179 | logCatMonitor.start() // The LogCat will continue running forever, so we don't wait for it |
| 180 | .catch(error => |
| 181 | Log.logWarning("Error while monitoring LogCat", error)) |
| 182 | .done(); |
| 183 | |
| 184 | return Q.resolve<void>(void 0); |
| 185 | } |
| 186 | |
| 187 | /** |
| 188 | * Message handler for OPEN_FILE_AT_LOCATION |
| 189 | */ |
| 190 | private openFileAtLocation(filename: string, lineNumber: number): Q.Promise<void> { |
| 191 | return Q(vscode.workspace.openTextDocument(vscode.Uri.file(filename)).then((document: vscode.TextDocument) => { |
| 192 | return vscode.window.showTextDocument(document).then((editor: vscode.TextEditor) => { |
| 193 | let range = editor.document.lineAt(lineNumber - 1).range; |
| 194 | editor.selection = new vscode.Selection(range.start, range.end); |
| 195 | editor.revealRange(range, vscode.TextEditorRevealType.InCenter); |
| 196 | }); |
| 197 | })); |
| 198 | } |
| 199 | |
| 200 | private stopMonitoringLogCat(): Q.Promise<void> { |
| 201 | if (this.logCatMonitor) { |
| 202 | this.logCatMonitor.dispose(); |
| 203 | this.logCatMonitor = null; |
| 204 | } |
| 205 | |
| 206 | return Q.resolve<void>(void 0); |
| 207 | } |
| 208 | |
| 209 | /** |
| 210 | * Sends telemetry |
| 211 | */ |
| 212 | private sendTelemetry(extensionId: string, extensionVersion: string, appInsightsKey: string, eventName: string, properties: {[key: string]: string}, measures: {[key: string]: number}): Q.Promise<any> { |
| 213 | Telemetry.sendExtensionTelemetry(extensionId, extensionVersion, appInsightsKey, eventName, properties, measures); |
| 214 | return Q.resolve({}); |
| 215 | } |
| 216 | |
| 217 | /** |
| 218 | * Extension message handler. |
| 219 | */ |
| 220 | private handleExtensionMessage(messageWithArgs: em.MessageWithArguments): Q.Promise<any> { |
| 221 | let handler = this.messageHandlerDictionary[messageWithArgs.message]; |
| 222 | if (handler) { |
| 223 | Log.logInternalMessage(LogLevel.Info, "Handling message: " + em.ExtensionMessage[messageWithArgs.message]); |
| 224 | return handler.apply(this, messageWithArgs.args); |
| 225 | } else { |
| 226 | return Q.reject("Invalid message: " + messageWithArgs.message); |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | /** |
| 231 | * Handles connections to the server. |
| 232 | */ |
| 233 | private handleSocket(socket: net.Socket): void { |
| 234 | let handleError = (e: any) => { |
| 235 | Log.logError(e); |
| 236 | socket.end(em.ErrorMarker); |
| 237 | }; |
| 238 | |
| 239 | let dataCallback = (data: any) => { |
| 240 | try { |
| 241 | let messageWithArgs: em.MessageWithArguments = JSON.parse(data); |
| 242 | this.handleExtensionMessage(messageWithArgs) |
| 243 | .then(result => { |
| 244 | socket.end(JSON.stringify(result)); |
| 245 | }) |
| 246 | .catch((e) => { handleError(e); }) |
| 247 | .done(); |
| 248 | } catch (e) { |
| 249 | handleError(e); |
| 250 | } |
| 251 | }; |
| 252 | |
| 253 | socket.on("data", dataCallback); |
| 254 | }; |
| 255 | |
| 256 | /** |
| 257 | * Recovers the server in case the named socket we use already exists, but no other instance of VSCode is active. |
| 258 | */ |
| 259 | private recoverServer(error: any): void { |
| 260 | let errorHandler = (e: any) => { |
| 261 | /* The named socket is not used. */ |
| 262 | if (e.code === "ECONNREFUSED") { |
| 263 | new FileSystem().removePathRecursivelyAsync(this.pipePath) |
| 264 | .then(() => { |
| 265 | this.serverInstance.listen(this.pipePath); |
| 266 | }) |
| 267 | .done(); |
| 268 | } |
| 269 | }; |
| 270 | |
| 271 | /* The named socket already exists. */ |
| 272 | if (error.code === "EADDRINUSE") { |
| 273 | let clientSocket = new net.Socket(); |
| 274 | clientSocket.on("error", errorHandler); |
| 275 | clientSocket.connect(this.pipePath, function() { |
| 276 | clientSocket.end(); |
| 277 | }); |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | /** |
| 282 | * Message handler for SHOW_INFORMATION_MESSAGE |
| 283 | */ |
| 284 | private showInformationMessage(message: string): Q.Promise<void> { |
| 285 | return Q(vscode.window.showInformationMessage(message)).then(() => {}); |
| 286 | } |
| 287 | } |
| 288 | |