-
Notifications
You must be signed in to change notification settings - Fork 655
/
server.ts
816 lines (655 loc) · 32.5 KB
/
server.ts
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as fs from 'fs';
import * as path from 'path';
import * as protocol from './protocol';
import * as utils from '../common';
import * as serverUtils from '../omnisharp/utils';
import { vscode, CancellationToken } from '../vscodeAdapter';
import { exec } from 'child_process';
import { LaunchTarget, findLaunchTargets, LaunchTargetKind, SpawnedChildProcess } from './launcher';
import { createInterface } from 'readline';
import { Request, RequestQueueCollection } from './requestQueue';
import { DelayTracker } from './delayTracker';
import { EventEmitter } from 'events';
import { OmnisharpManager } from './OmnisharpManager';
import { Options } from './options';
import { PlatformInformation } from '../platform';
import { launchOmniSharp } from './launcher';
import { setTimeout } from 'timers';
import { OmnisharpDownloader } from './OmnisharpDownloader';
import * as ObservableEvents from './loggingEvents';
import { EventStream } from '../EventStream';
import { NetworkSettingsProvider } from '../NetworkSettings';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import CompositeDisposable from '../CompositeDisposable';
import Disposable from '../Disposable';
import OptionProvider from '../observers/OptionProvider';
import { IHostExecutableResolver } from '../constants/IHostExecutableResolver';
import { showProjectSelector } from '../features/commands';
import { removeBOMFromBuffer, removeBOMFromString } from '../utils/removeBOM';
import { validateRequirements } from './requirementCheck';
enum ServerState {
Starting,
Started,
Stopped
}
type State = {
status: ServerState.Stopped,
} | {
status: ServerState.Starting,
disposables: CompositeDisposable,
} | {
status: ServerState.Started,
disposables: CompositeDisposable,
serverProcess: SpawnedChildProcess,
telemetryIntervalId: NodeJS.Timeout,
};
module Events {
export const StateChanged = 'stateChanged';
export const StdOut = 'stdout';
export const StdErr = 'stderr';
export const Error = 'Error';
export const ServerError = 'ServerError';
export const UnresolvedDependencies = 'UnresolvedDependencies';
export const PackageRestoreStarted = 'PackageRestoreStarted';
export const PackageRestoreFinished = 'PackageRestoreFinished';
export const ProjectChanged = 'ProjectChanged';
export const ProjectAdded = 'ProjectAdded';
export const ProjectRemoved = 'ProjectRemoved';
export const BackgroundDiagnosticStatus = 'BackgroundDiagnosticStatus';
export const MsBuildProjectDiagnostics = 'MsBuildProjectDiagnostics';
export const TestMessage = 'TestMessage';
export const BeforeServerInstall = 'BeforeServerInstall';
export const BeforeServerStart = 'BeforeServerStart';
export const ServerStart = 'ServerStart';
export const ServerStop = 'ServerStop';
export const MultipleLaunchTargets = 'server:MultipleLaunchTargets';
export const Started = 'started';
export const ProjectConfiguration = 'ProjectConfiguration';
}
const TelemetryReportingDelay = 2 * 60 * 1000; // two minutes
export class OmniSharpServer {
private static _nextId = 1;
private _delayTrackers: { [requestName: string]: DelayTracker } = {};
private _eventBus = new EventEmitter();
private _state: State = { status: ServerState.Stopped };
private _launchTarget: LaunchTarget | undefined;
private _requestQueue: RequestQueueCollection;
private _sessionProperties: { [key: string]: any } = {};
private _omnisharpManager: OmnisharpManager;
private updateProjectDebouncer = new Subject<ObservableEvents.ProjectModified>();
private firstUpdateProject: boolean;
constructor(
private vscode: vscode,
networkSettingsProvider: NetworkSettingsProvider,
private packageJSON: any,
private platformInfo: PlatformInformation,
private eventStream: EventStream,
private optionProvider: OptionProvider,
private extensionPath: string,
private monoResolver: IHostExecutableResolver,
private dotnetResolver: IHostExecutableResolver,
public decompilationAuthorized: boolean) {
this._requestQueue = new RequestQueueCollection(this.eventStream, 8, request => this._makeRequest(request));
let downloader = new OmnisharpDownloader(networkSettingsProvider, this.eventStream, this.packageJSON, platformInfo, extensionPath);
this._omnisharpManager = new OmnisharpManager(downloader, platformInfo);
this.updateProjectDebouncer.pipe(debounceTime(1500)).subscribe((event) => { this.updateProjectInfo(); });
this.firstUpdateProject = true;
}
public get sessionProperties() {
return this._sessionProperties;
}
public isRunning(): boolean {
return this._state.status === ServerState.Started;
}
public async waitForEmptyEventQueue(): Promise<void> {
while (!this._requestQueue.isEmpty()) {
let p = new Promise((resolve) => setTimeout(resolve, 100));
await p;
}
}
private _setState(state: State): void {
if (state.status !== this._state.status) {
this._state = state;
this._fireEvent(Events.StateChanged, this._state.status);
}
}
private _recordRequestDelay(requestName: string, elapsedTime: number) {
let tracker = this._delayTrackers[requestName];
if (!tracker) {
tracker = new DelayTracker(requestName);
this._delayTrackers[requestName] = tracker;
}
tracker.reportDelay(elapsedTime);
}
private _reportTelemetry() {
const delayTrackers = this._delayTrackers;
for (const requestName in delayTrackers) {
const tracker = delayTrackers[requestName];
const eventName = 'omnisharp' + requestName;
if (tracker.hasMeasures()) {
const measures = tracker.getMeasures();
tracker.clearMeasures();
this.eventStream.post(new ObservableEvents.OmnisharpDelayTrackerEventMeasures(eventName, measures));
}
}
}
public getSolutionPathOrFolder(): string | undefined {
return this._launchTarget?.target;
}
// --- eventing
public onStdout(listener: (e: string) => any, thisArg?: any) {
return this._addListener(Events.StdOut, listener, thisArg);
}
public onStderr(listener: (e: string) => any, thisArg?: any) {
return this._addListener(Events.StdErr, listener, thisArg);
}
public onError(listener: (e: protocol.ErrorMessage) => any, thisArg?: any) {
return this._addListener(Events.Error, listener, thisArg);
}
public onServerError(listener: (err: any) => any, thisArg?: any) {
return this._addListener(Events.ServerError, listener, thisArg);
}
public onUnresolvedDependencies(listener: (e: protocol.UnresolvedDependenciesMessage) => any, thisArg?: any) {
return this._addListener(Events.UnresolvedDependencies, listener, thisArg);
}
public onBeforePackageRestore(listener: () => any, thisArg?: any) {
return this._addListener(Events.PackageRestoreStarted, listener, thisArg);
}
public onPackageRestore(listener: () => any, thisArg?: any) {
return this._addListener(Events.PackageRestoreFinished, listener, thisArg);
}
public onProjectChange(listener: (e: protocol.ProjectInformationResponse) => any, thisArg?: any) {
return this._addListener(Events.ProjectChanged, listener, thisArg);
}
public onProjectAdded(listener: (e: protocol.ProjectInformationResponse) => any, thisArg?: any) {
return this._addListener(Events.ProjectAdded, listener, thisArg);
}
public onProjectRemoved(listener: (e: protocol.ProjectInformationResponse) => any, thisArg?: any) {
return this._addListener(Events.ProjectRemoved, listener, thisArg);
}
public onBackgroundDiagnosticStatus(listener: (e: protocol.BackgroundDiagnosticStatusMessage) => any, thisArg?: any) {
return this._addListener(Events.BackgroundDiagnosticStatus, listener, thisArg);
}
public onMsBuildProjectDiagnostics(listener: (e: protocol.MSBuildProjectDiagnostics) => any, thisArg?: any) {
return this._addListener(Events.MsBuildProjectDiagnostics, listener, thisArg);
}
public onTestMessage(listener: (e: protocol.V2.TestMessageEvent) => any, thisArg?: any) {
return this._addListener(Events.TestMessage, listener, thisArg);
}
public onBeforeServerInstall(listener: () => any) {
return this._addListener(Events.BeforeServerInstall, listener);
}
public onBeforeServerStart(listener: (e: string) => any) {
return this._addListener(Events.BeforeServerStart, listener);
}
public onServerStart(listener: (e: string) => any) {
return this._addListener(Events.ServerStart, listener);
}
public onServerStop(listener: () => any) {
return this._addListener(Events.ServerStop, listener);
}
public onMultipleLaunchTargets(listener: (targets: LaunchTarget[]) => any, thisArg?: any) {
return this._addListener(Events.MultipleLaunchTargets, listener, thisArg);
}
public onOmnisharpStart(listener: () => any) {
return this._addListener(Events.Started, listener);
}
private _addListener(event: string, listener: (e: any) => any, thisArg?: any): Disposable {
listener = thisArg ? listener.bind(thisArg) : listener;
this._eventBus.addListener(event, listener);
return new Disposable(() => this._eventBus.removeListener(event, listener));
}
protected _fireEvent(event: string, args: any): void {
this._eventBus.emit(event, args);
}
// --- start, stop, and connect
private async _start(launchTarget: LaunchTarget): Promise<void> {
if (this._state.status !== ServerState.Stopped) {
this.eventStream.post(new ObservableEvents.OmnisharpServerOnServerError("Attempt to start OmniSharp server failed because another server instance is running."));
return;
}
if (launchTarget.workspaceKind === LaunchTargetKind.LiveShare) {
this.eventStream.post(new ObservableEvents.OmnisharpServerMessage("During Live Share sessions language services are provided by the Live Share server."));
return;
}
const options = this.optionProvider.GetLatestOptions();
if (!await validateRequirements(options)) {
this.eventStream.post(new ObservableEvents.OmnisharpServerMessage("OmniSharp failed to start because of missing requirements."));
return;
}
const disposables = new CompositeDisposable();
disposables.add(this.onServerError(err =>
this.eventStream.post(new ObservableEvents.OmnisharpServerOnServerError(err))
));
disposables.add(this.onError((message: protocol.ErrorMessage) =>
this.eventStream.post(new ObservableEvents.OmnisharpServerOnError(message))
));
disposables.add(this.onMsBuildProjectDiagnostics((message: protocol.MSBuildProjectDiagnostics) =>
this.eventStream.post(new ObservableEvents.OmnisharpServerMsBuildProjectDiagnostics(message))
));
disposables.add(this.onUnresolvedDependencies((message: protocol.UnresolvedDependenciesMessage) =>
this.eventStream.post(new ObservableEvents.OmnisharpServerUnresolvedDependencies(message))
));
disposables.add(this.onStderr((message: string) =>
this.eventStream.post(new ObservableEvents.OmnisharpServerOnStdErr(message))
));
disposables.add(this.onMultipleLaunchTargets((targets: LaunchTarget[]) =>
this.eventStream.post(new ObservableEvents.OmnisharpOnMultipleLaunchTargets(targets))
));
disposables.add(this.onBeforeServerInstall(() =>
this.eventStream.post(new ObservableEvents.OmnisharpOnBeforeServerInstall())
));
disposables.add(this.onBeforeServerStart(() => {
this.eventStream.post(new ObservableEvents.OmnisharpOnBeforeServerStart());
}));
disposables.add(this.onServerStop(() =>
this.eventStream.post(new ObservableEvents.OmnisharpServerOnStop())
));
disposables.add(this.onServerStart(() => {
this.eventStream.post(new ObservableEvents.OmnisharpServerOnStart());
}));
disposables.add(this.onBackgroundDiagnosticStatus((message: protocol.BackgroundDiagnosticStatusMessage) =>
this.eventStream.post(new ObservableEvents.OmnisharpBackgroundDiagnosticStatus(message))
));
disposables.add(this.onProjectConfigurationReceived((message: protocol.ProjectConfigurationMessage) => {
this.eventStream.post(new ObservableEvents.ProjectConfiguration(message));
}));
disposables.add(this.onProjectAdded(this.debounceUpdateProjectWithLeadingTrue));
disposables.add(this.onProjectChange(this.debounceUpdateProjectWithLeadingTrue));
disposables.add(this.onProjectRemoved(this.debounceUpdateProjectWithLeadingTrue));
this._setState({
status: ServerState.Starting,
disposables,
});
this._launchTarget = launchTarget;
const solutionPath = launchTarget.target;
const cwd = path.dirname(solutionPath);
const args = [
'-z',
'-s', solutionPath,
'--hostPID', process.pid.toString(),
'DotNet:enablePackageRestore=false',
'--encoding', 'utf-8',
'--loglevel', options.loggingLevel
];
if (!options.razorDisabled) {
// Razor support only exists for certain platforms, so only load the plugin if present
const razorPluginPath = options.razorPluginPath.length > 0 ? options.razorPluginPath : path.join(
this.extensionPath,
'.razor',
'OmniSharpPlugin',
'Microsoft.AspNetCore.Razor.OmniSharpPlugin.dll');
if (fs.existsSync(razorPluginPath)) {
args.push('--plugin', razorPluginPath);
}
}
if (options.waitForDebugger === true) {
args.push('--debug');
}
for (let i = 0; i < options.excludePaths.length; i++) {
args.push(`FileOptions:SystemExcludeSearchPatterns:${i}=${options.excludePaths[i]}`);
}
if (options.enableMsBuildLoadProjectsOnDemand === true) {
args.push('MsBuild:LoadProjectsOnDemand=true');
}
if (options.enableRoslynAnalyzers === true) {
args.push('RoslynExtensionsOptions:EnableAnalyzersSupport=true');
}
if (options.enableEditorConfigSupport === true) {
args.push('FormattingOptions:EnableEditorConfigSupport=true');
}
if (options.organizeImportsOnFormat === true) {
args.push('FormattingOptions:OrganizeImports=true');
}
if (this.decompilationAuthorized && options.enableDecompilationSupport === true) {
args.push('RoslynExtensionsOptions:EnableDecompilationSupport=true');
}
if (options.enableImportCompletion === true) {
args.push('RoslynExtensionsOptions:EnableImportCompletion=true');
}
if (options.enableAsyncCompletion === true) {
args.push('RoslynExtensionsOptions:EnableAsyncCompletion=true');
}
if (options.sdkPath.length > 0) {
args.push(`Sdk:Path=${options.sdkPath}`);
}
if (options.sdkVersion.length > 0) {
args.push(`Sdk:Version=${options.sdkVersion}`);
}
if (options.sdkIncludePrereleases) {
args.push(`Sdk:IncludePrereleases=true`);
}
if (options.inlayHintsEnableForParameters === true) {
args.push(`RoslynExtensionsOptions:InlayHintsOptions:EnableForParameters=${options.inlayHintsEnableForParameters.toString()}`);
args.push(`RoslynExtensionsOptions:InlayHintsOptions:ForLiteralParameters=${options.inlayHintsForLiteralParameters.toString()}`);
args.push(`RoslynExtensionsOptions:InlayHintsOptions:ForIndexerParameters=${options.inlayHintsForIndexerParameters.toString()}`);
args.push(`RoslynExtensionsOptions:InlayHintsOptions:ForObjectCreationParameters=${options.inlayHintsForObjectCreationParameters.toString()}`);
args.push(`RoslynExtensionsOptions:InlayHintsOptions:ForOtherParameters=${options.inlayHintsForOtherParameters.toString()}`);
args.push(`RoslynExtensionsOptions:InlayHintsOptions:SuppressForParametersThatDifferOnlyBySuffix=${options.inlayHintsSuppressForParametersThatDifferOnlyBySuffix.toString()}`);
args.push(`RoslynExtensionsOptions:InlayHintsOptions:SuppressForParametersThatMatchMethodIntent=${options.inlayHintsSuppressForParametersThatMatchMethodIntent.toString()}`);
args.push(`RoslynExtensionsOptions:InlayHintsOptions:SuppressForParametersThatMatchArgumentName=${options.inlayHintsSuppressForParametersThatMatchArgumentName.toString()}`);
}
if (options.inlayHintsEnableForTypes === true) {
args.push(`RoslynExtensionsOptions:InlayHintsOptions:EnableForTypes=${options.inlayHintsEnableForTypes.toString()}`);
args.push(`RoslynExtensionsOptions:InlayHintsOptions:ForImplicitVariableTypes=${options.inlayHintsForImplicitVariableTypes.toString()}`);
args.push(`RoslynExtensionsOptions:InlayHintsOptions:ForLambdaParameterTypes=${options.inlayHintsForLambdaParameterTypes.toString()}`);
args.push(`RoslynExtensionsOptions:InlayHintsOptions:ForImplicitObjectCreation=${options.inlayHintsForImplicitObjectCreation.toString()}`);
}
if (options.analyzeOpenDocumentsOnly === true) {
args.push('RoslynExtensionsOptions:AnalyzeOpenDocumentsOnly=true');
}
for (let i = 0; i < options.dotNetCliPaths.length; i++) {
args.push(`DotNetCliOptions:LocationPaths:${i}=${options.dotNetCliPaths[i]}`);
}
let launchPath: string;
try {
launchPath = await this._omnisharpManager.GetOmniSharpLaunchPath(this.packageJSON.defaults.omniSharp, options.path, /* useFramework */ !options.useModernNet, this.extensionPath);
}
catch (e) {
const error = e as Error; // Unsafe TypeScript hack to recognize the catch type as Error.
this.eventStream.post(new ObservableEvents.OmnisharpFailure(`Error occurred in loading omnisharp from omnisharp.path\nCould not start the server due to ${error.toString()}`, error));
return;
}
this.eventStream.post(new ObservableEvents.OmnisharpInitialisation(options.dotNetCliPaths, new Date(), solutionPath));
this._fireEvent(Events.BeforeServerStart, solutionPath);
try {
const launchResult = await launchOmniSharp(cwd, args, launchPath, this.platformInfo, options, this.monoResolver, this.dotnetResolver);
this.eventStream.post(new ObservableEvents.OmnisharpLaunch(launchResult.hostVersion, launchResult.hostPath, launchResult.hostIsMono, launchResult.command, launchResult.process.pid));
if (!options.razorDisabled && options.razorPluginPath.length > 0) {
if (fs.existsSync(options.razorPluginPath)) {
this.eventStream.post(new ObservableEvents.RazorPluginPathSpecified(options.razorPluginPath));
} else {
this.eventStream.post(new ObservableEvents.RazorPluginPathDoesNotExist(options.razorPluginPath));
}
}
this._delayTrackers = {};
await this._doConnect(disposables, launchResult.process, options);
this._setState({
status: ServerState.Started,
disposables,
serverProcess: launchResult.process,
telemetryIntervalId: setInterval(() => this._reportTelemetry(), TelemetryReportingDelay),
});
this._fireEvent(Events.ServerStart, solutionPath);
this._requestQueue.drain();
}
catch (err) {
this._fireEvent(Events.ServerError, err);
return this.stop();
}
}
private onProjectConfigurationReceived(listener: (e: protocol.ProjectConfigurationMessage) => void) {
return this._addListener(Events.ProjectConfiguration, listener);
}
private debounceUpdateProjectWithLeadingTrue = () => {
// Call the updateProjectInfo directly if it is the first time, otherwise debounce the request
// This needs to be done so that we have a project information for the first incoming request
if (this.firstUpdateProject) {
this.updateProjectInfo();
}
else {
this.updateProjectDebouncer.next(new ObservableEvents.ProjectModified());
}
}
private updateProjectInfo = async () => {
this.firstUpdateProject = false;
let info = await serverUtils.requestWorkspaceInformation(this);
//once we get the info, push the event into the event stream
this.eventStream.post(new ObservableEvents.WorkspaceInformationUpdated(info));
}
public async stop(): Promise<void> {
// We're already stopped, nothing to do :).
if (this._state.status === ServerState.Stopped) {
return;
}
// Clear the session properties when the session ends.
this._sessionProperties = {};
if (this._state.status === ServerState.Started) {
const { serverProcess, telemetryIntervalId } = this._state;
clearInterval(telemetryIntervalId);
this._reportTelemetry();
if (process.platform === 'win32') {
// when killing a process in windows its child
// processes are *not* killed but become root
// processes. Therefore we use TASKKILL.EXE
await new Promise<void>((resolve, reject) => {
const killer = exec(`taskkill /F /T /PID ${serverProcess.pid}`, (err, stdout, stderr) => {
if (err) {
return reject(err);
}
});
killer.on('exit', resolve);
killer.on('error', reject);
});
}
else {
// Kill Unix process and children
const children = await utils.getUnixChildProcessIds(serverProcess.pid);
for (const child of children) {
process.kill(child, 'SIGTERM');
}
serverProcess.kill('SIGTERM');
}
}
const { disposables } = this._state;
this._setState({ status: ServerState.Stopped });
this._fireEvent(Events.ServerStop, this);
// Dispose of the disposables only _after_ we've fired the last server event.
disposables.dispose();
}
public async restart(launchTarget: LaunchTarget | undefined = this._launchTarget): Promise<void> {
if (this._state.status === ServerState.Starting) {
this.eventStream.post(new ObservableEvents.OmnisharpServerOnServerError("Attempt to restart OmniSharp server failed because another server instance is starting."));
return;
}
if (launchTarget !== undefined) {
await this.stop();
this.eventStream.post(new ObservableEvents.OmnisharpRestart());
await this._start(launchTarget);
}
}
public async autoStart(preferredPath: string): Promise<void> {
const options = this.optionProvider.GetLatestOptions();
const launchTargets = await findLaunchTargets(options);
// If there aren't any potential launch targets, we create file watcher and try to
// start the server again once a *.sln, *.slnf, *.csproj, project.json, CSX or Cake file is created.
if (launchTargets.length === 0) {
await new Promise<void>((resolve, reject) => {
// 1st watch for files
const watcher = this.vscode.workspace.createFileSystemWatcher('{**/*.sln,**/*.slnf,**/*.csproj,**/project.json,**/*.csx,**/*.cake}',
/*ignoreCreateEvents*/ false,
/*ignoreChangeEvents*/ true,
/*ignoreDeleteEvents*/ true);
watcher.onDidCreate(uri => {
watcher.dispose();
resolve();
});
});
// 2nd try again
return this.autoStart(preferredPath);
}
else if (launchTargets.length === 1) {
// If there's only one target, just start
return this._start(launchTargets[0]);
}
// First, try to launch against something that matches the user's preferred target
const defaultLaunchSolutionConfigValue = this.optionProvider.GetLatestOptions().defaultLaunchSolution;
const defaultLaunchSolutionTarget = launchTargets.find((a) => (path.basename(a.target) === defaultLaunchSolutionConfigValue));
if (defaultLaunchSolutionTarget) {
return this._start(defaultLaunchSolutionTarget);
}
// If there's more than one launch target, we start the server if one of the targets
// matches the preferred path.
if (preferredPath.length > 0) {
const preferredLaunchTarget = launchTargets.find((a_1) => a_1.target === preferredPath);
if (preferredLaunchTarget) {
return this._start(preferredLaunchTarget);
}
}
// To maintain previous behavior when there are mulitple targets available,
// launch with first Solution or Folder target.
const firstFolderOrSolutionTarget = launchTargets
.find(target => target.workspaceKind == LaunchTargetKind.Folder || target.workspaceKind == LaunchTargetKind.Solution);
if (firstFolderOrSolutionTarget) {
return this._start(firstFolderOrSolutionTarget);
}
// When running integration tests, open the first launch target.
if (process.env.RUNNING_INTEGRATION_TESTS === "true") {
return this._start(launchTargets[0]);
}
// Otherwise, we fire the "MultipleLaunchTargets" event,
// which is handled in status.ts to display the launch target selector.
this._fireEvent(Events.MultipleLaunchTargets, launchTargets);
return showProjectSelector(this, launchTargets);
}
// --- requests et al
public async makeRequest<TResponse>(command: string, data?: any, token?: CancellationToken): Promise<TResponse> {
if (!this.isRunning()) {
return Promise.reject<TResponse>('OmniSharp server is not running.');
}
let startTime: number;
let request: Request;
const promise = new Promise<TResponse>((resolve, reject) => {
startTime = Date.now();
request = {
command,
data,
onSuccess: value => resolve(value),
onError: err => reject(err)
};
this._requestQueue.enqueue(request);
});
if (token !== undefined) {
token.onCancellationRequested(() => {
this.eventStream.post(new ObservableEvents.OmnisharpServerRequestCancelled(request.command, request.id));
this._requestQueue.cancelRequest(request);
// Note: This calls reject() on the promise returned by OmniSharpServer.makeRequest
request.onError(new Error(`Request ${request.command} cancelled, id: ${request.id}`));
});
}
return promise.then(response => {
let endTime = Date.now();
let elapsedTime = endTime - startTime;
this._recordRequestDelay(command, elapsedTime);
return response;
});
}
private async _doConnect(
disposables: CompositeDisposable,
serverProcess: SpawnedChildProcess,
options: Options): Promise<void> {
serverProcess.stderr.on('data', (data: Buffer) => {
let trimData = removeBOMFromBuffer(data);
if (trimData.length > 0) {
this._fireEvent(Events.StdErr, trimData.toString());
}
});
const readLine = createInterface({
input: serverProcess.stdout,
output: serverProcess.stdin,
terminal: false
});
const promise = new Promise<void>((resolve, reject) => {
let listener: Disposable;
// Convert the timeout from the seconds to milliseconds, which is required by setTimeout().
const timeoutDuration = options.projectLoadTimeout * 1000;
// timeout logic
const handle = setTimeout(() => {
if (listener) {
listener.dispose();
}
reject(new Error("OmniSharp server load timed out. Use the 'omnisharp.projectLoadTimeout' setting to override the default delay (one minute)."));
}, timeoutDuration);
// handle started-event
listener = this.onOmnisharpStart(() => {
if (listener) {
listener.dispose();
}
clearTimeout(handle);
resolve();
});
});
const lineReceived = this._onLineReceived.bind(this);
readLine.addListener('line', lineReceived);
disposables.add(new Disposable(() => {
readLine.removeListener('line', lineReceived);
}));
return promise;
}
private _onLineReceived(line: string) {
line = removeBOMFromString(line);
if (line[0] !== '{') {
this.eventStream.post(new ObservableEvents.OmnisharpServerMessage(line));
return;
}
let packet: protocol.WireProtocol.Packet;
try {
packet = JSON.parse(line);
}
catch (err) {
// This isn't JSON
return;
}
if (!packet.Type) {
// Bogus packet
return;
}
switch (packet.Type) {
case 'response':
this._handleResponsePacket(<protocol.WireProtocol.ResponsePacket>packet);
break;
case 'event':
this._handleEventPacket(<protocol.WireProtocol.EventPacket>packet);
break;
default:
this.eventStream.post(new ObservableEvents.OmnisharpServerMessage(`Unknown packet type: ${packet.Type}`));
break;
}
}
private _handleResponsePacket(packet: protocol.WireProtocol.ResponsePacket) {
const request = this._requestQueue.dequeue(packet.Command, packet.Request_seq);
if (!request) {
this.eventStream.post(new ObservableEvents.OmnisharpServerMessage(`Received response for ${packet.Command} but could not find request.`));
return;
}
this.eventStream.post(new ObservableEvents.OmnisharpServerVerboseMessage(`handleResponse: ${packet.Command} (${packet.Request_seq})`));
if (packet.Success) {
request.onSuccess(packet.Body);
}
else {
request.onError(packet.Message || packet.Body);
}
this._requestQueue.drain();
}
private _handleEventPacket(packet: protocol.WireProtocol.EventPacket): void {
if (packet.Event === 'log') {
const entry = <{ LogLevel: string; Name: string; Message: string; }>packet.Body;
this.eventStream.post(new ObservableEvents.OmnisharpEventPacketReceived(entry.LogLevel, entry.Name, entry.Message));
}
else {
// fwd all other events
this._fireEvent(packet.Event, packet.Body);
}
}
private _makeRequest(request: Request): number {
if (this._state.status !== ServerState.Started) {
throw new Error("Tried to make a request when the OmniSharp server wasn't running");
}
const id = OmniSharpServer._nextId++;
request.id = id;
const requestPacket: protocol.WireProtocol.RequestPacket = {
Type: 'request',
Seq: id,
Command: request.command,
Arguments: request.data
};
this.eventStream.post(new ObservableEvents.OmnisharpRequestMessage(request, id));
this._state.serverProcess.stdin.write(JSON.stringify(requestPacket) + '\n');
return id;
}
}