-
Notifications
You must be signed in to change notification settings - Fork 420
/
Copy pathHost.cs
298 lines (265 loc) · 12.1 KB
/
Host.cs
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
using System;
using System.Collections.Generic;
using System.Composition.Hosting;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OmniSharp.Endpoint;
using OmniSharp.Mef;
using OmniSharp.Models.UpdateBuffer;
using OmniSharp.Plugins;
using OmniSharp.Services;
using OmniSharp.Protocol;
using OmniSharp.Utilities;
using System.Globalization;
namespace OmniSharp.Stdio
{
internal class Host : IDisposable
{
private readonly TextReader _input;
private readonly ISharedTextWriter _writer;
private readonly IServiceProvider _serviceProvider;
private readonly IDictionary<string, Lazy<EndpointHandler>> _endpointHandlers;
private readonly CompositionHost _compositionHost;
private readonly ILogger _logger;
private readonly IOmniSharpEnvironment _environment;
private readonly CancellationTokenSource _cancellationTokenSource;
private readonly CachedStringBuilder _cachedStringBuilder;
private static readonly double TimestampToTicks = TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency;
public Host(
TextReader input, ISharedTextWriter writer, IOmniSharpEnvironment environment,
IServiceProvider serviceProvider, CompositionHostBuilder compositionHostBuilder, ILoggerFactory loggerFactory, CancellationTokenSource cancellationTokenSource)
{
_cancellationTokenSource = cancellationTokenSource;
_input = input;
_writer = writer;
_environment = environment;
_serviceProvider = serviceProvider;
_logger = loggerFactory.CreateLogger<Host>();
_logger.LogInformation($"Starting OmniSharp on {Platform.Current}");
_compositionHost = compositionHostBuilder.Build(_environment.TargetDirectory);
_cachedStringBuilder = new CachedStringBuilder();
var handlers = Initialize();
_endpointHandlers = handlers;
}
private IDictionary<string, Lazy<EndpointHandler>> Initialize()
{
var workspace = _compositionHost.GetExport<OmniSharpWorkspace>();
var projectSystems = _compositionHost.GetExports<IProjectSystem>();
var endpointMetadatas = _compositionHost.GetExports<Lazy<IRequest, OmniSharpEndpointMetadata>>()
.Select(x => x.Metadata)
.ToArray();
var handlers = _compositionHost.GetExports<Lazy<IRequestHandler, OmniSharpRequestHandlerMetadata>>();
var updateBufferEndpointHandler = new Lazy<EndpointHandler<UpdateBufferRequest, object>>(
() => (EndpointHandler<UpdateBufferRequest, object>)_endpointHandlers[OmniSharpEndpoints.UpdateBuffer].Value);
var languagePredicateHandler = new LanguagePredicateHandler(projectSystems);
var projectSystemPredicateHandler = new StaticLanguagePredicateHandler("Projects");
var nugetPredicateHandler = new StaticLanguagePredicateHandler("NuGet");
var endpointHandlers = endpointMetadatas.ToDictionary(
x => x.EndpointName,
endpoint => new Lazy<EndpointHandler>(() =>
{
IPredicateHandler handler;
// Projects are a special case, this allows us to select the correct "Projects" language for them
if (endpoint.EndpointName == OmniSharpEndpoints.ProjectInformation || endpoint.EndpointName == OmniSharpEndpoints.WorkspaceInformation)
handler = projectSystemPredicateHandler;
else if (endpoint.EndpointName == OmniSharpEndpoints.PackageSearch || endpoint.EndpointName == OmniSharpEndpoints.PackageSource || endpoint.EndpointName == OmniSharpEndpoints.PackageVersion)
handler = nugetPredicateHandler;
else
handler = languagePredicateHandler;
// This lets any endpoint, that contains a Request object, invoke update buffer.
// The language will be same language as the caller, this means any language service
// must implement update buffer.
var updateEndpointHandler = updateBufferEndpointHandler;
if (endpoint.EndpointName == OmniSharpEndpoints.UpdateBuffer)
{
// We don't want to call update buffer on update buffer.
updateEndpointHandler = new Lazy<EndpointHandler<UpdateBufferRequest, object>>(() => null);
}
return EndpointHandler.Factory(handler, _compositionHost, _logger, endpoint, handlers, updateEndpointHandler, Enumerable.Empty<Plugin>());
}),
StringComparer.OrdinalIgnoreCase
);
// Handled as alternative middleware in http
endpointHandlers.Add(
OmniSharpEndpoints.CheckAliveStatus,
new Lazy<EndpointHandler>(
() => new GenericEndpointHandler(x => Task.FromResult<object>(true)))
);
endpointHandlers.Add(
OmniSharpEndpoints.CheckReadyStatus,
new Lazy<EndpointHandler>(
() => new GenericEndpointHandler(x => Task.FromResult<object>(workspace.Initialized)))
);
endpointHandlers.Add(
OmniSharpEndpoints.StopServer,
new Lazy<EndpointHandler>(
() => new GenericEndpointHandler(x =>
{
_cancellationTokenSource.Cancel();
return Task.FromResult<object>(null);
}))
);
return endpointHandlers;
}
public void Dispose()
{
_compositionHost?.Dispose();
_cancellationTokenSource?.Dispose();
}
public void Start()
{
WorkspaceInitializer.Initialize(_serviceProvider, _compositionHost);
Task.Factory.StartNew(async () =>
{
_writer.WriteLine(new EventPacket()
{
Event = "started"
});
while (!_cancellationTokenSource.IsCancellationRequested)
{
var line = await _input.ReadLineAsync();
if (line == null)
{
break;
}
var ignored = Task.Factory.StartNew(async () =>
{
try
{
await HandleRequest(line, _logger);
}
catch (Exception e)
{
if (e is AggregateException aggregateEx)
{
e = aggregateEx.Flatten().InnerException;
}
_writer.WriteLine(new EventPacket()
{
Event = "error",
Body = JsonConvert.ToString(e.ToString(), '"', StringEscapeHandling.Default)
});
}
});
}
});
_logger.LogInformation($"Omnisharp server running using {nameof(TransportType.Stdio)} at location '{_environment.TargetDirectory}' on host {_environment.HostProcessId}.");
Console.CancelKeyPress += (sender, e) =>
{
_cancellationTokenSource.Cancel();
e.Cancel = true;
};
if (_environment.HostProcessId != -1)
{
try
{
var hostProcess = Process.GetProcessById(_environment.HostProcessId);
hostProcess.EnableRaisingEvents = true;
hostProcess.OnExit(() => _cancellationTokenSource.Cancel());
}
catch
{
// If the process dies before we get here then request shutdown
// immediately
_cancellationTokenSource.Cancel();
}
}
}
private async Task HandleRequest(string json, ILogger logger)
{
var startTimestamp = Stopwatch.GetTimestamp();
var request = RequestPacket.Parse(json);
if (logger.IsEnabled(LogLevel.Debug))
{
LogRequest(json, logger, LogLevel.Debug);
}
var response = request.Reply();
try
{
if (!request.Command.StartsWith("/"))
{
request.Command = $"/{request.Command}";
}
// hand off request to next layer
if (_endpointHandlers.TryGetValue(request.Command, out var handler))
{
var result = await handler.Value.Handle(request);
response.Body = result;
return;
}
throw new NotSupportedException($"Command '{request.Command}' is not supported.");
}
catch (Exception e)
{
if (e is AggregateException aggregateEx)
{
e = aggregateEx.Flatten().InnerException;
}
// updating the response object here so that the ResponseStream
// prints the latest state when being closed
response.Success = false;
response.Message = JsonConvert.ToString(e.ToString(), '"', StringEscapeHandling.Default);
}
finally
{
// response gets logged when Debug or more detailed log level is enabled
// or when we have unsuccessful response (exception)
if (logger.IsEnabled(LogLevel.Debug) || !response.Success)
{
// if logging is at Debug level, request would have already been logged
// however not for higher log levels, so we want to explicitly log the request too
if (!logger.IsEnabled(LogLevel.Debug))
{
LogRequest(json, logger, LogLevel.Warning);
}
var currentTimestamp = Stopwatch.GetTimestamp();
var elapsed = new TimeSpan((long)(TimestampToTicks * (currentTimestamp - startTimestamp)));
LogResponse(response.ToString(), logger, response.Success, elapsed);
}
// actually write it
_writer.WriteLine(response);
}
}
void LogRequest(string json, ILogger logger, LogLevel logLevel)
{
var builder = _cachedStringBuilder.Acquire();
try
{
builder.AppendLine("************ Request ************");
builder.Append(JToken.Parse(json).ToString(Formatting.Indented));
logger.Log(logLevel, builder.ToString());
}
finally
{
_cachedStringBuilder.Release(builder);
}
}
void LogResponse(string json, ILogger logger, bool isSuccess, TimeSpan elapsed)
{
var builder = _cachedStringBuilder.Acquire();
try
{
builder.AppendLine($"************ Response ({elapsed.TotalMilliseconds.ToString("0.0000", CultureInfo.InvariantCulture)}ms) ************ ");
builder.Append(JToken.Parse(json).ToString(Formatting.Indented));
if (isSuccess)
{
logger.LogDebug(builder.ToString());
}
else
{
logger.LogError(builder.ToString());
}
}
finally
{
_cachedStringBuilder.Release(builder);
}
}
}
}