-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathlanguageClientManager.ts
More file actions
540 lines (488 loc) · 19.1 KB
/
languageClientManager.ts
File metadata and controls
540 lines (488 loc) · 19.1 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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
import * as vscode from "vscode";
import {
type Disposable,
type DocumentSelector,
type Executable,
LanguageClient,
type LanguageClientOptions,
RevealOutputChannelOn,
type ServerOptions,
} from "vscode-languageclient/node";
import { buildCommand } from "./executable";
import { WorkspaceMode, type WorkspaceTracker } from "./project";
import {
type TelemetryEvent,
preprocessStacktraceInProperties,
reporter,
} from "./telemetry";
// Languages fully handled by this extension
const languageIds = ["elixir", "eex", "html-eex", "phoenix-heex"];
// Template languages handled by their own extensions but require activation of this
// one for compiler diagnostics. Template languages that compile down to Elixir AST
// and embed other languages (e.g. HTML, CSS, JS and Elixir itself), should be moved
// here for proper language service forwarding via "embedded-content".
const templateLanguageIds = ["surface"];
const activationLanguageIds = languageIds.concat(templateLanguageIds);
const defaultDocumentSelector = languageIds.flatMap((language) => [
{ language, scheme: "file" },
{ language, scheme: "untitled" },
{ language, scheme: "embedded-content" },
]);
const untitledDocumentSelector = languageIds.map((language) => ({
language,
scheme: "untitled",
}));
const patternDocumentSelector = (pattern: string) =>
languageIds.map((language) => ({ language, scheme: "file", pattern }));
// Options to control the language client
const clientOptions: LanguageClientOptions = {
// Register the server for Elixir documents
// the client will iterate through this list and chose the first matching element
documentSelector: defaultDocumentSelector,
// Don't focus the Output pane on errors because request handler errors are no big deal
revealOutputChannelOn: RevealOutputChannelOn.Never,
};
function startClient(
context: vscode.ExtensionContext,
clientOptions: LanguageClientOptions,
): [LanguageClient, Promise<LanguageClient>, Disposable[]] {
const serverOpts: Executable = {
command: `"${buildCommand(
context,
"language_server",
clientOptions.workspaceFolder,
)}"`,
options: { shell: true },
};
// If the extension is launched in debug mode then the `debug` server options are used instead of `run`
// currently we pass the same options regardless of the mode
const serverOptions: ServerOptions = {
run: serverOpts,
debug: serverOpts,
};
let displayName: string;
if (clientOptions.workspaceFolder) {
console.log(
`ElixirLS: starting LSP client for ${clientOptions.workspaceFolder.uri.fsPath} with server options`,
serverOptions,
"client options",
clientOptions,
);
displayName = `ElixirLS - ${clientOptions.workspaceFolder?.name}`;
reporter.sendTelemetryEvent("language_client_starting", {
"elixir_ls.language_client_mode": "workspaceFolder",
});
} else {
console.log(
"ElixirLS: starting default LSP client with server options",
serverOptions,
"client options",
clientOptions,
);
displayName = "ElixirLS - (default)";
reporter.sendTelemetryEvent("language_client_starting", {
"elixir_ls.language_client_mode": "default",
});
}
const client = new LanguageClient(
"elixirLS", // langId
displayName, // display name
serverOptions,
clientOptions,
);
const clientDisposables: Disposable[] = [];
clientDisposables.push(
client.onTelemetry((event: TelemetryEvent) => {
if (event.name.endsWith("_error")) {
reporter.sendTelemetryErrorEvent(
event.name,
preprocessStacktraceInProperties(event.properties),
event.measurements,
);
} else {
reporter.sendTelemetryEvent(
event.name,
event.properties,
event.measurements,
);
}
}),
);
const clientPromise = new Promise<LanguageClient>((resolve, reject) => {
const startTime = performance.now();
client
.start()
.then(() => {
const elapsed = performance.now() - startTime;
if (clientOptions.workspaceFolder) {
console.log(
`ElixirLS: started LSP client for ${clientOptions.workspaceFolder.uri.toString()}`,
);
} else {
console.log("ElixirLS: started default LSP client");
}
reporter.sendTelemetryEvent(
"language_client_started",
{
"elixir_ls.language_client_mode": clientOptions.workspaceFolder
? "workspaceFolder"
: "default",
},
{ "elixir_ls.language_client_activation_time": elapsed },
);
resolve(client);
})
.catch((reason) => {
reporter.sendTelemetryErrorEvent("language_client_start_error", {
"elixir_ls.language_client_mode": clientOptions.workspaceFolder
? "workspaceFolder"
: "default",
"elixir_ls.language_client_start_error": String(reason),
"elixir_ls.language_client_start_error_stack": reason?.stack ?? "",
});
if (clientOptions.workspaceFolder) {
console.error(
`ElixirLS: failed to start LSP client for ${clientOptions.workspaceFolder.uri.toString()}: ${reason}`,
);
} else {
console.error(
`ElixirLS: failed to start default LSP client: ${reason}`,
);
}
reject(reason);
});
});
return [client, clientPromise, clientDisposables];
}
export class LanguageClientManager {
defaultClient: LanguageClient | null = null;
defaultClientPromise: Promise<LanguageClient> | null = null;
private defaultClientDisposables: Disposable[] | null = null;
clients: Map<string, LanguageClient> = new Map();
clientsPromises: Map<string, Promise<LanguageClient>> = new Map();
private clientsDisposables: Map<string, Disposable[]> = new Map();
private _onDidChange = new vscode.EventEmitter<void>();
get onDidChange(): vscode.Event<void> {
return this._onDidChange.event;
}
private _workspaceTracker: WorkspaceTracker;
constructor(workspaceTracker: WorkspaceTracker) {
this._workspaceTracker = workspaceTracker;
}
public getDefaultClient() {
return this.defaultClient;
}
public allClients(): LanguageClient[] {
const result = [...this.clients.values()];
if (this.defaultClient) {
result.push(this.defaultClient);
}
return result;
}
public allClientsPromises(): Promise<LanguageClient>[] {
const result = [...this.clientsPromises.values()];
if (this.defaultClientPromise) {
result.push(this.defaultClientPromise);
}
return result;
}
public restart() {
const restartPromise = async (
client: LanguageClient,
isDefault: boolean,
key?: string | undefined,
) =>
new Promise<LanguageClient>((resolve, reject) => {
reporter.sendTelemetryEvent("language_client_restarting", {
"elixir_ls.language_client_mode": !isDefault
? "workspaceFolder"
: "default",
});
const startTime = performance.now();
client
.restart()
.then(() => {
const elapsed = performance.now() - startTime;
reporter.sendTelemetryEvent(
"language_client_started",
{
"elixir_ls.language_client_mode": !isDefault
? "workspaceFolder"
: "default",
},
{ "elixir_ls.language_client_activation_time": elapsed },
);
if (!isDefault) {
console.log(`ElixirLS: started LSP client for ${key}`);
} else {
console.log("ElixirLS: started default LSP client");
}
resolve(client);
})
.catch((e) => {
reporter.sendTelemetryErrorEvent("language_client_restart_error", {
"elixir_ls.language_client_mode": !isDefault
? "workspaceFolder"
: "default",
"elixir_ls.language_client_start_error": String(e),
"elixir_ls.language_client_start_error_stack": e?.stack ?? "",
});
if (!isDefault) {
console.error(
`ElixirLS: failed to start LSP client for ${key}: ${e}`,
);
} else {
console.error(
`ElixirLS: failed to start default LSP client: ${e}`,
);
}
reject(e);
});
});
for (const [key, client] of this.clients) {
console.log(`ElixirLS: restarting LSP client for ${key}`);
this.clientsPromises.set(key, restartPromise(client, false, key));
}
if (this.defaultClient) {
console.log("ElixirLS: restarting default LSP client");
this.defaultClientPromise = restartPromise(this.defaultClient, true);
}
}
public getClientByUri(uri: vscode.Uri): LanguageClient {
// Files outside of workspace go to default client when no directory is open
// otherwise they go to first workspace
// (even if we pass undefined in clientOptions vs will pass first workspace as rootUri/rootPath)
let folder = vscode.workspace.getWorkspaceFolder(uri);
if (!folder) {
if (
vscode.workspace.workspaceFolders &&
vscode.workspace.workspaceFolders.length !== 0
) {
// untitled: and file: outside workspace folders assigned to first workspace
folder = vscode.workspace.workspaceFolders[0];
} else {
// no workspace folders - use default client
if (this.defaultClient) {
return this.defaultClient;
}
throw "default client LSP not started";
}
}
// If we have nested workspace folders we only start a server on the outer most workspace folder.
folder = this._workspaceTracker.getOuterMostWorkspaceFolder(folder);
const client = this.clients.get(folder.uri.toString());
if (client) {
return client;
}
throw `LSP client for ${folder.uri.toString()} not started`;
}
public getClientPromiseByUri(uri: vscode.Uri): Promise<LanguageClient> {
// Files outside of workspace go to default client when no directory is open
// otherwise they go to first workspace
// (even if we pass undefined in clientOptions vs will pass first workspace as rootUri/rootPath)
let folder = vscode.workspace.getWorkspaceFolder(uri);
if (!folder) {
if (
vscode.workspace.workspaceFolders &&
vscode.workspace.workspaceFolders.length !== 0
) {
// untitled: and file: outside workspace folders assigned to first workspace
folder = vscode.workspace.workspaceFolders[0];
} else {
// no folders - use default client
// biome-ignore lint/style/noNonNullAssertion: a default client is always started when no workspace folders exist
return this.defaultClientPromise!;
}
}
// If we have nested workspace folders we only start a server on the outer most workspace folder.
folder = this._workspaceTracker.getOuterMostWorkspaceFolder(folder);
// biome-ignore lint/style/noNonNullAssertion: the client promise is set when the workspace folder's client is started
return this.clientsPromises.get(folder.uri.toString())!;
}
public getClientByDocument(
document: vscode.TextDocument,
): LanguageClient | null {
// We are only interested in elixir files
if (document.languageId !== "elixir") {
return null;
}
return this.getClientByUri(document.uri);
}
public getClientPromiseByDocument(
document: vscode.TextDocument,
): Promise<LanguageClient> | null {
// We are only interested in elixir files
if (document.languageId !== "elixir") {
return null;
}
return this.getClientPromiseByUri(document.uri);
}
public handleDidOpenTextDocument(
document: vscode.TextDocument,
context: vscode.ExtensionContext,
) {
// We are only interested in elixir related files
if (!activationLanguageIds.includes(document.languageId)) {
return;
}
const uri = document.uri;
let folder = vscode.workspace.getWorkspaceFolder(uri);
// Files outside of workspace go to default client when no workspace folder is open
// otherwise they go to first workspace
// NOTE
// even if we pass undefined in clientOptions and try to create a default client
// vscode will pass first workspace as rootUri/rootPath and we will have 2 servers
// running in the same directory
if (!folder) {
if (
vscode.workspace.workspaceFolders &&
vscode.workspace.workspaceFolders.length !== 0
) {
// untitled: or file: outside the workspace folders assigned to first workspace
folder = vscode.workspace.workspaceFolders[0];
} else {
// no workspace - use default client
if (!this.defaultClient) {
// Create the language client and start the client
// the client will get all requests from untitled: file:
[
this.defaultClient,
this.defaultClientPromise,
this.defaultClientDisposables,
] = startClient(context, clientOptions);
this._onDidChange.fire();
}
return;
}
}
// If we have nested workspace folders we only start a server on the outer most workspace folder.
folder = this._workspaceTracker.getOuterMostWorkspaceFolder(folder);
if (!this.clients.has(folder.uri.toString())) {
// The document selector will be assigned based on workspace mode
let documentSelector: DocumentSelector = defaultDocumentSelector;
if (this._workspaceTracker.mode === WorkspaceMode.MULTI_ROOT) {
// multi-root workspace
// create document selector with glob pattern that will match files
// in that directory
const pattern = `${folder.uri.fsPath}/**/*`;
// additionally if this is the first workspace add untitled schema files
// NOTE that no client will match file: outside any of the workspace folders
// if we passed a glob allowing any file the first server would get requests form
// other workspace folders
const maybeUntitledDocumentSelector =
folder.index === 0 ? untitledDocumentSelector : [];
documentSelector = [
...patternDocumentSelector(pattern),
...maybeUntitledDocumentSelector,
];
} else if (this._workspaceTracker.mode === WorkspaceMode.SINGLE_FOLDER) {
// single folder workspace
// no need to filter with glob patterns
// the client will get all requests even from untitled: and files outside
// workspace folder
documentSelector = defaultDocumentSelector;
} else if (this._workspaceTracker.mode === WorkspaceMode.NO_WORKSPACE) {
throw "this should not happen";
}
const workspaceClientOptions: LanguageClientOptions = {
...clientOptions,
// the client will iterate through this list and chose the first matching element
documentSelector: documentSelector,
workspaceFolder: folder,
};
const [client, clientPromise, clientDisposables] = startClient(
context,
workspaceClientOptions,
);
this.clients.set(folder.uri.toString(), client);
this.clientsPromises.set(folder.uri.toString(), clientPromise);
this.clientsDisposables.set(folder.uri.toString(), clientDisposables);
this._onDidChange.fire();
}
}
public async deactivate() {
const clientStartPromises: Promise<unknown>[] = [];
const clientsToDispose: LanguageClient[] = [];
let changed = false;
if (this.defaultClient) {
// biome-ignore lint/complexity/noForEach: disposing all registered disposables is easier with forEach
this.defaultClientDisposables?.forEach((d) => d.dispose());
// biome-ignore lint/style/noNonNullAssertion: defaultClientPromise is defined whenever defaultClient is
clientStartPromises.push(this.defaultClientPromise!);
clientsToDispose.push(this.defaultClient);
this.defaultClient = null;
this.defaultClientPromise = null;
this.defaultClientDisposables = null;
changed = true;
}
for (const [uri, client] of this.clients.entries()) {
// biome-ignore lint/complexity/noForEach: disposing all registered disposables is easier with forEach
this.clientsDisposables.get(uri)?.forEach((d) => d.dispose());
// biome-ignore lint/style/noNonNullAssertion: a promise exists for every started client
clientStartPromises.push(this.clientsPromises.get(uri)!);
clientsToDispose.push(client);
changed = true;
}
this.clients.clear();
this.clientsPromises.clear();
this.clientsDisposables.clear();
if (changed) {
this._onDidChange.fire();
}
// need to await - disposing or stopping a starting client crashes
// in vscode-languageclient 8.1.0
// https://github.com/microsoft/vscode-languageserver-node/blob/d859bb14d1bcb3923eecaf0ef587e55c48502ccc/client/src/common/client.ts#L1311
try {
await Promise.all(clientStartPromises);
} catch {
/* no reason to log here */
}
try {
// dispose can timeout
await Promise.all(clientsToDispose.map((client) => client.dispose()));
} catch {
/* no reason to log here */
}
}
public async handleWorkspaceFolderRemoved(folder: vscode.WorkspaceFolder) {
const uri = folder.uri.toString();
const client = this.clients.get(uri);
if (client) {
console.log("ElixirLS: Stopping LSP client for", folder.uri.fsPath);
// biome-ignore lint/complexity/noForEach: disposing all registered disposables is easier with forEach
this.clientsDisposables.get(uri)?.forEach((d) => d.dispose());
// biome-ignore lint/style/noNonNullAssertion: a promise exists for every started client
const clientPromise = this.clientsPromises.get(uri)!;
this.clients.delete(uri);
this.clientsPromises.delete(uri);
this._onDidChange.fire();
// need to await - disposing or stopping a starting client crashes
// in vscode-languageclient 8.1.0
// https://github.com/microsoft/vscode-languageserver-node/blob/d859bb14d1bcb3923eecaf0ef587e55c48502ccc/client/src/common/client.ts#L1311
try {
await clientPromise;
} catch (e) {
console.warn(
"ElixirLS: error during wait for stoppable LSP client state",
e,
);
reporter.sendTelemetryErrorEvent("language_client_stop_error", {
"elixir_ls.language_client_stop_error": String(e),
// biome-ignore lint/suspicious/noExplicitAny: error may not be typed, cast to access stack trace
"elixir_ls.language_client_start_error_stack": (<any>e)?.stack ?? "",
});
}
try {
// dispose can timeout
await client.dispose();
} catch (e) {
console.warn("ElixirLS: error during LSP client dispose", e);
reporter.sendTelemetryErrorEvent("language_client_stop_error", {
"elixir_ls.language_client_stop_error": String(e),
// biome-ignore lint/suspicious/noExplicitAny: error may not be typed, cast to access stack trace
"elixir_ls.language_client_start_error_stack": (<any>e)?.stack ?? "",
});
}
}
}
}