-
Notifications
You must be signed in to change notification settings - Fork 752
Expand file tree
/
Copy pathrazorLanguageServerClient.ts
More file actions
321 lines (260 loc) · 12 KB
/
razorLanguageServerClient.ts
File metadata and controls
321 lines (260 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as cp from 'child_process';
import { EventEmitter } from 'events';
import * as vscode from 'vscode';
import { GenericNotificationHandler, RequestHandler, RequestType } from 'vscode-jsonrpc';
import { InitializeResult } from 'vscode-languageserver-protocol';
import { LanguageClientOptions, State } from 'vscode-languageclient';
import { ServerOptions } from 'vscode-languageclient/node';
import { RazorLanguage } from './razorLanguage';
import { RazorLanguageServerOptions } from './razorLanguageServerOptions';
import { resolveRazorLanguageServerOptions } from './razorLanguageServerOptionsResolver';
import { RazorLogger } from './razorLogger';
import { TelemetryReporter as RazorTelemetryReporter } from './telemetryReporter';
import { TelemetryReporter } from '@vscode/extension-telemetry';
import { randomUUID } from 'crypto';
import { showErrorMessage } from '../../shared/observers/utils/showMessage';
import { RazorLanguageClient } from './razorLanguageClient';
import { provideDiagnostics, provideWorkspaceDiagnostics } from '../../lsptoolshost/diagnostics/diagnosticMiddleware';
const events = {
ServerStop: 'ServerStop',
};
export class RazorLanguageServerClient implements vscode.Disposable {
private clientOptions!: LanguageClientOptions;
private serverOptions!: ServerOptions;
private client!: RazorLanguageClient;
private onStartListeners: Array<() => Promise<any>> = [];
private onStartedListeners: Array<() => Promise<any>> = [];
private eventBus: EventEmitter;
private isStarted: boolean;
private startHandle: Promise<void> | undefined;
private stopHandle: Promise<void> | undefined;
constructor(
private readonly vscodeType: typeof vscode,
private readonly languageServerDir: string,
private readonly razorTelemetryReporter: RazorTelemetryReporter,
private readonly vscodeTelemetryReporter: TelemetryReporter,
private readonly telemetryExtensionDllPath: string,
private readonly env: NodeJS.ProcessEnv,
private readonly dotnetExecutablePath: string,
private readonly logger: RazorLogger
) {
this.isStarted = false;
this.setupLanguageServer();
this.eventBus = new EventEmitter();
}
public get initializeResult(): InitializeResult | undefined {
return this.client.initializeResult;
}
public onStarted(listener: () => Promise<any>) {
this.onStartedListeners.push(listener);
}
public onStart(listener: () => Promise<any>) {
this.onStartListeners.push(listener);
}
public onStop(listener: () => any) {
this.eventBus.addListener(events.ServerStop, listener);
const disposable = new vscode.Disposable(() => this.eventBus.removeListener(events.ServerStop, listener));
return disposable;
}
public async start() {
if (this.startHandle) {
return this.startHandle;
}
let resolve: () => void = Function;
let reject: (reason: any) => void = Function;
// tslint:disable-next-line: promise-must-complete
this.startHandle = new Promise<void>((resolver, rejecter) => {
resolve = resolver;
reject = rejecter;
});
// Workaround https://github.com/Microsoft/vscode-languageserver-node/issues/472 by tying into state
// change events to detect when restarts are occuring and then properly reject the Language Server
// start listeners.
let restartCount = 0;
const didChangeStateDisposable = this.client.onDidChangeState(
(stateChangeEvent: { newState: any; oldState: any }) => {
if (stateChangeEvent.oldState === State.Starting && stateChangeEvent.newState === State.Stopped) {
restartCount++;
if (restartCount === 5) {
// Timeout, the built-in LanguageClient retries a hardcoded 5 times before giving up. We tie into that
// and then given up on starting the language server if we can't start by then.
reject(vscode.l10n.t('Server failed to start after retrying 5 times.'));
}
} else if (stateChangeEvent.newState === State.Running) {
restartCount = 0;
}
}
);
try {
this.logger.logInfo('Starting Razor Language Server...');
await this.client.start();
this.logger.logInfo('Server started, waiting for client to be ready...');
this.isStarted = true;
// Server is ready, hook up so logging changes can be reported
this.logger.languageServerClient = this;
for (const listener of this.onStartListeners) {
await listener();
}
// Succesfully started, notify listeners.
resolve();
this.logger.logInfo('Server ready!');
for (const listener of this.onStartedListeners) {
await listener();
}
// We don't want to track restart management after the server has been initially started,
// the language client will handle that.
didChangeStateDisposable.dispose();
} catch (error) {
showErrorMessage(
vscode,
vscode.l10n.t(
"Razor Language Server failed to start unexpectedly, please check the 'Razor Log' and report an issue."
)
);
this.razorTelemetryReporter.reportErrorOnServerStart(error as Error);
reject(error);
}
return this.startHandle;
}
public async sendRequest<TResponseType>(method: string, param: any) {
if (!this.isStarted) {
throw new Error(vscode.l10n.t('Tried to send requests while server is not started.'));
}
return this.client.sendRequest<TResponseType>(method, param);
}
public async sendNotification(method: string, param: any) {
if (!this.isStarted) {
throw new Error(vscode.l10n.t('Tried to send requests while server is not started.'));
}
return this.client.sendNotification(method, param);
}
public async onRequestWithParams<P, R, E>(method: RequestType<P, R, E>, handler: RequestHandler<P, R, E>) {
if (!this.isStarted) {
throw new Error(vscode.l10n.t('Tried to bind on request logic while server is not started.'));
}
this.client.onRequest(method, handler);
}
public onNotification(method: string, handler: GenericNotificationHandler) {
if (!this.isStarted) {
throw new Error(vscode.l10n.t('Tried to bind on notification logic while server is not started.'));
}
this.client.onNotification(method, handler);
}
public dispose() {
this.logger.logInfo('Disposing Razor Language Server.');
this.isStarted = false;
this.startHandle = undefined;
this.eventBus.emit(events.ServerStop);
}
public async stop() {
let resolve: () => void = Function;
let reject: (reason: any) => void = Function;
// tslint:disable-next-line: promise-must-complete
this.stopHandle = new Promise<void>((resolver, rejecter) => {
resolve = resolver;
reject = rejecter;
});
if (!this.startHandle) {
reject(new Error(vscode.l10n.t('Cannot stop Razor Language Server as it is already stopped.')));
}
this.logger.logInfo('Stopping Razor Language Server.');
try {
if (this.client) {
await this.client.stop();
}
this.dispose();
resolve();
} catch (error) {
showErrorMessage(
vscode,
vscode.l10n.t(
"Razor Language Server failed to stop correctly, please check the 'Razor Log' and report an issue."
)
);
reject(error);
}
return this.stopHandle;
}
public async connectNamedPipe(pipeName: string): Promise<void> {
await this.start();
// Params must match https://github.com/dotnet/razor/blob/92005deac54f3e9d1a4d1d8f04389379cccfa354/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/RazorNamedPipeConnectParams.cs#L9
await this.sendNotification('razor/namedPipeConnect', { pipeName: pipeName });
}
private setupLanguageServer() {
const options: RazorLanguageServerOptions = resolveRazorLanguageServerOptions(
this.vscodeType,
this.languageServerDir,
this.logger
);
this.clientOptions = {
outputChannel: options.outputChannel,
documentSelector: [{ language: RazorLanguage.id, pattern: RazorLanguage.globbingPattern }],
middleware: {
provideDiagnostics,
provideWorkspaceDiagnostics,
},
};
const args: string[] = [];
this.logger.logInfo(`Razor language server path: ${options.serverPath}`);
args.push('--logLevel');
args.push(this.logger.logLevelForRZLS.toString());
this.razorTelemetryReporter.reportTraceLevel(this.logger.logLevel);
if (options.debug) {
this.razorTelemetryReporter.reportDebugLanguageServer();
this.logger.logInfo('Debug flag set for Razor Language Server.');
args.push('--debug');
}
// TODO: When all of this code is on GitHub, should we just pass `--omnisharp` as a flag to rzls, and let it decide?
if (!options.usingOmniSharp) {
args.push('--DelegateToCSharpOnDiagnosticPublish');
args.push('true');
args.push('--UpdateBuffersForClosedDocuments');
args.push('true');
args.push('--SingleServerCompletionSupport');
args.push('true');
if (this.telemetryExtensionDllPath.length > 0) {
args.push('--telemetryLevel', this.vscodeTelemetryReporter.telemetryLevel);
args.push('--sessionId', getSessionId());
args.push('--telemetryExtensionPath', this.telemetryExtensionDllPath);
}
}
let childProcess: () => Promise<cp.ChildProcessWithoutNullStreams>;
const cpOptions: cp.SpawnOptionsWithoutStdio = {
detached: true,
windowsHide: true,
env: this.env,
};
if (options.serverPath.endsWith('.dll')) {
// If we were given a path to a dll, launch that via dotnet.
const argsWithPath = [options.serverPath].concat(args);
this.logger.logInfo(`Server arguments ${argsWithPath.join(' ')}`);
childProcess = async () => cp.spawn(this.dotnetExecutablePath, argsWithPath, cpOptions);
} else {
// Otherwise assume we were given a path to an executable.
this.logger.logInfo(`Server arguments ${args.join(' ')}`);
childProcess = async () => cp.spawn(options.serverPath, args, cpOptions);
}
this.serverOptions = childProcess;
this.client = new RazorLanguageClient(
'razorLanguageServer',
'Razor Language Server',
this.serverOptions,
this.clientOptions,
options
);
}
}
// VS code will have a default session id when running under tests. Since we may still
// report telemetry, we need to give a unique session id instead of the default value.
function getSessionId(): string {
const sessionId = vscode.env.sessionId;
// 'somevalue.sessionid' is the test session id provided by vs code
if (sessionId.toLowerCase() === 'somevalue.sessionid') {
return randomUUID();
}
return sessionId;
}