forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlanguageServerProxy.ts
More file actions
242 lines (213 loc) · 9.47 KB
/
Copy pathlanguageServerProxy.ts
File metadata and controls
242 lines (213 loc) · 9.47 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import '../../common/extensions';
import { inject, injectable } from 'inversify';
import {
DidChangeConfigurationNotification,
Disposable,
LanguageClient,
LanguageClientOptions,
State,
} from 'vscode-languageclient/node';
import { DeprecatePythonPath } from '../../common/experiments/groups';
import { traceDecorators, traceError } from '../../common/logger';
import { IConfigurationService, IExperimentService, IInterpreterPathService, Resource } from '../../common/types';
import { createDeferred, Deferred, sleep } from '../../common/utils/async';
import { swallowExceptions } from '../../common/utils/decorators';
import { noop } from '../../common/utils/misc';
import { IEnvironmentVariablesProvider } from '../../common/variables/types';
import { LanguageServerSymbolProvider } from '../../providers/symbolProvider';
import { PythonEnvironment } from '../../pythonEnvironments/info';
import { captureTelemetry, sendTelemetryEvent } from '../../telemetry';
import { EventName } from '../../telemetry/constants';
import { ITestingService } from '../../testing/types';
import { FileBasedCancellationStrategy } from '../common/cancellationUtils';
import { ProgressReporting } from '../progress';
import { ILanguageClientFactory, ILanguageServerFolderService, ILanguageServerProxy } from '../types';
namespace InExperiment {
export const Method = 'python/inExperiment';
export interface IRequest {
experimentName: string;
}
export interface IResponse {
inExperiment: boolean;
}
}
namespace GetExperimentValue {
export const Method = 'python/getExperimentValue';
export interface IRequest {
experimentName: string;
}
export interface IResponse<T extends boolean | number | string> {
value: T | undefined;
}
}
@injectable()
export class NodeLanguageServerProxy implements ILanguageServerProxy {
public languageClient: LanguageClient | undefined;
private startupCompleted: Deferred<void>;
private cancellationStrategy: FileBasedCancellationStrategy | undefined;
private readonly disposables: Disposable[] = [];
private disposed: boolean = false;
private lsVersion: string | undefined;
constructor(
@inject(ILanguageClientFactory) private readonly factory: ILanguageClientFactory,
@inject(ITestingService) private readonly testManager: ITestingService,
@inject(IConfigurationService) private readonly configurationService: IConfigurationService,
@inject(ILanguageServerFolderService) private readonly folderService: ILanguageServerFolderService,
@inject(IExperimentService) private readonly experimentService: IExperimentService,
@inject(IInterpreterPathService) private readonly interpreterPathService: IInterpreterPathService,
@inject(IEnvironmentVariablesProvider) private readonly environmentService: IEnvironmentVariablesProvider,
) {
this.startupCompleted = createDeferred<void>();
}
private static versionTelemetryProps(instance: NodeLanguageServerProxy) {
return {
lsVersion: instance.lsVersion,
};
}
@traceDecorators.verbose('Stopping language server')
public dispose() {
if (this.languageClient) {
// Do not await on this.
this.languageClient.stop().then(noop, (ex) => traceError('Stopping language client failed', ex));
this.languageClient = undefined;
}
if (this.cancellationStrategy) {
this.cancellationStrategy.dispose();
this.cancellationStrategy = undefined;
}
while (this.disposables.length > 0) {
const d = this.disposables.shift()!;
d.dispose();
}
if (this.startupCompleted.completed) {
this.startupCompleted.reject(new Error('Disposed language server'));
this.startupCompleted = createDeferred<void>();
}
this.disposed = true;
}
@traceDecorators.error('Failed to start language server')
@captureTelemetry(
EventName.LANGUAGE_SERVER_ENABLED,
undefined,
true,
undefined,
NodeLanguageServerProxy.versionTelemetryProps,
)
public async start(
resource: Resource,
interpreter: PythonEnvironment | undefined,
options: LanguageClientOptions,
): Promise<void> {
if (!this.languageClient) {
const directory = await this.folderService.getCurrentLanguageServerDirectory();
this.lsVersion = directory?.version.format();
this.cancellationStrategy = new FileBasedCancellationStrategy();
options.connectionOptions = { cancellationStrategy: this.cancellationStrategy };
this.languageClient = await this.factory.createLanguageClient(resource, interpreter, options);
this.languageClient.onDidChangeState((e) => {
// The client's on* methods must be called after the client has started, but if called too
// late the server may have already sent a message (which leads to failures). Register
// these on the state change to running to ensure they are ready soon enough.
if (e.newState === State.Running) {
this.registerHandlers(resource);
}
});
this.disposables.push(this.languageClient.start());
await this.serverReady();
if (this.disposed) {
// Check if it got disposed in the interim.
return;
}
await this.registerTestServices();
} else {
await this.startupCompleted.promise;
}
}
public loadExtension(_args?: {}) {}
@captureTelemetry(
EventName.LANGUAGE_SERVER_READY,
undefined,
true,
undefined,
NodeLanguageServerProxy.versionTelemetryProps,
)
protected async serverReady(): Promise<void> {
while (this.languageClient && !this.languageClient.initializeResult) {
await sleep(100);
}
if (this.languageClient) {
await this.languageClient.onReady();
}
this.startupCompleted.resolve();
}
@swallowExceptions('Activating Unit Tests Manager for Pylance language server')
protected async registerTestServices() {
if (!this.languageClient) {
throw new Error('languageClient not initialized');
}
await this.testManager.activate(new LanguageServerSymbolProvider(this.languageClient!));
}
private registerHandlers(resource: Resource) {
if (this.disposed) {
// Check if it got disposed in the interim.
return;
}
const progressReporting = new ProgressReporting(this.languageClient!);
this.disposables.push(progressReporting);
if (this.experimentService.inExperimentSync(DeprecatePythonPath.experiment)) {
this.disposables.push(
this.interpreterPathService.onDidChange(() => {
// Manually send didChangeConfiguration in order to get the server to requery
// the workspace configurations (to then pick up pythonPath set in the middleware).
// This is needed as interpreter changes via the interpreter path service happen
// outside of VS Code's settings (which would mean VS Code sends the config updates itself).
this.languageClient!.sendNotification(DidChangeConfigurationNotification.type, {
settings: null,
});
}),
);
}
this.disposables.push(
this.environmentService.onDidEnvironmentVariablesChange(() => {
this.languageClient!.sendNotification(DidChangeConfigurationNotification.type, {
settings: null,
});
}),
);
const settings = this.configurationService.getSettings(resource);
if (settings.downloadLanguageServer) {
this.languageClient!.onTelemetry((telemetryEvent) => {
const eventName = telemetryEvent.EventName || EventName.LANGUAGE_SERVER_TELEMETRY;
const formattedProperties = {
...telemetryEvent.Properties,
// Replace all slashes in the method name so it doesn't get scrubbed by vscode-extension-telemetry.
method: telemetryEvent.Properties.method?.replace(/\//g, '.'),
};
sendTelemetryEvent(
eventName,
telemetryEvent.Measurements,
formattedProperties,
telemetryEvent.Exception,
);
});
}
this.languageClient!.onRequest(
InExperiment.Method,
async (params: InExperiment.IRequest): Promise<InExperiment.IResponse> => {
const inExperiment = await this.experimentService.inExperiment(params.experimentName);
return { inExperiment };
},
);
this.languageClient!.onRequest(
GetExperimentValue.Method,
async <T extends boolean | number | string>(
params: GetExperimentValue.IRequest,
): Promise<GetExperimentValue.IResponse<T>> => {
const value = await this.experimentService.getExperimentValue<T>(params.experimentName);
return { value };
},
);
}
}